ImageSaver.cs 24 KB

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