ImageSaver.cs 23 KB

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