ProviderManager.cs 46 KB

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