ImageSaver.cs 23 KB

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