ProviderManager.cs 19 KB

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