ImageSaver.cs 24 KB

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