ProviderManager.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Audio;
  6. using MediaBrowser.Controller.Entities.Movies;
  7. using MediaBrowser.Controller.Entities.TV;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.LiveTv;
  10. using MediaBrowser.Controller.Providers;
  11. using MediaBrowser.Model.Configuration;
  12. using MediaBrowser.Model.Entities;
  13. using MediaBrowser.Model.Logging;
  14. using MediaBrowser.Model.Providers;
  15. using System;
  16. using System.Collections.Concurrent;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using CommonIO;
  23. namespace MediaBrowser.Providers.Manager
  24. {
  25. /// <summary>
  26. /// Class ProviderManager
  27. /// </summary>
  28. public class ProviderManager : IProviderManager, IDisposable
  29. {
  30. /// <summary>
  31. /// The _logger
  32. /// </summary>
  33. private readonly ILogger _logger;
  34. /// <summary>
  35. /// The _HTTP client
  36. /// </summary>
  37. private readonly IHttpClient _httpClient;
  38. /// <summary>
  39. /// The _directory watchers
  40. /// </summary>
  41. private readonly ILibraryMonitor _libraryMonitor;
  42. /// <summary>
  43. /// Gets or sets the configuration manager.
  44. /// </summary>
  45. /// <value>The configuration manager.</value>
  46. private IServerConfigurationManager ConfigurationManager { get; set; }
  47. private IImageProvider[] ImageProviders { get; set; }
  48. private readonly IFileSystem _fileSystem;
  49. private IMetadataService[] _metadataServices = { };
  50. private IItemIdentityProvider[] _identityProviders = { };
  51. private IItemIdentityConverter[] _identityConverters = { };
  52. private IMetadataProvider[] _metadataProviders = { };
  53. private IEnumerable<IMetadataSaver> _savers;
  54. private IImageSaver[] _imageSavers;
  55. private readonly IServerApplicationPaths _appPaths;
  56. private IExternalId[] _externalIds;
  57. private readonly Func<ILibraryManager> _libraryManagerFactory;
  58. /// <summary>
  59. /// Initializes a new instance of the <see cref="ProviderManager" /> class.
  60. /// </summary>
  61. /// <param name="httpClient">The HTTP client.</param>
  62. /// <param name="configurationManager">The configuration manager.</param>
  63. /// <param name="libraryMonitor">The directory watchers.</param>
  64. /// <param name="logManager">The log manager.</param>
  65. /// <param name="fileSystem">The file system.</param>
  66. public ProviderManager(IHttpClient httpClient, IServerConfigurationManager configurationManager, ILibraryMonitor libraryMonitor, ILogManager logManager, IFileSystem fileSystem, IServerApplicationPaths appPaths, Func<ILibraryManager> libraryManagerFactory)
  67. {
  68. _logger = logManager.GetLogger("ProviderManager");
  69. _httpClient = httpClient;
  70. ConfigurationManager = configurationManager;
  71. _libraryMonitor = libraryMonitor;
  72. _fileSystem = fileSystem;
  73. _appPaths = appPaths;
  74. _libraryManagerFactory = libraryManagerFactory;
  75. }
  76. /// <summary>
  77. /// Adds the metadata providers.
  78. /// </summary>
  79. /// <param name="imageProviders">The image providers.</param>
  80. /// <param name="metadataServices">The metadata services.</param>
  81. /// <param name="identityProviders">The identity providers.</param>
  82. /// <param name="identityConverters">The identity converters.</param>
  83. /// <param name="metadataProviders">The metadata providers.</param>
  84. /// <param name="metadataSavers">The metadata savers.</param>
  85. /// <param name="imageSavers">The image savers.</param>
  86. /// <param name="externalIds">The external ids.</param>
  87. public void AddParts(IEnumerable<IImageProvider> imageProviders, IEnumerable<IMetadataService> metadataServices,
  88. IEnumerable<IItemIdentityProvider> identityProviders, IEnumerable<IItemIdentityConverter> identityConverters,
  89. IEnumerable<IMetadataProvider> metadataProviders, IEnumerable<IMetadataSaver> metadataSavers,
  90. IEnumerable<IImageSaver> imageSavers, IEnumerable<IExternalId> externalIds)
  91. {
  92. ImageProviders = imageProviders.ToArray();
  93. _metadataServices = metadataServices.OrderBy(i => i.Order).ToArray();
  94. _identityProviders = identityProviders.ToArray();
  95. _identityConverters = identityConverters.ToArray();
  96. _metadataProviders = metadataProviders.ToArray();
  97. _imageSavers = imageSavers.ToArray();
  98. _externalIds = externalIds.OrderBy(i => i.Name).ToArray();
  99. _savers = metadataSavers.Where(i =>
  100. {
  101. var configurable = i as IConfigurableProvider;
  102. return configurable == null || configurable.IsEnabled;
  103. }).ToArray();
  104. }
  105. public Task<ItemUpdateType> RefreshSingleItem(IHasMetadata item, MetadataRefreshOptions options, CancellationToken cancellationToken)
  106. {
  107. var service = _metadataServices.FirstOrDefault(i => i.CanRefresh(item));
  108. if (service != null)
  109. {
  110. return service.RefreshMetadata(item, options, cancellationToken);
  111. }
  112. _logger.Error("Unable to find a metadata service for item of type " + item.GetType().Name);
  113. return Task.FromResult(ItemUpdateType.None);
  114. }
  115. public async Task SaveImage(IHasImages item, string url, SemaphoreSlim resourcePool, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  116. {
  117. var response = await _httpClient.GetResponse(new HttpRequestOptions
  118. {
  119. CancellationToken = cancellationToken,
  120. ResourcePool = resourcePool,
  121. Url = url
  122. }).ConfigureAwait(false);
  123. await SaveImage(item, response.Content, response.ContentType, type, imageIndex, cancellationToken)
  124. .ConfigureAwait(false);
  125. }
  126. public Task SaveImage(IHasImages item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  127. {
  128. return new ImageSaver(ConfigurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, source, mimeType, type, imageIndex, cancellationToken);
  129. }
  130. public Task SaveImage(IHasImages item, Stream source, string mimeType, ImageType type, int? imageIndex, string internalCacheKey, CancellationToken cancellationToken)
  131. {
  132. return new ImageSaver(ConfigurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, source, mimeType, type, imageIndex, internalCacheKey, cancellationToken);
  133. }
  134. public Task SaveImage(IHasImages item, string source, string mimeType, ImageType type, int? imageIndex, string internalCacheKey, CancellationToken cancellationToken)
  135. {
  136. if (string.IsNullOrWhiteSpace(source))
  137. {
  138. throw new ArgumentNullException("source");
  139. }
  140. var fileStream = _fileSystem.GetFileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  141. return new ImageSaver(ConfigurationManager, _libraryMonitor, _fileSystem, _logger).SaveImage(item, fileStream, mimeType, type, imageIndex, internalCacheKey, cancellationToken);
  142. }
  143. public async Task<IEnumerable<RemoteImageInfo>> GetAvailableRemoteImages(IHasImages item, RemoteImageQuery query, CancellationToken cancellationToken)
  144. {
  145. var providers = GetRemoteImageProviders(item, query.IncludeDisabledProviders);
  146. if (!string.IsNullOrEmpty(query.ProviderName))
  147. {
  148. var providerName = query.ProviderName;
  149. providers = providers.Where(i => string.Equals(i.Name, providerName, StringComparison.OrdinalIgnoreCase));
  150. }
  151. var preferredLanguage = item.GetPreferredMetadataLanguage();
  152. var languages = new List<string>();
  153. if (!query.IncludeAllLanguages && !string.IsNullOrWhiteSpace(preferredLanguage))
  154. {
  155. languages.Add(preferredLanguage);
  156. }
  157. var tasks = providers.Select(i => GetImages(item, cancellationToken, i, languages, query.ImageType));
  158. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  159. var images = results.SelectMany(i => i.ToList());
  160. return images;
  161. }
  162. /// <summary>
  163. /// Gets the images.
  164. /// </summary>
  165. /// <param name="item">The item.</param>
  166. /// <param name="cancellationToken">The cancellation token.</param>
  167. /// <param name="provider">The provider.</param>
  168. /// <param name="preferredLanguages">The preferred languages.</param>
  169. /// <param name="type">The type.</param>
  170. /// <returns>Task{IEnumerable{RemoteImageInfo}}.</returns>
  171. private async Task<IEnumerable<RemoteImageInfo>> GetImages(IHasImages item, CancellationToken cancellationToken, IRemoteImageProvider provider, List<string> preferredLanguages, ImageType? type = null)
  172. {
  173. try
  174. {
  175. var result = await provider.GetImages(item, cancellationToken).ConfigureAwait(false);
  176. if (type.HasValue)
  177. {
  178. result = result.Where(i => i.Type == type.Value);
  179. }
  180. if (preferredLanguages.Count > 0)
  181. {
  182. result = result.Where(i => string.IsNullOrEmpty(i.Language) ||
  183. preferredLanguages.Contains(i.Language, StringComparer.OrdinalIgnoreCase) ||
  184. string.Equals(i.Language, "en", StringComparison.OrdinalIgnoreCase));
  185. }
  186. return result;
  187. }
  188. catch (OperationCanceledException)
  189. {
  190. return new List<RemoteImageInfo>();
  191. }
  192. catch (Exception ex)
  193. {
  194. _logger.ErrorException("{0} failed in GetImageInfos for type {1}", ex, provider.GetType().Name, item.GetType().Name);
  195. return new List<RemoteImageInfo>();
  196. }
  197. }
  198. /// <summary>
  199. /// Gets the supported image providers.
  200. /// </summary>
  201. /// <param name="item">The item.</param>
  202. /// <returns>IEnumerable{IImageProvider}.</returns>
  203. public IEnumerable<ImageProviderInfo> GetRemoteImageProviderInfo(IHasImages item)
  204. {
  205. return GetRemoteImageProviders(item, true).Select(i => new ImageProviderInfo
  206. {
  207. Name = i.Name,
  208. SupportedImages = i.GetSupportedImages(item).ToList()
  209. });
  210. }
  211. public IEnumerable<IImageProvider> GetImageProviders(IHasImages item, ImageRefreshOptions refreshOptions)
  212. {
  213. return GetImageProviders(item, GetMetadataOptions(item), refreshOptions, false);
  214. }
  215. private IEnumerable<IImageProvider> GetImageProviders(IHasImages item, MetadataOptions options, ImageRefreshOptions refreshOptions, bool includeDisabled)
  216. {
  217. // Avoid implicitly captured closure
  218. var currentOptions = options;
  219. return ImageProviders.Where(i => CanRefresh(i, item, options, refreshOptions, includeDisabled))
  220. .OrderBy(i =>
  221. {
  222. // See if there's a user-defined order
  223. if (!(i is ILocalImageProvider))
  224. {
  225. var index = Array.IndexOf(currentOptions.ImageFetcherOrder, i.Name);
  226. if (index != -1)
  227. {
  228. return index;
  229. }
  230. }
  231. // Not configured. Just return some high number to put it at the end.
  232. return 100;
  233. })
  234. .ThenBy(GetOrder);
  235. }
  236. public IEnumerable<IMetadataProvider<T>> GetMetadataProviders<T>(IHasMetadata item)
  237. where T : IHasMetadata
  238. {
  239. var options = GetMetadataOptions(item);
  240. return GetMetadataProvidersInternal<T>(item, options, false, true);
  241. }
  242. private IEnumerable<IMetadataProvider<T>> GetMetadataProvidersInternal<T>(IHasMetadata item, MetadataOptions options, bool includeDisabled, bool checkIsOwnedItem)
  243. where T : IHasMetadata
  244. {
  245. // Avoid implicitly captured closure
  246. var currentOptions = options;
  247. return _metadataProviders.OfType<IMetadataProvider<T>>()
  248. .Where(i => CanRefresh(i, item, currentOptions, includeDisabled, checkIsOwnedItem))
  249. .OrderBy(i => GetConfiguredOrder(i, options))
  250. .ThenBy(GetDefaultOrder);
  251. }
  252. public IEnumerable<IItemIdentityProvider<TLookupInfo>> GetItemIdentityProviders<TLookupInfo>()
  253. where TLookupInfo : ItemLookupInfo
  254. {
  255. return _identityProviders.OfType<IItemIdentityProvider<TLookupInfo>>();
  256. }
  257. public IEnumerable<IItemIdentityConverter<TLookupInfo>> GetItemIdentityConverters<TLookupInfo>()
  258. where TLookupInfo : ItemLookupInfo
  259. {
  260. return _identityConverters.OfType<IItemIdentityConverter<TLookupInfo>>();
  261. }
  262. private IEnumerable<IRemoteImageProvider> GetRemoteImageProviders(IHasImages item, bool includeDisabled)
  263. {
  264. var options = GetMetadataOptions(item);
  265. return GetImageProviders(item, options, new ImageRefreshOptions(new DirectoryService(_fileSystem)), includeDisabled).OfType<IRemoteImageProvider>();
  266. }
  267. private bool CanRefresh(IMetadataProvider provider, IHasMetadata item, MetadataOptions options, bool includeDisabled, bool checkIsOwnedItem)
  268. {
  269. if (!includeDisabled)
  270. {
  271. // If locked only allow local providers
  272. if (item.IsLocked && !(provider is ILocalMetadataProvider) && !(provider is IForcedProvider))
  273. {
  274. return false;
  275. }
  276. if (provider is IRemoteMetadataProvider)
  277. {
  278. if (!item.IsInternetMetadataEnabled())
  279. {
  280. return false;
  281. }
  282. if (Array.IndexOf(options.DisabledMetadataFetchers, provider.Name) != -1)
  283. {
  284. return false;
  285. }
  286. }
  287. }
  288. if (!item.SupportsLocalMetadata && provider is ILocalMetadataProvider)
  289. {
  290. return false;
  291. }
  292. // If this restriction is ever lifted, movie xml providers will have to be updated to prevent owned items like trailers from reading those files
  293. if (checkIsOwnedItem && item.IsOwnedItem)
  294. {
  295. if (provider is ILocalMetadataProvider || provider is IRemoteMetadataProvider)
  296. {
  297. return false;
  298. }
  299. }
  300. return true;
  301. }
  302. private bool CanRefresh(IImageProvider provider, IHasImages item, MetadataOptions options, ImageRefreshOptions refreshOptions, bool includeDisabled)
  303. {
  304. if (!includeDisabled)
  305. {
  306. // If locked only allow local providers
  307. if (item.IsLocked && !(provider is ILocalImageProvider))
  308. {
  309. if (refreshOptions.ImageRefreshMode != ImageRefreshMode.FullRefresh)
  310. {
  311. return false;
  312. }
  313. }
  314. if (provider is IRemoteImageProvider || provider is IDynamicImageProvider)
  315. {
  316. if (Array.IndexOf(options.DisabledImageFetchers, provider.Name) != -1)
  317. {
  318. return false;
  319. }
  320. if (provider is IRemoteImageProvider)
  321. {
  322. if (!item.IsInternetMetadataEnabled())
  323. {
  324. return false;
  325. }
  326. }
  327. }
  328. }
  329. try
  330. {
  331. return provider.Supports(item);
  332. }
  333. catch (Exception ex)
  334. {
  335. _logger.ErrorException("{0} failed in Supports for type {1}", ex, provider.GetType().Name, item.GetType().Name);
  336. return false;
  337. }
  338. }
  339. /// <summary>
  340. /// Gets the order.
  341. /// </summary>
  342. /// <param name="provider">The provider.</param>
  343. /// <returns>System.Int32.</returns>
  344. private int GetOrder(IImageProvider provider)
  345. {
  346. var hasOrder = provider as IHasOrder;
  347. if (hasOrder == null)
  348. {
  349. return 0;
  350. }
  351. return hasOrder.Order;
  352. }
  353. private int GetConfiguredOrder(IMetadataProvider provider, MetadataOptions options)
  354. {
  355. // See if there's a user-defined order
  356. if (provider is ILocalMetadataProvider)
  357. {
  358. var index = Array.IndexOf(options.LocalMetadataReaderOrder, provider.Name);
  359. if (index != -1)
  360. {
  361. return index;
  362. }
  363. }
  364. // See if there's a user-defined order
  365. if (provider is IRemoteMetadataProvider)
  366. {
  367. var index = Array.IndexOf(options.MetadataFetcherOrder, provider.Name);
  368. if (index != -1)
  369. {
  370. return index;
  371. }
  372. }
  373. // Not configured. Just return some high number to put it at the end.
  374. return 100;
  375. }
  376. private int GetDefaultOrder(IMetadataProvider provider)
  377. {
  378. var hasOrder = provider as IHasOrder;
  379. if (hasOrder != null)
  380. {
  381. return hasOrder.Order;
  382. }
  383. return 0;
  384. }
  385. public IEnumerable<MetadataPluginSummary> GetAllMetadataPlugins()
  386. {
  387. var list = new List<MetadataPluginSummary>
  388. {
  389. GetPluginSummary<Game>(),
  390. GetPluginSummary<GameSystem>(),
  391. GetPluginSummary<Movie>(),
  392. GetPluginSummary<BoxSet>(),
  393. GetPluginSummary<Book>(),
  394. GetPluginSummary<Series>(),
  395. GetPluginSummary<Season>(),
  396. GetPluginSummary<Episode>(),
  397. GetPluginSummary<Person>(),
  398. GetPluginSummary<MusicAlbum>(),
  399. GetPluginSummary<MusicArtist>(),
  400. GetPluginSummary<Audio>(),
  401. GetPluginSummary<Genre>(),
  402. GetPluginSummary<Studio>(),
  403. GetPluginSummary<GameGenre>(),
  404. GetPluginSummary<MusicGenre>(),
  405. GetPluginSummary<MusicVideo>(),
  406. GetPluginSummary<Video>(),
  407. GetPluginSummary<LiveTvChannel>(),
  408. GetPluginSummary<LiveTvProgram>(),
  409. GetPluginSummary<LiveTvVideoRecording>(),
  410. GetPluginSummary<LiveTvAudioRecording>()
  411. };
  412. return list;
  413. }
  414. private MetadataPluginSummary GetPluginSummary<T>()
  415. where T : BaseItem, new()
  416. {
  417. // Give it a dummy path just so that it looks like a file system item
  418. var dummy = new T()
  419. {
  420. Path = Path.Combine(_appPaths.InternalMetadataPath, "dummy"),
  421. ParentId = Guid.NewGuid()
  422. };
  423. var options = GetMetadataOptions(dummy);
  424. var summary = new MetadataPluginSummary
  425. {
  426. ItemType = typeof(T).Name
  427. };
  428. var imageProviders = GetImageProviders(dummy, options, new ImageRefreshOptions(new DirectoryService(_fileSystem)), true).ToList();
  429. AddMetadataPlugins(summary.Plugins, dummy, options);
  430. AddImagePlugins(summary.Plugins, dummy, imageProviders);
  431. var supportedImageTypes = imageProviders.OfType<IRemoteImageProvider>()
  432. .SelectMany(i => i.GetSupportedImages(dummy))
  433. .ToList();
  434. supportedImageTypes.AddRange(imageProviders.OfType<IDynamicImageProvider>()
  435. .SelectMany(i => i.GetSupportedImages(dummy)));
  436. summary.SupportedImageTypes = supportedImageTypes.Distinct().ToList();
  437. return summary;
  438. }
  439. private void AddMetadataPlugins<T>(List<MetadataPlugin> list, T item, MetadataOptions options)
  440. where T : IHasMetadata
  441. {
  442. var providers = GetMetadataProvidersInternal<T>(item, options, true, false).ToList();
  443. // Locals
  444. list.AddRange(providers.Where(i => (i is ILocalMetadataProvider)).Select(i => new MetadataPlugin
  445. {
  446. Name = i.Name,
  447. Type = MetadataPluginType.LocalMetadataProvider
  448. }));
  449. if (item.IsInternetMetadataEnabled())
  450. {
  451. // Fetchers
  452. list.AddRange(providers.Where(i => (i is IRemoteMetadataProvider)).Select(i => new MetadataPlugin
  453. {
  454. Name = i.Name,
  455. Type = MetadataPluginType.MetadataFetcher
  456. }));
  457. }
  458. if (item.IsSaveLocalMetadataEnabled())
  459. {
  460. // Savers
  461. list.AddRange(_savers.Where(i => IsSaverEnabledForItem(i, item, ItemUpdateType.MetadataEdit, true)).OrderBy(i => i.Name).Select(i => new MetadataPlugin
  462. {
  463. Name = i.Name,
  464. Type = MetadataPluginType.MetadataSaver
  465. }));
  466. }
  467. }
  468. private void AddImagePlugins<T>(List<MetadataPlugin> list, T item, List<IImageProvider> imageProviders)
  469. where T : IHasImages
  470. {
  471. // Locals
  472. list.AddRange(imageProviders.Where(i => (i is ILocalImageProvider)).Select(i => new MetadataPlugin
  473. {
  474. Name = i.Name,
  475. Type = MetadataPluginType.LocalImageProvider
  476. }));
  477. var enableInternet = item.IsInternetMetadataEnabled();
  478. // Fetchers
  479. list.AddRange(imageProviders.Where(i => i is IDynamicImageProvider || (enableInternet && i is IRemoteImageProvider)).Select(i => new MetadataPlugin
  480. {
  481. Name = i.Name,
  482. Type = MetadataPluginType.ImageFetcher
  483. }));
  484. }
  485. public MetadataOptions GetMetadataOptions(IHasImages item)
  486. {
  487. var type = item.GetType().Name;
  488. return ConfigurationManager.Configuration.MetadataOptions
  489. .FirstOrDefault(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase)) ??
  490. new MetadataOptions();
  491. }
  492. private readonly ConcurrentDictionary<string, SemaphoreSlim> _fileLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  493. /// <summary>
  494. /// Saves the metadata.
  495. /// </summary>
  496. /// <param name="item">The item.</param>
  497. /// <param name="updateType">Type of the update.</param>
  498. /// <returns>Task.</returns>
  499. public Task SaveMetadata(IHasMetadata item, ItemUpdateType updateType)
  500. {
  501. return SaveMetadata(item, updateType, _savers);
  502. }
  503. /// <summary>
  504. /// Saves the metadata.
  505. /// </summary>
  506. /// <param name="item">The item.</param>
  507. /// <param name="updateType">Type of the update.</param>
  508. /// <param name="savers">The savers.</param>
  509. /// <returns>Task.</returns>
  510. public Task SaveMetadata(IHasMetadata item, ItemUpdateType updateType, IEnumerable<string> savers)
  511. {
  512. return SaveMetadata(item, updateType, _savers.Where(i => savers.Contains(i.Name, StringComparer.OrdinalIgnoreCase)));
  513. }
  514. /// <summary>
  515. /// Saves the metadata.
  516. /// </summary>
  517. /// <param name="item">The item.</param>
  518. /// <param name="updateType">Type of the update.</param>
  519. /// <param name="savers">The savers.</param>
  520. /// <returns>Task.</returns>
  521. private async Task SaveMetadata(IHasMetadata item, ItemUpdateType updateType, IEnumerable<IMetadataSaver> savers)
  522. {
  523. foreach (var saver in savers.Where(i => IsSaverEnabledForItem(i, item, updateType, false)))
  524. {
  525. _logger.Debug("Saving {0} to {1}.", item.Path ?? item.Name, saver.Name);
  526. var fileSaver = saver as IMetadataFileSaver;
  527. if (fileSaver != null)
  528. {
  529. string path = null;
  530. try
  531. {
  532. path = fileSaver.GetSavePath(item);
  533. }
  534. catch (Exception ex)
  535. {
  536. _logger.ErrorException("Error in {0} GetSavePath", ex, saver.Name);
  537. continue;
  538. }
  539. var semaphore = _fileLocks.GetOrAdd(path, key => new SemaphoreSlim(1, 1));
  540. await semaphore.WaitAsync().ConfigureAwait(false);
  541. try
  542. {
  543. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  544. saver.Save(item, CancellationToken.None);
  545. }
  546. catch (Exception ex)
  547. {
  548. _logger.ErrorException("Error in metadata saver", ex);
  549. }
  550. finally
  551. {
  552. _libraryMonitor.ReportFileSystemChangeComplete(path, false);
  553. semaphore.Release();
  554. }
  555. }
  556. else
  557. {
  558. try
  559. {
  560. saver.Save(item, CancellationToken.None);
  561. }
  562. catch (Exception ex)
  563. {
  564. _logger.ErrorException("Error in metadata saver", ex);
  565. }
  566. }
  567. }
  568. }
  569. /// <summary>
  570. /// Determines whether [is saver enabled for item] [the specified saver].
  571. /// </summary>
  572. /// <param name="saver">The saver.</param>
  573. /// <param name="item">The item.</param>
  574. /// <param name="updateType">Type of the update.</param>
  575. /// <param name="includeDisabled">if set to <c>true</c> [include disabled].</param>
  576. /// <returns><c>true</c> if [is saver enabled for item] [the specified saver]; otherwise, <c>false</c>.</returns>
  577. private bool IsSaverEnabledForItem(IMetadataSaver saver, IHasMetadata item, ItemUpdateType updateType, bool includeDisabled)
  578. {
  579. var options = GetMetadataOptions(item);
  580. try
  581. {
  582. var isEnabledFor = saver.IsEnabledFor(item, updateType);
  583. if (!includeDisabled)
  584. {
  585. if (options.DisabledMetadataSavers.Contains(saver.Name, StringComparer.OrdinalIgnoreCase))
  586. {
  587. return false;
  588. }
  589. if (!item.IsSaveLocalMetadataEnabled())
  590. {
  591. if (updateType >= ItemUpdateType.MetadataEdit)
  592. {
  593. var fileSaver = saver as IMetadataFileSaver;
  594. // Manual edit occurred
  595. // Even if save local is off, save locally anyway if the metadata file already exists
  596. if (fileSaver == null || !isEnabledFor || !_fileSystem.FileExists(fileSaver.GetSavePath(item)))
  597. {
  598. return false;
  599. }
  600. }
  601. else
  602. {
  603. // Manual edit did not occur
  604. // Since local metadata saving is disabled, consider it disabled
  605. return false;
  606. }
  607. }
  608. }
  609. return isEnabledFor;
  610. }
  611. catch (Exception ex)
  612. {
  613. _logger.ErrorException("Error in {0}.IsEnabledFor", ex, saver.Name);
  614. return false;
  615. }
  616. }
  617. public async Task<IEnumerable<RemoteSearchResult>> GetRemoteSearchResults<TItemType, TLookupType>(RemoteSearchQuery<TLookupType> searchInfo,
  618. CancellationToken cancellationToken)
  619. where TItemType : BaseItem, new()
  620. where TLookupType : ItemLookupInfo
  621. {
  622. const int maxResults = 10;
  623. // Give it a dummy path just so that it looks like a file system item
  624. var dummy = new TItemType
  625. {
  626. Path = Path.Combine(_appPaths.InternalMetadataPath, "dummy"),
  627. ParentId = Guid.NewGuid()
  628. };
  629. dummy.SetParent(new Folder());
  630. var options = GetMetadataOptions(dummy);
  631. var providers = GetMetadataProvidersInternal<TItemType>(dummy, options, searchInfo.IncludeDisabledProviders, false)
  632. .OfType<IRemoteSearchProvider<TLookupType>>();
  633. if (!string.IsNullOrEmpty(searchInfo.SearchProviderName))
  634. {
  635. providers = providers.Where(i => string.Equals(i.Name, searchInfo.SearchProviderName, StringComparison.OrdinalIgnoreCase));
  636. }
  637. if (string.IsNullOrWhiteSpace(searchInfo.SearchInfo.MetadataLanguage))
  638. {
  639. searchInfo.SearchInfo.MetadataLanguage = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  640. }
  641. if (string.IsNullOrWhiteSpace(searchInfo.SearchInfo.MetadataCountryCode))
  642. {
  643. searchInfo.SearchInfo.MetadataCountryCode = ConfigurationManager.Configuration.MetadataCountryCode;
  644. }
  645. var resultList = new List<RemoteSearchResult>();
  646. var foundProviderIds = new Dictionary<Tuple<string, string>, RemoteSearchResult>();
  647. foreach (var provider in providers)
  648. {
  649. try
  650. {
  651. var results = await GetSearchResults(provider, searchInfo.SearchInfo, cancellationToken).ConfigureAwait(false);
  652. foreach (var result in results)
  653. {
  654. var bFound = false;
  655. // This check prevents duplicate search results by comparing provider ids
  656. foreach (var providerId in result.ProviderIds)
  657. {
  658. var idTuple = new Tuple<string, string>(providerId.Key.ToLower(), providerId.Value.ToLower());
  659. if (!foundProviderIds.ContainsKey(idTuple))
  660. {
  661. foundProviderIds.Add(idTuple, result);
  662. }
  663. else
  664. {
  665. bFound = true;
  666. var existingResult = foundProviderIds[idTuple];
  667. if (string.IsNullOrEmpty(existingResult.ImageUrl) && !string.IsNullOrEmpty(result.ImageUrl))
  668. {
  669. existingResult.ImageUrl = result.ImageUrl;
  670. }
  671. }
  672. }
  673. if (!bFound && resultList.Count < maxResults)
  674. {
  675. resultList.Add(result);
  676. }
  677. }
  678. }
  679. catch (Exception ex)
  680. {
  681. // Logged at lower levels
  682. }
  683. }
  684. return resultList;
  685. }
  686. private async Task<IEnumerable<RemoteSearchResult>> GetSearchResults<TLookupType>(IRemoteSearchProvider<TLookupType> provider, TLookupType searchInfo,
  687. CancellationToken cancellationToken)
  688. where TLookupType : ItemLookupInfo
  689. {
  690. var results = await provider.GetSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
  691. var list = results.ToList();
  692. foreach (var item in list)
  693. {
  694. item.SearchProviderName = provider.Name;
  695. }
  696. return list;
  697. }
  698. public Task<HttpResponseInfo> GetSearchImage(string providerName, string url, CancellationToken cancellationToken)
  699. {
  700. var provider = _metadataProviders.OfType<IRemoteSearchProvider>().FirstOrDefault(i => string.Equals(i.Name, providerName, StringComparison.OrdinalIgnoreCase));
  701. if (provider == null)
  702. {
  703. throw new ArgumentException("Search provider not found.");
  704. }
  705. return provider.GetImageResponse(url, cancellationToken);
  706. }
  707. public IEnumerable<IExternalId> GetExternalIds(IHasProviderIds item)
  708. {
  709. return _externalIds.Where(i =>
  710. {
  711. try
  712. {
  713. return i.Supports(item);
  714. }
  715. catch (Exception ex)
  716. {
  717. _logger.ErrorException("Error in {0}.Suports", ex, i.GetType().Name);
  718. return false;
  719. }
  720. });
  721. }
  722. public IEnumerable<ExternalUrl> GetExternalUrls(IHasProviderIds item)
  723. {
  724. return GetExternalIds(item)
  725. .Select(i =>
  726. {
  727. if (string.IsNullOrEmpty(i.UrlFormatString))
  728. {
  729. return null;
  730. }
  731. var value = item.GetProviderId(i.Key);
  732. if (string.IsNullOrEmpty(value))
  733. {
  734. return null;
  735. }
  736. return new ExternalUrl
  737. {
  738. Name = i.Name,
  739. Url = string.Format(i.UrlFormatString, value)
  740. };
  741. }).Where(i => i != null);
  742. }
  743. public IEnumerable<ExternalIdInfo> GetExternalIdInfos(IHasProviderIds item)
  744. {
  745. return GetExternalIds(item)
  746. .Select(i => new ExternalIdInfo
  747. {
  748. Name = i.Name,
  749. Key = i.Key,
  750. UrlFormatString = i.UrlFormatString
  751. });
  752. }
  753. private readonly ConcurrentQueue<Tuple<Guid, MetadataRefreshOptions>> _refreshQueue =
  754. new ConcurrentQueue<Tuple<Guid, MetadataRefreshOptions>>();
  755. private readonly object _refreshTimerLock = new object();
  756. private Timer _refreshTimer;
  757. public void QueueRefresh(Guid id, MetadataRefreshOptions options)
  758. {
  759. if (_disposed)
  760. {
  761. return;
  762. }
  763. _refreshQueue.Enqueue(new Tuple<Guid, MetadataRefreshOptions>(id, options));
  764. StartRefreshTimer();
  765. }
  766. private void StartRefreshTimer()
  767. {
  768. if (_disposed)
  769. {
  770. return;
  771. }
  772. lock (_refreshTimerLock)
  773. {
  774. if (_refreshTimer == null)
  775. {
  776. _refreshTimer = new Timer(RefreshTimerCallback, null, 100, Timeout.Infinite);
  777. }
  778. }
  779. }
  780. private void StopRefreshTimer()
  781. {
  782. lock (_refreshTimerLock)
  783. {
  784. if (_refreshTimer != null)
  785. {
  786. _refreshTimer.Dispose();
  787. _refreshTimer = null;
  788. }
  789. }
  790. }
  791. private async void RefreshTimerCallback(object state)
  792. {
  793. Tuple<Guid, MetadataRefreshOptions> refreshItem;
  794. var libraryManager = _libraryManagerFactory();
  795. while (_refreshQueue.TryDequeue(out refreshItem))
  796. {
  797. if (_disposed)
  798. {
  799. return;
  800. }
  801. try
  802. {
  803. var item = libraryManager.GetItemById(refreshItem.Item1);
  804. if (item != null)
  805. {
  806. // Try to throttle this a little bit.
  807. await Task.Delay(100).ConfigureAwait(false);
  808. var artist = item as MusicArtist;
  809. var task = artist == null
  810. ? RefreshItem(item, refreshItem.Item2, CancellationToken.None)
  811. : RefreshArtist(artist, refreshItem.Item2);
  812. await task.ConfigureAwait(false);
  813. }
  814. }
  815. catch (Exception ex)
  816. {
  817. _logger.ErrorException("Error refreshing item", ex);
  818. }
  819. }
  820. StopRefreshTimer();
  821. }
  822. private async Task RefreshItem(BaseItem item, MetadataRefreshOptions options, CancellationToken cancellationToken)
  823. {
  824. await item.RefreshMetadata(options, CancellationToken.None).ConfigureAwait(false);
  825. if (item.IsFolder)
  826. {
  827. // Collection folders don't validate their children so we'll have to simulate that here
  828. var collectionFolder = item as CollectionFolder;
  829. if (collectionFolder != null)
  830. {
  831. await RefreshCollectionFolderChildren(options, collectionFolder).ConfigureAwait(false);
  832. }
  833. else
  834. {
  835. var folder = (Folder)item;
  836. await folder.ValidateChildren(new Progress<double>(), cancellationToken, options).ConfigureAwait(false);
  837. }
  838. }
  839. }
  840. private async Task RefreshCollectionFolderChildren(MetadataRefreshOptions options, CollectionFolder collectionFolder)
  841. {
  842. foreach (var child in collectionFolder.Children.ToList())
  843. {
  844. await child.RefreshMetadata(options, CancellationToken.None).ConfigureAwait(false);
  845. if (child.IsFolder)
  846. {
  847. var folder = (Folder)child;
  848. await folder.ValidateChildren(new Progress<double>(), CancellationToken.None, options, true).ConfigureAwait(false);
  849. }
  850. }
  851. }
  852. private async Task RefreshArtist(MusicArtist item, MetadataRefreshOptions options)
  853. {
  854. var cancellationToken = CancellationToken.None;
  855. var albums = _libraryManagerFactory().RootFolder
  856. .GetRecursiveChildren()
  857. .OfType<MusicAlbum>()
  858. .Where(i => i.HasAnyArtist(item.Name))
  859. .ToList();
  860. var musicArtists = albums
  861. .Select(i => i.MusicArtist)
  862. .Where(i => i != null)
  863. .ToList();
  864. var musicArtistRefreshTasks = musicArtists.Select(i => i.ValidateChildren(new Progress<double>(), cancellationToken, options, true));
  865. await Task.WhenAll(musicArtistRefreshTasks).ConfigureAwait(false);
  866. try
  867. {
  868. await item.RefreshMetadata(options, CancellationToken.None).ConfigureAwait(false);
  869. }
  870. catch (Exception ex)
  871. {
  872. _logger.ErrorException("Error refreshing library", ex);
  873. }
  874. }
  875. public Task RefreshFullItem(IHasMetadata item, MetadataRefreshOptions options,
  876. CancellationToken cancellationToken)
  877. {
  878. return RefreshItem((BaseItem)item, options, cancellationToken);
  879. }
  880. private bool _disposed;
  881. public void Dispose()
  882. {
  883. _disposed = true;
  884. StopRefreshTimer();
  885. }
  886. }
  887. }