ImageSaver.cs 23 KB

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