ImageSaver.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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 MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Entities.Audio;
  12. using MediaBrowser.Controller.Entities.TV;
  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. namespace MediaBrowser.Providers.Manager
  20. {
  21. /// <summary>
  22. /// Class ImageSaver
  23. /// </summary>
  24. public class ImageSaver
  25. {
  26. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  27. /// <summary>
  28. /// The _config
  29. /// </summary>
  30. private readonly IServerConfigurationManager _config;
  31. /// <summary>
  32. /// The _directory watchers
  33. /// </summary>
  34. private readonly ILibraryMonitor _libraryMonitor;
  35. private readonly IFileSystem _fileSystem;
  36. private readonly ILogger _logger;
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="ImageSaver" /> class.
  39. /// </summary>
  40. /// <param name="config">The config.</param>
  41. /// <param name="libraryMonitor">The directory watchers.</param>
  42. /// <param name="fileSystem">The file system.</param>
  43. /// <param name="logger">The logger.</param>
  44. public ImageSaver(IServerConfigurationManager config, ILibraryMonitor libraryMonitor, IFileSystem fileSystem, ILogger logger)
  45. {
  46. _config = config;
  47. _libraryMonitor = libraryMonitor;
  48. _fileSystem = fileSystem;
  49. _logger = logger;
  50. }
  51. /// <summary>
  52. /// Saves the image.
  53. /// </summary>
  54. /// <param name="item">The item.</param>
  55. /// <param name="source">The source.</param>
  56. /// <param name="mimeType">Type of the MIME.</param>
  57. /// <param name="type">The type.</param>
  58. /// <param name="imageIndex">Index of the image.</param>
  59. /// <param name="cancellationToken">The cancellation token.</param>
  60. /// <returns>Task.</returns>
  61. /// <exception cref="ArgumentNullException">mimeType</exception>
  62. public Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  63. {
  64. return SaveImage(item, source, mimeType, type, imageIndex, null, cancellationToken);
  65. }
  66. public async Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, bool? saveLocallyWithMedia, CancellationToken cancellationToken)
  67. {
  68. if (string.IsNullOrEmpty(mimeType))
  69. {
  70. throw new ArgumentNullException(nameof(mimeType));
  71. }
  72. var saveLocally = item.SupportsLocalMetadata && item.IsSaveLocalMetadataEnabled() && !item.ExtraType.HasValue && !(item is Audio);
  73. if (item is User)
  74. {
  75. saveLocally = true;
  76. }
  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 == null ? null : currentImage.Path;
  116. var savedPaths = new List<string>();
  117. 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. private async Task<string> SaveImageToLocation(Stream source, string path, string retryPath, CancellationToken cancellationToken)
  155. {
  156. try
  157. {
  158. await SaveImageToLocation(source, path, cancellationToken).ConfigureAwait(false);
  159. return path;
  160. }
  161. catch (UnauthorizedAccessException)
  162. {
  163. var retry = !string.IsNullOrWhiteSpace(retryPath) &&
  164. !string.Equals(path, retryPath, StringComparison.OrdinalIgnoreCase);
  165. if (retry)
  166. {
  167. _logger.LogError("UnauthorizedAccessException - Access to path {0} is denied. Will retry saving to {1}", path, retryPath);
  168. }
  169. else
  170. {
  171. throw;
  172. }
  173. }
  174. catch (IOException ex)
  175. {
  176. var retry = !string.IsNullOrWhiteSpace(retryPath) &&
  177. !string.Equals(path, retryPath, StringComparison.OrdinalIgnoreCase);
  178. if (retry)
  179. {
  180. _logger.LogError(ex, "IOException saving to {0}. Will retry saving to {1}", path, retryPath);
  181. }
  182. else
  183. {
  184. throw;
  185. }
  186. }
  187. source.Position = 0;
  188. await SaveImageToLocation(source, retryPath, cancellationToken).ConfigureAwait(false);
  189. return retryPath;
  190. }
  191. /// <summary>
  192. /// Saves the image to location.
  193. /// </summary>
  194. /// <param name="source">The source.</param>
  195. /// <param name="path">The path.</param>
  196. /// <param name="cancellationToken">The cancellation token.</param>
  197. /// <returns>Task.</returns>
  198. private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken)
  199. {
  200. _logger.LogDebug("Saving image to {0}", path);
  201. var parentFolder = _fileSystem.GetDirectoryName(path);
  202. try
  203. {
  204. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  205. _libraryMonitor.ReportFileSystemChangeBeginning(parentFolder);
  206. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  207. _fileSystem.SetAttributes(path, false, false);
  208. using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.Asynchronous))
  209. {
  210. await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  211. }
  212. if (_config.Configuration.SaveMetadataHidden)
  213. {
  214. SetHidden(path, true);
  215. }
  216. }
  217. finally
  218. {
  219. _libraryMonitor.ReportFileSystemChangeComplete(path, false);
  220. _libraryMonitor.ReportFileSystemChangeComplete(parentFolder, false);
  221. }
  222. }
  223. private void SetHidden(string path, bool hidden)
  224. {
  225. try
  226. {
  227. _fileSystem.SetHidden(path, hidden);
  228. }
  229. catch (Exception ex)
  230. {
  231. _logger.LogError(ex, "Error setting hidden attribute on {0}", path);
  232. }
  233. }
  234. /// <summary>
  235. /// Gets the save paths.
  236. /// </summary>
  237. /// <param name="item">The item.</param>
  238. /// <param name="type">The type.</param>
  239. /// <param name="imageIndex">Index of the image.</param>
  240. /// <param name="mimeType">Type of the MIME.</param>
  241. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  242. /// <returns>IEnumerable{System.String}.</returns>
  243. private string[] GetSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  244. {
  245. if (!saveLocally || (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy))
  246. {
  247. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
  248. }
  249. return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
  250. }
  251. /// <summary>
  252. /// Gets the current image path.
  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. /// <returns>System.String.</returns>
  258. /// <exception cref="ArgumentNullException">
  259. /// imageIndex
  260. /// or
  261. /// imageIndex
  262. /// </exception>
  263. private ItemImageInfo GetCurrentImage(BaseItem item, ImageType type, int imageIndex)
  264. {
  265. return item.GetImageInfo(type, imageIndex);
  266. }
  267. /// <summary>
  268. /// Sets the 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. /// <param name="path">The path.</param>
  274. /// <exception cref="ArgumentNullException">imageIndex
  275. /// or
  276. /// imageIndex</exception>
  277. private void SetImagePath(BaseItem item, ImageType type, int? imageIndex, string path)
  278. {
  279. item.SetImagePath(type, imageIndex ?? 0, _fileSystem.GetFileInfo(path));
  280. }
  281. /// <summary>
  282. /// Gets the save path.
  283. /// </summary>
  284. /// <param name="item">The item.</param>
  285. /// <param name="type">The type.</param>
  286. /// <param name="imageIndex">Index of the image.</param>
  287. /// <param name="mimeType">Type of the MIME.</param>
  288. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  289. /// <returns>System.String.</returns>
  290. /// <exception cref="ArgumentNullException">
  291. /// imageIndex
  292. /// or
  293. /// imageIndex
  294. /// </exception>
  295. private string GetStandardSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  296. {
  297. var season = item as Season;
  298. var extension = MimeTypes.ToExtension(mimeType);
  299. if (string.IsNullOrWhiteSpace(extension))
  300. {
  301. throw new ArgumentException(string.Format("Unable to determine image file extension from mime type {0}", mimeType));
  302. }
  303. if (type == ImageType.Thumb && saveLocally)
  304. {
  305. if (season != null && season.IndexNumber.HasValue)
  306. {
  307. var seriesFolder = season.SeriesPath;
  308. var seasonMarker = season.IndexNumber.Value == 0
  309. ? "-specials"
  310. : season.IndexNumber.Value.ToString("00", UsCulture);
  311. var imageFilename = "season" + seasonMarker + "-landscape" + extension;
  312. return Path.Combine(seriesFolder, imageFilename);
  313. }
  314. if (item.IsInMixedFolder)
  315. {
  316. return GetSavePathForItemInMixedFolder(item, type, "landscape", extension);
  317. }
  318. return Path.Combine(item.ContainingFolderPath, "landscape" + extension);
  319. }
  320. if (type == ImageType.Banner && 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 + "-banner" + extension;
  329. return Path.Combine(seriesFolder, imageFilename);
  330. }
  331. }
  332. string filename;
  333. var folderName = item is MusicAlbum ||
  334. item is MusicArtist ||
  335. item is PhotoAlbum ||
  336. item is Person ||
  337. (saveLocally && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy) ?
  338. "folder" :
  339. "poster";
  340. switch (type)
  341. {
  342. case ImageType.Art:
  343. filename = "clearart";
  344. break;
  345. case ImageType.BoxRear:
  346. filename = "back";
  347. break;
  348. case ImageType.Thumb:
  349. filename = "landscape";
  350. break;
  351. case ImageType.Disc:
  352. filename = item is MusicAlbum ? "cdart" : "disc";
  353. break;
  354. case ImageType.Primary:
  355. filename = saveLocally && item is Episode ? _fileSystem.GetFileNameWithoutExtension(item.Path) : folderName;
  356. break;
  357. case ImageType.Backdrop:
  358. filename = GetBackdropSaveFilename(item.GetImages(type), "backdrop", "backdrop", imageIndex);
  359. break;
  360. case ImageType.Screenshot:
  361. filename = GetBackdropSaveFilename(item.GetImages(type), "screenshot", "screenshot", imageIndex);
  362. break;
  363. default:
  364. filename = type.ToString().ToLower();
  365. break;
  366. }
  367. if (string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase))
  368. {
  369. extension = ".jpg";
  370. }
  371. extension = extension.ToLower();
  372. string path = null;
  373. if (saveLocally)
  374. {
  375. if (type == ImageType.Primary && item is Episode)
  376. {
  377. path = Path.Combine(_fileSystem.GetDirectoryName(item.Path), "metadata", filename + extension);
  378. }
  379. else if (item.IsInMixedFolder)
  380. {
  381. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  382. }
  383. if (string.IsNullOrEmpty(path))
  384. {
  385. path = Path.Combine(item.ContainingFolderPath, filename + extension);
  386. }
  387. }
  388. // None of the save local conditions passed, so store it in our internal folders
  389. if (string.IsNullOrEmpty(path))
  390. {
  391. if (string.IsNullOrEmpty(filename))
  392. {
  393. filename = folderName;
  394. }
  395. path = Path.Combine(item.GetInternalMetadataPath(), filename + extension);
  396. }
  397. return path;
  398. }
  399. private string GetBackdropSaveFilename(IEnumerable<ItemImageInfo> images, string zeroIndexFilename, string numberedIndexPrefix, int? index)
  400. {
  401. if (index.HasValue && index.Value == 0)
  402. {
  403. return zeroIndexFilename;
  404. }
  405. var filenames = images.Select(i => _fileSystem.GetFileNameWithoutExtension(i.Path)).ToList();
  406. var current = 1;
  407. while (filenames.Contains(numberedIndexPrefix + current.ToString(UsCulture), StringComparer.OrdinalIgnoreCase))
  408. {
  409. current++;
  410. }
  411. return numberedIndexPrefix + current.ToString(UsCulture);
  412. }
  413. /// <summary>
  414. /// Gets the compatible save paths.
  415. /// </summary>
  416. /// <param name="item">The item.</param>
  417. /// <param name="type">The type.</param>
  418. /// <param name="imageIndex">Index of the image.</param>
  419. /// <param name="mimeType">Type of the MIME.</param>
  420. /// <returns>IEnumerable{System.String}.</returns>
  421. /// <exception cref="ArgumentNullException">imageIndex</exception>
  422. private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType)
  423. {
  424. var season = item as Season;
  425. var extension = MimeTypes.ToExtension(mimeType);
  426. // Backdrop paths
  427. if (type == ImageType.Backdrop)
  428. {
  429. if (!imageIndex.HasValue)
  430. {
  431. throw new ArgumentNullException(nameof(imageIndex));
  432. }
  433. if (imageIndex.Value == 0)
  434. {
  435. if (item.IsInMixedFolder)
  436. {
  437. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart", extension) };
  438. }
  439. if (season != null && season.IndexNumber.HasValue)
  440. {
  441. var seriesFolder = season.SeriesPath;
  442. var seasonMarker = season.IndexNumber.Value == 0
  443. ? "-specials"
  444. : season.IndexNumber.Value.ToString("00", UsCulture);
  445. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  446. return new[] { Path.Combine(seriesFolder, imageFilename) };
  447. }
  448. return new[]
  449. {
  450. Path.Combine(item.ContainingFolderPath, "fanart" + extension)
  451. };
  452. }
  453. var outputIndex = imageIndex.Value;
  454. if (item.IsInMixedFolder)
  455. {
  456. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(UsCulture), extension) };
  457. }
  458. var extraFanartFilename = GetBackdropSaveFilename(item.GetImages(ImageType.Backdrop), "fanart", "fanart", outputIndex);
  459. var list = new List<string>
  460. {
  461. Path.Combine(item.ContainingFolderPath, "extrafanart", extraFanartFilename + extension)
  462. };
  463. if (EnableExtraThumbsDuplication)
  464. {
  465. list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension));
  466. }
  467. return list.ToArray();
  468. }
  469. if (type == ImageType.Primary)
  470. {
  471. if (season != null && season.IndexNumber.HasValue)
  472. {
  473. var seriesFolder = season.SeriesPath;
  474. var seasonMarker = season.IndexNumber.Value == 0
  475. ? "-specials"
  476. : season.IndexNumber.Value.ToString("00", UsCulture);
  477. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  478. return new[] { Path.Combine(seriesFolder, imageFilename) };
  479. }
  480. if (item is Episode)
  481. {
  482. var seasonFolder = _fileSystem.GetDirectoryName(item.Path);
  483. var imageFilename = _fileSystem.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
  484. return new[] { Path.Combine(seasonFolder, imageFilename) };
  485. }
  486. if (item.IsInMixedFolder || item is MusicVideo)
  487. {
  488. return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
  489. }
  490. if (item is MusicAlbum || item is MusicArtist)
  491. {
  492. return new[] { Path.Combine(item.ContainingFolderPath, "folder" + extension) };
  493. }
  494. return new[] { Path.Combine(item.ContainingFolderPath, "poster" + extension) };
  495. }
  496. // All other paths are the same
  497. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
  498. }
  499. private bool EnableExtraThumbsDuplication
  500. {
  501. get
  502. {
  503. var config = _config.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
  504. return config.EnableExtraThumbsDuplication;
  505. }
  506. }
  507. /// <summary>
  508. /// Gets the save path for item in mixed folder.
  509. /// </summary>
  510. /// <param name="item">The item.</param>
  511. /// <param name="type">The type.</param>
  512. /// <param name="imageFilename">The image filename.</param>
  513. /// <param name="extension">The extension.</param>
  514. /// <returns>System.String.</returns>
  515. private string GetSavePathForItemInMixedFolder(BaseItem item, ImageType type, string imageFilename, string extension)
  516. {
  517. if (type == ImageType.Primary)
  518. {
  519. imageFilename = "poster";
  520. }
  521. var folder = _fileSystem.GetDirectoryName(item.Path);
  522. return Path.Combine(folder, _fileSystem.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
  523. }
  524. }
  525. }