ProviderManager.cs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Net.Mime;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Jellyfin.Data.Events;
  13. using MediaBrowser.Common.Net;
  14. using MediaBrowser.Common.Progress;
  15. using MediaBrowser.Controller;
  16. using MediaBrowser.Controller.BaseItemManager;
  17. using MediaBrowser.Controller.Configuration;
  18. using MediaBrowser.Controller.Dto;
  19. using MediaBrowser.Controller.Entities;
  20. using MediaBrowser.Controller.Entities.Audio;
  21. using MediaBrowser.Controller.Entities.Movies;
  22. using MediaBrowser.Controller.Library;
  23. using MediaBrowser.Controller.Providers;
  24. using MediaBrowser.Controller.Subtitles;
  25. using MediaBrowser.Model.Configuration;
  26. using MediaBrowser.Model.Entities;
  27. using MediaBrowser.Model.IO;
  28. using MediaBrowser.Model.Net;
  29. using MediaBrowser.Model.Providers;
  30. using Microsoft.Extensions.Logging;
  31. using Priority_Queue;
  32. using Book = MediaBrowser.Controller.Entities.Book;
  33. using Episode = MediaBrowser.Controller.Entities.TV.Episode;
  34. using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
  35. using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
  36. using Season = MediaBrowser.Controller.Entities.TV.Season;
  37. using Series = MediaBrowser.Controller.Entities.TV.Series;
  38. namespace MediaBrowser.Providers.Manager
  39. {
  40. /// <summary>
  41. /// Class ProviderManager.
  42. /// </summary>
  43. public class ProviderManager : IProviderManager, IDisposable
  44. {
  45. private readonly object _refreshQueueLock = new object();
  46. private readonly ILogger<ProviderManager> _logger;
  47. private readonly IHttpClientFactory _httpClientFactory;
  48. private readonly ILibraryMonitor _libraryMonitor;
  49. private readonly IFileSystem _fileSystem;
  50. private readonly IServerApplicationPaths _appPaths;
  51. private readonly ILibraryManager _libraryManager;
  52. private readonly ISubtitleManager _subtitleManager;
  53. private readonly IServerConfigurationManager _configurationManager;
  54. private readonly IBaseItemManager _baseItemManager;
  55. private readonly ConcurrentDictionary<Guid, double> _activeRefreshes = new ConcurrentDictionary<Guid, double>();
  56. private readonly CancellationTokenSource _disposeCancellationTokenSource = new CancellationTokenSource();
  57. private readonly SimplePriorityQueue<Tuple<Guid, MetadataRefreshOptions>> _refreshQueue =
  58. new SimplePriorityQueue<Tuple<Guid, MetadataRefreshOptions>>();
  59. private IMetadataService[] _metadataServices = Array.Empty<IMetadataService>();
  60. private IMetadataProvider[] _metadataProviders = Array.Empty<IMetadataProvider>();
  61. private IMetadataSaver[] _savers = Array.Empty<IMetadataSaver>();
  62. private IExternalId[] _externalIds = Array.Empty<IExternalId>();
  63. private bool _isProcessingRefreshQueue;
  64. private bool _disposed;
  65. /// <summary>
  66. /// Initializes a new instance of the <see cref="ProviderManager"/> class.
  67. /// </summary>
  68. /// <param name="httpClientFactory">The Http client factory.</param>
  69. /// <param name="subtitleManager">The subtitle manager.</param>
  70. /// <param name="configurationManager">The configuration manager.</param>
  71. /// <param name="libraryMonitor">The library monitor.</param>
  72. /// <param name="logger">The logger.</param>
  73. /// <param name="fileSystem">The filesystem.</param>
  74. /// <param name="appPaths">The server application paths.</param>
  75. /// <param name="libraryManager">The library manager.</param>
  76. /// <param name="baseItemManager">The BaseItem manager.</param>
  77. public ProviderManager(
  78. IHttpClientFactory httpClientFactory,
  79. ISubtitleManager subtitleManager,
  80. IServerConfigurationManager configurationManager,
  81. ILibraryMonitor libraryMonitor,
  82. ILogger<ProviderManager> logger,
  83. IFileSystem fileSystem,
  84. IServerApplicationPaths appPaths,
  85. ILibraryManager libraryManager,
  86. IBaseItemManager baseItemManager)
  87. {
  88. _logger = logger;
  89. _httpClientFactory = httpClientFactory;
  90. _configurationManager = configurationManager;
  91. _libraryMonitor = libraryMonitor;
  92. _fileSystem = fileSystem;
  93. _appPaths = appPaths;
  94. _libraryManager = libraryManager;
  95. _subtitleManager = subtitleManager;
  96. _baseItemManager = baseItemManager;
  97. }
  98. /// <inheritdoc/>
  99. public event EventHandler<GenericEventArgs<BaseItem>> RefreshStarted;
  100. /// <inheritdoc/>
  101. public event EventHandler<GenericEventArgs<BaseItem>> RefreshCompleted;
  102. /// <inheritdoc/>
  103. public event EventHandler<GenericEventArgs<Tuple<BaseItem, double>>> RefreshProgress;
  104. private IImageProvider[] ImageProviders { get; set; }
  105. /// <inheritdoc/>
  106. public void AddParts(
  107. IEnumerable<IImageProvider> imageProviders,
  108. IEnumerable<IMetadataService> metadataServices,
  109. IEnumerable<IMetadataProvider> metadataProviders,
  110. IEnumerable<IMetadataSaver> metadataSavers,
  111. IEnumerable<IExternalId> externalIds)
  112. {
  113. ImageProviders = imageProviders.ToArray();
  114. _metadataServices = metadataServices.OrderBy(i => i.Order).ToArray();
  115. _metadataProviders = metadataProviders.ToArray();
  116. _externalIds = externalIds.OrderBy(i => i.ProviderName).ToArray();
  117. _savers = metadataSavers
  118. .Where(i => i is not IConfigurableProvider configurable || configurable.IsEnabled)
  119. .ToArray();
  120. }
  121. /// <inheritdoc/>
  122. public Task<ItemUpdateType> RefreshSingleItem(BaseItem item, MetadataRefreshOptions options, CancellationToken cancellationToken)
  123. {
  124. var type = item.GetType();
  125. var service = _metadataServices.FirstOrDefault(current => current.CanRefreshPrimary(type));
  126. if (service == null)
  127. {
  128. foreach (var current in _metadataServices)
  129. {
  130. if (current.CanRefresh(item))
  131. {
  132. service = current;
  133. break;
  134. }
  135. }
  136. }
  137. if (service != null)
  138. {
  139. return service.RefreshMetadata(item, options, cancellationToken);
  140. }
  141. _logger.LogError("Unable to find a metadata service for item of type {TypeName}", item.GetType().Name);
  142. return Task.FromResult(ItemUpdateType.None);
  143. }
  144. /// <inheritdoc/>
  145. public async Task SaveImage(BaseItem item, string url, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  146. {
  147. var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
  148. using var response = await httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false);
  149. if (response.StatusCode != HttpStatusCode.OK)
  150. {
  151. throw new HttpRequestException("Invalid image received.", null, response.StatusCode);
  152. }
  153. var contentType = response.Content.Headers.ContentType.MediaType;
  154. // Workaround for tvheadend channel icons
  155. // TODO: Isolate this hack into the tvh plugin
  156. if (string.IsNullOrEmpty(contentType))
  157. {
  158. if (url.IndexOf("/imagecache/", StringComparison.OrdinalIgnoreCase) != -1)
  159. {
  160. contentType = "image/png";
  161. }
  162. }
  163. // thetvdb will sometimes serve a rubbish 404 html page with a 200 OK code, because reasons...
  164. if (contentType.Equals(MediaTypeNames.Text.Html, StringComparison.OrdinalIgnoreCase))
  165. {
  166. throw new HttpRequestException("Invalid image received.", null, HttpStatusCode.NotFound);
  167. }
  168. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  169. await SaveImage(
  170. item,
  171. stream,
  172. contentType,
  173. type,
  174. imageIndex,
  175. cancellationToken).ConfigureAwait(false);
  176. }
  177. /// <inheritdoc/>
  178. public Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  179. {
  180. return new ImageSaver(_configurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, source, mimeType, type, imageIndex, cancellationToken);
  181. }
  182. /// <inheritdoc/>
  183. public Task SaveImage(BaseItem item, string source, string mimeType, ImageType type, int? imageIndex, bool? saveLocallyWithMedia, CancellationToken cancellationToken)
  184. {
  185. if (string.IsNullOrWhiteSpace(source))
  186. {
  187. throw new ArgumentNullException(nameof(source));
  188. }
  189. var fileStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, true);
  190. return new ImageSaver(_configurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, fileStream, mimeType, type, imageIndex, saveLocallyWithMedia, cancellationToken);
  191. }
  192. /// <inheritdoc/>
  193. public Task SaveImage(Stream source, string mimeType, string path)
  194. {
  195. return new ImageSaver(_configurationManager, _libraryMonitor, _fileSystem, _logger)
  196. .SaveImage(source, path);
  197. }
  198. /// <inheritdoc/>
  199. public async Task<IEnumerable<RemoteImageInfo>> GetAvailableRemoteImages(BaseItem item, RemoteImageQuery query, CancellationToken cancellationToken)
  200. {
  201. var providers = GetRemoteImageProviders(item, query.IncludeDisabledProviders);
  202. if (!string.IsNullOrEmpty(query.ProviderName))
  203. {
  204. var providerName = query.ProviderName;
  205. providers = providers.Where(i => string.Equals(i.Name, providerName, StringComparison.OrdinalIgnoreCase));
  206. }
  207. var preferredLanguage = item.GetPreferredMetadataLanguage();
  208. var languages = new List<string>();
  209. if (!query.IncludeAllLanguages && !string.IsNullOrWhiteSpace(preferredLanguage))
  210. {
  211. languages.Add(preferredLanguage);
  212. }
  213. // TODO include [query.IncludeAllLanguages] as an argument to the providers
  214. var tasks = providers.Select(i => GetImages(item, i, languages, cancellationToken, query.ImageType));
  215. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  216. return results.SelectMany(i => i.ToList());
  217. }
  218. /// <summary>
  219. /// Gets the images.
  220. /// </summary>
  221. /// <param name="item">The item.</param>
  222. /// <param name="provider">The provider.</param>
  223. /// <param name="preferredLanguages">The preferred languages.</param>
  224. /// <param name="cancellationToken">The cancellation token.</param>
  225. /// <param name="type">The type.</param>
  226. /// <returns>Task{IEnumerable{RemoteImageInfo}}.</returns>
  227. private async Task<IEnumerable<RemoteImageInfo>> GetImages(
  228. BaseItem item,
  229. IRemoteImageProvider provider,
  230. IReadOnlyCollection<string> preferredLanguages,
  231. CancellationToken cancellationToken,
  232. ImageType? type = null)
  233. {
  234. try
  235. {
  236. var result = await provider.GetImages(item, cancellationToken).ConfigureAwait(false);
  237. if (type.HasValue)
  238. {
  239. result = result.Where(i => i.Type == type.Value);
  240. }
  241. if (preferredLanguages.Count > 0)
  242. {
  243. result = result.Where(i => string.IsNullOrEmpty(i.Language) ||
  244. preferredLanguages.Contains(i.Language, StringComparer.OrdinalIgnoreCase) ||
  245. string.Equals(i.Language, "en", StringComparison.OrdinalIgnoreCase));
  246. }
  247. return result;
  248. }
  249. catch (OperationCanceledException)
  250. {
  251. return new List<RemoteImageInfo>();
  252. }
  253. catch (Exception ex)
  254. {
  255. _logger.LogError(ex, "{ProviderName} failed in GetImageInfos for type {ItemType} at {ItemPath}", provider.GetType().Name, item.GetType().Name, item.Path);
  256. return new List<RemoteImageInfo>();
  257. }
  258. }
  259. /// <inheritdoc/>
  260. public IEnumerable<ImageProviderInfo> GetRemoteImageProviderInfo(BaseItem item)
  261. {
  262. return GetRemoteImageProviders(item, true).Select(i => new ImageProviderInfo(i.Name, i.GetSupportedImages(item).ToArray()));
  263. }
  264. /// <summary>
  265. /// Gets the image providers for the provided item.
  266. /// </summary>
  267. /// <param name="item">The item.</param>
  268. /// <param name="refreshOptions">The image refresh options.</param>
  269. /// <returns>The image providers for the item.</returns>
  270. public IEnumerable<IImageProvider> GetImageProviders(BaseItem item, ImageRefreshOptions refreshOptions)
  271. {
  272. return GetImageProviders(item, _libraryManager.GetLibraryOptions(item), GetMetadataOptions(item), refreshOptions, false);
  273. }
  274. private IEnumerable<IImageProvider> GetImageProviders(BaseItem item, LibraryOptions libraryOptions, MetadataOptions options, ImageRefreshOptions refreshOptions, bool includeDisabled)
  275. {
  276. // Avoid implicitly captured closure
  277. var currentOptions = options;
  278. var typeOptions = libraryOptions.GetTypeOptions(item.GetType().Name);
  279. var typeFetcherOrder = typeOptions?.ImageFetcherOrder;
  280. return ImageProviders.Where(i => CanRefresh(i, item, libraryOptions, refreshOptions, includeDisabled))
  281. .OrderBy(i =>
  282. {
  283. // See if there's a user-defined order
  284. if (!(i is ILocalImageProvider))
  285. {
  286. var fetcherOrder = typeFetcherOrder ?? currentOptions.ImageFetcherOrder;
  287. var index = Array.IndexOf(fetcherOrder, i.Name);
  288. if (index != -1)
  289. {
  290. return index;
  291. }
  292. }
  293. // Not configured. Just return some high number to put it at the end.
  294. return 100;
  295. })
  296. .ThenBy(GetOrder);
  297. }
  298. /// <summary>
  299. /// Gets the metadata providers for the provided item.
  300. /// </summary>
  301. /// <param name="item">The item.</param>
  302. /// <param name="libraryOptions">The library options.</param>
  303. /// <typeparam name="T">The type of metadata provider.</typeparam>
  304. /// <returns>The metadata providers.</returns>
  305. public IEnumerable<IMetadataProvider<T>> GetMetadataProviders<T>(BaseItem item, LibraryOptions libraryOptions)
  306. where T : BaseItem
  307. {
  308. var globalMetadataOptions = GetMetadataOptions(item);
  309. return GetMetadataProvidersInternal<T>(item, libraryOptions, globalMetadataOptions, false, false);
  310. }
  311. private IEnumerable<IMetadataProvider<T>> GetMetadataProvidersInternal<T>(BaseItem item, LibraryOptions libraryOptions, MetadataOptions globalMetadataOptions, bool includeDisabled, bool forceEnableInternetMetadata)
  312. where T : BaseItem
  313. {
  314. // Avoid implicitly captured closure
  315. var currentOptions = globalMetadataOptions;
  316. return _metadataProviders.OfType<IMetadataProvider<T>>()
  317. .Where(i => CanRefresh(i, item, libraryOptions, includeDisabled, forceEnableInternetMetadata))
  318. .OrderBy(i => GetConfiguredOrder(item, i, libraryOptions, globalMetadataOptions))
  319. .ThenBy(GetDefaultOrder);
  320. }
  321. private IEnumerable<IRemoteImageProvider> GetRemoteImageProviders(BaseItem item, bool includeDisabled)
  322. {
  323. var options = GetMetadataOptions(item);
  324. var libraryOptions = _libraryManager.GetLibraryOptions(item);
  325. return GetImageProviders(
  326. item,
  327. libraryOptions,
  328. options,
  329. new ImageRefreshOptions(new DirectoryService(_fileSystem)),
  330. includeDisabled).OfType<IRemoteImageProvider>();
  331. }
  332. private bool CanRefresh(
  333. IMetadataProvider provider,
  334. BaseItem item,
  335. LibraryOptions libraryOptions,
  336. bool includeDisabled,
  337. bool forceEnableInternetMetadata)
  338. {
  339. if (!includeDisabled)
  340. {
  341. // If locked only allow local providers
  342. if (item.IsLocked && !(provider is ILocalMetadataProvider) && !(provider is IForcedProvider))
  343. {
  344. return false;
  345. }
  346. if (provider is IRemoteMetadataProvider)
  347. {
  348. if (!forceEnableInternetMetadata && !_baseItemManager.IsMetadataFetcherEnabled(item, libraryOptions, provider.Name))
  349. {
  350. return false;
  351. }
  352. }
  353. }
  354. if (!item.SupportsLocalMetadata && provider is ILocalMetadataProvider)
  355. {
  356. return false;
  357. }
  358. // If this restriction is ever lifted, movie xml providers will have to be updated to prevent owned items like trailers from reading those files
  359. if (!item.OwnerId.Equals(Guid.Empty))
  360. {
  361. if (provider is ILocalMetadataProvider || provider is IRemoteMetadataProvider)
  362. {
  363. return false;
  364. }
  365. }
  366. return true;
  367. }
  368. private bool CanRefresh(
  369. IImageProvider provider,
  370. BaseItem item,
  371. LibraryOptions libraryOptions,
  372. ImageRefreshOptions refreshOptions,
  373. bool includeDisabled)
  374. {
  375. if (!includeDisabled)
  376. {
  377. // If locked only allow local providers
  378. if (item.IsLocked && !(provider is ILocalImageProvider))
  379. {
  380. if (refreshOptions.ImageRefreshMode != MetadataRefreshMode.FullRefresh)
  381. {
  382. return false;
  383. }
  384. }
  385. if (provider is IRemoteImageProvider || provider is IDynamicImageProvider)
  386. {
  387. if (!_baseItemManager.IsImageFetcherEnabled(item, libraryOptions, provider.Name))
  388. {
  389. return false;
  390. }
  391. }
  392. }
  393. try
  394. {
  395. return provider.Supports(item);
  396. }
  397. catch (Exception ex)
  398. {
  399. _logger.LogError(ex, "{ProviderName} failed in Supports for type {ItemType} at {ItemPath}", provider.GetType().Name, item.GetType().Name, item.Path);
  400. return false;
  401. }
  402. }
  403. /// <summary>
  404. /// Gets the order.
  405. /// </summary>
  406. /// <param name="provider">The provider.</param>
  407. /// <returns>System.Int32.</returns>
  408. private int GetOrder(IImageProvider provider)
  409. {
  410. if (!(provider is IHasOrder hasOrder))
  411. {
  412. return 0;
  413. }
  414. return hasOrder.Order;
  415. }
  416. private int GetConfiguredOrder(BaseItem item, IMetadataProvider provider, LibraryOptions libraryOptions, MetadataOptions globalMetadataOptions)
  417. {
  418. // See if there's a user-defined order
  419. if (provider is ILocalMetadataProvider)
  420. {
  421. var configuredOrder = libraryOptions.LocalMetadataReaderOrder ?? globalMetadataOptions.LocalMetadataReaderOrder;
  422. var index = Array.IndexOf(configuredOrder, provider.Name);
  423. if (index != -1)
  424. {
  425. return index;
  426. }
  427. }
  428. // See if there's a user-defined order
  429. if (provider is IRemoteMetadataProvider)
  430. {
  431. var typeOptions = libraryOptions.GetTypeOptions(item.GetType().Name);
  432. var typeFetcherOrder = typeOptions?.MetadataFetcherOrder;
  433. var fetcherOrder = typeFetcherOrder ?? globalMetadataOptions.MetadataFetcherOrder;
  434. var index = Array.IndexOf(fetcherOrder, provider.Name);
  435. if (index != -1)
  436. {
  437. return index;
  438. }
  439. }
  440. // Not configured. Just return some high number to put it at the end.
  441. return 100;
  442. }
  443. private int GetDefaultOrder(IMetadataProvider provider)
  444. {
  445. if (provider is IHasOrder hasOrder)
  446. {
  447. return hasOrder.Order;
  448. }
  449. return 0;
  450. }
  451. /// <inheritdoc/>
  452. public MetadataPluginSummary[] GetAllMetadataPlugins()
  453. {
  454. return new[]
  455. {
  456. GetPluginSummary<Movie>(),
  457. GetPluginSummary<BoxSet>(),
  458. GetPluginSummary<Book>(),
  459. GetPluginSummary<Series>(),
  460. GetPluginSummary<Season>(),
  461. GetPluginSummary<Episode>(),
  462. GetPluginSummary<MusicAlbum>(),
  463. GetPluginSummary<MusicArtist>(),
  464. GetPluginSummary<Audio>(),
  465. GetPluginSummary<AudioBook>(),
  466. GetPluginSummary<Studio>(),
  467. GetPluginSummary<MusicVideo>(),
  468. GetPluginSummary<Video>()
  469. };
  470. }
  471. private MetadataPluginSummary GetPluginSummary<T>()
  472. where T : BaseItem, new()
  473. {
  474. // Give it a dummy path just so that it looks like a file system item
  475. var dummy = new T
  476. {
  477. Path = Path.Combine(_appPaths.InternalMetadataPath, "dummy"),
  478. ParentId = Guid.NewGuid()
  479. };
  480. var options = GetMetadataOptions(dummy);
  481. var summary = new MetadataPluginSummary
  482. {
  483. ItemType = typeof(T).Name
  484. };
  485. var libraryOptions = new LibraryOptions();
  486. var imageProviders = GetImageProviders(
  487. dummy,
  488. libraryOptions,
  489. options,
  490. new ImageRefreshOptions(new DirectoryService(_fileSystem)),
  491. true).ToList();
  492. var pluginList = summary.Plugins.ToList();
  493. AddMetadataPlugins(pluginList, dummy, libraryOptions, options);
  494. AddImagePlugins(pluginList, imageProviders);
  495. var subtitleProviders = _subtitleManager.GetSupportedProviders(dummy);
  496. // Subtitle fetchers
  497. pluginList.AddRange(subtitleProviders.Select(i => new MetadataPlugin
  498. {
  499. Name = i.Name,
  500. Type = MetadataPluginType.SubtitleFetcher
  501. }));
  502. summary.Plugins = pluginList.ToArray();
  503. var supportedImageTypes = imageProviders.OfType<IRemoteImageProvider>()
  504. .SelectMany(i => i.GetSupportedImages(dummy))
  505. .ToList();
  506. supportedImageTypes.AddRange(imageProviders.OfType<IDynamicImageProvider>()
  507. .SelectMany(i => i.GetSupportedImages(dummy)));
  508. summary.SupportedImageTypes = supportedImageTypes.Distinct().ToArray();
  509. return summary;
  510. }
  511. private void AddMetadataPlugins<T>(List<MetadataPlugin> list, T item, LibraryOptions libraryOptions, MetadataOptions options)
  512. where T : BaseItem
  513. {
  514. var providers = GetMetadataProvidersInternal<T>(item, libraryOptions, options, true, true).ToList();
  515. // Locals
  516. list.AddRange(providers.Where(i => i is ILocalMetadataProvider).Select(i => new MetadataPlugin
  517. {
  518. Name = i.Name,
  519. Type = MetadataPluginType.LocalMetadataProvider
  520. }));
  521. // Fetchers
  522. list.AddRange(providers.Where(i => i is IRemoteMetadataProvider).Select(i => new MetadataPlugin
  523. {
  524. Name = i.Name,
  525. Type = MetadataPluginType.MetadataFetcher
  526. }));
  527. // Savers
  528. list.AddRange(_savers.Where(i => IsSaverEnabledForItem(i, item, libraryOptions, ItemUpdateType.MetadataEdit, true)).OrderBy(i => i.Name).Select(i => new MetadataPlugin
  529. {
  530. Name = i.Name,
  531. Type = MetadataPluginType.MetadataSaver
  532. }));
  533. }
  534. private void AddImagePlugins(List<MetadataPlugin> list, List<IImageProvider> imageProviders)
  535. {
  536. // Locals
  537. list.AddRange(imageProviders.Where(i => i is ILocalImageProvider).Select(i => new MetadataPlugin
  538. {
  539. Name = i.Name,
  540. Type = MetadataPluginType.LocalImageProvider
  541. }));
  542. // Fetchers
  543. list.AddRange(imageProviders.Where(i => i is IDynamicImageProvider || (i is IRemoteImageProvider)).Select(i => new MetadataPlugin
  544. {
  545. Name = i.Name,
  546. Type = MetadataPluginType.ImageFetcher
  547. }));
  548. }
  549. /// <inheritdoc/>
  550. public MetadataOptions GetMetadataOptions(BaseItem item)
  551. {
  552. var type = item.GetType().Name;
  553. return _configurationManager.Configuration.MetadataOptions
  554. .FirstOrDefault(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase)) ??
  555. new MetadataOptions();
  556. }
  557. /// <inheritdoc/>
  558. public void SaveMetadata(BaseItem item, ItemUpdateType updateType)
  559. {
  560. SaveMetadata(item, updateType, _savers);
  561. }
  562. /// <inheritdoc/>
  563. public void SaveMetadata(BaseItem item, ItemUpdateType updateType, IEnumerable<string> savers)
  564. {
  565. SaveMetadata(item, updateType, _savers.Where(i => savers.Contains(i.Name, StringComparer.OrdinalIgnoreCase)));
  566. }
  567. /// <summary>
  568. /// Saves the metadata.
  569. /// </summary>
  570. /// <param name="item">The item.</param>
  571. /// <param name="updateType">Type of the update.</param>
  572. /// <param name="savers">The savers.</param>
  573. private void SaveMetadata(BaseItem item, ItemUpdateType updateType, IEnumerable<IMetadataSaver> savers)
  574. {
  575. var libraryOptions = _libraryManager.GetLibraryOptions(item);
  576. foreach (var saver in savers.Where(i => IsSaverEnabledForItem(i, item, libraryOptions, updateType, false)))
  577. {
  578. _logger.LogDebug("Saving {0} to {1}.", item.Path ?? item.Name, saver.Name);
  579. if (saver is IMetadataFileSaver fileSaver)
  580. {
  581. string path;
  582. try
  583. {
  584. path = fileSaver.GetSavePath(item);
  585. }
  586. catch (Exception ex)
  587. {
  588. _logger.LogError(ex, "Error in {0} GetSavePath", saver.Name);
  589. continue;
  590. }
  591. try
  592. {
  593. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  594. saver.Save(item, CancellationToken.None);
  595. }
  596. catch (Exception ex)
  597. {
  598. _logger.LogError(ex, "Error in metadata saver");
  599. }
  600. finally
  601. {
  602. _libraryMonitor.ReportFileSystemChangeComplete(path, false);
  603. }
  604. }
  605. else
  606. {
  607. try
  608. {
  609. saver.Save(item, CancellationToken.None);
  610. }
  611. catch (Exception ex)
  612. {
  613. _logger.LogError(ex, "Error in metadata saver");
  614. }
  615. }
  616. }
  617. }
  618. /// <summary>
  619. /// Determines whether [is saver enabled for item] [the specified saver].
  620. /// </summary>
  621. private bool IsSaverEnabledForItem(IMetadataSaver saver, BaseItem item, LibraryOptions libraryOptions, ItemUpdateType updateType, bool includeDisabled)
  622. {
  623. var options = GetMetadataOptions(item);
  624. try
  625. {
  626. if (!saver.IsEnabledFor(item, updateType))
  627. {
  628. return false;
  629. }
  630. if (!includeDisabled)
  631. {
  632. if (libraryOptions.MetadataSavers == null)
  633. {
  634. if (options.DisabledMetadataSavers.Contains(saver.Name, StringComparer.OrdinalIgnoreCase))
  635. {
  636. return false;
  637. }
  638. if (!item.IsSaveLocalMetadataEnabled())
  639. {
  640. if (updateType >= ItemUpdateType.MetadataEdit)
  641. {
  642. // Manual edit occurred
  643. // Even if save local is off, save locally anyway if the metadata file already exists
  644. if (!(saver is IMetadataFileSaver fileSaver) || !File.Exists(fileSaver.GetSavePath(item)))
  645. {
  646. return false;
  647. }
  648. }
  649. else
  650. {
  651. // Manual edit did not occur
  652. // Since local metadata saving is disabled, consider it disabled
  653. return false;
  654. }
  655. }
  656. }
  657. else
  658. {
  659. if (!libraryOptions.MetadataSavers.Contains(saver.Name, StringComparer.OrdinalIgnoreCase))
  660. {
  661. return false;
  662. }
  663. }
  664. }
  665. return true;
  666. }
  667. catch (Exception ex)
  668. {
  669. _logger.LogError(ex, "Error in {0}.IsEnabledFor", saver.Name);
  670. return false;
  671. }
  672. }
  673. /// <inheritdoc/>
  674. public Task<IEnumerable<RemoteSearchResult>> GetRemoteSearchResults<TItemType, TLookupType>(RemoteSearchQuery<TLookupType> searchInfo, CancellationToken cancellationToken)
  675. where TItemType : BaseItem, new()
  676. where TLookupType : ItemLookupInfo
  677. {
  678. BaseItem referenceItem = null;
  679. if (!searchInfo.ItemId.Equals(Guid.Empty))
  680. {
  681. referenceItem = _libraryManager.GetItemById(searchInfo.ItemId);
  682. }
  683. return GetRemoteSearchResults<TItemType, TLookupType>(searchInfo, referenceItem, cancellationToken);
  684. }
  685. private async Task<IEnumerable<RemoteSearchResult>> GetRemoteSearchResults<TItemType, TLookupType>(RemoteSearchQuery<TLookupType> searchInfo, BaseItem referenceItem, CancellationToken cancellationToken)
  686. where TItemType : BaseItem, new()
  687. where TLookupType : ItemLookupInfo
  688. {
  689. LibraryOptions libraryOptions;
  690. if (referenceItem == null)
  691. {
  692. // Give it a dummy path just so that it looks like a file system item
  693. var dummy = new TItemType
  694. {
  695. Path = Path.Combine(_appPaths.InternalMetadataPath, "dummy"),
  696. ParentId = Guid.NewGuid()
  697. };
  698. dummy.SetParent(new Folder());
  699. referenceItem = dummy;
  700. libraryOptions = new LibraryOptions();
  701. }
  702. else
  703. {
  704. libraryOptions = _libraryManager.GetLibraryOptions(referenceItem);
  705. }
  706. var options = GetMetadataOptions(referenceItem);
  707. var providers = GetMetadataProvidersInternal<TItemType>(referenceItem, libraryOptions, options, searchInfo.IncludeDisabledProviders, false)
  708. .OfType<IRemoteSearchProvider<TLookupType>>();
  709. if (!string.IsNullOrEmpty(searchInfo.SearchProviderName))
  710. {
  711. providers = providers.Where(i => string.Equals(i.Name, searchInfo.SearchProviderName, StringComparison.OrdinalIgnoreCase));
  712. }
  713. if (string.IsNullOrWhiteSpace(searchInfo.SearchInfo.MetadataLanguage))
  714. {
  715. searchInfo.SearchInfo.MetadataLanguage = _configurationManager.Configuration.PreferredMetadataLanguage;
  716. }
  717. if (string.IsNullOrWhiteSpace(searchInfo.SearchInfo.MetadataCountryCode))
  718. {
  719. searchInfo.SearchInfo.MetadataCountryCode = _configurationManager.Configuration.MetadataCountryCode;
  720. }
  721. var resultList = new List<RemoteSearchResult>();
  722. foreach (var provider in providers)
  723. {
  724. try
  725. {
  726. var results = await GetSearchResults(provider, searchInfo.SearchInfo, cancellationToken).ConfigureAwait(false);
  727. foreach (var result in results)
  728. {
  729. var existingMatch = resultList.FirstOrDefault(i => i.ProviderIds.Any(p => string.Equals(result.GetProviderId(p.Key), p.Value, StringComparison.OrdinalIgnoreCase)));
  730. if (existingMatch == null)
  731. {
  732. resultList.Add(result);
  733. }
  734. else
  735. {
  736. foreach (var providerId in result.ProviderIds)
  737. {
  738. if (!existingMatch.ProviderIds.ContainsKey(providerId.Key))
  739. {
  740. existingMatch.ProviderIds.Add(providerId.Key, providerId.Value);
  741. }
  742. }
  743. if (string.IsNullOrWhiteSpace(existingMatch.ImageUrl))
  744. {
  745. existingMatch.ImageUrl = result.ImageUrl;
  746. }
  747. }
  748. }
  749. }
  750. #pragma warning disable CA1031 // do not catch general exception types
  751. catch (Exception ex)
  752. #pragma warning restore CA1031 // do not catch general exception types
  753. {
  754. _logger.LogError(ex, "Provider {ProviderName} failed to retrieve search results", provider.Name);
  755. }
  756. }
  757. return resultList;
  758. }
  759. private async Task<IEnumerable<RemoteSearchResult>> GetSearchResults<TLookupType>(
  760. IRemoteSearchProvider<TLookupType> provider,
  761. TLookupType searchInfo,
  762. CancellationToken cancellationToken)
  763. where TLookupType : ItemLookupInfo
  764. {
  765. var results = await provider.GetSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
  766. var list = results.ToList();
  767. foreach (var item in list)
  768. {
  769. item.SearchProviderName = provider.Name;
  770. }
  771. return list;
  772. }
  773. /// <inheritdoc/>
  774. public Task<HttpResponseMessage> GetSearchImage(string providerName, string url, CancellationToken cancellationToken)
  775. {
  776. var provider = _metadataProviders.OfType<IRemoteSearchProvider>().FirstOrDefault(i => string.Equals(i.Name, providerName, StringComparison.OrdinalIgnoreCase));
  777. if (provider == null)
  778. {
  779. throw new ArgumentException("Search provider not found.");
  780. }
  781. return provider.GetImageResponse(url, cancellationToken);
  782. }
  783. private IEnumerable<IExternalId> GetExternalIds(IHasProviderIds item)
  784. {
  785. return _externalIds.Where(i =>
  786. {
  787. try
  788. {
  789. return i.Supports(item);
  790. }
  791. catch (Exception ex)
  792. {
  793. _logger.LogError(ex, "Error in {0}.Suports", i.GetType().Name);
  794. return false;
  795. }
  796. });
  797. }
  798. /// <inheritdoc/>
  799. public IEnumerable<ExternalUrl> GetExternalUrls(BaseItem item)
  800. {
  801. return GetExternalIds(item)
  802. .Select(i =>
  803. {
  804. if (string.IsNullOrEmpty(i.UrlFormatString))
  805. {
  806. return null;
  807. }
  808. var value = item.GetProviderId(i.Key);
  809. if (string.IsNullOrEmpty(value))
  810. {
  811. return null;
  812. }
  813. return new ExternalUrl
  814. {
  815. Name = i.ProviderName,
  816. Url = string.Format(
  817. CultureInfo.InvariantCulture,
  818. i.UrlFormatString,
  819. value)
  820. };
  821. }).Where(i => i != null).Concat(item.GetRelatedUrls());
  822. }
  823. /// <inheritdoc/>
  824. public IEnumerable<ExternalIdInfo> GetExternalIdInfos(IHasProviderIds item)
  825. {
  826. return GetExternalIds(item)
  827. .Select(i => new ExternalIdInfo(
  828. name: i.ProviderName,
  829. key: i.Key,
  830. type: i.Type,
  831. urlFormatString: i.UrlFormatString));
  832. }
  833. /// <inheritdoc/>
  834. public Dictionary<Guid, Guid> GetRefreshQueue()
  835. {
  836. lock (_refreshQueueLock)
  837. {
  838. var dict = new Dictionary<Guid, Guid>();
  839. foreach (var item in _refreshQueue)
  840. {
  841. dict[item.Item1] = item.Item1;
  842. }
  843. return dict;
  844. }
  845. }
  846. /// <inheritdoc/>
  847. public void OnRefreshStart(BaseItem item)
  848. {
  849. _logger.LogDebug("OnRefreshStart {0}", item.Id.ToString("N", CultureInfo.InvariantCulture));
  850. _activeRefreshes[item.Id] = 0;
  851. RefreshStarted?.Invoke(this, new GenericEventArgs<BaseItem>(item));
  852. }
  853. /// <inheritdoc/>
  854. public void OnRefreshComplete(BaseItem item)
  855. {
  856. _logger.LogDebug("OnRefreshComplete {0}", item.Id.ToString("N", CultureInfo.InvariantCulture));
  857. _activeRefreshes.Remove(item.Id, out _);
  858. RefreshCompleted?.Invoke(this, new GenericEventArgs<BaseItem>(item));
  859. }
  860. /// <inheritdoc/>
  861. public double? GetRefreshProgress(Guid id)
  862. {
  863. if (_activeRefreshes.TryGetValue(id, out double value))
  864. {
  865. return value;
  866. }
  867. return null;
  868. }
  869. /// <inheritdoc/>
  870. public void OnRefreshProgress(BaseItem item, double progress)
  871. {
  872. var id = item.Id;
  873. _logger.LogDebug("OnRefreshProgress {0} {1}", id.ToString("N", CultureInfo.InvariantCulture), progress);
  874. // TODO: Need to hunt down the conditions for this happening
  875. _activeRefreshes.AddOrUpdate(
  876. id,
  877. (_) => throw new Exception(
  878. string.Format(
  879. CultureInfo.InvariantCulture,
  880. "Cannot update refresh progress of item '{0}' ({1}) because a refresh for this item is not running",
  881. item.GetType().Name,
  882. item.Id.ToString("N", CultureInfo.InvariantCulture))),
  883. (_, __) => progress);
  884. RefreshProgress?.Invoke(this, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(item, progress)));
  885. }
  886. /// <inheritdoc/>
  887. public void QueueRefresh(Guid id, MetadataRefreshOptions options, RefreshPriority priority)
  888. {
  889. if (_disposed)
  890. {
  891. return;
  892. }
  893. _refreshQueue.Enqueue(new Tuple<Guid, MetadataRefreshOptions>(id, options), (int)priority);
  894. lock (_refreshQueueLock)
  895. {
  896. if (!_isProcessingRefreshQueue)
  897. {
  898. _isProcessingRefreshQueue = true;
  899. Task.Run(StartProcessingRefreshQueue);
  900. }
  901. }
  902. }
  903. private async Task StartProcessingRefreshQueue()
  904. {
  905. var libraryManager = _libraryManager;
  906. if (_disposed)
  907. {
  908. return;
  909. }
  910. var cancellationToken = _disposeCancellationTokenSource.Token;
  911. while (_refreshQueue.TryDequeue(out Tuple<Guid, MetadataRefreshOptions> refreshItem))
  912. {
  913. if (_disposed)
  914. {
  915. return;
  916. }
  917. try
  918. {
  919. var item = libraryManager.GetItemById(refreshItem.Item1);
  920. if (item != null)
  921. {
  922. // Try to throttle this a little bit.
  923. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  924. var task = item is MusicArtist artist
  925. ? RefreshArtist(artist, refreshItem.Item2, cancellationToken)
  926. : RefreshItem(item, refreshItem.Item2, cancellationToken);
  927. await task.ConfigureAwait(false);
  928. }
  929. }
  930. catch (OperationCanceledException)
  931. {
  932. break;
  933. }
  934. catch (Exception ex)
  935. {
  936. _logger.LogError(ex, "Error refreshing item");
  937. }
  938. }
  939. lock (_refreshQueueLock)
  940. {
  941. _isProcessingRefreshQueue = false;
  942. }
  943. }
  944. private async Task RefreshItem(BaseItem item, MetadataRefreshOptions options, CancellationToken cancellationToken)
  945. {
  946. await item.RefreshMetadata(options, cancellationToken).ConfigureAwait(false);
  947. // Collection folders don't validate their children so we'll have to simulate that here
  948. switch (item)
  949. {
  950. case CollectionFolder collectionFolder:
  951. await RefreshCollectionFolderChildren(options, collectionFolder, cancellationToken).ConfigureAwait(false);
  952. break;
  953. case Folder folder:
  954. await folder.ValidateChildren(new SimpleProgress<double>(), cancellationToken, options).ConfigureAwait(false);
  955. break;
  956. }
  957. }
  958. private async Task RefreshCollectionFolderChildren(MetadataRefreshOptions options, CollectionFolder collectionFolder, CancellationToken cancellationToken)
  959. {
  960. foreach (var child in collectionFolder.GetPhysicalFolders())
  961. {
  962. await child.RefreshMetadata(options, cancellationToken).ConfigureAwait(false);
  963. await child.ValidateChildren(new SimpleProgress<double>(), cancellationToken, options).ConfigureAwait(false);
  964. }
  965. }
  966. private async Task RefreshArtist(MusicArtist item, MetadataRefreshOptions options, CancellationToken cancellationToken)
  967. {
  968. var albums = _libraryManager
  969. .GetItemList(new InternalItemsQuery
  970. {
  971. IncludeItemTypes = new[] { nameof(MusicAlbum) },
  972. ArtistIds = new[] { item.Id },
  973. DtoOptions = new DtoOptions(false)
  974. {
  975. EnableImages = false
  976. }
  977. })
  978. .OfType<MusicAlbum>();
  979. var musicArtists = albums
  980. .Select(i => i.MusicArtist)
  981. .Where(i => i != null);
  982. var musicArtistRefreshTasks = musicArtists.Select(i => i.ValidateChildren(new SimpleProgress<double>(), cancellationToken, options, true));
  983. await Task.WhenAll(musicArtistRefreshTasks).ConfigureAwait(false);
  984. try
  985. {
  986. await item.RefreshMetadata(options, cancellationToken).ConfigureAwait(false);
  987. }
  988. catch (Exception ex)
  989. {
  990. _logger.LogError(ex, "Error refreshing library");
  991. }
  992. }
  993. /// <inheritdoc/>
  994. public Task RefreshFullItem(BaseItem item, MetadataRefreshOptions options, CancellationToken cancellationToken)
  995. {
  996. return RefreshItem(item, options, cancellationToken);
  997. }
  998. /// <summary>
  999. /// Runs multiple metadata refreshes concurrently.
  1000. /// </summary>
  1001. /// <param name="action">The action to run.</param>
  1002. /// <param name="cancellationToken">The cancellation token.</param>
  1003. /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
  1004. public async Task RunMetadataRefresh(Func<Task> action, CancellationToken cancellationToken)
  1005. {
  1006. // create a variable for this since it is possible MetadataRefreshThrottler could change due to a config update during a scan
  1007. var metadataRefreshThrottler = _baseItemManager.MetadataRefreshThrottler;
  1008. await metadataRefreshThrottler.WaitAsync(cancellationToken).ConfigureAwait(false);
  1009. try
  1010. {
  1011. await action().ConfigureAwait(false);
  1012. }
  1013. finally
  1014. {
  1015. metadataRefreshThrottler.Release();
  1016. }
  1017. }
  1018. /// <inheritdoc/>
  1019. public void Dispose()
  1020. {
  1021. Dispose(true);
  1022. GC.SuppressFinalize(this);
  1023. }
  1024. /// <summary>
  1025. /// Releases unmanaged and optionally managed resources.
  1026. /// </summary>
  1027. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1028. protected virtual void Dispose(bool disposing)
  1029. {
  1030. if (_disposed)
  1031. {
  1032. return;
  1033. }
  1034. if (!_disposeCancellationTokenSource.IsCancellationRequested)
  1035. {
  1036. _disposeCancellationTokenSource.Cancel();
  1037. }
  1038. if (disposing)
  1039. {
  1040. _disposeCancellationTokenSource.Dispose();
  1041. }
  1042. _disposed = true;
  1043. }
  1044. }
  1045. }