2
0

ProviderManager.cs 20 KB

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