ProviderManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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.Library;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Controller.Providers;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Providers;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Server.Implementations.Providers
  19. {
  20. /// <summary>
  21. /// Class ProviderManager
  22. /// </summary>
  23. public class ProviderManager : IProviderManager
  24. {
  25. /// <summary>
  26. /// The _logger
  27. /// </summary>
  28. private readonly ILogger _logger;
  29. /// <summary>
  30. /// The _HTTP client
  31. /// </summary>
  32. private readonly IHttpClient _httpClient;
  33. /// <summary>
  34. /// The _directory watchers
  35. /// </summary>
  36. private readonly IDirectoryWatchers _directoryWatchers;
  37. /// <summary>
  38. /// Gets or sets the configuration manager.
  39. /// </summary>
  40. /// <value>The configuration manager.</value>
  41. private IServerConfigurationManager ConfigurationManager { get; set; }
  42. /// <summary>
  43. /// Gets the list of currently registered metadata prvoiders
  44. /// </summary>
  45. /// <value>The metadata providers enumerable.</value>
  46. private BaseMetadataProvider[] MetadataProviders { get; set; }
  47. private IImageProvider[] ImageProviders { get; set; }
  48. private readonly IFileSystem _fileSystem;
  49. private readonly IItemRepository _itemRepo;
  50. /// <summary>
  51. /// Initializes a new instance of the <see cref="ProviderManager" /> class.
  52. /// </summary>
  53. /// <param name="httpClient">The HTTP client.</param>
  54. /// <param name="configurationManager">The configuration manager.</param>
  55. /// <param name="directoryWatchers">The directory watchers.</param>
  56. /// <param name="logManager">The log manager.</param>
  57. public ProviderManager(IHttpClient httpClient, IServerConfigurationManager configurationManager, IDirectoryWatchers directoryWatchers, ILogManager logManager, IFileSystem fileSystem, IItemRepository itemRepo)
  58. {
  59. _logger = logManager.GetLogger("ProviderManager");
  60. _httpClient = httpClient;
  61. ConfigurationManager = configurationManager;
  62. _directoryWatchers = directoryWatchers;
  63. _fileSystem = fileSystem;
  64. _itemRepo = itemRepo;
  65. }
  66. /// <summary>
  67. /// Adds the metadata providers.
  68. /// </summary>
  69. /// <param name="providers">The providers.</param>
  70. /// <param name="imageProviders">The image providers.</param>
  71. public void AddParts(IEnumerable<BaseMetadataProvider> providers, IEnumerable<IImageProvider> imageProviders)
  72. {
  73. MetadataProviders = providers.OrderBy(e => e.Priority).ToArray();
  74. ImageProviders = imageProviders.OrderByDescending(i => i.Priority).ToArray();
  75. }
  76. /// <summary>
  77. /// Runs all metadata providers for an entity, and returns true or false indicating if at least one was refreshed and requires persistence
  78. /// </summary>
  79. /// <param name="item">The item.</param>
  80. /// <param name="cancellationToken">The cancellation token.</param>
  81. /// <param name="force">if set to <c>true</c> [force].</param>
  82. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  83. /// <returns>Task{System.Boolean}.</returns>
  84. public async Task<ItemUpdateType?> ExecuteMetadataProviders(BaseItem item, CancellationToken cancellationToken, bool force = false, bool allowSlowProviders = true)
  85. {
  86. if (item == null)
  87. {
  88. throw new ArgumentNullException("item");
  89. }
  90. ItemUpdateType? result = null;
  91. cancellationToken.ThrowIfCancellationRequested();
  92. var enableInternetProviders = ConfigurationManager.Configuration.EnableInternetProviders;
  93. var excludeTypes = ConfigurationManager.Configuration.InternetProviderExcludeTypes;
  94. var providerHistories = item.DateLastSaved == DateTime.MinValue ?
  95. new List<BaseProviderInfo>() :
  96. _itemRepo.GetProviderHistory(item.Id).ToList();
  97. // Run the normal providers sequentially in order of priority
  98. foreach (var provider in MetadataProviders)
  99. {
  100. cancellationToken.ThrowIfCancellationRequested();
  101. if (!ProviderSupportsItem(provider, item))
  102. {
  103. continue;
  104. }
  105. // Skip if internet providers are currently disabled
  106. if (provider.RequiresInternet && !enableInternetProviders)
  107. {
  108. continue;
  109. }
  110. // Skip if is slow and we aren't allowing slow ones
  111. if (provider.IsSlow && !allowSlowProviders)
  112. {
  113. continue;
  114. }
  115. // Skip if internet provider and this type is not allowed
  116. if (provider.RequiresInternet &&
  117. enableInternetProviders &&
  118. excludeTypes.Length > 0 &&
  119. excludeTypes.Contains(item.GetType().Name, StringComparer.OrdinalIgnoreCase))
  120. {
  121. continue;
  122. }
  123. // Put this check below the await because the needs refresh of the next tier of providers may depend on the previous ones running
  124. // This is the case for the fan art provider which depends on the movie and tv providers having run before them
  125. if (provider.RequiresInternet && item.DontFetchMeta && provider.EnforceDontFetchMetadata)
  126. {
  127. continue;
  128. }
  129. var providerInfo = providerHistories.FirstOrDefault(i => i.ProviderId == provider.Id);
  130. if (providerInfo == null)
  131. {
  132. providerInfo = new BaseProviderInfo
  133. {
  134. ProviderId = provider.Id
  135. };
  136. providerHistories.Add(providerInfo);
  137. }
  138. try
  139. {
  140. if (!force && !provider.NeedsRefresh(item, providerInfo))
  141. {
  142. continue;
  143. }
  144. }
  145. catch (Exception ex)
  146. {
  147. _logger.Error("Error determining NeedsRefresh for {0}", ex, item.Path);
  148. }
  149. var updateType = await FetchAsync(provider, item, providerInfo, force, cancellationToken).ConfigureAwait(false);
  150. if (updateType.HasValue)
  151. {
  152. if (result.HasValue)
  153. {
  154. result = result.Value | updateType.Value;
  155. }
  156. else
  157. {
  158. result = updateType;
  159. }
  160. }
  161. }
  162. if (result.HasValue || force)
  163. {
  164. await _itemRepo.SaveProviderHistory(item.Id, providerHistories, cancellationToken);
  165. }
  166. return result;
  167. }
  168. /// <summary>
  169. /// Providers the supports item.
  170. /// </summary>
  171. /// <param name="provider">The provider.</param>
  172. /// <param name="item">The item.</param>
  173. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  174. private bool ProviderSupportsItem(BaseMetadataProvider provider, BaseItem item)
  175. {
  176. try
  177. {
  178. return provider.Supports(item);
  179. }
  180. catch (Exception ex)
  181. {
  182. _logger.ErrorException("{0} failed in Supports for type {1}", ex, provider.GetType().Name, item.GetType().Name);
  183. return false;
  184. }
  185. }
  186. /// <summary>
  187. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  188. /// </summary>
  189. /// <param name="provider">The provider.</param>
  190. /// <param name="item">The item.</param>
  191. /// <param name="providerInfo">The provider information.</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">item</exception>
  196. private async Task<ItemUpdateType?> FetchAsync(BaseMetadataProvider provider, BaseItem item, BaseProviderInfo providerInfo, bool force, CancellationToken cancellationToken)
  197. {
  198. if (item == null)
  199. {
  200. throw new ArgumentNullException("item");
  201. }
  202. cancellationToken.ThrowIfCancellationRequested();
  203. // Don't clog up the log with these providers
  204. if (!(provider is IDynamicInfoProvider))
  205. {
  206. _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name ?? "--Unknown--");
  207. }
  208. try
  209. {
  210. var changed = await provider.FetchAsync(item, force, providerInfo, cancellationToken).ConfigureAwait(false);
  211. if (changed)
  212. {
  213. return provider.ItemUpdateType;
  214. }
  215. return null;
  216. }
  217. catch (OperationCanceledException ex)
  218. {
  219. _logger.Debug("{0} canceled for {1}", provider.GetType().Name, item.Name);
  220. // If the outer cancellation token is the one that caused the cancellation, throw it
  221. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  222. {
  223. throw;
  224. }
  225. return null;
  226. }
  227. catch (Exception ex)
  228. {
  229. _logger.ErrorException("{0} failed refreshing {1} {2}", ex, provider.GetType().Name, item.Name, item.Path ?? string.Empty);
  230. provider.SetLastRefreshed(item, DateTime.UtcNow, providerInfo, ProviderRefreshStatus.Failure);
  231. return ItemUpdateType.Unspecified;
  232. }
  233. }
  234. /// <summary>
  235. /// Saves to library filesystem.
  236. /// </summary>
  237. /// <param name="item">The item.</param>
  238. /// <param name="path">The path.</param>
  239. /// <param name="dataToSave">The data to save.</param>
  240. /// <param name="cancellationToken">The cancellation token.</param>
  241. /// <returns>Task.</returns>
  242. /// <exception cref="System.ArgumentNullException"></exception>
  243. public async Task SaveToLibraryFilesystem(BaseItem item, string path, Stream dataToSave, CancellationToken cancellationToken)
  244. {
  245. if (item == null)
  246. {
  247. throw new ArgumentNullException();
  248. }
  249. if (string.IsNullOrEmpty(path))
  250. {
  251. throw new ArgumentNullException();
  252. }
  253. if (dataToSave == null)
  254. {
  255. throw new ArgumentNullException();
  256. }
  257. if (cancellationToken.IsCancellationRequested)
  258. {
  259. dataToSave.Dispose();
  260. cancellationToken.ThrowIfCancellationRequested();
  261. }
  262. //Tell the watchers to ignore
  263. _directoryWatchers.TemporarilyIgnore(path);
  264. if (dataToSave.CanSeek)
  265. {
  266. dataToSave.Position = 0;
  267. }
  268. try
  269. {
  270. using (dataToSave)
  271. {
  272. using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  273. {
  274. await dataToSave.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  275. }
  276. }
  277. // If this is ever used for something other than metadata we can add a file type param
  278. item.ResolveArgs.AddMetadataFile(path);
  279. }
  280. finally
  281. {
  282. //Remove the ignore
  283. _directoryWatchers.RemoveTempIgnore(path);
  284. }
  285. }
  286. /// <summary>
  287. /// Saves the image.
  288. /// </summary>
  289. /// <param name="item">The item.</param>
  290. /// <param name="url">The URL.</param>
  291. /// <param name="resourcePool">The resource pool.</param>
  292. /// <param name="type">The type.</param>
  293. /// <param name="imageIndex">Index of the image.</param>
  294. /// <param name="cancellationToken">The cancellation token.</param>
  295. /// <returns>Task.</returns>
  296. public async Task SaveImage(BaseItem item, string url, SemaphoreSlim resourcePool, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  297. {
  298. var response = await _httpClient.GetResponse(new HttpRequestOptions
  299. {
  300. CancellationToken = cancellationToken,
  301. ResourcePool = resourcePool,
  302. Url = url
  303. }).ConfigureAwait(false);
  304. await SaveImage(item, response.Content, response.ContentType, type, imageIndex, url, cancellationToken)
  305. .ConfigureAwait(false);
  306. }
  307. /// <summary>
  308. /// Saves the image.
  309. /// </summary>
  310. /// <param name="item">The item.</param>
  311. /// <param name="source">The source.</param>
  312. /// <param name="mimeType">Type of the MIME.</param>
  313. /// <param name="type">The type.</param>
  314. /// <param name="imageIndex">Index of the image.</param>
  315. /// <param name="sourceUrl">The source URL.</param>
  316. /// <param name="cancellationToken">The cancellation token.</param>
  317. /// <returns>Task.</returns>
  318. public Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, string sourceUrl, CancellationToken cancellationToken)
  319. {
  320. return new ImageSaver(ConfigurationManager, _directoryWatchers, _fileSystem, _logger).SaveImage(item, source, mimeType, type, imageIndex, sourceUrl, cancellationToken);
  321. }
  322. /// <summary>
  323. /// Gets the available remote images.
  324. /// </summary>
  325. /// <param name="item">The item.</param>
  326. /// <param name="cancellationToken">The cancellation token.</param>
  327. /// <param name="providerName">Name of the provider.</param>
  328. /// <param name="type">The type.</param>
  329. /// <returns>Task{IEnumerable{RemoteImageInfo}}.</returns>
  330. public async Task<IEnumerable<RemoteImageInfo>> GetAvailableRemoteImages(BaseItem item, CancellationToken cancellationToken, string providerName = null, ImageType? type = null)
  331. {
  332. var providers = GetImageProviders(item);
  333. if (!string.IsNullOrEmpty(providerName))
  334. {
  335. providers = providers.Where(i => string.Equals(i.Name, providerName, StringComparison.OrdinalIgnoreCase));
  336. }
  337. var preferredLanguage = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  338. var tasks = providers.Select(i => Task.Run(async () =>
  339. {
  340. try
  341. {
  342. if (type.HasValue)
  343. {
  344. var result = await i.GetImages(item, type.Value, cancellationToken).ConfigureAwait(false);
  345. return FilterImages(result, preferredLanguage);
  346. }
  347. else
  348. {
  349. var result = await i.GetAllImages(item, cancellationToken).ConfigureAwait(false);
  350. return FilterImages(result, preferredLanguage);
  351. }
  352. }
  353. catch (Exception ex)
  354. {
  355. _logger.ErrorException("{0} failed in GetImages for type {1}", ex, i.GetType().Name, item.GetType().Name);
  356. return new List<RemoteImageInfo>();
  357. }
  358. }, cancellationToken));
  359. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  360. return results.SelectMany(i => i);
  361. }
  362. private IEnumerable<RemoteImageInfo> FilterImages(IEnumerable<RemoteImageInfo> images, string preferredLanguage)
  363. {
  364. if (string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase))
  365. {
  366. images = images.Where(i => string.IsNullOrEmpty(i.Language) ||
  367. string.Equals(i.Language, "en", StringComparison.OrdinalIgnoreCase));
  368. }
  369. return images;
  370. }
  371. /// <summary>
  372. /// Gets the supported image providers.
  373. /// </summary>
  374. /// <param name="item">The item.</param>
  375. /// <returns>IEnumerable{IImageProvider}.</returns>
  376. public IEnumerable<IImageProvider> GetImageProviders(BaseItem item)
  377. {
  378. return ImageProviders.Where(i =>
  379. {
  380. try
  381. {
  382. return i.Supports(item);
  383. }
  384. catch (Exception ex)
  385. {
  386. _logger.ErrorException("{0} failed in Supports for type {1}", ex, i.GetType().Name, item.GetType().Name);
  387. return false;
  388. }
  389. });
  390. }
  391. }
  392. }