ImageSaver.cs 23 KB

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