Radarr/src/NzbDrone.Core/Configuration/ConfigFileProvider.cs

355 lines
11 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using NzbDrone.Common.Cache;
using NzbDrone.Common.Disk;
using NzbDrone.Common.EnvironmentInfo;
using NzbDrone.Common.Extensions;
2015-01-26 02:03:21 +00:00
using NzbDrone.Core.Authentication;
2013-07-24 15:08:31 +00:00
using NzbDrone.Core.Configuration.Events;
using NzbDrone.Core.Lifecycle;
using NzbDrone.Core.Messaging.Commands;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.Update;
2013-09-11 06:33:47 +00:00
namespace NzbDrone.Core.Configuration
{
public interface IConfigFileProvider : IHandleAsync<ApplicationStartedEvent>,
IExecute<ResetApiKeyCommand>
{
Dictionary<string, object> GetConfigDictionary();
void SaveConfigDictionary(Dictionary<string, object> configValues);
string BindAddress { get; }
2013-07-14 07:00:50 +00:00
int Port { get; }
2013-09-22 19:57:03 +00:00
int SslPort { get; }
bool EnableSsl { get; }
2013-07-14 07:00:50 +00:00
bool LaunchBrowser { get; }
2015-01-26 02:03:21 +00:00
AuthenticationType AuthenticationMethod { get; }
bool AnalyticsEnabled { get; }
2013-07-24 15:08:31 +00:00
string LogLevel { get; }
string Branch { get; }
2013-09-20 07:31:02 +00:00
string ApiKey { get; }
2013-09-22 19:57:03 +00:00
string SslCertHash { get; }
string UrlBase { get; }
2015-07-22 02:42:38 +00:00
string UiFolder { get; }
bool UpdateAutomatically { get; }
UpdateMechanism UpdateMechanism { get; }
string UpdateScriptPath { get; }
}
public class ConfigFileProvider : IConfigFileProvider
{
2013-09-21 02:07:42 +00:00
public const string CONFIG_ELEMENT_NAME = "Config";
private readonly IEventAggregator _eventAggregator;
private readonly IDiskProvider _diskProvider;
private readonly ICached<string> _cache;
private readonly string _configFile;
private static readonly Regex HiddenCharacterRegex = new Regex("[^a-z0-9]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly object Mutex = new object();
public ConfigFileProvider(IAppFolderInfo appFolderInfo,
ICacheManager cacheManager,
IEventAggregator eventAggregator,
IDiskProvider diskProvider)
{
_cache = cacheManager.GetCache<string>(GetType());
_eventAggregator = eventAggregator;
_diskProvider = diskProvider;
_configFile = appFolderInfo.GetConfigPath();
}
public Dictionary<string, object> GetConfigDictionary()
{
var dict = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase);
var type = GetType();
var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
var value = propertyInfo.GetValue(this, null);
dict.Add(propertyInfo.Name, value);
}
return dict;
}
public void SaveConfigDictionary(Dictionary<string, object> configValues)
{
_cache.Clear();
var allWithDefaults = GetConfigDictionary();
foreach (var configValue in configValues)
{
if (configValue.Key.Equals("ApiKey", StringComparison.InvariantCultureIgnoreCase))
{
continue;
}
if (configValue.Key.Equals("SslCertHash", StringComparison.InvariantCultureIgnoreCase) && configValue.Value.ToString().IsNotNullOrWhiteSpace())
{
SetValue(configValue.Key.FirstCharToUpper(), HiddenCharacterRegex.Replace(configValue.Value.ToString(), string.Empty));
continue;
}
object currentValue;
allWithDefaults.TryGetValue(configValue.Key, out currentValue);
if (currentValue == null) continue;
var equal = configValue.Value.ToString().Equals(currentValue.ToString());
if (!equal)
{
SetValue(configValue.Key.FirstCharToUpper(), configValue.Value.ToString());
}
}
_eventAggregator.PublishEvent(new ConfigFileSavedEvent());
}
public string BindAddress
{
get
{
const string defaultValue = "*";
string bindAddress = GetValue("BindAddress", defaultValue);
if (string.IsNullOrWhiteSpace(bindAddress))
{
return defaultValue;
}
return bindAddress;
}
}
public int Port => GetValueInt("Port", 7878);
2016-12-09 06:54:15 +00:00
public int SslPort => GetValueInt("SslPort", 9898);
2013-09-22 19:57:03 +00:00
2016-12-09 06:54:15 +00:00
public bool EnableSsl => GetValueBoolean("EnableSsl", false);
2013-09-22 19:57:03 +00:00
2016-12-09 06:54:15 +00:00
public bool LaunchBrowser => GetValueBoolean("LaunchBrowser", true);
2016-12-09 06:54:15 +00:00
public string ApiKey => GetValue("ApiKey", GenerateApiKey());
2013-09-20 07:31:02 +00:00
2015-01-26 02:03:21 +00:00
public AuthenticationType AuthenticationMethod
{
2015-01-26 02:03:21 +00:00
get
{
var enabled = GetValueBoolean("AuthenticationEnabled", false, false);
2015-01-26 02:03:21 +00:00
if (enabled)
{
SetValue("AuthenticationMethod", AuthenticationType.Basic);
return AuthenticationType.Basic;
}
return GetValueEnum("AuthenticationMethod", AuthenticationType.None);
}
}
2016-12-09 06:54:15 +00:00
public bool AnalyticsEnabled => GetValueBoolean("AnalyticsEnabled", true, persist: false);
2016-12-09 06:54:15 +00:00
public string Branch => GetValue("Branch", "master").ToLowerInvariant();
2016-12-09 06:54:15 +00:00
public string LogLevel => GetValue("LogLevel", "Info");
2013-07-24 15:08:31 +00:00
2016-12-09 06:54:15 +00:00
public string SslCertHash => GetValue("SslCertHash", "");
2013-09-22 19:57:03 +00:00
public string UrlBase
{
get
{
var urlBase = GetValue("UrlBase", "").Trim('/');
if (urlBase.IsNullOrWhiteSpace())
{
return urlBase;
}
return "/" + urlBase.Trim('/').ToLower();
}
}
2016-12-09 06:54:15 +00:00
public string UiFolder => GetValue("UiFolder", "UI", false);
2015-07-22 02:42:38 +00:00
2016-12-09 06:54:15 +00:00
public bool UpdateAutomatically => GetValueBoolean("UpdateAutomatically", false, false);
2016-12-09 06:54:15 +00:00
public UpdateMechanism UpdateMechanism => GetValueEnum("UpdateMechanism", UpdateMechanism.BuiltIn, false);
2016-12-09 06:54:15 +00:00
public string UpdateScriptPath => GetValue("UpdateScriptPath", "", false );
public int GetValueInt(string key, int defaultValue)
{
return Convert.ToInt32(GetValue(key, defaultValue));
}
public bool GetValueBoolean(string key, bool defaultValue, bool persist = true)
{
return Convert.ToBoolean(GetValue(key, defaultValue, persist));
}
public T GetValueEnum<T>(string key, T defaultValue, bool persist = true)
{
return (T)Enum.Parse(typeof(T), GetValue(key, defaultValue), persist);
}
public string GetValue(string key, object defaultValue, bool persist = true)
{
return _cache.Get(key, () =>
2013-07-24 00:35:35 +00:00
{
var xDoc = LoadConfigFile();
var config = xDoc.Descendants(CONFIG_ELEMENT_NAME).Single();
2013-07-24 00:35:35 +00:00
var parentContainer = config;
2013-07-24 00:35:35 +00:00
var valueHolder = parentContainer.Descendants(key).ToList();
2013-07-24 00:35:35 +00:00
if (valueHolder.Count() == 1)
{
return valueHolder.First().Value.Trim();
}
2013-07-24 00:35:35 +00:00
//Save the value
if (persist)
{
SetValue(key, defaultValue);
}
2013-07-24 00:35:35 +00:00
//return the default value
return defaultValue.ToString();
});
}
public void SetValue(string key, object value)
{
var valueString = value.ToString().Trim();
var xDoc = LoadConfigFile();
var config = xDoc.Descendants(CONFIG_ELEMENT_NAME).Single();
var parentContainer = config;
var keyHolder = parentContainer.Descendants(key);
if (keyHolder.Count() != 1)
{
parentContainer.Add(new XElement(key, valueString));
}
else
{
parentContainer.Descendants(key).Single().Value = valueString;
}
_cache.Set(key, valueString);
SaveConfigFile(xDoc);
}
public void SetValue(string key, Enum value)
{
SetValue(key, value.ToString().ToLower());
}
private void EnsureDefaultConfigFile()
{
if (!File.Exists(_configFile))
{
2013-09-21 02:07:42 +00:00
SaveConfigDictionary(GetConfigDictionary());
}
}
private void DeleteOldValues()
{
var xDoc = LoadConfigFile();
var config = xDoc.Descendants(CONFIG_ELEMENT_NAME).Single();
var type = GetType();
var properties = type.GetProperties();
foreach (var configValue in config.Descendants().ToList())
{
var name = configValue.Name.LocalName;
if (!properties.Any(p => p.Name == name))
{
config.Descendants(name).Remove();
}
}
SaveConfigFile(xDoc);
}
private XDocument LoadConfigFile()
{
try
{
lock (Mutex)
{
if (_diskProvider.FileExists(_configFile))
{
var contents = _diskProvider.ReadAllText(_configFile);
if (contents.IsNullOrWhiteSpace())
{
throw new InvalidConfigFileException($"{_configFile} is empty. Please delete the config file and Radarr will recreate it.");
}
if (contents.All(char.IsControl))
{
throw new InvalidConfigFileException($"{_configFile} is corrupt. Please delete the config file and Radarr will recreate it.");
}
2015-01-22 18:46:55 +00:00
return XDocument.Parse(_diskProvider.ReadAllText(_configFile));
}
var xDoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
xDoc.Add(new XElement(CONFIG_ELEMENT_NAME));
return xDoc;
}
}
catch (XmlException ex)
{
throw new InvalidConfigFileException($"{_configFile} is corrupt is invalid. Please delete the config file and Radarr will recreate it.", ex);
}
}
private void SaveConfigFile(XDocument xDoc)
{
lock (Mutex)
{
_diskProvider.WriteAllText(_configFile, xDoc.ToString());
}
}
private string GenerateApiKey()
{
return Guid.NewGuid().ToString().Replace("-", "");
}
public void HandleAsync(ApplicationStartedEvent message)
{
EnsureDefaultConfigFile();
DeleteOldValues();
}
public void Execute(ResetApiKeyCommand message)
{
SetValue("ApiKey", GenerateApiKey());
}
}
}