ProviderManager.cs 18 KB

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