ImageSaver.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. fileStreamOptions.PreallocationSize = source.Length;
  225. await using (var fs = new FileStream(path, fileStreamOptions))
  226. {
  227. await source.CopyToAsync(fs, cancellationToken).ConfigureAwait(false);
  228. }
  229. if (_config.Configuration.SaveMetadataHidden)
  230. {
  231. SetHidden(path, true);
  232. }
  233. }
  234. finally
  235. {
  236. _libraryMonitor.ReportFileSystemChangeComplete(path, false);
  237. _libraryMonitor.ReportFileSystemChangeComplete(parentFolder, false);
  238. }
  239. }
  240. private void SetHidden(string path, bool hidden)
  241. {
  242. try
  243. {
  244. _fileSystem.SetHidden(path, hidden);
  245. }
  246. catch (Exception ex)
  247. {
  248. _logger.LogError(ex, "Error setting hidden attribute on {0}", path);
  249. }
  250. }
  251. /// <summary>
  252. /// Gets the save paths.
  253. /// </summary>
  254. /// <param name="item">The item.</param>
  255. /// <param name="type">The type.</param>
  256. /// <param name="imageIndex">Index of the image.</param>
  257. /// <param name="mimeType">Type of the MIME.</param>
  258. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  259. /// <returns>IEnumerable{System.String}.</returns>
  260. private string[] GetSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  261. {
  262. if (!saveLocally || (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy))
  263. {
  264. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
  265. }
  266. return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
  267. }
  268. /// <summary>
  269. /// Gets the current image path.
  270. /// </summary>
  271. /// <param name="item">The item.</param>
  272. /// <param name="type">The type.</param>
  273. /// <param name="imageIndex">Index of the image.</param>
  274. /// <returns>System.String.</returns>
  275. /// <exception cref="ArgumentNullException">
  276. /// imageIndex
  277. /// or
  278. /// imageIndex.
  279. /// </exception>
  280. private ItemImageInfo GetCurrentImage(BaseItem item, ImageType type, int imageIndex)
  281. {
  282. return item.GetImageInfo(type, imageIndex);
  283. }
  284. /// <summary>
  285. /// Sets the image path.
  286. /// </summary>
  287. /// <param name="item">The item.</param>
  288. /// <param name="type">The type.</param>
  289. /// <param name="imageIndex">Index of the image.</param>
  290. /// <param name="path">The path.</param>
  291. /// <exception cref="ArgumentNullException">imageIndex
  292. /// or
  293. /// imageIndex.
  294. /// </exception>
  295. private void SetImagePath(BaseItem item, ImageType type, int? imageIndex, string path)
  296. {
  297. item.SetImagePath(type, imageIndex ?? 0, _fileSystem.GetFileInfo(path));
  298. }
  299. /// <summary>
  300. /// Gets the save path.
  301. /// </summary>
  302. /// <param name="item">The item.</param>
  303. /// <param name="type">The type.</param>
  304. /// <param name="imageIndex">Index of the image.</param>
  305. /// <param name="mimeType">Type of the MIME.</param>
  306. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  307. /// <returns>System.String.</returns>
  308. /// <exception cref="ArgumentNullException">
  309. /// imageIndex
  310. /// or
  311. /// imageIndex.
  312. /// </exception>
  313. private string GetStandardSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  314. {
  315. var season = item as Season;
  316. var extension = MimeTypes.ToExtension(mimeType);
  317. if (string.IsNullOrWhiteSpace(extension))
  318. {
  319. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unable to determine image file extension from mime type {0}", mimeType));
  320. }
  321. if (type == ImageType.Thumb && saveLocally)
  322. {
  323. if (season is not null && season.IndexNumber.HasValue)
  324. {
  325. var seriesFolder = season.SeriesPath;
  326. var seasonMarker = season.IndexNumber.Value == 0
  327. ? "-specials"
  328. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  329. var imageFilename = "season" + seasonMarker + "-landscape" + extension;
  330. return Path.Combine(seriesFolder, imageFilename);
  331. }
  332. if (item.IsInMixedFolder)
  333. {
  334. return GetSavePathForItemInMixedFolder(item, type, "landscape", extension);
  335. }
  336. return Path.Combine(item.ContainingFolderPath, "landscape" + extension);
  337. }
  338. if (type == ImageType.Banner && saveLocally)
  339. {
  340. if (season is not null && season.IndexNumber.HasValue)
  341. {
  342. var seriesFolder = season.SeriesPath;
  343. var seasonMarker = season.IndexNumber.Value == 0
  344. ? "-specials"
  345. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  346. var imageFilename = "season" + seasonMarker + "-banner" + extension;
  347. return Path.Combine(seriesFolder, imageFilename);
  348. }
  349. }
  350. string filename;
  351. var folderName = item is MusicAlbum ||
  352. item is MusicArtist ||
  353. item is PhotoAlbum ||
  354. item is Person ||
  355. (saveLocally && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy) ?
  356. "folder" :
  357. "poster";
  358. switch (type)
  359. {
  360. case ImageType.Art:
  361. filename = "clearart";
  362. break;
  363. case ImageType.BoxRear:
  364. filename = "back";
  365. break;
  366. case ImageType.Thumb:
  367. filename = "landscape";
  368. break;
  369. case ImageType.Disc:
  370. filename = item is MusicAlbum ? "cdart" : "disc";
  371. break;
  372. case ImageType.Primary:
  373. filename = saveLocally && item is Episode ? Path.GetFileNameWithoutExtension(item.Path) : folderName;
  374. break;
  375. case ImageType.Backdrop:
  376. filename = GetBackdropSaveFilename(item.GetImages(type), "backdrop", "backdrop", imageIndex);
  377. break;
  378. default:
  379. filename = type.ToString().ToLowerInvariant();
  380. break;
  381. }
  382. if (string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase))
  383. {
  384. extension = ".jpg";
  385. }
  386. extension = extension.ToLowerInvariant();
  387. string path = null;
  388. if (saveLocally)
  389. {
  390. if (type == ImageType.Primary && item is Episode)
  391. {
  392. path = Path.Combine(Path.GetDirectoryName(item.Path), "metadata", filename + extension);
  393. }
  394. else if (item.IsInMixedFolder)
  395. {
  396. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  397. }
  398. if (string.IsNullOrEmpty(path))
  399. {
  400. path = Path.Combine(item.ContainingFolderPath, filename + extension);
  401. }
  402. }
  403. // None of the save local conditions passed, so store it in our internal folders
  404. if (string.IsNullOrEmpty(path))
  405. {
  406. if (string.IsNullOrEmpty(filename))
  407. {
  408. filename = folderName;
  409. }
  410. path = Path.Combine(item.GetInternalMetadataPath(), filename + extension);
  411. }
  412. return path;
  413. }
  414. private string GetBackdropSaveFilename(IEnumerable<ItemImageInfo> images, string zeroIndexFilename, string numberedIndexPrefix, int? index)
  415. {
  416. if (index.HasValue && index.Value == 0)
  417. {
  418. return zeroIndexFilename;
  419. }
  420. var filenames = images.Select(i => Path.GetFileNameWithoutExtension(i.Path)).ToList();
  421. var current = 1;
  422. while (filenames.Contains(numberedIndexPrefix + current.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase))
  423. {
  424. current++;
  425. }
  426. return numberedIndexPrefix + current.ToString(CultureInfo.InvariantCulture);
  427. }
  428. /// <summary>
  429. /// Gets the compatible save paths.
  430. /// </summary>
  431. /// <param name="item">The item.</param>
  432. /// <param name="type">The type.</param>
  433. /// <param name="imageIndex">Index of the image.</param>
  434. /// <param name="mimeType">Type of the MIME.</param>
  435. /// <returns>IEnumerable{System.String}.</returns>
  436. /// <exception cref="ArgumentNullException">imageIndex.</exception>
  437. private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType)
  438. {
  439. var season = item as Season;
  440. var extension = MimeTypes.ToExtension(mimeType);
  441. // Backdrop paths
  442. if (type == ImageType.Backdrop)
  443. {
  444. if (!imageIndex.HasValue)
  445. {
  446. throw new ArgumentNullException(nameof(imageIndex));
  447. }
  448. if (imageIndex.Value == 0)
  449. {
  450. if (item.IsInMixedFolder)
  451. {
  452. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart", extension) };
  453. }
  454. if (season is not null && season.IndexNumber.HasValue)
  455. {
  456. var seriesFolder = season.SeriesPath;
  457. var seasonMarker = season.IndexNumber.Value == 0
  458. ? "-specials"
  459. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  460. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  461. return new[] { Path.Combine(seriesFolder, imageFilename) };
  462. }
  463. return new[]
  464. {
  465. Path.Combine(item.ContainingFolderPath, "fanart" + extension)
  466. };
  467. }
  468. var outputIndex = imageIndex.Value;
  469. if (item.IsInMixedFolder)
  470. {
  471. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(CultureInfo.InvariantCulture), extension) };
  472. }
  473. var extraFanartFilename = GetBackdropSaveFilename(item.GetImages(ImageType.Backdrop), "fanart", "fanart", outputIndex);
  474. var list = new List<string>
  475. {
  476. Path.Combine(item.ContainingFolderPath, "extrafanart", extraFanartFilename + extension)
  477. };
  478. if (EnableExtraThumbsDuplication)
  479. {
  480. list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(CultureInfo.InvariantCulture) + extension));
  481. }
  482. return list.ToArray();
  483. }
  484. if (type == ImageType.Primary)
  485. {
  486. if (season is not null && season.IndexNumber.HasValue)
  487. {
  488. var seriesFolder = season.SeriesPath;
  489. var seasonMarker = season.IndexNumber.Value == 0
  490. ? "-specials"
  491. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  492. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  493. return new[] { Path.Combine(seriesFolder, imageFilename) };
  494. }
  495. if (item is Episode)
  496. {
  497. var seasonFolder = Path.GetDirectoryName(item.Path);
  498. var imageFilename = Path.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
  499. return new[] { Path.Combine(seasonFolder, imageFilename) };
  500. }
  501. if (item.IsInMixedFolder || item is MusicVideo)
  502. {
  503. return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
  504. }
  505. if (item is MusicAlbum || item is MusicArtist)
  506. {
  507. return new[] { Path.Combine(item.ContainingFolderPath, "folder" + extension) };
  508. }
  509. return new[] { Path.Combine(item.ContainingFolderPath, "poster" + extension) };
  510. }
  511. // All other paths are the same
  512. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
  513. }
  514. /// <summary>
  515. /// Gets the save path for item in mixed folder.
  516. /// </summary>
  517. /// <param name="item">The item.</param>
  518. /// <param name="type">The type.</param>
  519. /// <param name="imageFilename">The image filename.</param>
  520. /// <param name="extension">The extension.</param>
  521. /// <returns>System.String.</returns>
  522. private string GetSavePathForItemInMixedFolder(BaseItem item, ImageType type, string imageFilename, string extension)
  523. {
  524. if (type == ImageType.Primary)
  525. {
  526. imageFilename = "poster";
  527. }
  528. var folder = Path.GetDirectoryName(item.Path);
  529. return Path.Combine(folder, Path.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
  530. }
  531. }
  532. }