ProviderManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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.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;
  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(FetchAsync(provider, 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. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  189. /// </summary>
  190. /// <param name="provider">The provider.</param>
  191. /// <param name="item">The item.</param>
  192. /// <param name="force">if set to <c>true</c> [force].</param>
  193. /// <param name="cancellationToken">The cancellation token.</param>
  194. /// <returns>Task{System.Boolean}.</returns>
  195. /// <exception cref="System.ArgumentNullException"></exception>
  196. private async Task<bool> FetchAsync(BaseMetadataProvider provider, BaseItem item, bool force, CancellationToken cancellationToken)
  197. {
  198. if (item == null)
  199. {
  200. throw new ArgumentNullException();
  201. }
  202. cancellationToken.ThrowIfCancellationRequested();
  203. _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name ?? "--Unknown--");
  204. // This provides the ability to cancel just this one provider
  205. var innerCancellationTokenSource = new CancellationTokenSource();
  206. OnProviderRefreshBeginning(provider, item, innerCancellationTokenSource);
  207. try
  208. {
  209. return await provider.FetchAsync(item, force, CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token).ConfigureAwait(false);
  210. }
  211. catch (OperationCanceledException ex)
  212. {
  213. _logger.Debug("{0} cancelled for {1}", provider.GetType().Name, item.Name);
  214. // If the outer cancellation token is the one that caused the cancellation, throw it
  215. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  216. {
  217. throw;
  218. }
  219. return false;
  220. }
  221. catch (Exception ex)
  222. {
  223. _logger.ErrorException("{0} failed refreshing {1}", ex, provider.GetType().Name, item.Name);
  224. provider.SetLastRefreshed(item, DateTime.UtcNow, ProviderRefreshStatus.Failure);
  225. return true;
  226. }
  227. finally
  228. {
  229. innerCancellationTokenSource.Dispose();
  230. OnProviderRefreshCompleted(provider, item);
  231. }
  232. }
  233. /// <summary>
  234. /// Notifies the kernal that a provider has begun refreshing
  235. /// </summary>
  236. /// <param name="provider">The provider.</param>
  237. /// <param name="item">The item.</param>
  238. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  239. public void OnProviderRefreshBeginning(BaseMetadataProvider provider, BaseItem item, CancellationTokenSource cancellationTokenSource)
  240. {
  241. var key = item.Id + provider.GetType().Name;
  242. Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource> current;
  243. if (_currentlyRunningProviders.TryGetValue(key, out current))
  244. {
  245. try
  246. {
  247. current.Item3.Cancel();
  248. }
  249. catch (ObjectDisposedException)
  250. {
  251. }
  252. }
  253. var tuple = new Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource>(provider, item, cancellationTokenSource);
  254. _currentlyRunningProviders.AddOrUpdate(key, tuple, (k, v) => tuple);
  255. }
  256. /// <summary>
  257. /// Notifies the kernal that a provider has completed refreshing
  258. /// </summary>
  259. /// <param name="provider">The provider.</param>
  260. /// <param name="item">The item.</param>
  261. public void OnProviderRefreshCompleted(BaseMetadataProvider provider, BaseItem item)
  262. {
  263. var key = item.Id + provider.GetType().Name;
  264. Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource> current;
  265. if (_currentlyRunningProviders.TryRemove(key, out current))
  266. {
  267. current.Item3.Dispose();
  268. }
  269. }
  270. /// <summary>
  271. /// Validates the currently running providers and cancels any that should not be run due to configuration changes
  272. /// </summary>
  273. private void ValidateCurrentlyRunningProviders()
  274. {
  275. var enableInternetProviders = ConfigurationManager.Configuration.EnableInternetProviders;
  276. var internetProviderExcludeTypes = ConfigurationManager.Configuration.InternetProviderExcludeTypes;
  277. foreach (var tuple in _currentlyRunningProviders.Values
  278. .Where(p => p.Item1.RequiresInternet && (!enableInternetProviders || internetProviderExcludeTypes.Contains(p.Item2.GetType().Name, StringComparer.OrdinalIgnoreCase)))
  279. .ToList())
  280. {
  281. tuple.Item3.Cancel();
  282. }
  283. }
  284. /// <summary>
  285. /// Downloads the and save image.
  286. /// </summary>
  287. /// <param name="item">The item.</param>
  288. /// <param name="source">The source.</param>
  289. /// <param name="targetName">Name of the target.</param>
  290. /// <param name="resourcePool">The resource pool.</param>
  291. /// <param name="cancellationToken">The cancellation token.</param>
  292. /// <returns>Task{System.String}.</returns>
  293. /// <exception cref="System.ArgumentNullException">item</exception>
  294. public async Task<string> DownloadAndSaveImage(BaseItem item, string source, string targetName, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  295. {
  296. if (item == null)
  297. {
  298. throw new ArgumentNullException("item");
  299. }
  300. if (string.IsNullOrEmpty(source))
  301. {
  302. throw new ArgumentNullException("source");
  303. }
  304. if (string.IsNullOrEmpty(targetName))
  305. {
  306. throw new ArgumentNullException("targetName");
  307. }
  308. if (resourcePool == null)
  309. {
  310. throw new ArgumentNullException("resourcePool");
  311. }
  312. //download and save locally
  313. var localPath = (ConfigurationManager.Configuration.SaveLocalMeta && item.MetaLocation != null) ?
  314. Path.Combine(item.MetaLocation, targetName) :
  315. _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Path.ToLower(), targetName);
  316. var img = await _httpClient.GetMemoryStream(source, resourcePool, cancellationToken).ConfigureAwait(false);
  317. if (ConfigurationManager.Configuration.SaveLocalMeta) // queue to media directories
  318. {
  319. await SaveToLibraryFilesystem(item, localPath, img, cancellationToken).ConfigureAwait(false);
  320. }
  321. else
  322. {
  323. // we can write directly here because it won't affect the watchers
  324. try
  325. {
  326. using (var fs = new FileStream(localPath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  327. {
  328. await img.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  329. }
  330. }
  331. catch (OperationCanceledException)
  332. {
  333. throw;
  334. }
  335. catch (Exception e)
  336. {
  337. _logger.ErrorException("Error downloading and saving image " + localPath, e);
  338. throw;
  339. }
  340. finally
  341. {
  342. img.Dispose();
  343. }
  344. }
  345. return localPath;
  346. }
  347. /// <summary>
  348. /// Saves to library filesystem.
  349. /// </summary>
  350. /// <param name="item">The item.</param>
  351. /// <param name="path">The path.</param>
  352. /// <param name="dataToSave">The data to save.</param>
  353. /// <param name="cancellationToken">The cancellation token.</param>
  354. /// <returns>Task.</returns>
  355. /// <exception cref="System.ArgumentNullException"></exception>
  356. public async Task SaveToLibraryFilesystem(BaseItem item, string path, Stream dataToSave, CancellationToken cancellationToken)
  357. {
  358. if (item == null)
  359. {
  360. throw new ArgumentNullException();
  361. }
  362. if (string.IsNullOrEmpty(path))
  363. {
  364. throw new ArgumentNullException();
  365. }
  366. if (dataToSave == null)
  367. {
  368. throw new ArgumentNullException();
  369. }
  370. if (cancellationToken == null)
  371. {
  372. throw new ArgumentNullException();
  373. }
  374. cancellationToken.ThrowIfCancellationRequested();
  375. //Tell the watchers to ignore
  376. _directoryWatchers.TemporarilyIgnore(path);
  377. //Make the mod
  378. dataToSave.Position = 0;
  379. try
  380. {
  381. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  382. {
  383. await dataToSave.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  384. dataToSave.Dispose();
  385. // If this is ever used for something other than metadata we can add a file type param
  386. item.ResolveArgs.AddMetadataFile(path);
  387. }
  388. }
  389. finally
  390. {
  391. //Remove the ignore
  392. _directoryWatchers.RemoveTempIgnore(path);
  393. }
  394. }
  395. /// <summary>
  396. /// Releases unmanaged and - optionally - managed resources.
  397. /// </summary>
  398. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  399. protected virtual void Dispose(bool dispose)
  400. {
  401. if (dispose)
  402. {
  403. _remoteImageCache.Dispose();
  404. }
  405. }
  406. /// <summary>
  407. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  408. /// </summary>
  409. public void Dispose()
  410. {
  411. Dispose(true);
  412. }
  413. }
  414. }