ProviderManager.cs 16 KB

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