ImageSaver.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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. // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 .
  224. await using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous))
  225. {
  226. await source.CopyToAsync(fs, cancellationToken).ConfigureAwait(false);
  227. }
  228. if (_config.Configuration.SaveMetadataHidden)
  229. {
  230. SetHidden(path, true);
  231. }
  232. }
  233. finally
  234. {
  235. _libraryMonitor.ReportFileSystemChangeComplete(path, false);
  236. _libraryMonitor.ReportFileSystemChangeComplete(parentFolder, false);
  237. }
  238. }
  239. private void SetHidden(string path, bool hidden)
  240. {
  241. try
  242. {
  243. _fileSystem.SetHidden(path, hidden);
  244. }
  245. catch (Exception ex)
  246. {
  247. _logger.LogError(ex, "Error setting hidden attribute on {0}", path);
  248. }
  249. }
  250. /// <summary>
  251. /// Gets the save paths.
  252. /// </summary>
  253. /// <param name="item">The item.</param>
  254. /// <param name="type">The type.</param>
  255. /// <param name="imageIndex">Index of the image.</param>
  256. /// <param name="mimeType">Type of the MIME.</param>
  257. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  258. /// <returns>IEnumerable{System.String}.</returns>
  259. private string[] GetSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  260. {
  261. if (!saveLocally || (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy))
  262. {
  263. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
  264. }
  265. return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
  266. }
  267. /// <summary>
  268. /// Gets the current image path.
  269. /// </summary>
  270. /// <param name="item">The item.</param>
  271. /// <param name="type">The type.</param>
  272. /// <param name="imageIndex">Index of the image.</param>
  273. /// <returns>System.String.</returns>
  274. /// <exception cref="ArgumentNullException">
  275. /// imageIndex
  276. /// or
  277. /// imageIndex.
  278. /// </exception>
  279. private ItemImageInfo GetCurrentImage(BaseItem item, ImageType type, int imageIndex)
  280. {
  281. return item.GetImageInfo(type, imageIndex);
  282. }
  283. /// <summary>
  284. /// Sets the image path.
  285. /// </summary>
  286. /// <param name="item">The item.</param>
  287. /// <param name="type">The type.</param>
  288. /// <param name="imageIndex">Index of the image.</param>
  289. /// <param name="path">The path.</param>
  290. /// <exception cref="ArgumentNullException">imageIndex
  291. /// or
  292. /// imageIndex.
  293. /// </exception>
  294. private void SetImagePath(BaseItem item, ImageType type, int? imageIndex, string path)
  295. {
  296. item.SetImagePath(type, imageIndex ?? 0, _fileSystem.GetFileInfo(path));
  297. }
  298. /// <summary>
  299. /// Gets the save path.
  300. /// </summary>
  301. /// <param name="item">The item.</param>
  302. /// <param name="type">The type.</param>
  303. /// <param name="imageIndex">Index of the image.</param>
  304. /// <param name="mimeType">Type of the MIME.</param>
  305. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  306. /// <returns>System.String.</returns>
  307. /// <exception cref="ArgumentNullException">
  308. /// imageIndex
  309. /// or
  310. /// imageIndex.
  311. /// </exception>
  312. private string GetStandardSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  313. {
  314. var season = item as Season;
  315. var extension = MimeTypes.ToExtension(mimeType);
  316. if (string.IsNullOrWhiteSpace(extension))
  317. {
  318. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unable to determine image file extension from mime type {0}", mimeType));
  319. }
  320. if (type == ImageType.Thumb && saveLocally)
  321. {
  322. if (season != null && season.IndexNumber.HasValue)
  323. {
  324. var seriesFolder = season.SeriesPath;
  325. var seasonMarker = season.IndexNumber.Value == 0
  326. ? "-specials"
  327. : season.IndexNumber.Value.ToString("00", UsCulture);
  328. var imageFilename = "season" + seasonMarker + "-landscape" + extension;
  329. return Path.Combine(seriesFolder, imageFilename);
  330. }
  331. if (item.IsInMixedFolder)
  332. {
  333. return GetSavePathForItemInMixedFolder(item, type, "landscape", extension);
  334. }
  335. return Path.Combine(item.ContainingFolderPath, "landscape" + extension);
  336. }
  337. if (type == ImageType.Banner && saveLocally)
  338. {
  339. if (season != null && season.IndexNumber.HasValue)
  340. {
  341. var seriesFolder = season.SeriesPath;
  342. var seasonMarker = season.IndexNumber.Value == 0
  343. ? "-specials"
  344. : season.IndexNumber.Value.ToString("00", UsCulture);
  345. var imageFilename = "season" + seasonMarker + "-banner" + extension;
  346. return Path.Combine(seriesFolder, imageFilename);
  347. }
  348. }
  349. string filename;
  350. var folderName = item is MusicAlbum ||
  351. item is MusicArtist ||
  352. item is PhotoAlbum ||
  353. item is Person ||
  354. (saveLocally && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy) ?
  355. "folder" :
  356. "poster";
  357. switch (type)
  358. {
  359. case ImageType.Art:
  360. filename = "clearart";
  361. break;
  362. case ImageType.BoxRear:
  363. filename = "back";
  364. break;
  365. case ImageType.Thumb:
  366. filename = "landscape";
  367. break;
  368. case ImageType.Disc:
  369. filename = item is MusicAlbum ? "cdart" : "disc";
  370. break;
  371. case ImageType.Primary:
  372. filename = saveLocally && item is Episode ? Path.GetFileNameWithoutExtension(item.Path) : folderName;
  373. break;
  374. case ImageType.Backdrop:
  375. filename = GetBackdropSaveFilename(item.GetImages(type), "backdrop", "backdrop", imageIndex);
  376. break;
  377. case ImageType.Screenshot:
  378. filename = GetBackdropSaveFilename(item.GetImages(type), "screenshot", "screenshot", imageIndex);
  379. break;
  380. default:
  381. filename = type.ToString().ToLowerInvariant();
  382. break;
  383. }
  384. if (string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase))
  385. {
  386. extension = ".jpg";
  387. }
  388. extension = extension.ToLowerInvariant();
  389. string path = null;
  390. if (saveLocally)
  391. {
  392. if (type == ImageType.Primary && item is Episode)
  393. {
  394. path = Path.Combine(Path.GetDirectoryName(item.Path), "metadata", filename + extension);
  395. }
  396. else if (item.IsInMixedFolder)
  397. {
  398. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  399. }
  400. if (string.IsNullOrEmpty(path))
  401. {
  402. path = Path.Combine(item.ContainingFolderPath, filename + extension);
  403. }
  404. }
  405. // None of the save local conditions passed, so store it in our internal folders
  406. if (string.IsNullOrEmpty(path))
  407. {
  408. if (string.IsNullOrEmpty(filename))
  409. {
  410. filename = folderName;
  411. }
  412. path = Path.Combine(item.GetInternalMetadataPath(), filename + extension);
  413. }
  414. return path;
  415. }
  416. private string GetBackdropSaveFilename(IEnumerable<ItemImageInfo> images, string zeroIndexFilename, string numberedIndexPrefix, int? index)
  417. {
  418. if (index.HasValue && index.Value == 0)
  419. {
  420. return zeroIndexFilename;
  421. }
  422. var filenames = images.Select(i => Path.GetFileNameWithoutExtension(i.Path)).ToList();
  423. var current = 1;
  424. while (filenames.Contains(numberedIndexPrefix + current.ToString(UsCulture), StringComparer.OrdinalIgnoreCase))
  425. {
  426. current++;
  427. }
  428. return numberedIndexPrefix + current.ToString(UsCulture);
  429. }
  430. /// <summary>
  431. /// Gets the compatible save paths.
  432. /// </summary>
  433. /// <param name="item">The item.</param>
  434. /// <param name="type">The type.</param>
  435. /// <param name="imageIndex">Index of the image.</param>
  436. /// <param name="mimeType">Type of the MIME.</param>
  437. /// <returns>IEnumerable{System.String}.</returns>
  438. /// <exception cref="ArgumentNullException">imageIndex.</exception>
  439. private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType)
  440. {
  441. var season = item as Season;
  442. var extension = MimeTypes.ToExtension(mimeType);
  443. // Backdrop paths
  444. if (type == ImageType.Backdrop)
  445. {
  446. if (!imageIndex.HasValue)
  447. {
  448. throw new ArgumentNullException(nameof(imageIndex));
  449. }
  450. if (imageIndex.Value == 0)
  451. {
  452. if (item.IsInMixedFolder)
  453. {
  454. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart", extension) };
  455. }
  456. if (season != null && season.IndexNumber.HasValue)
  457. {
  458. var seriesFolder = season.SeriesPath;
  459. var seasonMarker = season.IndexNumber.Value == 0
  460. ? "-specials"
  461. : season.IndexNumber.Value.ToString("00", UsCulture);
  462. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  463. return new[] { Path.Combine(seriesFolder, imageFilename) };
  464. }
  465. return new[]
  466. {
  467. Path.Combine(item.ContainingFolderPath, "fanart" + extension)
  468. };
  469. }
  470. var outputIndex = imageIndex.Value;
  471. if (item.IsInMixedFolder)
  472. {
  473. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(UsCulture), extension) };
  474. }
  475. var extraFanartFilename = GetBackdropSaveFilename(item.GetImages(ImageType.Backdrop), "fanart", "fanart", outputIndex);
  476. var list = new List<string>
  477. {
  478. Path.Combine(item.ContainingFolderPath, "extrafanart", extraFanartFilename + extension)
  479. };
  480. if (EnableExtraThumbsDuplication)
  481. {
  482. list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension));
  483. }
  484. return list.ToArray();
  485. }
  486. if (type == ImageType.Primary)
  487. {
  488. if (season != null && season.IndexNumber.HasValue)
  489. {
  490. var seriesFolder = season.SeriesPath;
  491. var seasonMarker = season.IndexNumber.Value == 0
  492. ? "-specials"
  493. : season.IndexNumber.Value.ToString("00", UsCulture);
  494. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  495. return new[] { Path.Combine(seriesFolder, imageFilename) };
  496. }
  497. if (item is Episode)
  498. {
  499. var seasonFolder = Path.GetDirectoryName(item.Path);
  500. var imageFilename = Path.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
  501. return new[] { Path.Combine(seasonFolder, imageFilename) };
  502. }
  503. if (item.IsInMixedFolder || item is MusicVideo)
  504. {
  505. return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
  506. }
  507. if (item is MusicAlbum || item is MusicArtist)
  508. {
  509. return new[] { Path.Combine(item.ContainingFolderPath, "folder" + extension) };
  510. }
  511. return new[] { Path.Combine(item.ContainingFolderPath, "poster" + extension) };
  512. }
  513. // All other paths are the same
  514. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
  515. }
  516. /// <summary>
  517. /// Gets the save path for item in mixed folder.
  518. /// </summary>
  519. /// <param name="item">The item.</param>
  520. /// <param name="type">The type.</param>
  521. /// <param name="imageFilename">The image filename.</param>
  522. /// <param name="extension">The extension.</param>
  523. /// <returns>System.String.</returns>
  524. private string GetSavePathForItemInMixedFolder(BaseItem item, ImageType type, string imageFilename, string extension)
  525. {
  526. if (type == ImageType.Primary)
  527. {
  528. imageFilename = "poster";
  529. }
  530. var folder = Path.GetDirectoryName(item.Path);
  531. return Path.Combine(folder, Path.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
  532. }
  533. }
  534. }