ProviderManager.cs 13 KB

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