ProviderManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. if (!force && !provider.NeedsRefresh(item))
  135. {
  136. continue;
  137. }
  138. currentTasks.Add(FetchAsync(provider, item, force, cancellationToken));
  139. currentPriority = provider.Priority;
  140. }
  141. if (currentTasks.Count > 0)
  142. {
  143. var results = await Task.WhenAll(currentTasks).ConfigureAwait(false);
  144. result |= results.Contains(true);
  145. }
  146. return result;
  147. }
  148. /// <summary>
  149. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  150. /// </summary>
  151. /// <param name="provider">The provider.</param>
  152. /// <param name="item">The item.</param>
  153. /// <param name="force">if set to <c>true</c> [force].</param>
  154. /// <param name="cancellationToken">The cancellation token.</param>
  155. /// <returns>Task{System.Boolean}.</returns>
  156. /// <exception cref="System.ArgumentNullException"></exception>
  157. private async Task<bool> FetchAsync(BaseMetadataProvider provider, BaseItem item, bool force, CancellationToken cancellationToken)
  158. {
  159. if (item == null)
  160. {
  161. throw new ArgumentNullException();
  162. }
  163. cancellationToken.ThrowIfCancellationRequested();
  164. _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name ?? "--Unknown--");
  165. // This provides the ability to cancel just this one provider
  166. var innerCancellationTokenSource = new CancellationTokenSource();
  167. OnProviderRefreshBeginning(provider, item, innerCancellationTokenSource);
  168. try
  169. {
  170. return await provider.FetchAsync(item, force, CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token).ConfigureAwait(false);
  171. }
  172. catch (OperationCanceledException ex)
  173. {
  174. _logger.Debug("{0} canceled for {1}", provider.GetType().Name, item.Name);
  175. // If the outer cancellation token is the one that caused the cancellation, throw it
  176. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  177. {
  178. throw;
  179. }
  180. return false;
  181. }
  182. catch (Exception ex)
  183. {
  184. _logger.ErrorException("{0} failed refreshing {1}", ex, provider.GetType().Name, item.Name);
  185. provider.SetLastRefreshed(item, DateTime.UtcNow, ProviderRefreshStatus.Failure);
  186. return true;
  187. }
  188. finally
  189. {
  190. innerCancellationTokenSource.Dispose();
  191. OnProviderRefreshCompleted(provider, item);
  192. }
  193. }
  194. /// <summary>
  195. /// Notifies the kernal that a provider has begun refreshing
  196. /// </summary>
  197. /// <param name="provider">The provider.</param>
  198. /// <param name="item">The item.</param>
  199. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  200. public void OnProviderRefreshBeginning(BaseMetadataProvider provider, BaseItem item, CancellationTokenSource cancellationTokenSource)
  201. {
  202. var key = item.Id + provider.GetType().Name;
  203. Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource> current;
  204. if (_currentlyRunningProviders.TryGetValue(key, out current))
  205. {
  206. try
  207. {
  208. current.Item3.Cancel();
  209. }
  210. catch (ObjectDisposedException)
  211. {
  212. }
  213. }
  214. var tuple = new Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource>(provider, item, cancellationTokenSource);
  215. _currentlyRunningProviders.AddOrUpdate(key, tuple, (k, v) => tuple);
  216. }
  217. /// <summary>
  218. /// Notifies the kernal that a provider has completed refreshing
  219. /// </summary>
  220. /// <param name="provider">The provider.</param>
  221. /// <param name="item">The item.</param>
  222. public void OnProviderRefreshCompleted(BaseMetadataProvider provider, BaseItem item)
  223. {
  224. var key = item.Id + provider.GetType().Name;
  225. Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource> current;
  226. if (_currentlyRunningProviders.TryRemove(key, out current))
  227. {
  228. current.Item3.Dispose();
  229. }
  230. }
  231. /// <summary>
  232. /// Validates the currently running providers and cancels any that should not be run due to configuration changes
  233. /// </summary>
  234. private void ValidateCurrentlyRunningProviders()
  235. {
  236. var enableInternetProviders = ConfigurationManager.Configuration.EnableInternetProviders;
  237. var internetProviderExcludeTypes = ConfigurationManager.Configuration.InternetProviderExcludeTypes;
  238. foreach (var tuple in _currentlyRunningProviders.Values
  239. .Where(p => p.Item1.RequiresInternet && (!enableInternetProviders || internetProviderExcludeTypes.Contains(p.Item2.GetType().Name, StringComparer.OrdinalIgnoreCase)))
  240. .ToList())
  241. {
  242. tuple.Item3.Cancel();
  243. }
  244. }
  245. /// <summary>
  246. /// Downloads the and save image.
  247. /// </summary>
  248. /// <param name="item">The item.</param>
  249. /// <param name="source">The source.</param>
  250. /// <param name="targetName">Name of the target.</param>
  251. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  252. /// <param name="resourcePool">The resource pool.</param>
  253. /// <param name="cancellationToken">The cancellation token.</param>
  254. /// <returns>Task{System.String}.</returns>
  255. /// <exception cref="System.ArgumentNullException">item</exception>
  256. public async Task<string> DownloadAndSaveImage(BaseItem item, string source, string targetName, bool saveLocally, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  257. {
  258. if (item == null)
  259. {
  260. throw new ArgumentNullException("item");
  261. }
  262. if (string.IsNullOrEmpty(source))
  263. {
  264. throw new ArgumentNullException("source");
  265. }
  266. if (string.IsNullOrEmpty(targetName))
  267. {
  268. throw new ArgumentNullException("targetName");
  269. }
  270. if (resourcePool == null)
  271. {
  272. throw new ArgumentNullException("resourcePool");
  273. }
  274. var img = await _httpClient.Get(source, resourcePool, cancellationToken).ConfigureAwait(false);
  275. //download and save locally
  276. return await SaveImage(item, img, targetName, saveLocally, cancellationToken).ConfigureAwait(false);
  277. }
  278. public async Task<string> SaveImage(BaseItem item, Stream source, string targetName, bool saveLocally, CancellationToken cancellationToken)
  279. {
  280. //download and save locally
  281. var localPath = GetSavePath(item, targetName, saveLocally);
  282. if (saveLocally) // queue to media directories
  283. {
  284. await SaveToLibraryFilesystem(item, localPath, source, cancellationToken).ConfigureAwait(false);
  285. }
  286. else
  287. {
  288. // we can write directly here because it won't affect the watchers
  289. try
  290. {
  291. using (var fs = new FileStream(localPath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  292. {
  293. await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  294. }
  295. }
  296. catch (OperationCanceledException)
  297. {
  298. throw;
  299. }
  300. catch (Exception e)
  301. {
  302. _logger.ErrorException("Error downloading and saving image " + localPath, e);
  303. throw;
  304. }
  305. finally
  306. {
  307. source.Dispose();
  308. }
  309. }
  310. return localPath;
  311. }
  312. /// <summary>
  313. /// Gets the save path.
  314. /// </summary>
  315. /// <param name="item">The item.</param>
  316. /// <param name="targetFileName">Name of the target file.</param>
  317. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  318. /// <returns>System.String.</returns>
  319. public string GetSavePath(BaseItem item, string targetFileName, bool saveLocally)
  320. {
  321. var path = (saveLocally && item.MetaLocation != null) ?
  322. Path.Combine(item.MetaLocation, targetFileName) :
  323. _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Id.ToString(), targetFileName);
  324. var parentPath = Path.GetDirectoryName(path);
  325. if (!Directory.Exists(parentPath))
  326. {
  327. Directory.CreateDirectory(parentPath);
  328. }
  329. return path;
  330. }
  331. /// <summary>
  332. /// Saves to library filesystem.
  333. /// </summary>
  334. /// <param name="item">The item.</param>
  335. /// <param name="path">The path.</param>
  336. /// <param name="dataToSave">The data to save.</param>
  337. /// <param name="cancellationToken">The cancellation token.</param>
  338. /// <returns>Task.</returns>
  339. /// <exception cref="System.ArgumentNullException"></exception>
  340. public async Task SaveToLibraryFilesystem(BaseItem item, string path, Stream dataToSave, CancellationToken cancellationToken)
  341. {
  342. if (item == null)
  343. {
  344. throw new ArgumentNullException();
  345. }
  346. if (string.IsNullOrEmpty(path))
  347. {
  348. throw new ArgumentNullException();
  349. }
  350. if (dataToSave == null)
  351. {
  352. throw new ArgumentNullException();
  353. }
  354. if (cancellationToken == null)
  355. {
  356. throw new ArgumentNullException();
  357. }
  358. if (cancellationToken.IsCancellationRequested)
  359. {
  360. dataToSave.Dispose();
  361. cancellationToken.ThrowIfCancellationRequested();
  362. }
  363. //Tell the watchers to ignore
  364. _directoryWatchers.TemporarilyIgnore(path);
  365. if (dataToSave.CanSeek)
  366. {
  367. dataToSave.Position = 0;
  368. }
  369. try
  370. {
  371. using (dataToSave)
  372. {
  373. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  374. {
  375. await dataToSave.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  376. }
  377. }
  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. finally
  382. {
  383. //Remove the ignore
  384. _directoryWatchers.RemoveTempIgnore(path);
  385. }
  386. }
  387. }
  388. }