ProviderManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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("item");
  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. try
  189. {
  190. var changed = await provider.FetchAsync(item, force, cancellationToken).ConfigureAwait(false);
  191. if (changed)
  192. {
  193. return provider.ItemUpdateType;
  194. }
  195. return null;
  196. }
  197. catch (OperationCanceledException ex)
  198. {
  199. _logger.Debug("{0} canceled for {1}", provider.GetType().Name, item.Name);
  200. // If the outer cancellation token is the one that caused the cancellation, throw it
  201. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  202. {
  203. throw;
  204. }
  205. return null;
  206. }
  207. catch (Exception ex)
  208. {
  209. _logger.ErrorException("{0} failed refreshing {1} {2}", ex, provider.GetType().Name, item.Name, item.Path ?? string.Empty);
  210. provider.SetLastRefreshed(item, DateTime.UtcNow, ProviderRefreshStatus.Failure);
  211. return ItemUpdateType.Unspecified;
  212. }
  213. }
  214. /// <summary>
  215. /// Saves to library filesystem.
  216. /// </summary>
  217. /// <param name="item">The item.</param>
  218. /// <param name="path">The path.</param>
  219. /// <param name="dataToSave">The data to save.</param>
  220. /// <param name="cancellationToken">The cancellation token.</param>
  221. /// <returns>Task.</returns>
  222. /// <exception cref="System.ArgumentNullException"></exception>
  223. public async Task SaveToLibraryFilesystem(BaseItem item, string path, Stream dataToSave, CancellationToken cancellationToken)
  224. {
  225. if (item == null)
  226. {
  227. throw new ArgumentNullException();
  228. }
  229. if (string.IsNullOrEmpty(path))
  230. {
  231. throw new ArgumentNullException();
  232. }
  233. if (dataToSave == null)
  234. {
  235. throw new ArgumentNullException();
  236. }
  237. if (cancellationToken.IsCancellationRequested)
  238. {
  239. dataToSave.Dispose();
  240. cancellationToken.ThrowIfCancellationRequested();
  241. }
  242. //Tell the watchers to ignore
  243. _directoryWatchers.TemporarilyIgnore(path);
  244. if (dataToSave.CanSeek)
  245. {
  246. dataToSave.Position = 0;
  247. }
  248. try
  249. {
  250. using (dataToSave)
  251. {
  252. using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  253. {
  254. await dataToSave.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  255. }
  256. }
  257. // If this is ever used for something other than metadata we can add a file type param
  258. item.ResolveArgs.AddMetadataFile(path);
  259. }
  260. finally
  261. {
  262. //Remove the ignore
  263. _directoryWatchers.RemoveTempIgnore(path);
  264. }
  265. }
  266. /// <summary>
  267. /// Saves the image.
  268. /// </summary>
  269. /// <param name="item">The item.</param>
  270. /// <param name="url">The URL.</param>
  271. /// <param name="resourcePool">The resource pool.</param>
  272. /// <param name="type">The type.</param>
  273. /// <param name="imageIndex">Index of the image.</param>
  274. /// <param name="cancellationToken">The cancellation token.</param>
  275. /// <returns>Task.</returns>
  276. public async Task SaveImage(BaseItem item, string url, SemaphoreSlim resourcePool, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  277. {
  278. var response = await _httpClient.GetResponse(new HttpRequestOptions
  279. {
  280. CancellationToken = cancellationToken,
  281. ResourcePool = resourcePool,
  282. Url = url
  283. }).ConfigureAwait(false);
  284. await SaveImage(item, response.Content, response.ContentType, type, imageIndex, url, cancellationToken)
  285. .ConfigureAwait(false);
  286. }
  287. /// <summary>
  288. /// Saves the image.
  289. /// </summary>
  290. /// <param name="item">The item.</param>
  291. /// <param name="source">The source.</param>
  292. /// <param name="mimeType">Type of the MIME.</param>
  293. /// <param name="type">The type.</param>
  294. /// <param name="imageIndex">Index of the image.</param>
  295. /// <param name="sourceUrl">The source URL.</param>
  296. /// <param name="cancellationToken">The cancellation token.</param>
  297. /// <returns>Task.</returns>
  298. public Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, string sourceUrl, CancellationToken cancellationToken)
  299. {
  300. return new ImageSaver(ConfigurationManager, _directoryWatchers, _fileSystem, _logger).SaveImage(item, source, mimeType, type, imageIndex, sourceUrl, cancellationToken);
  301. }
  302. /// <summary>
  303. /// Gets the available remote images.
  304. /// </summary>
  305. /// <param name="item">The item.</param>
  306. /// <param name="cancellationToken">The cancellation token.</param>
  307. /// <param name="providerName">Name of the provider.</param>
  308. /// <param name="type">The type.</param>
  309. /// <returns>Task{IEnumerable{RemoteImageInfo}}.</returns>
  310. public async Task<IEnumerable<RemoteImageInfo>> GetAvailableRemoteImages(BaseItem item, CancellationToken cancellationToken, string providerName = null, ImageType? type = null)
  311. {
  312. var providers = GetImageProviders(item);
  313. if (!string.IsNullOrEmpty(providerName))
  314. {
  315. providers = providers.Where(i => string.Equals(i.Name, providerName, StringComparison.OrdinalIgnoreCase));
  316. }
  317. var preferredLanguage = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  318. var tasks = providers.Select(i => Task.Run(async () =>
  319. {
  320. try
  321. {
  322. if (type.HasValue)
  323. {
  324. var result = await i.GetImages(item, type.Value, cancellationToken).ConfigureAwait(false);
  325. return FilterImages(result, preferredLanguage);
  326. }
  327. else
  328. {
  329. var result = await i.GetAllImages(item, cancellationToken).ConfigureAwait(false);
  330. return FilterImages(result, preferredLanguage);
  331. }
  332. }
  333. catch (Exception ex)
  334. {
  335. _logger.ErrorException("{0} failed in GetImages for type {1}", ex, i.GetType().Name, item.GetType().Name);
  336. return new List<RemoteImageInfo>();
  337. }
  338. }, cancellationToken));
  339. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  340. return results.SelectMany(i => i);
  341. }
  342. private IEnumerable<RemoteImageInfo> FilterImages(IEnumerable<RemoteImageInfo> images, string preferredLanguage)
  343. {
  344. if (string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase))
  345. {
  346. images = images.Where(i => string.IsNullOrEmpty(i.Language) ||
  347. string.Equals(i.Language, "en", StringComparison.OrdinalIgnoreCase));
  348. }
  349. return images;
  350. }
  351. /// <summary>
  352. /// Gets the supported image providers.
  353. /// </summary>
  354. /// <param name="item">The item.</param>
  355. /// <returns>IEnumerable{IImageProvider}.</returns>
  356. public IEnumerable<IImageProvider> GetImageProviders(BaseItem item)
  357. {
  358. return ImageProviders.Where(i =>
  359. {
  360. try
  361. {
  362. return i.Supports(item);
  363. }
  364. catch (Exception ex)
  365. {
  366. _logger.ErrorException("{0} failed in Supports for type {1}", ex, i.GetType().Name, item.GetType().Name);
  367. return false;
  368. }
  369. });
  370. }
  371. }
  372. }