ProviderManager.cs 18 KB

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