ImageSaver.cs 24 KB

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