ItemImageProvider.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. #nullable disable
  2. using System;
  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.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Entities.Audio;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.LiveTv;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.MediaInfo;
  19. using MediaBrowser.Model.Net;
  20. using MediaBrowser.Model.Providers;
  21. using Microsoft.Extensions.Logging;
  22. namespace MediaBrowser.Providers.Manager
  23. {
  24. /// <summary>
  25. /// Utilities for managing images attached to items.
  26. /// </summary>
  27. public class ItemImageProvider
  28. {
  29. private readonly ILogger _logger;
  30. private readonly IProviderManager _providerManager;
  31. private readonly IFileSystem _fileSystem;
  32. /// <summary>
  33. /// Image types that are only one per item.
  34. /// </summary>
  35. private static readonly ImageType[] _singularImages =
  36. {
  37. ImageType.Primary,
  38. ImageType.Art,
  39. ImageType.Banner,
  40. ImageType.Box,
  41. ImageType.BoxRear,
  42. ImageType.Disc,
  43. ImageType.Logo,
  44. ImageType.Menu,
  45. ImageType.Thumb
  46. };
  47. /// <summary>
  48. /// Initializes a new instance of the <see cref="ItemImageProvider"/> class.
  49. /// </summary>
  50. /// <param name="logger">The logger.</param>
  51. /// <param name="providerManager">The provider manager for interacting with provider image references.</param>
  52. /// <param name="fileSystem">The filesystem.</param>
  53. public ItemImageProvider(ILogger logger, IProviderManager providerManager, IFileSystem fileSystem)
  54. {
  55. _logger = logger;
  56. _providerManager = providerManager;
  57. _fileSystem = fileSystem;
  58. }
  59. /// <summary>
  60. /// Verifies existing images have valid paths and adds any new local images provided.
  61. /// </summary>
  62. /// <param name="item">The <see cref="BaseItem"/> to validate images for.</param>
  63. /// <param name="providers">The providers to use, must include <see cref="ILocalImageProvider"/>(s) for local scanning.</param>
  64. /// <param name="directoryService">The directory service for <see cref="ILocalImageProvider"/>s to use.</param>
  65. /// <returns><c>true</c> if changes were made to the item; otherwise <c>false</c>.</returns>
  66. public bool ValidateImages(BaseItem item, IEnumerable<IImageProvider> providers, IDirectoryService directoryService)
  67. {
  68. var hasChanges = false;
  69. if (item is not Photo)
  70. {
  71. var images = providers.OfType<ILocalImageProvider>()
  72. .SelectMany(i => i.GetImages(item, directoryService))
  73. .ToList();
  74. if (MergeImages(item, images))
  75. {
  76. hasChanges = true;
  77. }
  78. }
  79. return hasChanges;
  80. }
  81. /// <summary>
  82. /// Refreshes from the providers according to the given options.
  83. /// </summary>
  84. /// <param name="item">The <see cref="BaseItem"/> to gather images for.</param>
  85. /// <param name="libraryOptions">The library options.</param>
  86. /// <param name="providers">The providers to query for images.</param>
  87. /// <param name="refreshOptions">The refresh options.</param>
  88. /// <param name="cancellationToken">The cancellation token.</param>
  89. /// <returns>The refresh result.</returns>
  90. public async Task<RefreshResult> RefreshImages(
  91. BaseItem item,
  92. LibraryOptions libraryOptions,
  93. List<IImageProvider> providers,
  94. ImageRefreshOptions refreshOptions,
  95. CancellationToken cancellationToken)
  96. {
  97. var oldBackdropImages = Array.Empty<ItemImageInfo>();
  98. if (refreshOptions.IsReplacingImage(ImageType.Backdrop))
  99. {
  100. oldBackdropImages = item.GetImages(ImageType.Backdrop).ToArray();
  101. }
  102. var result = new RefreshResult { UpdateType = ItemUpdateType.None };
  103. var typeName = item.GetType().Name;
  104. var typeOptions = libraryOptions.GetTypeOptions(typeName) ?? new TypeOptions { Type = typeName };
  105. // track library limits, adding buffer to allow lazy replacing of current images
  106. var backdropLimit = typeOptions.GetLimit(ImageType.Backdrop) + oldBackdropImages.Length;
  107. var downloadedImages = new List<ImageType>();
  108. foreach (var provider in providers)
  109. {
  110. if (provider is IRemoteImageProvider remoteProvider)
  111. {
  112. await RefreshFromProvider(item, remoteProvider, refreshOptions, typeOptions, backdropLimit, downloadedImages, result, cancellationToken).ConfigureAwait(false);
  113. continue;
  114. }
  115. if (provider is IDynamicImageProvider dynamicImageProvider)
  116. {
  117. await RefreshFromProvider(item, dynamicImageProvider, refreshOptions, typeOptions, downloadedImages, result, cancellationToken).ConfigureAwait(false);
  118. }
  119. }
  120. // only delete existing multi-images if new ones were added
  121. if (oldBackdropImages.Length > 0 && oldBackdropImages.Length < item.GetImages(ImageType.Backdrop).Count())
  122. {
  123. PruneImages(item, oldBackdropImages);
  124. }
  125. return result;
  126. }
  127. /// <summary>
  128. /// Refreshes from a dynamic provider.
  129. /// </summary>
  130. private async Task RefreshFromProvider(
  131. BaseItem item,
  132. IDynamicImageProvider provider,
  133. ImageRefreshOptions refreshOptions,
  134. TypeOptions savedOptions,
  135. ICollection<ImageType> downloadedImages,
  136. RefreshResult result,
  137. CancellationToken cancellationToken)
  138. {
  139. try
  140. {
  141. var images = provider.GetSupportedImages(item);
  142. foreach (var imageType in images)
  143. {
  144. if (!IsEnabled(savedOptions, imageType))
  145. {
  146. continue;
  147. }
  148. if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType)))
  149. {
  150. _logger.LogDebug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);
  151. var response = await provider.GetImage(item, imageType, cancellationToken).ConfigureAwait(false);
  152. if (response.HasImage)
  153. {
  154. if (!string.IsNullOrEmpty(response.Path))
  155. {
  156. if (response.Protocol == MediaProtocol.Http)
  157. {
  158. _logger.LogDebug("Setting image url into item {0}", item.Id);
  159. var index = item.AllowsMultipleImages(imageType) ? item.GetImages(imageType).Count() : 0;
  160. item.SetImage(
  161. new ItemImageInfo
  162. {
  163. Path = response.Path,
  164. Type = imageType
  165. },
  166. index);
  167. }
  168. else
  169. {
  170. var mimeType = MimeTypes.GetMimeType(response.Path);
  171. var stream = AsyncFile.OpenRead(response.Path);
  172. await _providerManager.SaveImage(item, stream, mimeType, imageType, null, cancellationToken).ConfigureAwait(false);
  173. }
  174. }
  175. else
  176. {
  177. var mimeType = "image/" + response.Format.ToString().ToLowerInvariant();
  178. await _providerManager.SaveImage(item, response.Stream, mimeType, imageType, null, cancellationToken).ConfigureAwait(false);
  179. }
  180. downloadedImages.Add(imageType);
  181. result.UpdateType |= ItemUpdateType.ImageUpdate;
  182. }
  183. }
  184. }
  185. }
  186. catch (OperationCanceledException)
  187. {
  188. throw;
  189. }
  190. catch (Exception ex)
  191. {
  192. result.ErrorMessage = ex.Message;
  193. _logger.LogError(ex, "Error in {Provider}", provider.Name);
  194. }
  195. }
  196. private bool HasImage(BaseItem item, ImageType type)
  197. {
  198. return item.HasImage(type);
  199. }
  200. /// <summary>
  201. /// Determines if an item already contains the given images.
  202. /// </summary>
  203. /// <param name="item">The item.</param>
  204. /// <param name="images">The images.</param>
  205. /// <param name="savedOptions">The saved options.</param>
  206. /// <param name="backdropLimit">The backdrop limit.</param>
  207. /// <returns><c>true</c> if the specified item contains images; otherwise, <c>false</c>.</returns>
  208. private bool ContainsImages(BaseItem item, List<ImageType> images, TypeOptions savedOptions, int backdropLimit)
  209. {
  210. // Using .Any causes the creation of a DisplayClass aka. variable capture
  211. for (var i = 0; i < _singularImages.Length; i++)
  212. {
  213. var type = _singularImages[i];
  214. if (images.Contains(type) && !HasImage(item, type) && savedOptions.GetLimit(type) > 0)
  215. {
  216. return false;
  217. }
  218. }
  219. if (images.Contains(ImageType.Backdrop) && item.GetImages(ImageType.Backdrop).Count() < backdropLimit)
  220. {
  221. return false;
  222. }
  223. return true;
  224. }
  225. /// <summary>
  226. /// Refreshes from a remote provider.
  227. /// </summary>
  228. /// <param name="item">The item.</param>
  229. /// <param name="provider">The provider.</param>
  230. /// <param name="refreshOptions">The refresh options.</param>
  231. /// <param name="savedOptions">The saved options.</param>
  232. /// <param name="backdropLimit">The backdrop limit.</param>
  233. /// <param name="downloadedImages">The downloaded images.</param>
  234. /// <param name="result">The result.</param>
  235. /// <param name="cancellationToken">The cancellation token.</param>
  236. /// <returns>Task.</returns>
  237. private async Task RefreshFromProvider(
  238. BaseItem item,
  239. IRemoteImageProvider provider,
  240. ImageRefreshOptions refreshOptions,
  241. TypeOptions savedOptions,
  242. int backdropLimit,
  243. ICollection<ImageType> downloadedImages,
  244. RefreshResult result,
  245. CancellationToken cancellationToken)
  246. {
  247. try
  248. {
  249. if (!item.SupportsRemoteImageDownloading)
  250. {
  251. return;
  252. }
  253. if (!refreshOptions.ReplaceAllImages &&
  254. refreshOptions.ReplaceImages.Length == 0 &&
  255. ContainsImages(item, provider.GetSupportedImages(item).ToList(), savedOptions, backdropLimit))
  256. {
  257. return;
  258. }
  259. _logger.LogDebug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);
  260. var images = await _providerManager.GetAvailableRemoteImages(
  261. item,
  262. new RemoteImageQuery(provider.Name)
  263. {
  264. IncludeAllLanguages = true,
  265. IncludeDisabledProviders = false,
  266. },
  267. cancellationToken).ConfigureAwait(false);
  268. var list = images.ToList();
  269. int minWidth;
  270. foreach (var imageType in _singularImages)
  271. {
  272. if (!IsEnabled(savedOptions, imageType))
  273. {
  274. continue;
  275. }
  276. if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType)))
  277. {
  278. minWidth = savedOptions.GetMinWidth(imageType);
  279. var downloaded = await DownloadImage(item, provider, result, list, minWidth, imageType, cancellationToken).ConfigureAwait(false);
  280. if (downloaded)
  281. {
  282. downloadedImages.Add(imageType);
  283. }
  284. }
  285. }
  286. minWidth = savedOptions.GetMinWidth(ImageType.Backdrop);
  287. await DownloadMultiImages(item, ImageType.Backdrop, refreshOptions, backdropLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false);
  288. }
  289. catch (OperationCanceledException)
  290. {
  291. throw;
  292. }
  293. catch (Exception ex)
  294. {
  295. result.ErrorMessage = ex.Message;
  296. _logger.LogError(ex, "Error in {Provider}", provider.Name);
  297. }
  298. }
  299. private bool IsEnabled(TypeOptions options, ImageType type)
  300. {
  301. return options.IsEnabled(type);
  302. }
  303. private void PruneImages(BaseItem item, ItemImageInfo[] images)
  304. {
  305. for (var i = 0; i < images.Length; i++)
  306. {
  307. var image = images[i];
  308. if (image.IsLocalFile)
  309. {
  310. try
  311. {
  312. _fileSystem.DeleteFile(image.Path);
  313. }
  314. catch (FileNotFoundException)
  315. {
  316. }
  317. }
  318. }
  319. item.RemoveImages(images);
  320. }
  321. /// <summary>
  322. /// Merges a list of images into the provided item, validating existing images and replacing them or adding new images as necessary.
  323. /// </summary>
  324. /// <param name="item">The <see cref="BaseItem"/> to modify.</param>
  325. /// <param name="images">The new images to place in <c>item</c>.</param>
  326. /// <returns><c>true</c> if changes were made to the item; otherwise <c>false</c>.</returns>
  327. public bool MergeImages(BaseItem item, IReadOnlyList<LocalImageInfo> images)
  328. {
  329. var changed = item.ValidateImages(new DirectoryService(_fileSystem));
  330. for (var i = 0; i < _singularImages.Length; i++)
  331. {
  332. var type = _singularImages[i];
  333. var image = GetFirstLocalImageInfoByType(images, type);
  334. if (image != null)
  335. {
  336. var currentImage = item.GetImageInfo(type, 0);
  337. if (currentImage == null)
  338. {
  339. item.SetImagePath(type, image.FileInfo);
  340. changed = true;
  341. }
  342. else if (!string.Equals(currentImage.Path, image.FileInfo.FullName, StringComparison.OrdinalIgnoreCase))
  343. {
  344. item.SetImagePath(type, image.FileInfo);
  345. changed = true;
  346. }
  347. else
  348. {
  349. var newDateModified = _fileSystem.GetLastWriteTimeUtc(image.FileInfo);
  350. // If date changed then we need to reset saved image dimensions
  351. if (currentImage.DateModified != newDateModified && (currentImage.Width > 0 || currentImage.Height > 0))
  352. {
  353. currentImage.Width = 0;
  354. currentImage.Height = 0;
  355. changed = true;
  356. }
  357. currentImage.DateModified = newDateModified;
  358. }
  359. }
  360. }
  361. if (UpdateMultiImages(item, images, ImageType.Backdrop))
  362. {
  363. changed = true;
  364. }
  365. return changed;
  366. }
  367. private static LocalImageInfo GetFirstLocalImageInfoByType(IReadOnlyList<LocalImageInfo> images, ImageType type)
  368. {
  369. var len = images.Count;
  370. for (var i = 0; i < len; i++)
  371. {
  372. var image = images[i];
  373. if (image.Type == type)
  374. {
  375. return image;
  376. }
  377. }
  378. return null;
  379. }
  380. private bool UpdateMultiImages(BaseItem item, IReadOnlyList<LocalImageInfo> images, ImageType type)
  381. {
  382. var changed = false;
  383. var newImageFileInfos = images
  384. .Where(i => i.Type == type)
  385. .Select(i => i.FileInfo)
  386. .ToList();
  387. if (item.AddImages(type, newImageFileInfos))
  388. {
  389. changed = true;
  390. }
  391. return changed;
  392. }
  393. private async Task<bool> DownloadImage(
  394. BaseItem item,
  395. IRemoteImageProvider provider,
  396. RefreshResult result,
  397. IEnumerable<RemoteImageInfo> images,
  398. int minWidth,
  399. ImageType type,
  400. CancellationToken cancellationToken)
  401. {
  402. var eligibleImages = images
  403. .Where(i => i.Type == type && i.Width >= minWidth)
  404. .ToList();
  405. if (EnableImageStub(item) && eligibleImages.Count > 0)
  406. {
  407. SaveImageStub(item, type, eligibleImages.Select(i => i.Url));
  408. result.UpdateType |= ItemUpdateType.ImageUpdate;
  409. return true;
  410. }
  411. foreach (var image in eligibleImages)
  412. {
  413. var url = image.Url;
  414. try
  415. {
  416. using var response = await provider.GetImageResponse(url, cancellationToken).ConfigureAwait(false);
  417. // Sometimes providers send back bad urls. Just move to the next image
  418. if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Forbidden)
  419. {
  420. _logger.LogDebug("{Url} returned {StatusCode}, ignoring", url, response.StatusCode);
  421. continue;
  422. }
  423. if (!response.IsSuccessStatusCode)
  424. {
  425. _logger.LogWarning("{Url} returned {StatusCode}, skipping all remaining requests", url, response.StatusCode);
  426. break;
  427. }
  428. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  429. await _providerManager.SaveImage(
  430. item,
  431. stream,
  432. response.Content.Headers.ContentType.MediaType,
  433. type,
  434. null,
  435. cancellationToken).ConfigureAwait(false);
  436. result.UpdateType |= ItemUpdateType.ImageUpdate;
  437. return true;
  438. }
  439. catch (HttpRequestException)
  440. {
  441. break;
  442. }
  443. }
  444. return false;
  445. }
  446. private bool EnableImageStub(BaseItem item)
  447. {
  448. if (item is LiveTvProgram)
  449. {
  450. return true;
  451. }
  452. if (!item.IsFileProtocol)
  453. {
  454. return true;
  455. }
  456. if (item is IItemByName and not MusicArtist)
  457. {
  458. var hasDualAccess = item as IHasDualAccess;
  459. if (hasDualAccess == null || hasDualAccess.IsAccessedByName)
  460. {
  461. return true;
  462. }
  463. }
  464. // We always want to use prefetched images
  465. return false;
  466. }
  467. private void SaveImageStub(BaseItem item, ImageType imageType, IEnumerable<string> urls)
  468. {
  469. var newIndex = item.AllowsMultipleImages(imageType) ? item.GetImages(imageType).Count() : 0;
  470. SaveImageStub(item, imageType, urls, newIndex);
  471. }
  472. private void SaveImageStub(BaseItem item, ImageType imageType, IEnumerable<string> urls, int newIndex)
  473. {
  474. var path = string.Join('|', urls.Take(1));
  475. item.SetImage(
  476. new ItemImageInfo
  477. {
  478. Path = path,
  479. Type = imageType
  480. },
  481. newIndex);
  482. }
  483. private async Task DownloadMultiImages(BaseItem item, ImageType imageType, ImageRefreshOptions refreshOptions, int limit, IRemoteImageProvider provider, RefreshResult result, IEnumerable<RemoteImageInfo> images, int minWidth, CancellationToken cancellationToken)
  484. {
  485. foreach (var image in images.Where(i => i.Type == imageType))
  486. {
  487. if (item.GetImages(imageType).Count() >= limit)
  488. {
  489. break;
  490. }
  491. if (image.Width.HasValue && image.Width.Value < minWidth)
  492. {
  493. continue;
  494. }
  495. var url = image.Url;
  496. if (EnableImageStub(item))
  497. {
  498. SaveImageStub(item, imageType, new[] { url });
  499. result.UpdateType |= ItemUpdateType.ImageUpdate;
  500. continue;
  501. }
  502. try
  503. {
  504. using var response = await provider.GetImageResponse(url, cancellationToken).ConfigureAwait(false);
  505. // Sometimes providers send back bad urls. Just move to the next image
  506. if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Forbidden)
  507. {
  508. _logger.LogDebug("{Url} returned {StatusCode}, ignoring", url, response.StatusCode);
  509. continue;
  510. }
  511. if (!response.IsSuccessStatusCode)
  512. {
  513. _logger.LogWarning("{Url} returned {StatusCode}, skipping all remaining requests", url, response.StatusCode);
  514. break;
  515. }
  516. // If there's already an image of the same file size, skip it unless doing a full refresh
  517. if (response.Content.Headers.ContentLength.HasValue && !refreshOptions.IsReplacingImage(imageType))
  518. {
  519. try
  520. {
  521. if (item.GetImages(imageType).Any(i => _fileSystem.GetFileInfo(i.Path).Length == response.Content.Headers.ContentLength.Value))
  522. {
  523. response.Content.Dispose();
  524. continue;
  525. }
  526. }
  527. catch (IOException ex)
  528. {
  529. _logger.LogError(ex, "Error examining images");
  530. }
  531. }
  532. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  533. await _providerManager.SaveImage(
  534. item,
  535. stream,
  536. response.Content.Headers.ContentType.MediaType,
  537. imageType,
  538. null,
  539. cancellationToken).ConfigureAwait(false);
  540. result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
  541. }
  542. catch (HttpRequestException)
  543. {
  544. break;
  545. }
  546. }
  547. }
  548. }
  549. }