2
0

ImageSaver.cs 24 KB

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