aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorthe1HOknocks <the1HOknocks@randohg.com>2026-10-18 10:58:14 +0000
committerthe1HOknocks <the1HOknocks@randohg.com>2026-10-18 10:58:14 +0000
commit5cc214943cfd70154f0a2a3ae8139a1a1e69e71d (patch)
treeb74c395aac578c60c6b5ee56959515abbdb74700
parent292b13d1daf36316274211a8b3c13385c60efdb5 (diff)
Keep defaults out of DTOs while keeping API compatibility
-rw-r--r--Jellyfin.Api/Helpers/ConfigurationJsonTypeInfoModifier.cs48
-rw-r--r--Jellyfin.Api/Helpers/ConfigurationMapper.cs5
-rw-r--r--Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs7
-rw-r--r--MediaBrowser.Common/Net/NetworkConfigurationDto.cs38
-rw-r--r--MediaBrowser.Model/Configuration/EncodingOptionsDto.cs54
-rw-r--r--MediaBrowser.Model/Configuration/MetadataConfigurationDto.cs2
-rw-r--r--MediaBrowser.Model/Configuration/ServerConfigurationDto.cs134
-rw-r--r--MediaBrowser.Model/Configuration/XbmcMetadataOptionsDto.cs6
-rw-r--r--MediaBrowser.Model/LiveTv/LiveTvOptionsDto.cs25
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs248
10 files changed, 376 insertions, 191 deletions
diff --git a/Jellyfin.Api/Helpers/ConfigurationJsonTypeInfoModifier.cs b/Jellyfin.Api/Helpers/ConfigurationJsonTypeInfoModifier.cs
new file mode 100644
index 0000000000..83cccd0678
--- /dev/null
+++ b/Jellyfin.Api/Helpers/ConfigurationJsonTypeInfoModifier.cs
@@ -0,0 +1,48 @@
+using System.Text.Json.Serialization.Metadata;
+using MediaBrowser.Common.Net;
+using MediaBrowser.Model.Configuration;
+using MediaBrowser.Model.LiveTv;
+
+namespace Jellyfin.Api.Helpers;
+
+/// <summary>
+/// Keeps config defaults out of the DTOs.
+/// </summary>
+public static class ConfigurationJsonTypeInfoModifier
+{
+ /// <summary>
+ /// Fills in defaults from the internal config before reading the request.
+ /// </summary>
+ /// <remarks>
+ /// Missing fields keep their defaults. Values sent by the client, including null, replace them.
+ /// Use a new config each time so requests don't share arrays or other objects.
+ /// </remarks>
+ /// <param name="typeInfo">The JSON type information.</param>
+ public static void Modify(JsonTypeInfo typeInfo)
+ {
+ if (typeInfo.Type == typeof(ServerConfigurationDto))
+ {
+ typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new ServerConfiguration());
+ }
+ else if (typeInfo.Type == typeof(EncodingOptionsDto))
+ {
+ typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new EncodingOptions());
+ }
+ else if (typeInfo.Type == typeof(NetworkConfigurationDto))
+ {
+ typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new NetworkConfiguration());
+ }
+ else if (typeInfo.Type == typeof(MetadataConfigurationDto))
+ {
+ typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new MetadataConfiguration());
+ }
+ else if (typeInfo.Type == typeof(XbmcMetadataOptionsDto))
+ {
+ typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new XbmcMetadataOptions());
+ }
+ else if (typeInfo.Type == typeof(LiveTvOptionsDto))
+ {
+ typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new LiveTvOptions());
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/ConfigurationMapper.cs b/Jellyfin.Api/Helpers/ConfigurationMapper.cs
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;
/// <summary>
@@ -12,7 +10,7 @@ public class NetworkConfigurationDto
/// <summary>
/// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at.
/// </summary>
- public string BaseUrl { get; set; } = string.Empty;
+ public string BaseUrl { get; set; } = null!;
/// <summary>
/// Gets or sets a value indicating whether to use HTTPS.
@@ -27,37 +25,37 @@ public class NetworkConfigurationDto
/// <summary>
/// Gets or sets the filesystem path of an X.509 certificate to use for SSL.
/// </summary>
- public string CertificatePath { get; set; } = string.Empty;
+ public string? CertificatePath { get; set; }
/// <summary>
/// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>.
/// </summary>
- public string CertificatePassword { get; set; } = string.Empty;
+ public string? CertificatePassword { get; set; }
/// <summary>
/// Gets or sets the internal HTTP server port.
/// </summary>
- public int InternalHttpPort { get; set; } = NetworkConfiguration.DefaultHttpPort;
+ public int InternalHttpPort { get; set; }
/// <summary>
/// Gets or sets the internal HTTPS server port.
/// </summary>
- public int InternalHttpsPort { get; set; } = NetworkConfiguration.DefaultHttpsPort;
+ public int InternalHttpsPort { get; set; }
/// <summary>
/// Gets or sets the public HTTP port.
/// </summary>
- public int PublicHttpPort { get; set; } = NetworkConfiguration.DefaultHttpPort;
+ public int PublicHttpPort { get; set; }
/// <summary>
/// Gets or sets the public HTTPS port.
/// </summary>
- public int PublicHttpsPort { get; set; } = NetworkConfiguration.DefaultHttpsPort;
+ public int PublicHttpsPort { get; set; }
/// <summary>
/// Gets or sets a value indicating whether Autodiscovery is enabled.
/// </summary>
- public bool AutoDiscovery { get; set; } = true;
+ public bool AutoDiscovery { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to enable automatic port forwarding.
@@ -67,7 +65,7 @@ public class NetworkConfigurationDto
/// <summary>
/// Gets or sets a value indicating whether IPv4 is enabled.
/// </summary>
- public bool EnableIPv4 { get; set; } = true;
+ public bool EnableIPv4 { get; set; }
/// <summary>
/// Gets or sets a value indicating whether IPv6 is enabled.
@@ -77,47 +75,47 @@ public class NetworkConfigurationDto
/// <summary>
/// Gets or sets a value indicating whether access from outside of the LAN is permitted.
/// </summary>
- public bool EnableRemoteAccess { get; set; } = true;
+ public bool EnableRemoteAccess { get; set; }
/// <summary>
/// Gets or sets the subnets that are deemed to make up the LAN.
/// </summary>
- public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>();
+ public string[] LocalNetworkSubnets { get; set; } = null!;
/// <summary>
/// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.
/// </summary>
- public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>();
+ public string[] LocalNetworkAddresses { get; set; } = null!;
/// <summary>
/// Gets or sets the known proxies.
/// </summary>
- public string[] KnownProxies { get; set; } = Array.Empty<string>();
+ public string[] KnownProxies { get; set; } = null!;
/// <summary>
/// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be ignored for the purposes of binding.
/// </summary>
- public bool IgnoreVirtualInterfaces { get; set; } = true;
+ public bool IgnoreVirtualInterfaces { get; set; }
/// <summary>
/// Gets or sets a value indicating the interface name prefixes that should be ignored.
/// </summary>
- public string[] VirtualInterfaceNames { get; set; } = new string[] { "veth" };
+ public string[] VirtualInterfaceNames { get; set; } = null!;
/// <summary>
/// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests.
/// </summary>
- public bool EnablePublishedServerUriByRequest { get; set; } = false;
+ public bool EnablePublishedServerUriByRequest { get; set; }
/// <summary>
/// Gets or sets PublishedServerUri to advertise for specific subnets.
/// </summary>
- public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>();
+ public string[] PublishedServerUriBySubnet { get; set; } = null!;
/// <summary>
/// Gets or sets the filter for remote IP connectivity. Used in conjunction with <seealso cref="IsRemoteIPFilterBlacklist"/>.
/// </summary>
- public string[] RemoteIPFilter { get; set; } = Array.Empty<string>();
+ public string[] RemoteIPFilter { get; set; } = null!;
/// <summary>
/// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist.
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;
@@ -12,56 +11,6 @@ namespace MediaBrowser.Model.Configuration;
public class EncodingOptionsDto
{
/// <summary>
- /// Initializes a new instance of the <see cref="EncodingOptionsDto" /> class.
- /// </summary>
- 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;
- }
-
- /// <summary>
/// Gets or sets the thread count used for encoding.
/// </summary>
public int EncodingThreadCount { get; set; }
@@ -214,7 +163,7 @@ public class EncodingOptionsDto
/// <summary>
/// Gets or sets the encoder preset.
/// </summary>
- public EncoderPreset? EncoderPreset { get; set; }
+ public EncoderPreset EncoderPreset { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the framerate is doubled when deinterlacing.
@@ -304,6 +253,5 @@ public class EncodingOptionsDto
/// <summary>
/// Gets or sets the method used for audio seeking in HLS.
/// </summary>
- [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
/// <summary>
/// Gets or sets a value indicating whether to use file creation time for date added.
/// </summary>
- 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;
/// </summary>
public class ServerConfigurationDto
{
- /// <summary>
- /// Initializes a new instance of the <see cref="ServerConfigurationDto" /> class.
- /// </summary>
- 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<NameValuePair>();
+ 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<string>();
+ public string[] CodecsUsed { get; set; } = null!;
- public RepositoryInfo[] PluginRepositories { get; set; } = Array.Empty<RepositoryInfo>();
+ 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<PathSubstitution>();
+ 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<CastReceiverApplication>();
+ 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
/// <summary>
/// Gets or sets the release date format.
/// </summary>
- public string ReleaseDateFormat { get; set; } = "yyyy-MM-dd";
+ public string ReleaseDateFormat { get; set; } = null!;
/// <summary>
/// Gets or sets a value indicating whether to save image paths in NFO.
/// </summary>
- public bool SaveImagePathsInNfo { get; set; } = true;
+ public bool SaveImagePathsInNfo { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to enable path substitution.
/// </summary>
- public bool EnablePathSubstitution { get; set; } = true;
+ public bool EnablePathSubstitution { get; set; }
/// <summary>
/// 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;
/// <summary>
@@ -10,17 +8,6 @@ namespace MediaBrowser.Model.LiveTv;
public class LiveTvOptionsDto
{
/// <summary>
- /// Initializes a new instance of the <see cref="LiveTvOptionsDto" /> class.
- /// </summary>
- public LiveTvOptionsDto()
- {
- TunerHosts = Array.Empty<TunerHostInfo>();
- ListingProviders = Array.Empty<ListingsProviderInfo>();
- MediaLocationsCreated = Array.Empty<string>();
- RecordingPostProcessorArguments = "\"{path}\"";
- }
-
- /// <summary>
/// Gets or sets the guide days.
/// </summary>
public int? GuideDays { get; set; }
@@ -53,12 +40,12 @@ public class LiveTvOptionsDto
/// <summary>
/// Gets or sets the tuner hosts.
/// </summary>
- public TunerHostInfo[] TunerHosts { get; set; }
+ public TunerHostInfo[] TunerHosts { get; set; } = null!;
/// <summary>
/// Gets or sets the listing providers.
/// </summary>
- public ListingsProviderInfo[] ListingProviders { get; set; }
+ public ListingsProviderInfo[] ListingProviders { get; set; } = null!;
/// <summary>
/// Gets or sets the pre-padding seconds.
@@ -73,7 +60,7 @@ public class LiveTvOptionsDto
/// <summary>
/// Gets or sets the media locations created.
/// </summary>
- public string[] MediaLocationsCreated { get; set; }
+ public string[] MediaLocationsCreated { get; set; } = null!;
/// <summary>
/// Gets or sets the recording post processor.
@@ -83,15 +70,15 @@ public class LiveTvOptionsDto
/// <summary>
/// Gets or sets the recording post processor arguments.
/// </summary>
- public string RecordingPostProcessorArguments { get; set; }
+ public string RecordingPostProcessorArguments { get; set; } = null!;
/// <summary>
/// Gets or sets a value indicating whether to save recording NFO.
/// </summary>
- public bool SaveRecordingNFO { get; set; } = true;
+ public bool SaveRecordingNFO { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to save recording images.
/// </summary>
- 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<string, object> _configurations = new()
+ {
+ [string.Empty] = new ServerConfiguration(),
+ ["encoding"] = new EncodingOptions(),
+ ["network"] = new NetworkConfiguration(),
+ ["metadata"] = new MetadataConfiguration(),
+ ["xbmcmetadata"] = new XbmcMetadataOptions(),
+ ["livetv"] = new LiveTvOptions()
+ };
+
+ private readonly Mock<IServerConfigurationManager> _configurationManager = new();
+ private readonly IHost _host;
+ private readonly HttpClient _client;
+
+ public ConfigurationControllerTests()
+ {
+ _configurationManager.Setup(manager => manager.Configuration)
+ .Returns(() => (ServerConfiguration)_configurations[string.Empty]);
+ _configurationManager.Setup(manager => manager.ReplaceConfiguration(It.IsAny<BaseApplicationConfiguration>()))
+ .Callback<BaseApplicationConfiguration>(configuration => _configurations[string.Empty] = configuration);
+ _configurationManager.Setup(manager => manager.GetConfiguration(It.IsAny<string>()))
+ .Returns((string key) => _configurations[key]);
+ _configurationManager.Setup(manager => manager.SaveConfiguration(It.IsAny<string>(), It.IsAny<object>()))
+ .Callback<string, object>((key, configuration) => _configurations[key] = configuration);
+
+ // Use the real API setup, but keep config in memory for these tests.
+ _host = new HostBuilder().ConfigureWebHost(webHost => webHost
+ .UseTestServer()
+ .ConfigureServices(services =>
+ {
+ services.AddSingleton(_configurationManager.Object);
+ services.AddAuthentication();
+ services.AddAuthorization(options =>
+ {
+ options.AddPolicy(Policies.RequiresElevation, policy => policy.RequireAuthenticatedUser());
+ });
+ services.AddJellyfinApi(Array.Empty<Assembly>(), new NetworkConfiguration());
+ })
+ .Configure(app =>
+ {
+ app.UseRouting();
+ app.Use((context, next) =>
+ {
+ context.User = new ClaimsPrincipal(new ClaimsIdentity("Test"));
+ return next(context);
+ });
+ app.UseAuthorization();
+ app.UseEndpoints(endpoints => endpoints.MapControllers());
+ })).Start();
+ _client = _host.GetTestClient();
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData("encoding")]
+ [InlineData("network")]
+ [InlineData("metadata")]
+ [InlineData("xbmcmetadata")]
+ [InlineData("livetv")]
+ public async Task UpdateConfiguration_EmptyRequest_UsesInternalDefaults(string key)
+ {
+ await AssertMatchesLegacyDeserialization(key, "{}");
+ }
+
+ [Theory]
+ [InlineData("", """
+ {"ActivityLogRetentionDays":null,"QuickConnectAvailable":false,"MinResumePct":0,
+ "SortRemoveWords":[],"TrickplayOptions":{"EnableHwAcceleration":true}}
+ """)]
+ [InlineData("encoding", """
+ {"EnableHardwareEncoding":false,"EncodingThreadCount":0,"HardwareDecodingCodecs":[],
+ "H264Crf":"19","EncoderPreset":"slow","VaapiDevice":null,"UnknownOption":true}
+ """)]
+ [InlineData("network", """
+ {"CertificatePath":null,"CertificatePassword":null,"InternalHttpPort":"8097",
+ "EnableRemoteAccess":false,"BaseUrl":"jellyfin/","KnownProxies":[]}
+ """)]
+ [InlineData("network", """
+ {"BaseUrl":"","LocalNetworkSubnets":[],"LocalNetworkAddresses":[],"KnownProxies":[],
+ "VirtualInterfaceNames":[],"PublishedServerUriBySubnet":[],"RemoteIPFilter":[]}
+ """)]
+ [InlineData("metadata", """{"UseFileCreationTimeForDateAdded":false}""")]
+ [InlineData("xbmcmetadata", """{"UserId":"","ReleaseDateFormat":"yyyy-MM-dd","SaveImagePathsInNfo":false}""")]
+ [InlineData("livetv", """
+ {"GuideDays":"","RecordingPath":null,"SaveRecordingNFO":false,
+ "TunerHosts":[{"Url":"http://tuner"}],"ListingProviders":[{"Type":"XmlTv"}]}
+ """)]
+ [InlineData("livetv", """{"TunerHosts":[],"ListingProviders":[],"MediaLocationsCreated":[]}""")]
+ public async Task UpdateConfiguration_SuppliedProperties_MatchLegacyDeserialization(string key, string json)
+ {
+ await AssertMatchesLegacyDeserialization(key, json);
+ }
+
+ [Theory]
+ [InlineData("", "ServerName", "\"My server\"")]
+ [InlineData("encoding", "H264Crf", "18")]
+ [InlineData("network", "InternalHttpPort", "8097")]
+ [InlineData("metadata", "UseFileCreationTimeForDateAdded", "false")]
+ [InlineData("xbmcmetadata", "SaveImagePathsInNfo", "false")]
+ [InlineData("livetv", "GuideDays", "7")]
+ public async Task GetAndUpdateConfiguration_LowercaseRoute_RoundTripsConfiguration(string key, string property, string value)
+ {
+ using var response = await _client.GetAsync(GetUrl(key), TestContext.Current.CancellationToken);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType);
+
+ var body = JsonNode.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken))!.AsObject();
+ var expected = JsonSerializer.SerializeToNode(_configurations[key], JsonDefaults.Options)!.AsObject();
+ Assert.True(JsonNode.DeepEquals(expected, body));
+
+ body[property] = JsonNode.Parse(value);
+ expected[property] = JsonNode.Parse(value);
+ await PostConfiguration(key, body.ToJsonString());
+
+ Assert.True(JsonNode.DeepEquals(expected, JsonSerializer.SerializeToNode(_configurations[key], JsonDefaults.Options)));
+ }
+
+ [Fact]
+ public async Task UpdateConfiguration_CamelCaseProperties_AreApplied()
+ {
+ await PostConfiguration("encoding", """{"h264Crf":18,"enableHardwareEncoding":false}""");
+
+ var configuration = Assert.IsType<EncodingOptions>(_configurations["encoding"]);
+ Assert.Equal(18, configuration.H264Crf);
+ Assert.False(configuration.EnableHardwareEncoding);
+ Assert.Equal(new EncodingOptions().H265Crf, configuration.H265Crf);
+
+ using var request = new HttpRequestMessage(HttpMethod.Get, GetUrl("encoding"));
+ request.Headers.Accept.ParseAdd(JsonDefaults.CamelCaseMediaType);
+ using var response = await _client.SendAsync(request, TestContext.Current.CancellationToken);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var body = JsonNode.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken));
+ Assert.Equal(18, body!["h264Crf"]!.GetValue<int>());
+ }
+
+ [Fact]
+ public async Task UpdateConfiguration_OmittedProperties_ResetToDefaultsRatherThanCurrentValues()
+ {
+ await PostConfiguration("encoding", """{"H264Crf":18,"EnableHardwareEncoding":false}""");
+ await AssertMatchesLegacyDeserialization("encoding", "{}");
+ }
+
+ [Fact]
+ public async Task UpdateConfiguration_DefaultObjects_AreNotSharedBetweenRequests()
+ {
+ await PostConfiguration(string.Empty, "{}");
+ var first = Assert.IsType<ServerConfiguration>(_configurations[string.Empty]);
+ first.MetadataOptions[0].ItemType = "Changed";
+ first.TrickplayOptions.WidthResolutions[0] = 123;
+
+ await AssertMatchesLegacyDeserialization(string.Empty, "{}");
+ var second = Assert.IsType<ServerConfiguration>(_configurations[string.Empty]);
+ Assert.NotSame(first.MetadataOptions, second.MetadataOptions);
+ Assert.NotSame(first.TrickplayOptions, second.TrickplayOptions);
+ }
+
+ [Theory]
+ [InlineData("encoding", "null")]
+ [InlineData("encoding", """{"H264Crf":null}""")]
+ [InlineData("network", """{"InternalHttpPort":"invalid"}""")]
+ [InlineData("network", """{"BaseUrl":null}""")]
+ [InlineData("network", """{"LocalNetworkSubnets":null}""")]
+ [InlineData("network", """{"LocalNetworkAddresses":null}""")]
+ [InlineData("network", """{"KnownProxies":null}""")]
+ [InlineData("network", """{"VirtualInterfaceNames":null}""")]
+ [InlineData("network", """{"PublishedServerUriBySubnet":null}""")]
+ [InlineData("network", """{"RemoteIPFilter":null}""")]
+ [InlineData("livetv", """{"TunerHosts":null}""")]
+ [InlineData("livetv", """{"ListingProviders":null}""")]
+ [InlineData("livetv", """{"MediaLocationsCreated":null}""")]
+ [InlineData("livetv", """{"RecordingPostProcessorArguments":null}""")]
+ [InlineData("xbmcmetadata", """{"ReleaseDateFormat":null}""")]
+ [InlineData("", """{"ServerName":null}""")]
+ public async Task UpdateConfiguration_InvalidRequest_DoesNotSave(string key, string json)
+ {
+ using var content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);
+ using var response = await _client.PostAsync(GetUrl(key), content, TestContext.Current.CancellationToken);
+
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ _configurationManager.Verify(manager => manager.SaveConfiguration(It.IsAny<string>(), It.IsAny<object>()), Times.Never);
+ _configurationManager.Verify(manager => manager.ReplaceConfiguration(It.IsAny<BaseApplicationConfiguration>()), Times.Never);
+ }
+
+ public void Dispose()
+ {
+ _client.Dispose();
+ _host.Dispose();
+ }
+
+ private static string GetUrl(string key)
+ {
+ return string.IsNullOrEmpty(key) ? "/System/Configuration" : "/System/Configuration/" + key;
+ }
+
+ private async Task AssertMatchesLegacyDeserialization(string key, string json)
+ {
+ // Compare with how the old endpoint read the same JSON.
+ var type = _configurations[key].GetType();
+ var expected = JsonSerializer.Deserialize(json, type, JsonDefaults.Options);
+
+ await PostConfiguration(key, json);
+
+ var actual = _configurations[key];
+ Assert.IsType(type, actual);
+ Assert.True(JsonNode.DeepEquals(
+ JsonSerializer.SerializeToNode(expected, type, JsonDefaults.Options),
+ JsonSerializer.SerializeToNode(actual, type, JsonDefaults.Options)));
+ }
+
+ private async Task PostConfiguration(string key, string json)
+ {
+ using var content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);
+ using var response = await _client.PostAsync(GetUrl(key), content, TestContext.Current.CancellationToken);
+ Assert.True(
+ response.StatusCode == HttpStatusCode.NoContent,
+ $"{response.StatusCode}: {await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)}");
+ }
+}