ImageSaver.cs 22 KB

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