ProviderManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.IO;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Logging;
  9. using System;
  10. using System.Collections.Concurrent;
  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 remote image cache
  25. /// </summary>
  26. private readonly FileSystemRepository _remoteImageCache;
  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. public ProviderManager(IHttpClient httpClient, IServerConfigurationManager configurationManager, IDirectoryWatchers directoryWatchers, ILogManager logManager)
  62. {
  63. _logger = logManager.GetLogger("ProviderManager");
  64. _httpClient = httpClient;
  65. ConfigurationManager = configurationManager;
  66. _directoryWatchers = directoryWatchers;
  67. _remoteImageCache = new FileSystemRepository(configurationManager.ApplicationPaths.DownloadedImagesDataPath);
  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 AddMetadataProviders(IEnumerable<BaseMetadataProvider> providers)
  85. {
  86. MetadataProviders = providers.OrderBy(e => e.Priority).ToArray();
  87. }
  88. /// <summary>
  89. /// The _supported providers key
  90. /// </summary>
  91. private readonly Guid _supportedProvidersKey = "SupportedProviders".GetMD5();
  92. /// <summary>
  93. /// Runs all metadata providers for an entity, and returns true or false indicating if at least one was refreshed and requires persistence
  94. /// </summary>
  95. /// <param name="item">The item.</param>
  96. /// <param name="cancellationToken">The cancellation token.</param>
  97. /// <param name="force">if set to <c>true</c> [force].</param>
  98. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  99. /// <returns>Task{System.Boolean}.</returns>
  100. public async Task<bool> ExecuteMetadataProviders(BaseItem item, CancellationToken cancellationToken, bool force = false, bool allowSlowProviders = true)
  101. {
  102. // Allow providers of the same priority to execute in parallel
  103. MetadataProviderPriority? currentPriority = null;
  104. var currentTasks = new List<Task<bool>>();
  105. var result = false;
  106. cancellationToken.ThrowIfCancellationRequested();
  107. // Determine if supported providers have changed
  108. var supportedProviders = MetadataProviders.Where(p => p.Supports(item)).ToList();
  109. BaseProviderInfo supportedProvidersInfo;
  110. var supportedProvidersValue = string.Join(string.Empty, supportedProviders.Select(i => i.GetType().Name));
  111. var providersChanged = false;
  112. item.ProviderData.TryGetValue(_supportedProvidersKey, out supportedProvidersInfo);
  113. var supportedProvidersHash = supportedProvidersValue.GetMD5();
  114. if (supportedProvidersInfo != null)
  115. {
  116. // Force refresh if the supported providers have changed
  117. providersChanged = force = force || supportedProvidersHash != supportedProvidersInfo.Data;
  118. // If providers have changed, clear provider info and update the supported providers hash
  119. if (providersChanged)
  120. {
  121. _logger.Debug("Providers changed for {0}. Clearing and forcing refresh.", item.Name);
  122. item.ProviderData.Clear();
  123. }
  124. }
  125. if (providersChanged)
  126. {
  127. supportedProvidersInfo.Data = supportedProvidersHash;
  128. }
  129. if (force) item.ClearMetaValues();
  130. // Run the normal providers sequentially in order of priority
  131. foreach (var provider in supportedProviders)
  132. {
  133. cancellationToken.ThrowIfCancellationRequested();
  134. // Skip if internet providers are currently disabled
  135. if (provider.RequiresInternet && !ConfigurationManager.Configuration.EnableInternetProviders)
  136. {
  137. continue;
  138. }
  139. // Skip if is slow and we aren't allowing slow ones
  140. if (provider.IsSlow && !allowSlowProviders)
  141. {
  142. continue;
  143. }
  144. // Skip if internet provider and this type is not allowed
  145. if (provider.RequiresInternet && ConfigurationManager.Configuration.EnableInternetProviders && ConfigurationManager.Configuration.InternetProviderExcludeTypes.Contains(item.GetType().Name, StringComparer.OrdinalIgnoreCase))
  146. {
  147. continue;
  148. }
  149. // When a new priority is reached, await the ones that are currently running and clear the list
  150. if (currentPriority.HasValue && currentPriority.Value != provider.Priority && currentTasks.Count > 0)
  151. {
  152. var results = await Task.WhenAll(currentTasks).ConfigureAwait(false);
  153. result |= results.Contains(true);
  154. currentTasks.Clear();
  155. }
  156. // Put this check below the await because the needs refresh of the next tier of providers may depend on the previous ones running
  157. // This is the case for the fan art provider which depends on the movie and tv providers having run before them
  158. if (!force && !provider.NeedsRefresh(item))
  159. {
  160. continue;
  161. }
  162. currentTasks.Add(FetchAsync(provider, item, force, cancellationToken));
  163. currentPriority = provider.Priority;
  164. }
  165. if (currentTasks.Count > 0)
  166. {
  167. var results = await Task.WhenAll(currentTasks).ConfigureAwait(false);
  168. result |= results.Contains(true);
  169. }
  170. if (providersChanged)
  171. {
  172. item.ProviderData[_supportedProvidersKey] = supportedProvidersInfo;
  173. }
  174. return result || providersChanged;
  175. }
  176. /// <summary>
  177. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  178. /// </summary>
  179. /// <param name="provider">The provider.</param>
  180. /// <param name="item">The item.</param>
  181. /// <param name="force">if set to <c>true</c> [force].</param>
  182. /// <param name="cancellationToken">The cancellation token.</param>
  183. /// <returns>Task{System.Boolean}.</returns>
  184. /// <exception cref="System.ArgumentNullException"></exception>
  185. private async Task<bool> FetchAsync(BaseMetadataProvider provider, BaseItem item, bool force, CancellationToken cancellationToken)
  186. {
  187. if (item == null)
  188. {
  189. throw new ArgumentNullException();
  190. }
  191. cancellationToken.ThrowIfCancellationRequested();
  192. _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name ?? "--Unknown--");
  193. // This provides the ability to cancel just this one provider
  194. var innerCancellationTokenSource = new CancellationTokenSource();
  195. OnProviderRefreshBeginning(provider, item, innerCancellationTokenSource);
  196. try
  197. {
  198. return await provider.FetchAsync(item, force, CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token).ConfigureAwait(false);
  199. }
  200. catch (OperationCanceledException ex)
  201. {
  202. _logger.Debug("{0} canceled for {1}", provider.GetType().Name, item.Name);
  203. // If the outer cancellation token is the one that caused the cancellation, throw it
  204. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  205. {
  206. throw;
  207. }
  208. return false;
  209. }
  210. catch (Exception ex)
  211. {
  212. _logger.ErrorException("{0} failed refreshing {1}", ex, provider.GetType().Name, item.Name);
  213. provider.SetLastRefreshed(item, DateTime.UtcNow, ProviderRefreshStatus.Failure);
  214. return true;
  215. }
  216. finally
  217. {
  218. innerCancellationTokenSource.Dispose();
  219. OnProviderRefreshCompleted(provider, item);
  220. }
  221. }
  222. /// <summary>
  223. /// Notifies the kernal that a provider has begun refreshing
  224. /// </summary>
  225. /// <param name="provider">The provider.</param>
  226. /// <param name="item">The item.</param>
  227. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  228. public void OnProviderRefreshBeginning(BaseMetadataProvider provider, BaseItem item, CancellationTokenSource cancellationTokenSource)
  229. {
  230. var key = item.Id + provider.GetType().Name;
  231. Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource> current;
  232. if (_currentlyRunningProviders.TryGetValue(key, out current))
  233. {
  234. try
  235. {
  236. current.Item3.Cancel();
  237. }
  238. catch (ObjectDisposedException)
  239. {
  240. }
  241. }
  242. var tuple = new Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource>(provider, item, cancellationTokenSource);
  243. _currentlyRunningProviders.AddOrUpdate(key, tuple, (k, v) => tuple);
  244. }
  245. /// <summary>
  246. /// Notifies the kernal that a provider has completed refreshing
  247. /// </summary>
  248. /// <param name="provider">The provider.</param>
  249. /// <param name="item">The item.</param>
  250. public void OnProviderRefreshCompleted(BaseMetadataProvider provider, BaseItem item)
  251. {
  252. var key = item.Id + provider.GetType().Name;
  253. Tuple<BaseMetadataProvider, BaseItem, CancellationTokenSource> current;
  254. if (_currentlyRunningProviders.TryRemove(key, out current))
  255. {
  256. current.Item3.Dispose();
  257. }
  258. }
  259. /// <summary>
  260. /// Validates the currently running providers and cancels any that should not be run due to configuration changes
  261. /// </summary>
  262. private void ValidateCurrentlyRunningProviders()
  263. {
  264. var enableInternetProviders = ConfigurationManager.Configuration.EnableInternetProviders;
  265. var internetProviderExcludeTypes = ConfigurationManager.Configuration.InternetProviderExcludeTypes;
  266. foreach (var tuple in _currentlyRunningProviders.Values
  267. .Where(p => p.Item1.RequiresInternet && (!enableInternetProviders || internetProviderExcludeTypes.Contains(p.Item2.GetType().Name, StringComparer.OrdinalIgnoreCase)))
  268. .ToList())
  269. {
  270. tuple.Item3.Cancel();
  271. }
  272. }
  273. /// <summary>
  274. /// Downloads the and save image.
  275. /// </summary>
  276. /// <param name="item">The item.</param>
  277. /// <param name="source">The source.</param>
  278. /// <param name="targetName">Name of the target.</param>
  279. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  280. /// <param name="resourcePool">The resource pool.</param>
  281. /// <param name="cancellationToken">The cancellation token.</param>
  282. /// <returns>Task{System.String}.</returns>
  283. /// <exception cref="System.ArgumentNullException">item</exception>
  284. public async Task<string> DownloadAndSaveImage(BaseItem item, string source, string targetName, bool saveLocally, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  285. {
  286. if (item == null)
  287. {
  288. throw new ArgumentNullException("item");
  289. }
  290. if (string.IsNullOrEmpty(source))
  291. {
  292. throw new ArgumentNullException("source");
  293. }
  294. if (string.IsNullOrEmpty(targetName))
  295. {
  296. throw new ArgumentNullException("targetName");
  297. }
  298. if (resourcePool == null)
  299. {
  300. throw new ArgumentNullException("resourcePool");
  301. }
  302. var img = await _httpClient.Get(source, resourcePool, cancellationToken).ConfigureAwait(false);
  303. //download and save locally
  304. return await SaveImage(item, img, targetName, saveLocally, cancellationToken).ConfigureAwait(false);
  305. }
  306. public async Task<string> SaveImage(BaseItem item, Stream source, string targetName, bool saveLocally, CancellationToken cancellationToken)
  307. {
  308. //download and save locally
  309. var localPath = (saveLocally && item.MetaLocation != null) ?
  310. Path.Combine(item.MetaLocation, targetName) :
  311. _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Path.ToLower(), targetName);
  312. if (saveLocally) // queue to media directories
  313. {
  314. await SaveToLibraryFilesystem(item, localPath, source, cancellationToken).ConfigureAwait(false);
  315. }
  316. else
  317. {
  318. // we can write directly here because it won't affect the watchers
  319. try
  320. {
  321. using (var fs = new FileStream(localPath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  322. {
  323. await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  324. }
  325. }
  326. catch (OperationCanceledException)
  327. {
  328. throw;
  329. }
  330. catch (Exception e)
  331. {
  332. _logger.ErrorException("Error downloading and saving image " + localPath, e);
  333. throw;
  334. }
  335. finally
  336. {
  337. source.Dispose();
  338. }
  339. }
  340. return localPath;
  341. }
  342. /// <summary>
  343. /// Gets the save path.
  344. /// </summary>
  345. /// <param name="item">The item.</param>
  346. /// <param name="targetFileName">Name of the target file.</param>
  347. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  348. /// <returns>System.String.</returns>
  349. public string GetSavePath(BaseItem item, string targetFileName, bool saveLocally)
  350. {
  351. return (saveLocally && item.MetaLocation != null) ?
  352. Path.Combine(item.MetaLocation, targetFileName) :
  353. _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Id.ToString(), targetFileName);
  354. }
  355. /// <summary>
  356. /// Saves to library filesystem.
  357. /// </summary>
  358. /// <param name="item">The item.</param>
  359. /// <param name="path">The path.</param>
  360. /// <param name="dataToSave">The data to save.</param>
  361. /// <param name="cancellationToken">The cancellation token.</param>
  362. /// <returns>Task.</returns>
  363. /// <exception cref="System.ArgumentNullException"></exception>
  364. public async Task SaveToLibraryFilesystem(BaseItem item, string path, Stream dataToSave, CancellationToken cancellationToken)
  365. {
  366. if (item == null)
  367. {
  368. throw new ArgumentNullException();
  369. }
  370. if (string.IsNullOrEmpty(path))
  371. {
  372. throw new ArgumentNullException();
  373. }
  374. if (dataToSave == null)
  375. {
  376. throw new ArgumentNullException();
  377. }
  378. if (cancellationToken == null)
  379. {
  380. throw new ArgumentNullException();
  381. }
  382. if (cancellationToken.IsCancellationRequested)
  383. {
  384. dataToSave.Dispose();
  385. cancellationToken.ThrowIfCancellationRequested();
  386. }
  387. //Tell the watchers to ignore
  388. _directoryWatchers.TemporarilyIgnore(path);
  389. if (dataToSave.CanSeek)
  390. {
  391. dataToSave.Position = 0;
  392. }
  393. if (!(dataToSave is MemoryStream || dataToSave is FileStream))
  394. {
  395. var ms = new MemoryStream();
  396. using (dataToSave)
  397. {
  398. await dataToSave.CopyToAsync(ms).ConfigureAwait(false);
  399. }
  400. ms.Position = 0;
  401. dataToSave = ms;
  402. }
  403. try
  404. {
  405. using (dataToSave)
  406. {
  407. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  408. {
  409. await dataToSave.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  410. }
  411. }
  412. // If this is ever used for something other than metadata we can add a file type param
  413. item.ResolveArgs.AddMetadataFile(path);
  414. }
  415. finally
  416. {
  417. //Remove the ignore
  418. _directoryWatchers.RemoveTempIgnore(path);
  419. }
  420. }
  421. }
  422. }