ImageSaver.cs 24 KB

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