BaseConfigurationManager.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Model.Configuration;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading;
  12. namespace MediaBrowser.Common.Implementations.Configuration
  13. {
  14. /// <summary>
  15. /// Class BaseConfigurationManager
  16. /// </summary>
  17. public abstract class BaseConfigurationManager : IConfigurationManager
  18. {
  19. /// <summary>
  20. /// Gets the type of the configuration.
  21. /// </summary>
  22. /// <value>The type of the configuration.</value>
  23. protected abstract Type ConfigurationType { get; }
  24. /// <summary>
  25. /// Occurs when [configuration updated].
  26. /// </summary>
  27. public event EventHandler<EventArgs> ConfigurationUpdated;
  28. /// <summary>
  29. /// Occurs when [configuration updating].
  30. /// </summary>
  31. public event EventHandler<ConfigurationUpdateEventArgs> NamedConfigurationUpdating;
  32. /// <summary>
  33. /// Occurs when [named configuration updated].
  34. /// </summary>
  35. public event EventHandler<ConfigurationUpdateEventArgs> NamedConfigurationUpdated;
  36. /// <summary>
  37. /// Gets the logger.
  38. /// </summary>
  39. /// <value>The logger.</value>
  40. protected ILogger Logger { get; private set; }
  41. /// <summary>
  42. /// Gets the XML serializer.
  43. /// </summary>
  44. /// <value>The XML serializer.</value>
  45. protected IXmlSerializer XmlSerializer { get; private set; }
  46. /// <summary>
  47. /// Gets or sets the application paths.
  48. /// </summary>
  49. /// <value>The application paths.</value>
  50. public IApplicationPaths CommonApplicationPaths { get; private set; }
  51. /// <summary>
  52. /// The _configuration loaded
  53. /// </summary>
  54. private bool _configurationLoaded;
  55. /// <summary>
  56. /// The _configuration sync lock
  57. /// </summary>
  58. private object _configurationSyncLock = new object();
  59. /// <summary>
  60. /// The _configuration
  61. /// </summary>
  62. private BaseApplicationConfiguration _configuration;
  63. /// <summary>
  64. /// Gets the system configuration
  65. /// </summary>
  66. /// <value>The configuration.</value>
  67. public BaseApplicationConfiguration CommonConfiguration
  68. {
  69. get
  70. {
  71. // Lazy load
  72. LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationLoaded, ref _configurationSyncLock, () => (BaseApplicationConfiguration)ConfigurationHelper.GetXmlConfiguration(ConfigurationType, CommonApplicationPaths.SystemConfigurationFilePath, XmlSerializer));
  73. return _configuration;
  74. }
  75. protected set
  76. {
  77. _configuration = value;
  78. _configurationLoaded = value != null;
  79. }
  80. }
  81. private ConfigurationStore[] _configurationStores = {};
  82. private IConfigurationFactory[] _configurationFactories = {};
  83. /// <summary>
  84. /// Initializes a new instance of the <see cref="BaseConfigurationManager" /> class.
  85. /// </summary>
  86. /// <param name="applicationPaths">The application paths.</param>
  87. /// <param name="logManager">The log manager.</param>
  88. /// <param name="xmlSerializer">The XML serializer.</param>
  89. protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILogManager logManager, IXmlSerializer xmlSerializer)
  90. {
  91. CommonApplicationPaths = applicationPaths;
  92. XmlSerializer = xmlSerializer;
  93. Logger = logManager.GetLogger(GetType().Name);
  94. UpdateCachePath();
  95. }
  96. public virtual void AddParts(IEnumerable<IConfigurationFactory> factories)
  97. {
  98. _configurationFactories = factories.ToArray();
  99. _configurationStores = _configurationFactories
  100. .SelectMany(i => i.GetConfigurations())
  101. .ToArray();
  102. }
  103. /// <summary>
  104. /// Saves the configuration.
  105. /// </summary>
  106. public void SaveConfiguration()
  107. {
  108. var path = CommonApplicationPaths.SystemConfigurationFilePath;
  109. Directory.CreateDirectory(Path.GetDirectoryName(path));
  110. lock (_configurationSyncLock)
  111. {
  112. XmlSerializer.SerializeToFile(CommonConfiguration, path);
  113. }
  114. OnConfigurationUpdated();
  115. }
  116. /// <summary>
  117. /// Called when [configuration updated].
  118. /// </summary>
  119. protected virtual void OnConfigurationUpdated()
  120. {
  121. UpdateCachePath();
  122. EventHelper.QueueEventIfNotNull(ConfigurationUpdated, this, EventArgs.Empty, Logger);
  123. }
  124. /// <summary>
  125. /// Replaces the configuration.
  126. /// </summary>
  127. /// <param name="newConfiguration">The new configuration.</param>
  128. /// <exception cref="System.ArgumentNullException">newConfiguration</exception>
  129. public virtual void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration)
  130. {
  131. if (newConfiguration == null)
  132. {
  133. throw new ArgumentNullException("newConfiguration");
  134. }
  135. ValidateCachePath(newConfiguration);
  136. CommonConfiguration = newConfiguration;
  137. SaveConfiguration();
  138. }
  139. /// <summary>
  140. /// Updates the items by name path.
  141. /// </summary>
  142. private void UpdateCachePath()
  143. {
  144. ((BaseApplicationPaths)CommonApplicationPaths).CachePath = string.IsNullOrEmpty(CommonConfiguration.CachePath) ?
  145. null :
  146. CommonConfiguration.CachePath;
  147. }
  148. /// <summary>
  149. /// Replaces the cache path.
  150. /// </summary>
  151. /// <param name="newConfig">The new configuration.</param>
  152. /// <exception cref="System.IO.DirectoryNotFoundException"></exception>
  153. private void ValidateCachePath(BaseApplicationConfiguration newConfig)
  154. {
  155. var newPath = newConfig.CachePath;
  156. if (!string.IsNullOrWhiteSpace(newPath)
  157. && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath))
  158. {
  159. // Validate
  160. if (!Directory.Exists(newPath))
  161. {
  162. throw new DirectoryNotFoundException(string.Format("{0} does not exist.", newPath));
  163. }
  164. }
  165. }
  166. private readonly ConcurrentDictionary<string, object> _configurations = new ConcurrentDictionary<string, object>();
  167. private string GetConfigurationFile(string key)
  168. {
  169. return Path.Combine(CommonApplicationPaths.ConfigurationDirectoryPath, key.ToLower() + ".xml");
  170. }
  171. public object GetConfiguration(string key)
  172. {
  173. return _configurations.GetOrAdd(key, k =>
  174. {
  175. var file = GetConfigurationFile(key);
  176. var configurationType = _configurationStores
  177. .First(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase))
  178. .ConfigurationType;
  179. lock (_configurationSyncLock)
  180. {
  181. return LoadConfiguration(file, configurationType);
  182. }
  183. });
  184. }
  185. private object LoadConfiguration(string path, Type configurationType)
  186. {
  187. try
  188. {
  189. return XmlSerializer.DeserializeFromFile(configurationType, path);
  190. }
  191. catch (FileNotFoundException)
  192. {
  193. return Activator.CreateInstance(configurationType);
  194. }
  195. catch (DirectoryNotFoundException)
  196. {
  197. return Activator.CreateInstance(configurationType);
  198. }
  199. catch (Exception ex)
  200. {
  201. Logger.ErrorException("Error loading configuration file: {0}", ex, path);
  202. return Activator.CreateInstance(configurationType);
  203. }
  204. }
  205. public void SaveConfiguration(string key, object configuration)
  206. {
  207. var configurationStore = GetConfigurationStore(key);
  208. var configurationType = configurationStore.ConfigurationType;
  209. if (configuration.GetType() != configurationType)
  210. {
  211. throw new ArgumentException("Expected configuration type is " + configurationType.Name);
  212. }
  213. var validatingStore = configurationStore as IValidatingConfiguration;
  214. if (validatingStore != null)
  215. {
  216. var currentConfiguration = GetConfiguration(key);
  217. validatingStore.Validate(currentConfiguration, configuration);
  218. }
  219. EventHelper.FireEventIfNotNull(NamedConfigurationUpdating, this, new ConfigurationUpdateEventArgs
  220. {
  221. Key = key,
  222. NewConfiguration = configuration
  223. }, Logger);
  224. _configurations.AddOrUpdate(key, configuration, (k, v) => configuration);
  225. var path = GetConfigurationFile(key);
  226. Directory.CreateDirectory(Path.GetDirectoryName(path));
  227. lock (_configurationSyncLock)
  228. {
  229. XmlSerializer.SerializeToFile(configuration, path);
  230. }
  231. OnNamedConfigurationUpdated(key, configuration);
  232. }
  233. protected virtual void OnNamedConfigurationUpdated(string key, object configuration)
  234. {
  235. EventHelper.FireEventIfNotNull(NamedConfigurationUpdated, this, new ConfigurationUpdateEventArgs
  236. {
  237. Key = key,
  238. NewConfiguration = configuration
  239. }, Logger);
  240. }
  241. public Type GetConfigurationType(string key)
  242. {
  243. return GetConfigurationStore(key)
  244. .ConfigurationType;
  245. }
  246. private ConfigurationStore GetConfigurationStore(string key)
  247. {
  248. return _configurationStores
  249. .First(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase));
  250. }
  251. }
  252. }