ImageSaver.cs 24 KB

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