ImageSaver.cs 24 KB

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