ImageSaver.cs 22 KB

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