ProviderManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. //download and save locally
  303. var localPath = (saveLocally && item.MetaLocation != null) ?
  304. Path.Combine(item.MetaLocation, targetName) :
  305. _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Path.ToLower(), targetName);
  306. var img = await _httpClient.Get(source, resourcePool, cancellationToken).ConfigureAwait(false);
  307. if (saveLocally) // queue to media directories
  308. {
  309. await SaveToLibraryFilesystem(item, localPath, img, cancellationToken).ConfigureAwait(false);
  310. }
  311. else
  312. {
  313. // we can write directly here because it won't affect the watchers
  314. try
  315. {
  316. // If the file already exists but is hidden, the below save will throw an UnauthorizedAccessException
  317. var existingFileInfo = new FileInfo(localPath);
  318. if (existingFileInfo.Exists && existingFileInfo.Attributes.HasFlag(FileAttributes.Hidden))
  319. {
  320. existingFileInfo.Delete();
  321. }
  322. using (var fs = new FileStream(localPath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  323. {
  324. await img.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  325. }
  326. }
  327. catch (OperationCanceledException)
  328. {
  329. throw;
  330. }
  331. catch (Exception e)
  332. {
  333. _logger.ErrorException("Error downloading and saving image " + localPath, e);
  334. throw;
  335. }
  336. finally
  337. {
  338. img.Dispose();
  339. }
  340. }
  341. return localPath;
  342. }
  343. /// <summary>
  344. /// Gets the save path.
  345. /// </summary>
  346. /// <param name="item">The item.</param>
  347. /// <param name="targetFileName">Name of the target file.</param>
  348. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  349. /// <returns>System.String.</returns>
  350. public string GetSavePath(BaseItem item, string targetFileName, bool saveLocally)
  351. {
  352. return (saveLocally && item.MetaLocation != null) ?
  353. Path.Combine(item.MetaLocation, targetFileName) :
  354. _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Path.ToLower(), targetFileName);
  355. }
  356. /// <summary>
  357. /// Saves to library filesystem.
  358. /// </summary>
  359. /// <param name="item">The item.</param>
  360. /// <param name="path">The path.</param>
  361. /// <param name="dataToSave">The data to save.</param>
  362. /// <param name="cancellationToken">The cancellation token.</param>
  363. /// <returns>Task.</returns>
  364. /// <exception cref="System.ArgumentNullException"></exception>
  365. public async Task SaveToLibraryFilesystem(BaseItem item, string path, Stream dataToSave, CancellationToken cancellationToken)
  366. {
  367. if (item == null)
  368. {
  369. throw new ArgumentNullException();
  370. }
  371. if (string.IsNullOrEmpty(path))
  372. {
  373. throw new ArgumentNullException();
  374. }
  375. if (dataToSave == null)
  376. {
  377. throw new ArgumentNullException();
  378. }
  379. if (cancellationToken == null)
  380. {
  381. throw new ArgumentNullException();
  382. }
  383. if (cancellationToken.IsCancellationRequested)
  384. {
  385. dataToSave.Dispose();
  386. cancellationToken.ThrowIfCancellationRequested();
  387. }
  388. //Tell the watchers to ignore
  389. _directoryWatchers.TemporarilyIgnore(path);
  390. if (dataToSave.CanSeek)
  391. {
  392. dataToSave.Position = 0;
  393. }
  394. if (!(dataToSave is MemoryStream || dataToSave is FileStream))
  395. {
  396. var ms = new MemoryStream();
  397. using (dataToSave)
  398. {
  399. await dataToSave.CopyToAsync(ms).ConfigureAwait(false);
  400. }
  401. ms.Position = 0;
  402. dataToSave = ms;
  403. }
  404. try
  405. {
  406. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  407. {
  408. using (dataToSave)
  409. {
  410. await dataToSave.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  411. }
  412. }
  413. // If this is ever used for something other than metadata we can add a file type param
  414. item.ResolveArgs.AddMetadataFile(path);
  415. }
  416. finally
  417. {
  418. //Remove the ignore
  419. _directoryWatchers.RemoveTempIgnore(path);
  420. }
  421. }
  422. }
  423. }