ImageSaver.cs 23 KB

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