diff options
Diffstat (limited to 'Emby.Server.Implementations/AppBase')
3 files changed, 190 insertions, 106 deletions
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; } } } |
