From 0bbb2ae633225425e4af6839198dcb382a153cf7 Mon Sep 17 00:00:00 2001 From: KGT1 Date: Tue, 5 May 2026 12:08:11 +0000 Subject: create DTOs for all config endpoints --- .../Configuration/EncodingOptionsDto.cs | 309 +++++++++++++++++++++ 1 file changed, 309 insertions(+) create mode 100644 MediaBrowser.Model/Configuration/EncodingOptionsDto.cs (limited to 'MediaBrowser.Model/Configuration/EncodingOptionsDto.cs') diff --git a/MediaBrowser.Model/Configuration/EncodingOptionsDto.cs b/MediaBrowser.Model/Configuration/EncodingOptionsDto.cs new file mode 100644 index 0000000000..755ba577ca --- /dev/null +++ b/MediaBrowser.Model/Configuration/EncodingOptionsDto.cs @@ -0,0 +1,309 @@ +#pragma warning disable CA1819 + +#nullable disable +using System.ComponentModel; +using MediaBrowser.Model.Entities; + +namespace MediaBrowser.Model.Configuration; + +/// +/// The encoding options DTO for API use. +/// +public class EncodingOptionsDto +{ + /// + /// Initializes a new instance of the class. + /// + public EncodingOptionsDto() + { + EnableFallbackFont = false; + EnableAudioVbr = false; + DownMixAudioBoost = 2; + DownMixStereoAlgorithm = DownMixStereoAlgorithms.None; + MaxMuxingQueueSize = 2048; + EnableThrottling = false; + ThrottleDelaySeconds = 180; + EnableSegmentDeletion = false; + SegmentKeepSeconds = 720; + EncodingThreadCount = -1; + VaapiDevice = "/dev/dri/renderD128"; + QsvDevice = string.Empty; + EnableTonemapping = false; + EnableVppTonemapping = false; + EnableVideoToolboxTonemapping = false; + TonemappingAlgorithm = TonemappingAlgorithm.bt2390; + TonemappingMode = TonemappingMode.auto; + TonemappingRange = TonemappingRange.auto; + TonemappingDesat = 0; + TonemappingPeak = 100; + TonemappingParam = 0; + VppTonemappingBrightness = 16; + VppTonemappingContrast = 1; + H264Crf = 23; + H265Crf = 28; + DeinterlaceDoubleRate = false; + DeinterlaceMethod = DeinterlaceMethod.yadif; + EnableDecodingColorDepth10Hevc = true; + EnableDecodingColorDepth10Vp9 = true; + EnableDecodingColorDepth10HevcRext = false; + EnableDecodingColorDepth12HevcRext = false; + EnableEnhancedNvdecDecoder = true; + PreferSystemNativeHwDecoder = true; + EnableIntelLowPowerH264HwEncoder = false; + EnableIntelLowPowerHevcHwEncoder = false; + EnableHardwareEncoding = true; + AllowHevcEncoding = false; + AllowAv1Encoding = false; + EnableSubtitleExtraction = true; + SubtitleExtractionTimeoutMinutes = 30; + AllowOnDemandMetadataBasedKeyframeExtractionForExtensions = ["mkv"]; + HardwareDecodingCodecs = ["h264", "vc1"]; + HlsAudioSeekStrategy = HlsAudioSeekStrategy.DisableAccurateSeek; + } + + /// + /// Gets or sets the thread count used for encoding. + /// + public int EncodingThreadCount { get; set; } + + /// + /// Gets or sets the temporary transcoding path. + /// + public string TranscodingTempPath { get; set; } + + /// + /// Gets or sets the path to the fallback font. + /// + public string FallbackFontPath { get; set; } + + /// + /// Gets or sets a value indicating whether to use the fallback font. + /// + public bool EnableFallbackFont { get; set; } + + /// + /// Gets or sets a value indicating whether audio VBR is enabled. + /// + public bool EnableAudioVbr { get; set; } + + /// + /// Gets or sets the audio boost applied when downmixing audio. + /// + public double DownMixAudioBoost { get; set; } + + /// + /// Gets or sets the algorithm used for downmixing audio to stereo. + /// + public DownMixStereoAlgorithms DownMixStereoAlgorithm { get; set; } + + /// + /// Gets or sets the maximum size of the muxing queue. + /// + public int MaxMuxingQueueSize { get; set; } + + /// + /// Gets or sets a value indicating whether throttling is enabled. + /// + public bool EnableThrottling { get; set; } + + /// + /// Gets or sets the delay after which throttling happens. + /// + public int ThrottleDelaySeconds { get; set; } + + /// + /// Gets or sets a value indicating whether segment deletion is enabled. + /// + public bool EnableSegmentDeletion { get; set; } + + /// + /// Gets or sets seconds for which segments should be kept before being deleted. + /// + public int SegmentKeepSeconds { get; set; } + + /// + /// Gets or sets the hardware acceleration type. + /// + public HardwareAccelerationType HardwareAccelerationType { get; set; } + + /// + /// Gets or sets the FFmpeg path as set by the user via the UI. + /// + public string EncoderAppPath { get; set; } + + /// + /// Gets or sets the current FFmpeg path being used by the system and displayed on the transcode page. + /// + public string EncoderAppPathDisplay { get; set; } + + /// + /// Gets or sets the VA-API device. + /// + public string VaapiDevice { get; set; } + + /// + /// Gets or sets the QSV device. + /// + public string QsvDevice { get; set; } + + /// + /// Gets or sets a value indicating whether tonemapping is enabled. + /// + public bool EnableTonemapping { get; set; } + + /// + /// Gets or sets a value indicating whether VPP tonemapping is enabled. + /// + public bool EnableVppTonemapping { get; set; } + + /// + /// Gets or sets a value indicating whether videotoolbox tonemapping is enabled. + /// + public bool EnableVideoToolboxTonemapping { get; set; } + + /// + /// Gets or sets the tone-mapping algorithm. + /// + public TonemappingAlgorithm TonemappingAlgorithm { get; set; } + + /// + /// Gets or sets the tone-mapping mode. + /// + public TonemappingMode TonemappingMode { get; set; } + + /// + /// Gets or sets the tone-mapping range. + /// + public TonemappingRange TonemappingRange { get; set; } + + /// + /// Gets or sets the tone-mapping desaturation. + /// + public double TonemappingDesat { get; set; } + + /// + /// Gets or sets the tone-mapping peak. + /// + public double TonemappingPeak { get; set; } + + /// + /// Gets or sets the tone-mapping parameters. + /// + public double TonemappingParam { get; set; } + + /// + /// Gets or sets the VPP tone-mapping brightness. + /// + public double VppTonemappingBrightness { get; set; } + + /// + /// Gets or sets the VPP tone-mapping contrast. + /// + public double VppTonemappingContrast { get; set; } + + /// + /// Gets or sets the H264 CRF. + /// + public int H264Crf { get; set; } + + /// + /// Gets or sets the H265 CRF. + /// + public int H265Crf { get; set; } + + /// + /// Gets or sets the encoder preset. + /// + public EncoderPreset? EncoderPreset { get; set; } + + /// + /// Gets or sets a value indicating whether the framerate is doubled when deinterlacing. + /// + public bool DeinterlaceDoubleRate { get; set; } + + /// + /// Gets or sets the deinterlace method. + /// + public DeinterlaceMethod DeinterlaceMethod { get; set; } + + /// + /// Gets or sets a value indicating whether 10bit HEVC decoding is enabled. + /// + public bool EnableDecodingColorDepth10Hevc { get; set; } + + /// + /// Gets or sets a value indicating whether 10bit VP9 decoding is enabled. + /// + public bool EnableDecodingColorDepth10Vp9 { get; set; } + + /// + /// Gets or sets a value indicating whether 8/10bit HEVC RExt decoding is enabled. + /// + public bool EnableDecodingColorDepth10HevcRext { get; set; } + + /// + /// Gets or sets a value indicating whether 12bit HEVC RExt decoding is enabled. + /// + public bool EnableDecodingColorDepth12HevcRext { get; set; } + + /// + /// Gets or sets a value indicating whether the enhanced NVDEC is enabled. + /// + public bool EnableEnhancedNvdecDecoder { get; set; } + + /// + /// Gets or sets a value indicating whether the system native hardware decoder should be used. + /// + public bool PreferSystemNativeHwDecoder { get; set; } + + /// + /// Gets or sets a value indicating whether the Intel H264 low-power hardware encoder should be used. + /// + public bool EnableIntelLowPowerH264HwEncoder { get; set; } + + /// + /// Gets or sets a value indicating whether the Intel HEVC low-power hardware encoder should be used. + /// + public bool EnableIntelLowPowerHevcHwEncoder { get; set; } + + /// + /// Gets or sets a value indicating whether hardware encoding is enabled. + /// + public bool EnableHardwareEncoding { get; set; } + + /// + /// Gets or sets a value indicating whether HEVC encoding is enabled. + /// + public bool AllowHevcEncoding { get; set; } + + /// + /// Gets or sets a value indicating whether AV1 encoding is enabled. + /// + public bool AllowAv1Encoding { get; set; } + + /// + /// Gets or sets a value indicating whether subtitle extraction is enabled. + /// + public bool EnableSubtitleExtraction { get; set; } + + /// + /// Gets or sets the timeout for subtitle extraction in minutes. + /// + public int SubtitleExtractionTimeoutMinutes { get; set; } + + /// + /// Gets or sets the codecs hardware encoding is used for. + /// + public string[] HardwareDecodingCodecs { get; set; } + + /// + /// Gets or sets the file extensions on-demand metadata based keyframe extraction is enabled for. + /// + public string[] AllowOnDemandMetadataBasedKeyframeExtractionForExtensions { get; set; } + + /// + /// Gets or sets the method used for audio seeking in HLS. + /// + [DefaultValue(HlsAudioSeekStrategy.DisableAccurateSeek)] + public HlsAudioSeekStrategy HlsAudioSeekStrategy { get; set; } +} -- cgit v1.2.3 From 5cc214943cfd70154f0a2a3ae8139a1a1e69e71d Mon Sep 17 00:00:00 2001 From: the1HOknocks Date: Sun, 18 Oct 2026 10:58:14 +0000 Subject: Keep defaults out of DTOs while keeping API compatibility --- .../Helpers/ConfigurationJsonTypeInfoModifier.cs | 48 ++++ Jellyfin.Api/Helpers/ConfigurationMapper.cs | 5 +- .../Extensions/ApiServiceCollectionExtensions.cs | 7 + MediaBrowser.Common/Net/NetworkConfigurationDto.cs | 38 ++-- .../Configuration/EncodingOptionsDto.cs | 54 +---- .../Configuration/MetadataConfigurationDto.cs | 2 +- .../Configuration/ServerConfigurationDto.cs | 134 ++++------- .../Configuration/XbmcMetadataOptionsDto.cs | 6 +- MediaBrowser.Model/LiveTv/LiveTvOptionsDto.cs | 25 +-- .../Controllers/ConfigurationControllerTests.cs | 248 +++++++++++++++++++++ 10 files changed, 376 insertions(+), 191 deletions(-) create mode 100644 Jellyfin.Api/Helpers/ConfigurationJsonTypeInfoModifier.cs create mode 100644 tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs (limited to 'MediaBrowser.Model/Configuration/EncodingOptionsDto.cs') diff --git a/Jellyfin.Api/Helpers/ConfigurationJsonTypeInfoModifier.cs b/Jellyfin.Api/Helpers/ConfigurationJsonTypeInfoModifier.cs new file mode 100644 index 0000000000..83cccd0678 --- /dev/null +++ b/Jellyfin.Api/Helpers/ConfigurationJsonTypeInfoModifier.cs @@ -0,0 +1,48 @@ +using System.Text.Json.Serialization.Metadata; +using MediaBrowser.Common.Net; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.LiveTv; + +namespace Jellyfin.Api.Helpers; + +/// +/// Keeps config defaults out of the DTOs. +/// +public static class ConfigurationJsonTypeInfoModifier +{ + /// + /// Fills in defaults from the internal config before reading the request. + /// + /// + /// Missing fields keep their defaults. Values sent by the client, including null, replace them. + /// Use a new config each time so requests don't share arrays or other objects. + /// + /// The JSON type information. + public static void Modify(JsonTypeInfo typeInfo) + { + if (typeInfo.Type == typeof(ServerConfigurationDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new ServerConfiguration()); + } + else if (typeInfo.Type == typeof(EncodingOptionsDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new EncodingOptions()); + } + else if (typeInfo.Type == typeof(NetworkConfigurationDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new NetworkConfiguration()); + } + else if (typeInfo.Type == typeof(MetadataConfigurationDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new MetadataConfiguration()); + } + else if (typeInfo.Type == typeof(XbmcMetadataOptionsDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new XbmcMetadataOptions()); + } + else if (typeInfo.Type == typeof(LiveTvOptionsDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new LiveTvOptions()); + } + } +} diff --git a/Jellyfin.Api/Helpers/ConfigurationMapper.cs b/Jellyfin.Api/Helpers/ConfigurationMapper.cs index 2b636ca6dc..8cfb847177 100644 --- a/Jellyfin.Api/Helpers/ConfigurationMapper.cs +++ b/Jellyfin.Api/Helpers/ConfigurationMapper.cs @@ -313,8 +313,9 @@ public static class ConfigurationMapper BaseUrl = dto.BaseUrl, EnableHttps = dto.EnableHttps, RequireHttps = dto.RequireHttps, - CertificatePath = dto.CertificatePath, - CertificatePassword = dto.CertificatePassword, + // The web client sends null for blank certificate fields. + CertificatePath = dto.CertificatePath!, + CertificatePassword = dto.CertificatePassword!, InternalHttpPort = dto.InternalHttpPort, InternalHttpsPort = dto.InternalHttpsPort, PublicHttpPort = dto.PublicHttpPort, diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index a498901481..a767e7e5c7 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -6,6 +6,7 @@ using System.Net.Sockets; using System.Reflection; using System.Security.Claims; using System.Text.Json.Nodes; +using System.Text.Json.Serialization.Metadata; using Emby.Server.Implementations; using Jellyfin.Api.Auth; using Jellyfin.Api.Auth.AnonymousLanAccessPolicy; @@ -17,6 +18,7 @@ using Jellyfin.Api.Auth.UserPermissionPolicy; using Jellyfin.Api.Constants; using Jellyfin.Api.Controllers; using Jellyfin.Api.Formatters; +using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Enums; using Jellyfin.Database.Implementations.Enums; @@ -153,6 +155,11 @@ namespace Jellyfin.Server.Extensions // From JsonDefaults.PascalCase options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy; + + options.JsonSerializerOptions.TypeInfoResolver = new DefaultJsonTypeInfoResolver + { + Modifiers = { ConfigurationJsonTypeInfoModifier.Modify } + }; }); foreach (Assembly pluginAssembly in pluginAssemblies) diff --git a/MediaBrowser.Common/Net/NetworkConfigurationDto.cs b/MediaBrowser.Common/Net/NetworkConfigurationDto.cs index 5726b92728..12be0d9fb8 100644 --- a/MediaBrowser.Common/Net/NetworkConfigurationDto.cs +++ b/MediaBrowser.Common/Net/NetworkConfigurationDto.cs @@ -1,7 +1,5 @@ #pragma warning disable CA1819 -using System; - namespace MediaBrowser.Common.Net; /// @@ -12,7 +10,7 @@ public class NetworkConfigurationDto /// /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at. /// - public string BaseUrl { get; set; } = string.Empty; + public string BaseUrl { get; set; } = null!; /// /// Gets or sets a value indicating whether to use HTTPS. @@ -27,37 +25,37 @@ public class NetworkConfigurationDto /// /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. /// - public string CertificatePath { get; set; } = string.Empty; + public string? CertificatePath { get; set; } /// /// Gets or sets the password required to access the X.509 certificate data in the file specified by . /// - public string CertificatePassword { get; set; } = string.Empty; + public string? CertificatePassword { get; set; } /// /// Gets or sets the internal HTTP server port. /// - public int InternalHttpPort { get; set; } = NetworkConfiguration.DefaultHttpPort; + public int InternalHttpPort { get; set; } /// /// Gets or sets the internal HTTPS server port. /// - public int InternalHttpsPort { get; set; } = NetworkConfiguration.DefaultHttpsPort; + public int InternalHttpsPort { get; set; } /// /// Gets or sets the public HTTP port. /// - public int PublicHttpPort { get; set; } = NetworkConfiguration.DefaultHttpPort; + public int PublicHttpPort { get; set; } /// /// Gets or sets the public HTTPS port. /// - public int PublicHttpsPort { get; set; } = NetworkConfiguration.DefaultHttpsPort; + public int PublicHttpsPort { get; set; } /// /// Gets or sets a value indicating whether Autodiscovery is enabled. /// - public bool AutoDiscovery { get; set; } = true; + public bool AutoDiscovery { get; set; } /// /// Gets or sets a value indicating whether to enable automatic port forwarding. @@ -67,7 +65,7 @@ public class NetworkConfigurationDto /// /// Gets or sets a value indicating whether IPv4 is enabled. /// - public bool EnableIPv4 { get; set; } = true; + public bool EnableIPv4 { get; set; } /// /// Gets or sets a value indicating whether IPv6 is enabled. @@ -77,47 +75,47 @@ public class NetworkConfigurationDto /// /// Gets or sets a value indicating whether access from outside of the LAN is permitted. /// - public bool EnableRemoteAccess { get; set; } = true; + public bool EnableRemoteAccess { get; set; } /// /// Gets or sets the subnets that are deemed to make up the LAN. /// - public string[] LocalNetworkSubnets { get; set; } = Array.Empty(); + public string[] LocalNetworkSubnets { get; set; } = null!; /// /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used. /// - public string[] LocalNetworkAddresses { get; set; } = Array.Empty(); + public string[] LocalNetworkAddresses { get; set; } = null!; /// /// Gets or sets the known proxies. /// - public string[] KnownProxies { get; set; } = Array.Empty(); + public string[] KnownProxies { get; set; } = null!; /// /// Gets or sets a value indicating whether address names that match should be ignored for the purposes of binding. /// - public bool IgnoreVirtualInterfaces { get; set; } = true; + public bool IgnoreVirtualInterfaces { get; set; } /// /// Gets or sets a value indicating the interface name prefixes that should be ignored. /// - public string[] VirtualInterfaceNames { get; set; } = new string[] { "veth" }; + public string[] VirtualInterfaceNames { get; set; } = null!; /// /// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests. /// - public bool EnablePublishedServerUriByRequest { get; set; } = false; + public bool EnablePublishedServerUriByRequest { get; set; } /// /// Gets or sets PublishedServerUri to advertise for specific subnets. /// - public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); + public string[] PublishedServerUriBySubnet { get; set; } = null!; /// /// Gets or sets the filter for remote IP connectivity. Used in conjunction with . /// - public string[] RemoteIPFilter { get; set; } = Array.Empty(); + public string[] RemoteIPFilter { get; set; } = null!; /// /// Gets or sets a value indicating whether contains a blacklist or a whitelist. Default is a whitelist. diff --git a/MediaBrowser.Model/Configuration/EncodingOptionsDto.cs b/MediaBrowser.Model/Configuration/EncodingOptionsDto.cs index 755ba577ca..0bc009f402 100644 --- a/MediaBrowser.Model/Configuration/EncodingOptionsDto.cs +++ b/MediaBrowser.Model/Configuration/EncodingOptionsDto.cs @@ -1,7 +1,6 @@ #pragma warning disable CA1819 #nullable disable -using System.ComponentModel; using MediaBrowser.Model.Entities; namespace MediaBrowser.Model.Configuration; @@ -11,56 +10,6 @@ namespace MediaBrowser.Model.Configuration; /// public class EncodingOptionsDto { - /// - /// Initializes a new instance of the class. - /// - public EncodingOptionsDto() - { - EnableFallbackFont = false; - EnableAudioVbr = false; - DownMixAudioBoost = 2; - DownMixStereoAlgorithm = DownMixStereoAlgorithms.None; - MaxMuxingQueueSize = 2048; - EnableThrottling = false; - ThrottleDelaySeconds = 180; - EnableSegmentDeletion = false; - SegmentKeepSeconds = 720; - EncodingThreadCount = -1; - VaapiDevice = "/dev/dri/renderD128"; - QsvDevice = string.Empty; - EnableTonemapping = false; - EnableVppTonemapping = false; - EnableVideoToolboxTonemapping = false; - TonemappingAlgorithm = TonemappingAlgorithm.bt2390; - TonemappingMode = TonemappingMode.auto; - TonemappingRange = TonemappingRange.auto; - TonemappingDesat = 0; - TonemappingPeak = 100; - TonemappingParam = 0; - VppTonemappingBrightness = 16; - VppTonemappingContrast = 1; - H264Crf = 23; - H265Crf = 28; - DeinterlaceDoubleRate = false; - DeinterlaceMethod = DeinterlaceMethod.yadif; - EnableDecodingColorDepth10Hevc = true; - EnableDecodingColorDepth10Vp9 = true; - EnableDecodingColorDepth10HevcRext = false; - EnableDecodingColorDepth12HevcRext = false; - EnableEnhancedNvdecDecoder = true; - PreferSystemNativeHwDecoder = true; - EnableIntelLowPowerH264HwEncoder = false; - EnableIntelLowPowerHevcHwEncoder = false; - EnableHardwareEncoding = true; - AllowHevcEncoding = false; - AllowAv1Encoding = false; - EnableSubtitleExtraction = true; - SubtitleExtractionTimeoutMinutes = 30; - AllowOnDemandMetadataBasedKeyframeExtractionForExtensions = ["mkv"]; - HardwareDecodingCodecs = ["h264", "vc1"]; - HlsAudioSeekStrategy = HlsAudioSeekStrategy.DisableAccurateSeek; - } - /// /// Gets or sets the thread count used for encoding. /// @@ -214,7 +163,7 @@ public class EncodingOptionsDto /// /// Gets or sets the encoder preset. /// - public EncoderPreset? EncoderPreset { get; set; } + public EncoderPreset EncoderPreset { get; set; } /// /// Gets or sets a value indicating whether the framerate is doubled when deinterlacing. @@ -304,6 +253,5 @@ public class EncodingOptionsDto /// /// Gets or sets the method used for audio seeking in HLS. /// - [DefaultValue(HlsAudioSeekStrategy.DisableAccurateSeek)] public HlsAudioSeekStrategy HlsAudioSeekStrategy { get; set; } } diff --git a/MediaBrowser.Model/Configuration/MetadataConfigurationDto.cs b/MediaBrowser.Model/Configuration/MetadataConfigurationDto.cs index 8b39523bc7..e07f9e34de 100644 --- a/MediaBrowser.Model/Configuration/MetadataConfigurationDto.cs +++ b/MediaBrowser.Model/Configuration/MetadataConfigurationDto.cs @@ -8,5 +8,5 @@ public class MetadataConfigurationDto /// /// Gets or sets a value indicating whether to use file creation time for date added. /// - public bool UseFileCreationTimeForDateAdded { get; set; } = true; + public bool UseFileCreationTimeForDateAdded { get; set; } } diff --git a/MediaBrowser.Model/Configuration/ServerConfigurationDto.cs b/MediaBrowser.Model/Configuration/ServerConfigurationDto.cs index 62af8b9626..3f2bfe04f0 100644 --- a/MediaBrowser.Model/Configuration/ServerConfigurationDto.cs +++ b/MediaBrowser.Model/Configuration/ServerConfigurationDto.cs @@ -1,7 +1,6 @@ #pragma warning disable CS1591 #pragma warning disable CA1819 -using System; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.System; @@ -14,57 +13,6 @@ namespace MediaBrowser.Model.Configuration; /// public class ServerConfigurationDto { - /// - /// Initializes a new instance of the class. - /// - public ServerConfigurationDto() - { - LogFileRetentionDays = 3; - 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", - } - }; - } - public int LogFileRetentionDays { get; set; } public bool IsStartupWizardCompleted { get; set; } @@ -73,105 +21,105 @@ public class ServerConfigurationDto public string? PreviousVersionStr { get; set; } - public bool EnableMetrics { get; set; } = false; + public bool EnableMetrics { get; set; } - public bool EnableNormalizedItemByNameIds { get; set; } = true; + public bool EnableNormalizedItemByNameIds { get; set; } public bool IsPortAuthorized { get; set; } - public bool QuickConnectAvailable { get; set; } = true; + public bool QuickConnectAvailable { get; set; } - public bool EnableCaseSensitiveItemIds { get; set; } = true; + public bool EnableCaseSensitiveItemIds { get; set; } - public bool DisableLiveTvChannelUserDataName { get; set; } = true; + public bool DisableLiveTvChannelUserDataName { get; set; } - public string MetadataPath { get; set; } = string.Empty; + public string MetadataPath { get; set; } = null!; - public string PreferredMetadataLanguage { get; set; } = "en"; + public string PreferredMetadataLanguage { get; set; } = null!; - public string MetadataCountryCode { get; set; } = "US"; + public string MetadataCountryCode { get; set; } = null!; - public string[] SortReplaceCharacters { get; set; } = new[] { ".", "+", "%" }; + public string[] SortReplaceCharacters { get; set; } = null!; - public string[] SortRemoveCharacters { get; set; } = new[] { ",", "&", "-", "{", "}", "'" }; + public string[] SortRemoveCharacters { get; set; } = null!; - public string[] SortRemoveWords { get; set; } = new[] { "the", "a", "an" }; + public string[] SortRemoveWords { get; set; } = null!; - public int MinResumePct { get; set; } = 5; + public int MinResumePct { get; set; } - public int MaxResumePct { get; set; } = 90; + public int MaxResumePct { get; set; } - public int MinResumeDurationSeconds { get; set; } = 300; + public int MinResumeDurationSeconds { get; set; } - public int MinAudiobookResume { get; set; } = 5; + public int MinAudiobookResume { get; set; } - public int MaxAudiobookResume { get; set; } = 5; + public int MaxAudiobookResume { get; set; } public int InactiveSessionThreshold { get; set; } - public int LibraryMonitorDelay { get; set; } = 60; + public int LibraryMonitorDelay { get; set; } - public int LibraryUpdateDuration { get; set; } = 30; + public int LibraryUpdateDuration { get; set; } - public int CacheSize { get; set; } = Environment.ProcessorCount * 100; + public int CacheSize { get; set; } public ImageSavingConvention ImageSavingConvention { get; set; } - public MetadataOptions[] MetadataOptions { get; set; } + public MetadataOptions[] MetadataOptions { get; set; } = null!; - public bool SkipDeserializationForBasicTypes { get; set; } = true; + public bool SkipDeserializationForBasicTypes { get; set; } - public string ServerName { get; set; } = string.Empty; + public string ServerName { get; set; } = null!; - public string UICulture { get; set; } = "en-US"; + public string UICulture { get; set; } = null!; - public bool SaveMetadataHidden { get; set; } = false; + public bool SaveMetadataHidden { get; set; } - public NameValuePair[] ContentTypes { get; set; } = Array.Empty(); + public NameValuePair[] ContentTypes { get; set; } = null!; public int RemoteClientBitrateLimit { get; set; } - public bool EnableFolderView { get; set; } = false; + public bool EnableFolderView { get; set; } - public bool EnableGroupingMoviesIntoCollections { get; set; } = false; + public bool EnableGroupingMoviesIntoCollections { get; set; } - public bool EnableGroupingShowsIntoCollections { get; set; } = false; + public bool EnableGroupingShowsIntoCollections { get; set; } - public bool DisplaySpecialsWithinSeasons { get; set; } = true; + public bool DisplaySpecialsWithinSeasons { get; set; } - public string[] CodecsUsed { get; set; } = Array.Empty(); + public string[] CodecsUsed { get; set; } = null!; - public RepositoryInfo[] PluginRepositories { get; set; } = Array.Empty(); + public RepositoryInfo[] PluginRepositories { get; set; } = null!; - public bool EnableExternalContentInSuggestions { get; set; } = true; + public bool EnableExternalContentInSuggestions { get; set; } public int ImageExtractionTimeoutMs { get; set; } - public PathSubstitution[] PathSubstitutions { get; set; } = Array.Empty(); + public PathSubstitution[] PathSubstitutions { get; set; } = null!; - public bool EnableSlowResponseWarning { get; set; } = true; + public bool EnableSlowResponseWarning { get; set; } - public long SlowResponseThresholdMs { get; set; } = 500; + public long SlowResponseThresholdMs { get; set; } - public string[] CorsHosts { get; set; } = new[] { "*" }; + public string[] CorsHosts { get; set; } = null!; - public int? ActivityLogRetentionDays { get; set; } = 30; + public int? ActivityLogRetentionDays { get; set; } public int LibraryScanFanoutConcurrency { get; set; } public int LibraryMetadataRefreshConcurrency { get; set; } - public bool AllowClientLogUpload { get; set; } = true; + public bool AllowClientLogUpload { get; set; } public int DummyChapterDuration { get; set; } - public ImageResolution ChapterImageResolution { get; set; } = ImageResolution.MatchSource; + public ImageResolution ChapterImageResolution { get; set; } public int ParallelImageEncodingLimit { get; set; } - public CastReceiverApplication[] CastReceiverApplications { get; set; } = Array.Empty(); + public CastReceiverApplication[] CastReceiverApplications { get; set; } = null!; - public TrickplayOptions TrickplayOptions { get; set; } = new TrickplayOptions(); + public TrickplayOptions TrickplayOptions { get; set; } = null!; public bool EnableLegacyAuthorization { get; set; } } diff --git a/MediaBrowser.Model/Configuration/XbmcMetadataOptionsDto.cs b/MediaBrowser.Model/Configuration/XbmcMetadataOptionsDto.cs index ba27381dae..e2c118ddbe 100644 --- a/MediaBrowser.Model/Configuration/XbmcMetadataOptionsDto.cs +++ b/MediaBrowser.Model/Configuration/XbmcMetadataOptionsDto.cs @@ -13,17 +13,17 @@ public class XbmcMetadataOptionsDto /// /// Gets or sets the release date format. /// - public string ReleaseDateFormat { get; set; } = "yyyy-MM-dd"; + public string ReleaseDateFormat { get; set; } = null!; /// /// Gets or sets a value indicating whether to save image paths in NFO. /// - public bool SaveImagePathsInNfo { get; set; } = true; + public bool SaveImagePathsInNfo { get; set; } /// /// Gets or sets a value indicating whether to enable path substitution. /// - public bool EnablePathSubstitution { get; set; } = true; + public bool EnablePathSubstitution { get; set; } /// /// Gets or sets a value indicating whether to enable extra thumbs duplication. diff --git a/MediaBrowser.Model/LiveTv/LiveTvOptionsDto.cs b/MediaBrowser.Model/LiveTv/LiveTvOptionsDto.cs index 923128d999..3ed7d5b2e5 100644 --- a/MediaBrowser.Model/LiveTv/LiveTvOptionsDto.cs +++ b/MediaBrowser.Model/LiveTv/LiveTvOptionsDto.cs @@ -1,7 +1,5 @@ #pragma warning disable CA1819 -using System; - namespace MediaBrowser.Model.LiveTv; /// @@ -9,17 +7,6 @@ namespace MediaBrowser.Model.LiveTv; /// public class LiveTvOptionsDto { - /// - /// Initializes a new instance of the class. - /// - public LiveTvOptionsDto() - { - TunerHosts = Array.Empty(); - ListingProviders = Array.Empty(); - MediaLocationsCreated = Array.Empty(); - RecordingPostProcessorArguments = "\"{path}\""; - } - /// /// Gets or sets the guide days. /// @@ -53,12 +40,12 @@ public class LiveTvOptionsDto /// /// Gets or sets the tuner hosts. /// - public TunerHostInfo[] TunerHosts { get; set; } + public TunerHostInfo[] TunerHosts { get; set; } = null!; /// /// Gets or sets the listing providers. /// - public ListingsProviderInfo[] ListingProviders { get; set; } + public ListingsProviderInfo[] ListingProviders { get; set; } = null!; /// /// Gets or sets the pre-padding seconds. @@ -73,7 +60,7 @@ public class LiveTvOptionsDto /// /// Gets or sets the media locations created. /// - public string[] MediaLocationsCreated { get; set; } + public string[] MediaLocationsCreated { get; set; } = null!; /// /// Gets or sets the recording post processor. @@ -83,15 +70,15 @@ public class LiveTvOptionsDto /// /// Gets or sets the recording post processor arguments. /// - public string RecordingPostProcessorArguments { get; set; } + public string RecordingPostProcessorArguments { get; set; } = null!; /// /// Gets or sets a value indicating whether to save recording NFO. /// - public bool SaveRecordingNFO { get; set; } = true; + public bool SaveRecordingNFO { get; set; } /// /// Gets or sets a value indicating whether to save recording images. /// - public bool SaveRecordingImages { get; set; } = true; + public bool SaveRecordingImages { get; set; } } diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs new file mode 100644 index 0000000000..94672d5c7b --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs @@ -0,0 +1,248 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Mime; +using System.Reflection; +using System.Security.Claims; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading.Tasks; +using Jellyfin.Extensions.Json; +using Jellyfin.Server.Extensions; +using MediaBrowser.Common.Api; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.LiveTv; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Integration.Tests.Controllers; + +public sealed class ConfigurationControllerTests : IDisposable +{ + private readonly Dictionary _configurations = new() + { + [string.Empty] = new ServerConfiguration(), + ["encoding"] = new EncodingOptions(), + ["network"] = new NetworkConfiguration(), + ["metadata"] = new MetadataConfiguration(), + ["xbmcmetadata"] = new XbmcMetadataOptions(), + ["livetv"] = new LiveTvOptions() + }; + + private readonly Mock _configurationManager = new(); + private readonly IHost _host; + private readonly HttpClient _client; + + public ConfigurationControllerTests() + { + _configurationManager.Setup(manager => manager.Configuration) + .Returns(() => (ServerConfiguration)_configurations[string.Empty]); + _configurationManager.Setup(manager => manager.ReplaceConfiguration(It.IsAny())) + .Callback(configuration => _configurations[string.Empty] = configuration); + _configurationManager.Setup(manager => manager.GetConfiguration(It.IsAny())) + .Returns((string key) => _configurations[key]); + _configurationManager.Setup(manager => manager.SaveConfiguration(It.IsAny(), It.IsAny())) + .Callback((key, configuration) => _configurations[key] = configuration); + + // Use the real API setup, but keep config in memory for these tests. + _host = new HostBuilder().ConfigureWebHost(webHost => webHost + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(_configurationManager.Object); + services.AddAuthentication(); + services.AddAuthorization(options => + { + options.AddPolicy(Policies.RequiresElevation, policy => policy.RequireAuthenticatedUser()); + }); + services.AddJellyfinApi(Array.Empty(), new NetworkConfiguration()); + }) + .Configure(app => + { + app.UseRouting(); + app.Use((context, next) => + { + context.User = new ClaimsPrincipal(new ClaimsIdentity("Test")); + return next(context); + }); + app.UseAuthorization(); + app.UseEndpoints(endpoints => endpoints.MapControllers()); + })).Start(); + _client = _host.GetTestClient(); + } + + [Theory] + [InlineData("")] + [InlineData("encoding")] + [InlineData("network")] + [InlineData("metadata")] + [InlineData("xbmcmetadata")] + [InlineData("livetv")] + public async Task UpdateConfiguration_EmptyRequest_UsesInternalDefaults(string key) + { + await AssertMatchesLegacyDeserialization(key, "{}"); + } + + [Theory] + [InlineData("", """ + {"ActivityLogRetentionDays":null,"QuickConnectAvailable":false,"MinResumePct":0, + "SortRemoveWords":[],"TrickplayOptions":{"EnableHwAcceleration":true}} + """)] + [InlineData("encoding", """ + {"EnableHardwareEncoding":false,"EncodingThreadCount":0,"HardwareDecodingCodecs":[], + "H264Crf":"19","EncoderPreset":"slow","VaapiDevice":null,"UnknownOption":true} + """)] + [InlineData("network", """ + {"CertificatePath":null,"CertificatePassword":null,"InternalHttpPort":"8097", + "EnableRemoteAccess":false,"BaseUrl":"jellyfin/","KnownProxies":[]} + """)] + [InlineData("network", """ + {"BaseUrl":"","LocalNetworkSubnets":[],"LocalNetworkAddresses":[],"KnownProxies":[], + "VirtualInterfaceNames":[],"PublishedServerUriBySubnet":[],"RemoteIPFilter":[]} + """)] + [InlineData("metadata", """{"UseFileCreationTimeForDateAdded":false}""")] + [InlineData("xbmcmetadata", """{"UserId":"","ReleaseDateFormat":"yyyy-MM-dd","SaveImagePathsInNfo":false}""")] + [InlineData("livetv", """ + {"GuideDays":"","RecordingPath":null,"SaveRecordingNFO":false, + "TunerHosts":[{"Url":"http://tuner"}],"ListingProviders":[{"Type":"XmlTv"}]} + """)] + [InlineData("livetv", """{"TunerHosts":[],"ListingProviders":[],"MediaLocationsCreated":[]}""")] + public async Task UpdateConfiguration_SuppliedProperties_MatchLegacyDeserialization(string key, string json) + { + await AssertMatchesLegacyDeserialization(key, json); + } + + [Theory] + [InlineData("", "ServerName", "\"My server\"")] + [InlineData("encoding", "H264Crf", "18")] + [InlineData("network", "InternalHttpPort", "8097")] + [InlineData("metadata", "UseFileCreationTimeForDateAdded", "false")] + [InlineData("xbmcmetadata", "SaveImagePathsInNfo", "false")] + [InlineData("livetv", "GuideDays", "7")] + public async Task GetAndUpdateConfiguration_LowercaseRoute_RoundTripsConfiguration(string key, string property, string value) + { + using var response = await _client.GetAsync(GetUrl(key), TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType); + + var body = JsonNode.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken))!.AsObject(); + var expected = JsonSerializer.SerializeToNode(_configurations[key], JsonDefaults.Options)!.AsObject(); + Assert.True(JsonNode.DeepEquals(expected, body)); + + body[property] = JsonNode.Parse(value); + expected[property] = JsonNode.Parse(value); + await PostConfiguration(key, body.ToJsonString()); + + Assert.True(JsonNode.DeepEquals(expected, JsonSerializer.SerializeToNode(_configurations[key], JsonDefaults.Options))); + } + + [Fact] + public async Task UpdateConfiguration_CamelCaseProperties_AreApplied() + { + await PostConfiguration("encoding", """{"h264Crf":18,"enableHardwareEncoding":false}"""); + + var configuration = Assert.IsType(_configurations["encoding"]); + Assert.Equal(18, configuration.H264Crf); + Assert.False(configuration.EnableHardwareEncoding); + Assert.Equal(new EncodingOptions().H265Crf, configuration.H265Crf); + + using var request = new HttpRequestMessage(HttpMethod.Get, GetUrl("encoding")); + request.Headers.Accept.ParseAdd(JsonDefaults.CamelCaseMediaType); + using var response = await _client.SendAsync(request, TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var body = JsonNode.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)); + Assert.Equal(18, body!["h264Crf"]!.GetValue()); + } + + [Fact] + public async Task UpdateConfiguration_OmittedProperties_ResetToDefaultsRatherThanCurrentValues() + { + await PostConfiguration("encoding", """{"H264Crf":18,"EnableHardwareEncoding":false}"""); + await AssertMatchesLegacyDeserialization("encoding", "{}"); + } + + [Fact] + public async Task UpdateConfiguration_DefaultObjects_AreNotSharedBetweenRequests() + { + await PostConfiguration(string.Empty, "{}"); + var first = Assert.IsType(_configurations[string.Empty]); + first.MetadataOptions[0].ItemType = "Changed"; + first.TrickplayOptions.WidthResolutions[0] = 123; + + await AssertMatchesLegacyDeserialization(string.Empty, "{}"); + var second = Assert.IsType(_configurations[string.Empty]); + Assert.NotSame(first.MetadataOptions, second.MetadataOptions); + Assert.NotSame(first.TrickplayOptions, second.TrickplayOptions); + } + + [Theory] + [InlineData("encoding", "null")] + [InlineData("encoding", """{"H264Crf":null}""")] + [InlineData("network", """{"InternalHttpPort":"invalid"}""")] + [InlineData("network", """{"BaseUrl":null}""")] + [InlineData("network", """{"LocalNetworkSubnets":null}""")] + [InlineData("network", """{"LocalNetworkAddresses":null}""")] + [InlineData("network", """{"KnownProxies":null}""")] + [InlineData("network", """{"VirtualInterfaceNames":null}""")] + [InlineData("network", """{"PublishedServerUriBySubnet":null}""")] + [InlineData("network", """{"RemoteIPFilter":null}""")] + [InlineData("livetv", """{"TunerHosts":null}""")] + [InlineData("livetv", """{"ListingProviders":null}""")] + [InlineData("livetv", """{"MediaLocationsCreated":null}""")] + [InlineData("livetv", """{"RecordingPostProcessorArguments":null}""")] + [InlineData("xbmcmetadata", """{"ReleaseDateFormat":null}""")] + [InlineData("", """{"ServerName":null}""")] + public async Task UpdateConfiguration_InvalidRequest_DoesNotSave(string key, string json) + { + using var content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json); + using var response = await _client.PostAsync(GetUrl(key), content, TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + _configurationManager.Verify(manager => manager.SaveConfiguration(It.IsAny(), It.IsAny()), Times.Never); + _configurationManager.Verify(manager => manager.ReplaceConfiguration(It.IsAny()), Times.Never); + } + + public void Dispose() + { + _client.Dispose(); + _host.Dispose(); + } + + private static string GetUrl(string key) + { + return string.IsNullOrEmpty(key) ? "/System/Configuration" : "/System/Configuration/" + key; + } + + private async Task AssertMatchesLegacyDeserialization(string key, string json) + { + // Compare with how the old endpoint read the same JSON. + var type = _configurations[key].GetType(); + var expected = JsonSerializer.Deserialize(json, type, JsonDefaults.Options); + + await PostConfiguration(key, json); + + var actual = _configurations[key]; + Assert.IsType(type, actual); + Assert.True(JsonNode.DeepEquals( + JsonSerializer.SerializeToNode(expected, type, JsonDefaults.Options), + JsonSerializer.SerializeToNode(actual, type, JsonDefaults.Options))); + } + + private async Task PostConfiguration(string key, string json) + { + using var content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json); + using var response = await _client.PostAsync(GetUrl(key), content, TestContext.Current.CancellationToken); + Assert.True( + response.StatusCode == HttpStatusCode.NoContent, + $"{response.StatusCode}: {await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)}"); + } +} -- cgit v1.2.3