ProviderManager.cs 18 KB

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