ProviderManager.cs 18 KB

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