ImageSaver.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Extensions;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Entities.Audio;
  15. using MediaBrowser.Controller.Library;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.Net;
  20. using Microsoft.Extensions.Logging;
  21. using Episode = MediaBrowser.Controller.Entities.TV.Episode;
  22. using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
  23. using Person = MediaBrowser.Controller.Entities.Person;
  24. using Season = MediaBrowser.Controller.Entities.TV.Season;
  25. namespace MediaBrowser.Providers.Manager
  26. {
  27. /// <summary>
  28. /// Class ImageSaver.
  29. /// </summary>
  30. public class ImageSaver
  31. {
  32. /// <summary>
  33. /// The _config.
  34. /// </summary>
  35. private readonly IServerConfigurationManager _config;
  36. /// <summary>
  37. /// The _directory watchers.
  38. /// </summary>
  39. private readonly ILibraryMonitor _libraryMonitor;
  40. private readonly IFileSystem _fileSystem;
  41. private readonly ILogger _logger;
  42. /// <summary>
  43. /// Initializes a new instance of the <see cref="ImageSaver" /> class.
  44. /// </summary>
  45. /// <param name="config">The config.</param>
  46. /// <param name="libraryMonitor">The directory watchers.</param>
  47. /// <param name="fileSystem">The file system.</param>
  48. /// <param name="logger">The logger.</param>
  49. public ImageSaver(IServerConfigurationManager config, ILibraryMonitor libraryMonitor, IFileSystem fileSystem, ILogger logger)
  50. {
  51. _config = config;
  52. _libraryMonitor = libraryMonitor;
  53. _fileSystem = fileSystem;
  54. _logger = logger;
  55. }
  56. private bool EnableExtraThumbsDuplication
  57. {
  58. get
  59. {
  60. var config = _config.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
  61. return config.EnableExtraThumbsDuplication;
  62. }
  63. }
  64. /// <summary>
  65. /// Saves the image.
  66. /// </summary>
  67. /// <param name="item">The item.</param>
  68. /// <param name="source">The source.</param>
  69. /// <param name="mimeType">Type of the MIME.</param>
  70. /// <param name="type">The type.</param>
  71. /// <param name="imageIndex">Index of the image.</param>
  72. /// <param name="cancellationToken">The cancellation token.</param>
  73. /// <returns>Task.</returns>
  74. /// <exception cref="ArgumentNullException">mimeType.</exception>
  75. public Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  76. {
  77. return SaveImage(item, source, mimeType, type, imageIndex, null, cancellationToken);
  78. }
  79. public async Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, bool? saveLocallyWithMedia, CancellationToken cancellationToken)
  80. {
  81. ArgumentException.ThrowIfNullOrEmpty(mimeType);
  82. var saveLocally = item.SupportsLocalMetadata && item.IsSaveLocalMetadataEnabled() && !item.ExtraType.HasValue && item is not Audio;
  83. if (type != ImageType.Primary && item is Episode)
  84. {
  85. saveLocally = false;
  86. }
  87. if (!item.IsFileProtocol)
  88. {
  89. saveLocally = false;
  90. // If season is virtual under a physical series, save locally if using compatible convention
  91. if (item is Season season && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Compatible)
  92. {
  93. var series = season.Series;
  94. if (series is not null && series.SupportsLocalMetadata && series.IsSaveLocalMetadataEnabled())
  95. {
  96. saveLocally = true;
  97. }
  98. }
  99. }
  100. if (saveLocallyWithMedia.HasValue && !saveLocallyWithMedia.Value)
  101. {
  102. saveLocally = saveLocallyWithMedia.Value;
  103. }
  104. if (!imageIndex.HasValue && item.AllowsMultipleImages(type))
  105. {
  106. imageIndex = item.GetImages(type).Count();
  107. }
  108. var index = imageIndex ?? 0;
  109. var paths = GetSavePaths(item, type, imageIndex, mimeType, saveLocally);
  110. var retryPaths = GetSavePaths(item, type, imageIndex, mimeType, false);
  111. // If there are more than one output paths, the stream will need to be seekable
  112. if (paths.Length > 1 && !source.CanSeek)
  113. {
  114. var memoryStream = new MemoryStream();
  115. await using (source.ConfigureAwait(false))
  116. {
  117. await source.CopyToAsync(memoryStream, cancellationToken).ConfigureAwait(false);
  118. }
  119. source = memoryStream;
  120. }
  121. var currentImage = GetCurrentImage(item, type, index);
  122. var currentImageIsLocalFile = currentImage is not null && currentImage.IsLocalFile;
  123. var currentImagePath = currentImage?.Path;
  124. var savedPaths = new List<string>();
  125. await using (source.ConfigureAwait(false))
  126. {
  127. for (int i = 0; i < paths.Length; i++)
  128. {
  129. if (i != 0)
  130. {
  131. source.Position = 0;
  132. }
  133. string retryPath = null;
  134. if (paths.Length == retryPaths.Length)
  135. {
  136. retryPath = retryPaths[i];
  137. }
  138. var savedPath = await SaveImageToLocation(source, paths[i], retryPath, cancellationToken).ConfigureAwait(false);
  139. savedPaths.Add(savedPath);
  140. }
  141. }
  142. // Set the path into the item
  143. SetImagePath(item, type, imageIndex, savedPaths[0]);
  144. // Delete the current path
  145. if (currentImageIsLocalFile
  146. && !savedPaths.Contains(currentImagePath, StringComparison.OrdinalIgnoreCase)
  147. && (saveLocally || currentImagePath.Contains(_config.ApplicationPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase)))
  148. {
  149. var currentPath = currentImagePath;
  150. _logger.LogInformation("Deleting previous image {0}", currentPath);
  151. _libraryMonitor.ReportFileSystemChangeBeginning(currentPath);
  152. try
  153. {
  154. _fileSystem.DeleteFile(currentPath);
  155. }
  156. catch (FileNotFoundException)
  157. {
  158. }
  159. finally
  160. {
  161. _libraryMonitor.ReportFileSystemChangeComplete(currentPath, false);
  162. }
  163. }
  164. }
  165. public async Task SaveImage(Stream source, string path)
  166. {
  167. await SaveImageToLocation(source, path, path, CancellationToken.None).ConfigureAwait(false);
  168. }
  169. private async Task<string> SaveImageToLocation(Stream source, string path, string retryPath, CancellationToken cancellationToken)
  170. {
  171. try
  172. {
  173. await SaveImageToLocation(source, path, cancellationToken).ConfigureAwait(false);
  174. return path;
  175. }
  176. catch (UnauthorizedAccessException)
  177. {
  178. var retry = !string.IsNullOrWhiteSpace(retryPath) &&
  179. !string.Equals(path, retryPath, StringComparison.OrdinalIgnoreCase);
  180. if (retry)
  181. {
  182. _logger.LogError("UnauthorizedAccessException - Access to path {0} is denied. Will retry saving to {1}", path, retryPath);
  183. }
  184. else
  185. {
  186. throw;
  187. }
  188. }
  189. catch (IOException ex)
  190. {
  191. var retry = !string.IsNullOrWhiteSpace(retryPath) &&
  192. !string.Equals(path, retryPath, StringComparison.OrdinalIgnoreCase);
  193. if (retry)
  194. {
  195. _logger.LogError(ex, "IOException saving to {0}. Will retry saving to {1}", path, retryPath);
  196. }
  197. else
  198. {
  199. throw;
  200. }
  201. }
  202. await SaveImageToLocation(source, retryPath, cancellationToken).ConfigureAwait(false);
  203. return retryPath;
  204. }
  205. /// <summary>
  206. /// Saves the image to location.
  207. /// </summary>
  208. /// <param name="source">The source.</param>
  209. /// <param name="path">The path.</param>
  210. /// <param name="cancellationToken">The cancellation token.</param>
  211. /// <returns>Task.</returns>
  212. private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken)
  213. {
  214. _logger.LogDebug("Saving image to {0}", path);
  215. var parentFolder = Path.GetDirectoryName(path);
  216. try
  217. {
  218. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  219. _libraryMonitor.ReportFileSystemChangeBeginning(parentFolder);
  220. Directory.CreateDirectory(Path.GetDirectoryName(path));
  221. _fileSystem.SetAttributes(path, false, false);
  222. var fileStreamOptions = AsyncFile.WriteOptions;
  223. fileStreamOptions.Mode = FileMode.Create;
  224. if (source.CanSeek)
  225. {
  226. fileStreamOptions.PreallocationSize = source.Length;
  227. }
  228. var fs = new FileStream(path, fileStreamOptions);
  229. await using (fs.ConfigureAwait(false))
  230. {
  231. await source.CopyToAsync(fs, cancellationToken).ConfigureAwait(false);
  232. }
  233. if (_config.Configuration.SaveMetadataHidden)
  234. {
  235. SetHidden(path, true);
  236. }
  237. }
  238. finally
  239. {
  240. _libraryMonitor.ReportFileSystemChangeComplete(path, false);
  241. _libraryMonitor.ReportFileSystemChangeComplete(parentFolder, false);
  242. }
  243. }
  244. private void SetHidden(string path, bool hidden)
  245. {
  246. try
  247. {
  248. _fileSystem.SetHidden(path, hidden);
  249. }
  250. catch (Exception ex)
  251. {
  252. _logger.LogError(ex, "Error setting hidden attribute on {0}", path);
  253. }
  254. }
  255. /// <summary>
  256. /// Gets the save paths.
  257. /// </summary>
  258. /// <param name="item">The item.</param>
  259. /// <param name="type">The type.</param>
  260. /// <param name="imageIndex">Index of the image.</param>
  261. /// <param name="mimeType">Type of the MIME.</param>
  262. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  263. /// <returns>IEnumerable{System.String}.</returns>
  264. private string[] GetSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  265. {
  266. if (!saveLocally || (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy))
  267. {
  268. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
  269. }
  270. return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
  271. }
  272. /// <summary>
  273. /// Gets the current image path.
  274. /// </summary>
  275. /// <param name="item">The item.</param>
  276. /// <param name="type">The type.</param>
  277. /// <param name="imageIndex">Index of the image.</param>
  278. /// <returns>System.String.</returns>
  279. /// <exception cref="ArgumentNullException">
  280. /// imageIndex
  281. /// or
  282. /// imageIndex.
  283. /// </exception>
  284. private ItemImageInfo GetCurrentImage(BaseItem item, ImageType type, int imageIndex)
  285. {
  286. return item.GetImageInfo(type, imageIndex);
  287. }
  288. /// <summary>
  289. /// Sets the image path.
  290. /// </summary>
  291. /// <param name="item">The item.</param>
  292. /// <param name="type">The type.</param>
  293. /// <param name="imageIndex">Index of the image.</param>
  294. /// <param name="path">The path.</param>
  295. /// <exception cref="ArgumentNullException">imageIndex
  296. /// or
  297. /// imageIndex.
  298. /// </exception>
  299. private void SetImagePath(BaseItem item, ImageType type, int? imageIndex, string path)
  300. {
  301. item.SetImagePath(type, imageIndex ?? 0, _fileSystem.GetFileInfo(path));
  302. }
  303. /// <summary>
  304. /// Gets the save path.
  305. /// </summary>
  306. /// <param name="item">The item.</param>
  307. /// <param name="type">The type.</param>
  308. /// <param name="imageIndex">Index of the image.</param>
  309. /// <param name="mimeType">Type of the MIME.</param>
  310. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  311. /// <returns>System.String.</returns>
  312. /// <exception cref="ArgumentNullException">
  313. /// imageIndex
  314. /// or
  315. /// imageIndex.
  316. /// </exception>
  317. private string GetStandardSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  318. {
  319. var season = item as Season;
  320. var extension = MimeTypes.ToExtension(mimeType);
  321. if (string.IsNullOrWhiteSpace(extension))
  322. {
  323. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unable to determine image file extension from mime type {0}", mimeType));
  324. }
  325. if (type == ImageType.Thumb && saveLocally)
  326. {
  327. if (season is not null && season.IndexNumber.HasValue)
  328. {
  329. var seriesFolder = season.SeriesPath;
  330. var seasonMarker = season.IndexNumber.Value == 0
  331. ? "-specials"
  332. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  333. var imageFilename = "season" + seasonMarker + "-landscape" + extension;
  334. return Path.Combine(seriesFolder, imageFilename);
  335. }
  336. if (item.IsInMixedFolder)
  337. {
  338. return GetSavePathForItemInMixedFolder(item, type, "landscape", extension);
  339. }
  340. return Path.Combine(item.ContainingFolderPath, "landscape" + extension);
  341. }
  342. if (type == ImageType.Banner && saveLocally)
  343. {
  344. if (season is not null && season.IndexNumber.HasValue)
  345. {
  346. var seriesFolder = season.SeriesPath;
  347. var seasonMarker = season.IndexNumber.Value == 0
  348. ? "-specials"
  349. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  350. var imageFilename = "season" + seasonMarker + "-banner" + extension;
  351. return Path.Combine(seriesFolder, imageFilename);
  352. }
  353. }
  354. string filename;
  355. var folderName = item is MusicAlbum ||
  356. item is MusicArtist ||
  357. item is PhotoAlbum ||
  358. item is Person ||
  359. (saveLocally && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy) ?
  360. "folder" :
  361. "poster";
  362. switch (type)
  363. {
  364. case ImageType.Art:
  365. filename = "clearart";
  366. break;
  367. case ImageType.BoxRear:
  368. filename = "back";
  369. break;
  370. case ImageType.Thumb:
  371. filename = "landscape";
  372. break;
  373. case ImageType.Disc:
  374. filename = item is MusicAlbum ? "cdart" : "disc";
  375. break;
  376. case ImageType.Primary:
  377. filename = saveLocally && item is Episode ? Path.GetFileNameWithoutExtension(item.Path) : folderName;
  378. break;
  379. case ImageType.Backdrop:
  380. filename = GetBackdropSaveFilename(item.GetImages(type), "backdrop", "backdrop", imageIndex);
  381. break;
  382. default:
  383. filename = type.ToString().ToLowerInvariant();
  384. break;
  385. }
  386. if (string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase))
  387. {
  388. extension = ".jpg";
  389. }
  390. extension = extension.ToLowerInvariant();
  391. string path = null;
  392. if (saveLocally)
  393. {
  394. if (type == ImageType.Primary && item is Episode)
  395. {
  396. path = Path.Combine(Path.GetDirectoryName(item.Path), "metadata", filename + extension);
  397. }
  398. else if (item.IsInMixedFolder)
  399. {
  400. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  401. }
  402. if (string.IsNullOrEmpty(path))
  403. {
  404. path = Path.Combine(item.ContainingFolderPath, filename + extension);
  405. }
  406. }
  407. // None of the save local conditions passed, so store it in our internal folders
  408. if (string.IsNullOrEmpty(path))
  409. {
  410. if (string.IsNullOrEmpty(filename))
  411. {
  412. filename = folderName;
  413. }
  414. path = Path.Combine(item.GetInternalMetadataPath(), filename + extension);
  415. }
  416. return path;
  417. }
  418. private string GetBackdropSaveFilename(IEnumerable<ItemImageInfo> images, string zeroIndexFilename, string numberedIndexPrefix, int? index)
  419. {
  420. if (index.HasValue && index.Value == 0)
  421. {
  422. return zeroIndexFilename;
  423. }
  424. var filenames = images.Select(i => Path.GetFileNameWithoutExtension(i.Path)).ToList();
  425. var current = 1;
  426. while (filenames.Contains(numberedIndexPrefix + current.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase))
  427. {
  428. current++;
  429. }
  430. return numberedIndexPrefix + current.ToString(CultureInfo.InvariantCulture);
  431. }
  432. /// <summary>
  433. /// Gets the compatible save paths.
  434. /// </summary>
  435. /// <param name="item">The item.</param>
  436. /// <param name="type">The type.</param>
  437. /// <param name="imageIndex">Index of the image.</param>
  438. /// <param name="mimeType">Type of the MIME.</param>
  439. /// <returns>IEnumerable{System.String}.</returns>
  440. /// <exception cref="ArgumentNullException">imageIndex.</exception>
  441. private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType)
  442. {
  443. var season = item as Season;
  444. var extension = MimeTypes.ToExtension(mimeType);
  445. // Backdrop paths
  446. if (type == ImageType.Backdrop)
  447. {
  448. if (!imageIndex.HasValue)
  449. {
  450. throw new ArgumentNullException(nameof(imageIndex));
  451. }
  452. if (imageIndex.Value == 0)
  453. {
  454. if (item.IsInMixedFolder)
  455. {
  456. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart", extension) };
  457. }
  458. if (season is not null && season.IndexNumber.HasValue)
  459. {
  460. var seriesFolder = season.SeriesPath;
  461. var seasonMarker = season.IndexNumber.Value == 0
  462. ? "-specials"
  463. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  464. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  465. return new[] { Path.Combine(seriesFolder, imageFilename) };
  466. }
  467. return new[]
  468. {
  469. Path.Combine(item.ContainingFolderPath, "fanart" + extension)
  470. };
  471. }
  472. var outputIndex = imageIndex.Value;
  473. if (item.IsInMixedFolder)
  474. {
  475. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(CultureInfo.InvariantCulture), extension) };
  476. }
  477. var extraFanartFilename = GetBackdropSaveFilename(item.GetImages(ImageType.Backdrop), "fanart", "fanart", outputIndex);
  478. var list = new List<string>
  479. {
  480. Path.Combine(item.ContainingFolderPath, "extrafanart", extraFanartFilename + extension)
  481. };
  482. if (EnableExtraThumbsDuplication)
  483. {
  484. list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(CultureInfo.InvariantCulture) + extension));
  485. }
  486. return list.ToArray();
  487. }
  488. if (type == ImageType.Primary)
  489. {
  490. if (season is not null && season.IndexNumber.HasValue)
  491. {
  492. var seriesFolder = season.SeriesPath;
  493. var seasonMarker = season.IndexNumber.Value == 0
  494. ? "-specials"
  495. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  496. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  497. return new[] { Path.Combine(seriesFolder, imageFilename) };
  498. }
  499. if (item is Episode)
  500. {
  501. var seasonFolder = Path.GetDirectoryName(item.Path);
  502. var imageFilename = Path.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
  503. return new[] { Path.Combine(seasonFolder, imageFilename) };
  504. }
  505. if (item.IsInMixedFolder || item is MusicVideo)
  506. {
  507. return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
  508. }
  509. if (item is MusicAlbum || item is MusicArtist)
  510. {
  511. return new[] { Path.Combine(item.ContainingFolderPath, "folder" + extension) };
  512. }
  513. return new[] { Path.Combine(item.ContainingFolderPath, "poster" + extension) };
  514. }
  515. // All other paths are the same
  516. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
  517. }
  518. /// <summary>
  519. /// Gets the save path for item in mixed folder.
  520. /// </summary>
  521. /// <param name="item">The item.</param>
  522. /// <param name="type">The type.</param>
  523. /// <param name="imageFilename">The image filename.</param>
  524. /// <param name="extension">The extension.</param>
  525. /// <returns>System.String.</returns>
  526. private string GetSavePathForItemInMixedFolder(BaseItem item, ImageType type, string imageFilename, string extension)
  527. {
  528. if (type == ImageType.Primary)
  529. {
  530. imageFilename = "poster";
  531. }
  532. var folder = Path.GetDirectoryName(item.Path);
  533. return Path.Combine(folder, Path.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
  534. }
  535. }
  536. }