ImageSaver.cs 24 KB

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