ProviderManager.cs 20 KB

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