ProviderManager.cs 18 KB

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