ProviderManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Controller.Providers
  16. {
  17. /// <summary>
  18. /// Class ProviderManager
  19. /// </summary>
  20. public class ProviderManager : IDisposable
  21. {
  22. /// <summary>
  23. /// The remote image cache
  24. /// </summary>
  25. private readonly FileSystemRepository _remoteImageCache;
  26. /// <summary>
  27. /// The currently running metadata providers
  28. /// </summary>
  29. private readonly ConcurrentDictionary<string, Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource>> _currentlyRunningProviders =
  30. new ConcurrentDictionary<string, Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource>>();
  31. /// <summary>
  32. /// The _logger
  33. /// </summary>
  34. private readonly ILogger _logger;
  35. /// <summary>
  36. /// The _HTTP client
  37. /// </summary>
  38. private readonly IHttpClient _httpClient;
  39. private IServerConfigurationManager ConfigurationManager { get; set; }
  40. private Kernel Kernel { get; set; }
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="ProviderManager" /> class.
  43. /// </summary>
  44. /// <param name="kernel">The kernel.</param>
  45. /// <param name="httpClient">The HTTP client.</param>
  46. /// <param name="logger">The logger.</param>
  47. public ProviderManager(Kernel kernel, IHttpClient httpClient, ILogger logger, IServerConfigurationManager configurationManager)
  48. {
  49. _logger = logger;
  50. Kernel = kernel;
  51. _httpClient = httpClient;
  52. ConfigurationManager = configurationManager;
  53. _remoteImageCache = new FileSystemRepository(ImagesDataPath);
  54. configurationManager.ConfigurationUpdated += configurationManager_ConfigurationUpdated;
  55. }
  56. /// <summary>
  57. /// Handles the ConfigurationUpdated event of the configurationManager control.
  58. /// </summary>
  59. /// <param name="sender">The source of the event.</param>
  60. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  61. void configurationManager_ConfigurationUpdated(object sender, EventArgs e)
  62. {
  63. // Validate currently executing providers, in the background
  64. Task.Run(() =>
  65. {
  66. ValidateCurrentlyRunningProviders();
  67. });
  68. }
  69. /// <summary>
  70. /// The _images data path
  71. /// </summary>
  72. private string _imagesDataPath;
  73. /// <summary>
  74. /// Gets the images data path.
  75. /// </summary>
  76. /// <value>The images data path.</value>
  77. public string ImagesDataPath
  78. {
  79. get
  80. {
  81. if (_imagesDataPath == null)
  82. {
  83. _imagesDataPath = Path.Combine(ConfigurationManager.ApplicationPaths.DataPath, "remote-images");
  84. if (!Directory.Exists(_imagesDataPath))
  85. {
  86. Directory.CreateDirectory(_imagesDataPath);
  87. }
  88. }
  89. return _imagesDataPath;
  90. }
  91. }
  92. /// <summary>
  93. /// Gets or sets the supported providers key.
  94. /// </summary>
  95. /// <value>The supported providers key.</value>
  96. private Guid SupportedProvidersKey { get; set; }
  97. /// <summary>
  98. /// Runs all metadata providers for an entity, and returns true or false indicating if at least one was refreshed and requires persistence
  99. /// </summary>
  100. /// <param name="item">The item.</param>
  101. /// <param name="cancellationToken">The cancellation token.</param>
  102. /// <param name="force">if set to <c>true</c> [force].</param>
  103. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  104. /// <returns>Task{System.Boolean}.</returns>
  105. internal async Task<bool> ExecuteMetadataProviders(BaseItem item, CancellationToken cancellationToken, bool force = false, bool allowSlowProviders = true)
  106. {
  107. // Allow providers of the same priority to execute in parallel
  108. MetadataProviderPriority? currentPriority = null;
  109. var currentTasks = new List<Task<bool>>();
  110. var result = false;
  111. cancellationToken.ThrowIfCancellationRequested();
  112. // Determine if supported providers have changed
  113. var supportedProviders = Kernel.MetadataProviders.Where(p => p.Supports(item)).ToList();
  114. BaseProviderInfo supportedProvidersInfo;
  115. if (SupportedProvidersKey == Guid.Empty)
  116. {
  117. SupportedProvidersKey = "SupportedProviders".GetMD5();
  118. }
  119. var supportedProvidersHash = string.Join("+", supportedProviders.Select(i => i.GetType().Name)).GetMD5();
  120. bool providersChanged;
  121. item.ProviderData.TryGetValue(SupportedProvidersKey, out supportedProvidersInfo);
  122. if (supportedProvidersInfo == null)
  123. {
  124. // First time
  125. supportedProvidersInfo = new BaseProviderInfo { ProviderId = SupportedProvidersKey, FileSystemStamp = supportedProvidersHash };
  126. providersChanged = force = true;
  127. }
  128. else
  129. {
  130. // Force refresh if the supported providers have changed
  131. providersChanged = force = force || supportedProvidersInfo.FileSystemStamp != supportedProvidersHash;
  132. }
  133. // If providers have changed, clear provider info and update the supported providers hash
  134. if (providersChanged)
  135. {
  136. _logger.Debug("Providers changed for {0}. Clearing and forcing refresh.", item.Name);
  137. item.ProviderData.Clear();
  138. supportedProvidersInfo.FileSystemStamp = supportedProvidersHash;
  139. }
  140. if (force) item.ClearMetaValues();
  141. // Run the normal providers sequentially in order of priority
  142. foreach (var provider in supportedProviders)
  143. {
  144. cancellationToken.ThrowIfCancellationRequested();
  145. // Skip if internet providers are currently disabled
  146. if (provider.RequiresInternet && !ConfigurationManager.Configuration.EnableInternetProviders)
  147. {
  148. continue;
  149. }
  150. // Skip if is slow and we aren't allowing slow ones
  151. if (provider.IsSlow && !allowSlowProviders)
  152. {
  153. continue;
  154. }
  155. // Skip if internet provider and this type is not allowed
  156. if (provider.RequiresInternet && ConfigurationManager.Configuration.EnableInternetProviders && ConfigurationManager.Configuration.InternetProviderExcludeTypes.Contains(item.GetType().Name, StringComparer.OrdinalIgnoreCase))
  157. {
  158. continue;
  159. }
  160. // When a new priority is reached, await the ones that are currently running and clear the list
  161. if (currentPriority.HasValue && currentPriority.Value != provider.Priority && currentTasks.Count > 0)
  162. {
  163. var results = await Task.WhenAll(currentTasks).ConfigureAwait(false);
  164. result |= results.Contains(true);
  165. currentTasks.Clear();
  166. }
  167. // Put this check below the await because the needs refresh of the next tier of providers may depend on the previous ones running
  168. // This is the case for the fan art provider which depends on the movie and tv providers having run before them
  169. if (!force && !provider.NeedsRefresh(item))
  170. {
  171. continue;
  172. }
  173. currentTasks.Add(provider.FetchAsync(item, force, cancellationToken));
  174. currentPriority = provider.Priority;
  175. }
  176. if (currentTasks.Count > 0)
  177. {
  178. var results = await Task.WhenAll(currentTasks).ConfigureAwait(false);
  179. result |= results.Contains(true);
  180. }
  181. if (providersChanged)
  182. {
  183. item.ProviderData[SupportedProvidersKey] = supportedProvidersInfo;
  184. }
  185. return result || providersChanged;
  186. }
  187. /// <summary>
  188. /// Notifies the kernal that a provider has begun refreshing
  189. /// </summary>
  190. /// <param name="provider">The provider.</param>
  191. /// <param name="item">The item.</param>
  192. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  193. internal void OnProviderRefreshBeginning(BaseMetadataProvider provider, BaseItem item, CancellationTokenSource cancellationTokenSource)
  194. {
  195. var key = item.Id + provider.GetType().Name;
  196. Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource> current;
  197. if (_currentlyRunningProviders.TryGetValue(key, out current))
  198. {
  199. try
  200. {
  201. current.Item3.Cancel();
  202. }
  203. catch (ObjectDisposedException)
  204. {
  205. }
  206. }
  207. var tuple = new Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource>(provider, item, cancellationTokenSource);
  208. _currentlyRunningProviders.AddOrUpdate(key, tuple, (k, v) => tuple);
  209. }
  210. /// <summary>
  211. /// Notifies the kernal that a provider has completed refreshing
  212. /// </summary>
  213. /// <param name="provider">The provider.</param>
  214. /// <param name="item">The item.</param>
  215. internal void OnProviderRefreshCompleted(BaseMetadataProvider provider, BaseItem item)
  216. {
  217. var key = item.Id + provider.GetType().Name;
  218. Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource> current;
  219. if (_currentlyRunningProviders.TryRemove(key, out current))
  220. {
  221. current.Item3.Dispose();
  222. }
  223. }
  224. /// <summary>
  225. /// Validates the currently running providers and cancels any that should not be run due to configuration changes
  226. /// </summary>
  227. internal void ValidateCurrentlyRunningProviders()
  228. {
  229. _logger.Info("Validing currently running providers");
  230. var enableInternetProviders = ConfigurationManager.Configuration.EnableInternetProviders;
  231. var internetProviderExcludeTypes = ConfigurationManager.Configuration.InternetProviderExcludeTypes;
  232. foreach (var tuple in _currentlyRunningProviders.Values
  233. .Where(p => p.Item1.RequiresInternet && (!enableInternetProviders || internetProviderExcludeTypes.Contains(p.Item2.GetType().Name, StringComparer.OrdinalIgnoreCase)))
  234. .ToList())
  235. {
  236. tuple.Item3.Cancel();
  237. }
  238. }
  239. /// <summary>
  240. /// Downloads the and save image.
  241. /// </summary>
  242. /// <param name="item">The item.</param>
  243. /// <param name="source">The source.</param>
  244. /// <param name="targetName">Name of the target.</param>
  245. /// <param name="resourcePool">The resource pool.</param>
  246. /// <param name="cancellationToken">The cancellation token.</param>
  247. /// <returns>Task{System.String}.</returns>
  248. /// <exception cref="System.ArgumentNullException">item</exception>
  249. public async Task<string> DownloadAndSaveImage(BaseItem item, string source, string targetName, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  250. {
  251. if (item == null)
  252. {
  253. throw new ArgumentNullException("item");
  254. }
  255. if (string.IsNullOrEmpty(source))
  256. {
  257. throw new ArgumentNullException("source");
  258. }
  259. if (string.IsNullOrEmpty(targetName))
  260. {
  261. throw new ArgumentNullException("targetName");
  262. }
  263. if (resourcePool == null)
  264. {
  265. throw new ArgumentNullException("resourcePool");
  266. }
  267. //download and save locally
  268. var localPath = ConfigurationManager.Configuration.SaveLocalMeta ?
  269. Path.Combine(item.MetaLocation, targetName) :
  270. _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Path.ToLower(), targetName);
  271. var img = await _httpClient.GetMemoryStream(source, resourcePool, cancellationToken).ConfigureAwait(false);
  272. if (ConfigurationManager.Configuration.SaveLocalMeta) // queue to media directories
  273. {
  274. await Kernel.FileSystemManager.SaveToLibraryFilesystem(item, localPath, img, cancellationToken).ConfigureAwait(false);
  275. }
  276. else
  277. {
  278. // we can write directly here because it won't affect the watchers
  279. try
  280. {
  281. using (var fs = new FileStream(localPath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  282. {
  283. await img.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  284. }
  285. }
  286. catch (OperationCanceledException)
  287. {
  288. throw;
  289. }
  290. catch (Exception e)
  291. {
  292. _logger.ErrorException("Error downloading and saving image " + localPath, e);
  293. throw;
  294. }
  295. finally
  296. {
  297. img.Dispose();
  298. }
  299. }
  300. return localPath;
  301. }
  302. /// <summary>
  303. /// Releases unmanaged and - optionally - managed resources.
  304. /// </summary>
  305. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  306. protected virtual void Dispose(bool dispose)
  307. {
  308. if (dispose)
  309. {
  310. _remoteImageCache.Dispose();
  311. }
  312. }
  313. public void Dispose()
  314. {
  315. Dispose(true);
  316. }
  317. }
  318. }