ProviderManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. // Run the normal providers sequentially in order of priority
  85. foreach (var provider in MetadataProviders.Where(p => ProviderSupportsItem(p, item)))
  86. {
  87. cancellationToken.ThrowIfCancellationRequested();
  88. // Skip if internet providers are currently disabled
  89. if (provider.RequiresInternet && !ConfigurationManager.Configuration.EnableInternetProviders)
  90. {
  91. continue;
  92. }
  93. // Skip if is slow and we aren't allowing slow ones
  94. if (provider.IsSlow && !allowSlowProviders)
  95. {
  96. continue;
  97. }
  98. // Skip if internet provider and this type is not allowed
  99. if (provider.RequiresInternet && ConfigurationManager.Configuration.EnableInternetProviders && ConfigurationManager.Configuration.InternetProviderExcludeTypes.Contains(item.GetType().Name, StringComparer.OrdinalIgnoreCase))
  100. {
  101. continue;
  102. }
  103. // Put this check below the await because the needs refresh of the next tier of providers may depend on the previous ones running
  104. // This is the case for the fan art provider which depends on the movie and tv providers having run before them
  105. if (provider.RequiresInternet && item.DontFetchMeta)
  106. {
  107. continue;
  108. }
  109. try
  110. {
  111. if (!force && !provider.NeedsRefresh(item))
  112. {
  113. continue;
  114. }
  115. }
  116. catch (Exception ex)
  117. {
  118. _logger.Error("Error determining NeedsRefresh for {0}", ex, item.Path);
  119. }
  120. var updateType = await FetchAsync(provider, item, force, cancellationToken).ConfigureAwait(false);
  121. if (updateType.HasValue)
  122. {
  123. if (result.HasValue)
  124. {
  125. result = result.Value | updateType.Value;
  126. }
  127. else
  128. {
  129. result = updateType;
  130. }
  131. }
  132. }
  133. return result;
  134. }
  135. /// <summary>
  136. /// Providers the supports item.
  137. /// </summary>
  138. /// <param name="provider">The provider.</param>
  139. /// <param name="item">The item.</param>
  140. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  141. private bool ProviderSupportsItem(BaseMetadataProvider provider, BaseItem item)
  142. {
  143. try
  144. {
  145. return provider.Supports(item);
  146. }
  147. catch (Exception ex)
  148. {
  149. _logger.ErrorException("{0} failed in Supports for type {1}", ex, provider.GetType().Name, item.GetType().Name);
  150. return false;
  151. }
  152. }
  153. /// <summary>
  154. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  155. /// </summary>
  156. /// <param name="provider">The provider.</param>
  157. /// <param name="item">The item.</param>
  158. /// <param name="force">if set to <c>true</c> [force].</param>
  159. /// <param name="cancellationToken">The cancellation token.</param>
  160. /// <returns>Task{System.Boolean}.</returns>
  161. /// <exception cref="System.ArgumentNullException"></exception>
  162. private async Task<ItemUpdateType?> FetchAsync(BaseMetadataProvider provider, BaseItem item, bool force, CancellationToken cancellationToken)
  163. {
  164. if (item == null)
  165. {
  166. throw new ArgumentNullException();
  167. }
  168. cancellationToken.ThrowIfCancellationRequested();
  169. _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name ?? "--Unknown--");
  170. // This provides the ability to cancel just this one provider
  171. var innerCancellationTokenSource = new CancellationTokenSource();
  172. try
  173. {
  174. var changed = await provider.FetchAsync(item, force, CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token).ConfigureAwait(false);
  175. if (changed)
  176. {
  177. return provider.ItemUpdateType;
  178. }
  179. return null;
  180. }
  181. catch (OperationCanceledException ex)
  182. {
  183. _logger.Debug("{0} canceled for {1}", provider.GetType().Name, item.Name);
  184. // If the outer cancellation token is the one that caused the cancellation, throw it
  185. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  186. {
  187. throw;
  188. }
  189. return null;
  190. }
  191. catch (Exception ex)
  192. {
  193. _logger.ErrorException("{0} failed refreshing {1} {2}", ex, provider.GetType().Name, item.Name, item.Path ?? string.Empty);
  194. provider.SetLastRefreshed(item, DateTime.UtcNow, ProviderRefreshStatus.Failure);
  195. return ItemUpdateType.Unspecified;
  196. }
  197. finally
  198. {
  199. innerCancellationTokenSource.Dispose();
  200. }
  201. }
  202. /// <summary>
  203. /// Saves to library filesystem.
  204. /// </summary>
  205. /// <param name="item">The item.</param>
  206. /// <param name="path">The path.</param>
  207. /// <param name="dataToSave">The data to save.</param>
  208. /// <param name="cancellationToken">The cancellation token.</param>
  209. /// <returns>Task.</returns>
  210. /// <exception cref="System.ArgumentNullException"></exception>
  211. public async Task SaveToLibraryFilesystem(BaseItem item, string path, Stream dataToSave, CancellationToken cancellationToken)
  212. {
  213. if (item == null)
  214. {
  215. throw new ArgumentNullException();
  216. }
  217. if (string.IsNullOrEmpty(path))
  218. {
  219. throw new ArgumentNullException();
  220. }
  221. if (dataToSave == null)
  222. {
  223. throw new ArgumentNullException();
  224. }
  225. if (cancellationToken == null)
  226. {
  227. throw new ArgumentNullException();
  228. }
  229. if (cancellationToken.IsCancellationRequested)
  230. {
  231. dataToSave.Dispose();
  232. cancellationToken.ThrowIfCancellationRequested();
  233. }
  234. //Tell the watchers to ignore
  235. _directoryWatchers.TemporarilyIgnore(path);
  236. if (dataToSave.CanSeek)
  237. {
  238. dataToSave.Position = 0;
  239. }
  240. try
  241. {
  242. using (dataToSave)
  243. {
  244. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  245. {
  246. await dataToSave.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  247. }
  248. }
  249. // If this is ever used for something other than metadata we can add a file type param
  250. item.ResolveArgs.AddMetadataFile(path);
  251. }
  252. finally
  253. {
  254. //Remove the ignore
  255. _directoryWatchers.RemoveTempIgnore(path);
  256. }
  257. }
  258. /// <summary>
  259. /// Saves the image.
  260. /// </summary>
  261. /// <param name="item">The item.</param>
  262. /// <param name="url">The URL.</param>
  263. /// <param name="resourcePool">The resource pool.</param>
  264. /// <param name="type">The type.</param>
  265. /// <param name="imageIndex">Index of the image.</param>
  266. /// <param name="cancellationToken">The cancellation token.</param>
  267. /// <returns>Task.</returns>
  268. public async Task SaveImage(BaseItem item, string url, SemaphoreSlim resourcePool, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  269. {
  270. var response = await _httpClient.GetResponse(new HttpRequestOptions
  271. {
  272. CancellationToken = cancellationToken,
  273. ResourcePool = resourcePool,
  274. Url = url
  275. }).ConfigureAwait(false);
  276. await SaveImage(item, response.Content, response.ContentType, type, imageIndex, cancellationToken)
  277. .ConfigureAwait(false);
  278. }
  279. /// <summary>
  280. /// Saves the image.
  281. /// </summary>
  282. /// <param name="item">The item.</param>
  283. /// <param name="source">The source.</param>
  284. /// <param name="mimeType">Type of the MIME.</param>
  285. /// <param name="type">The type.</param>
  286. /// <param name="imageIndex">Index of the image.</param>
  287. /// <param name="cancellationToken">The cancellation token.</param>
  288. /// <returns>Task.</returns>
  289. public Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  290. {
  291. return new ImageSaver(ConfigurationManager, _directoryWatchers).SaveImage(item, source, mimeType, type, imageIndex, cancellationToken);
  292. }
  293. }
  294. }