ImageSaver.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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 CommonIO;
  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 IMemoryStreamProvider _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, IMemoryStreamProvider 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 = new FileInfo(currentPath);
  149. // This will fail if the file is hidden
  150. if (currentFile.Exists)
  151. {
  152. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  153. {
  154. currentFile.Attributes &= ~FileAttributes.Hidden;
  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 = new FileInfo(path);
  220. // This will fail if the file is hidden
  221. if (file.Exists)
  222. {
  223. if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  224. {
  225. file.Attributes &= ~FileAttributes.Hidden;
  226. }
  227. }
  228. using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  229. {
  230. await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken)
  231. .ConfigureAwait(false);
  232. }
  233. if (_config.Configuration.SaveMetadataHidden)
  234. {
  235. file.Refresh();
  236. // Add back the attribute
  237. file.Attributes |= FileAttributes.Hidden;
  238. }
  239. }
  240. finally
  241. {
  242. _libraryMonitor.ReportFileSystemChangeComplete(path, false);
  243. _libraryMonitor.ReportFileSystemChangeComplete(parentFolder, false);
  244. }
  245. }
  246. /// <summary>
  247. /// Gets the save paths.
  248. /// </summary>
  249. /// <param name="item">The item.</param>
  250. /// <param name="type">The type.</param>
  251. /// <param name="imageIndex">Index of the image.</param>
  252. /// <param name="mimeType">Type of the MIME.</param>
  253. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  254. /// <returns>IEnumerable{System.String}.</returns>
  255. private string[] GetSavePaths(IHasImages item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  256. {
  257. if (!saveLocally || (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy))
  258. {
  259. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
  260. }
  261. return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
  262. }
  263. /// <summary>
  264. /// Gets the current image path.
  265. /// </summary>
  266. /// <param name="item">The item.</param>
  267. /// <param name="type">The type.</param>
  268. /// <param name="imageIndex">Index of the image.</param>
  269. /// <returns>System.String.</returns>
  270. /// <exception cref="System.ArgumentNullException">
  271. /// imageIndex
  272. /// or
  273. /// imageIndex
  274. /// </exception>
  275. private ItemImageInfo GetCurrentImage(IHasImages item, ImageType type, int imageIndex)
  276. {
  277. return item.GetImageInfo(type, imageIndex);
  278. }
  279. /// <summary>
  280. /// Sets the image path.
  281. /// </summary>
  282. /// <param name="item">The item.</param>
  283. /// <param name="type">The type.</param>
  284. /// <param name="imageIndex">Index of the image.</param>
  285. /// <param name="path">The path.</param>
  286. /// <exception cref="System.ArgumentNullException">imageIndex
  287. /// or
  288. /// imageIndex</exception>
  289. private void SetImagePath(IHasImages item, ImageType type, int? imageIndex, string path)
  290. {
  291. item.SetImagePath(type, imageIndex ?? 0, _fileSystem.GetFileInfo(path));
  292. }
  293. /// <summary>
  294. /// Gets the save path.
  295. /// </summary>
  296. /// <param name="item">The item.</param>
  297. /// <param name="type">The type.</param>
  298. /// <param name="imageIndex">Index of the image.</param>
  299. /// <param name="mimeType">Type of the MIME.</param>
  300. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  301. /// <returns>System.String.</returns>
  302. /// <exception cref="System.ArgumentNullException">
  303. /// imageIndex
  304. /// or
  305. /// imageIndex
  306. /// </exception>
  307. private string GetStandardSavePath(IHasImages item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  308. {
  309. var season = item as Season;
  310. var extension = MimeTypes.ToExtension(mimeType);
  311. if (string.IsNullOrWhiteSpace(extension))
  312. {
  313. throw new ArgumentException(string.Format("Unable to determine image file extension from mime type {0}", mimeType));
  314. }
  315. if (type == ImageType.Thumb && saveLocally)
  316. {
  317. if (season != null && season.IndexNumber.HasValue)
  318. {
  319. var seriesFolder = season.SeriesPath;
  320. var seasonMarker = season.IndexNumber.Value == 0
  321. ? "-specials"
  322. : season.IndexNumber.Value.ToString("00", UsCulture);
  323. var imageFilename = "season" + seasonMarker + "-landscape" + extension;
  324. return Path.Combine(seriesFolder, imageFilename);
  325. }
  326. if (item.DetectIsInMixedFolder())
  327. {
  328. return GetSavePathForItemInMixedFolder(item, type, "landscape", extension);
  329. }
  330. return Path.Combine(item.ContainingFolderPath, "landscape" + extension);
  331. }
  332. if (type == ImageType.Banner && saveLocally)
  333. {
  334. if (season != null && season.IndexNumber.HasValue)
  335. {
  336. var seriesFolder = season.SeriesPath;
  337. var seasonMarker = season.IndexNumber.Value == 0
  338. ? "-specials"
  339. : season.IndexNumber.Value.ToString("00", UsCulture);
  340. var imageFilename = "season" + seasonMarker + "-banner" + extension;
  341. return Path.Combine(seriesFolder, imageFilename);
  342. }
  343. }
  344. string filename;
  345. var folderName = item is MusicAlbum ||
  346. item is MusicArtist ||
  347. item is PhotoAlbum ||
  348. (saveLocally && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy) ?
  349. "folder" :
  350. "poster";
  351. switch (type)
  352. {
  353. case ImageType.Art:
  354. filename = "clearart";
  355. break;
  356. case ImageType.BoxRear:
  357. filename = "back";
  358. break;
  359. case ImageType.Thumb:
  360. filename = "landscape";
  361. break;
  362. case ImageType.Disc:
  363. filename = item is MusicAlbum ? "cdart" : "disc";
  364. break;
  365. case ImageType.Primary:
  366. filename = item is Episode ? _fileSystem.GetFileNameWithoutExtension(item.Path) : folderName;
  367. break;
  368. case ImageType.Backdrop:
  369. filename = GetBackdropSaveFilename(item.GetImages(type), "backdrop", "backdrop", imageIndex);
  370. break;
  371. case ImageType.Screenshot:
  372. filename = GetBackdropSaveFilename(item.GetImages(type), "screenshot", "screenshot", imageIndex);
  373. break;
  374. default:
  375. filename = type.ToString().ToLower();
  376. break;
  377. }
  378. if (string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase))
  379. {
  380. extension = ".jpg";
  381. }
  382. extension = extension.ToLower();
  383. string path = null;
  384. if (saveLocally)
  385. {
  386. if (type == ImageType.Primary && item is Episode)
  387. {
  388. path = Path.Combine(Path.GetDirectoryName(item.Path), "metadata", filename + extension);
  389. }
  390. else if (item.DetectIsInMixedFolder())
  391. {
  392. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  393. }
  394. if (string.IsNullOrEmpty(path))
  395. {
  396. path = Path.Combine(item.ContainingFolderPath, filename + extension);
  397. }
  398. }
  399. // None of the save local conditions passed, so store it in our internal folders
  400. if (string.IsNullOrEmpty(path))
  401. {
  402. if (string.IsNullOrEmpty(filename))
  403. {
  404. filename = folderName;
  405. }
  406. path = Path.Combine(item.GetInternalMetadataPath(), filename + extension);
  407. }
  408. return path;
  409. }
  410. private string GetBackdropSaveFilename(IEnumerable<ItemImageInfo> images, string zeroIndexFilename, string numberedIndexPrefix, int? index)
  411. {
  412. if (index.HasValue && index.Value == 0)
  413. {
  414. return zeroIndexFilename;
  415. }
  416. var filenames = images.Select(i => _fileSystem.GetFileNameWithoutExtension(i.Path)).ToList();
  417. var current = 1;
  418. while (filenames.Contains(numberedIndexPrefix + current.ToString(UsCulture), StringComparer.OrdinalIgnoreCase))
  419. {
  420. current++;
  421. }
  422. return numberedIndexPrefix + current.ToString(UsCulture);
  423. }
  424. /// <summary>
  425. /// Gets the compatible save paths.
  426. /// </summary>
  427. /// <param name="item">The item.</param>
  428. /// <param name="type">The type.</param>
  429. /// <param name="imageIndex">Index of the image.</param>
  430. /// <param name="mimeType">Type of the MIME.</param>
  431. /// <returns>IEnumerable{System.String}.</returns>
  432. /// <exception cref="System.ArgumentNullException">imageIndex</exception>
  433. private string[] GetCompatibleSavePaths(IHasImages item, ImageType type, int? imageIndex, string mimeType)
  434. {
  435. var season = item as Season;
  436. var extension = MimeTypes.ToExtension(mimeType);
  437. // Backdrop paths
  438. if (type == ImageType.Backdrop)
  439. {
  440. if (!imageIndex.HasValue)
  441. {
  442. throw new ArgumentNullException("imageIndex");
  443. }
  444. if (imageIndex.Value == 0)
  445. {
  446. if (item.DetectIsInMixedFolder())
  447. {
  448. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart", extension) };
  449. }
  450. if (season != null && season.IndexNumber.HasValue)
  451. {
  452. var seriesFolder = season.SeriesPath;
  453. var seasonMarker = season.IndexNumber.Value == 0
  454. ? "-specials"
  455. : season.IndexNumber.Value.ToString("00", UsCulture);
  456. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  457. return new[] { Path.Combine(seriesFolder, imageFilename) };
  458. }
  459. return new[]
  460. {
  461. Path.Combine(item.ContainingFolderPath, "fanart" + extension)
  462. };
  463. }
  464. var outputIndex = imageIndex.Value;
  465. if (item.DetectIsInMixedFolder())
  466. {
  467. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(UsCulture), extension) };
  468. }
  469. var extraFanartFilename = GetBackdropSaveFilename(item.GetImages(ImageType.Backdrop), "fanart", "fanart", outputIndex);
  470. var list = new List<string>
  471. {
  472. Path.Combine(item.ContainingFolderPath, "extrafanart", extraFanartFilename + extension)
  473. };
  474. if (EnableExtraThumbsDuplication)
  475. {
  476. list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension));
  477. }
  478. return list.ToArray();
  479. }
  480. if (type == ImageType.Primary)
  481. {
  482. if (season != null && season.IndexNumber.HasValue)
  483. {
  484. var seriesFolder = season.SeriesPath;
  485. var seasonMarker = season.IndexNumber.Value == 0
  486. ? "-specials"
  487. : season.IndexNumber.Value.ToString("00", UsCulture);
  488. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  489. return new[] { Path.Combine(seriesFolder, imageFilename) };
  490. }
  491. if (item is Episode)
  492. {
  493. var seasonFolder = Path.GetDirectoryName(item.Path);
  494. var imageFilename = _fileSystem.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
  495. return new[] { Path.Combine(seasonFolder, imageFilename) };
  496. }
  497. if (item.DetectIsInMixedFolder() || item is MusicVideo)
  498. {
  499. return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
  500. }
  501. if (item is MusicAlbum || item is MusicArtist)
  502. {
  503. return new[] { Path.Combine(item.ContainingFolderPath, "folder" + extension) };
  504. }
  505. return new[] { Path.Combine(item.ContainingFolderPath, "poster" + extension) };
  506. }
  507. // All other paths are the same
  508. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
  509. }
  510. private bool EnableExtraThumbsDuplication
  511. {
  512. get
  513. {
  514. var config = _config.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
  515. return config.EnableExtraThumbsDuplication;
  516. }
  517. }
  518. /// <summary>
  519. /// Gets the save path for item in mixed folder.
  520. /// </summary>
  521. /// <param name="item">The item.</param>
  522. /// <param name="type">The type.</param>
  523. /// <param name="imageFilename">The image filename.</param>
  524. /// <param name="extension">The extension.</param>
  525. /// <returns>System.String.</returns>
  526. private string GetSavePathForItemInMixedFolder(IHasImages item, ImageType type, string imageFilename, string extension)
  527. {
  528. if (type == ImageType.Primary)
  529. {
  530. imageFilename = "poster";
  531. }
  532. var folder = Path.GetDirectoryName(item.Path);
  533. return Path.Combine(folder, _fileSystem.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
  534. }
  535. }
  536. }