ProviderManager.cs 17 KB

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