ProviderManager.cs 15 KB

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