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