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