ImageSaver.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Audio;
  5. using MediaBrowser.Controller.Entities.TV;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Model.Configuration;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Providers.Manager
  18. {
  19. /// <summary>
  20. /// Class ImageSaver
  21. /// </summary>
  22. public class ImageSaver
  23. {
  24. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  25. /// <summary>
  26. /// The _config
  27. /// </summary>
  28. private readonly IServerConfigurationManager _config;
  29. /// <summary>
  30. /// The _directory watchers
  31. /// </summary>
  32. private readonly ILibraryMonitor _libraryMonitor;
  33. private readonly IFileSystem _fileSystem;
  34. private readonly ILogger _logger;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="ImageSaver" /> class.
  37. /// </summary>
  38. /// <param name="config">The config.</param>
  39. /// <param name="libraryMonitor">The directory watchers.</param>
  40. /// <param name="fileSystem">The file system.</param>
  41. /// <param name="logger">The logger.</param>
  42. public ImageSaver(IServerConfigurationManager config, ILibraryMonitor libraryMonitor, IFileSystem fileSystem, ILogger logger)
  43. {
  44. _config = config;
  45. _libraryMonitor = libraryMonitor;
  46. _fileSystem = fileSystem;
  47. _logger = logger;
  48. }
  49. /// <summary>
  50. /// Saves the image.
  51. /// </summary>
  52. /// <param name="item">The item.</param>
  53. /// <param name="source">The source.</param>
  54. /// <param name="mimeType">Type of the MIME.</param>
  55. /// <param name="type">The type.</param>
  56. /// <param name="imageIndex">Index of the image.</param>
  57. /// <param name="cancellationToken">The cancellation token.</param>
  58. /// <returns>Task.</returns>
  59. /// <exception cref="System.ArgumentNullException">mimeType</exception>
  60. public async Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  61. {
  62. if (string.IsNullOrEmpty(mimeType))
  63. {
  64. throw new ArgumentNullException("mimeType");
  65. }
  66. var saveLocally = item.IsSaveLocalMetadataEnabled() && item.Parent != null && !(item is Audio);
  67. if (item is IItemByName || item is User)
  68. {
  69. saveLocally = true;
  70. }
  71. if (type != ImageType.Primary && item is Episode)
  72. {
  73. saveLocally = false;
  74. }
  75. var locationType = item.LocationType;
  76. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  77. {
  78. saveLocally = false;
  79. var season = item as Season;
  80. // If season is virtual under a physical series, save locally if using compatible convention
  81. if (season != null && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Compatible)
  82. {
  83. var series = season.Series;
  84. if (series != null && series.SupportsLocalMetadata)
  85. {
  86. saveLocally = true;
  87. }
  88. }
  89. }
  90. if (!imageIndex.HasValue && item.AllowsMultipleImages(type))
  91. {
  92. imageIndex = item.GetImages(type).Count();
  93. }
  94. var index = imageIndex ?? 0;
  95. var paths = GetSavePaths(item, type, imageIndex, mimeType, saveLocally);
  96. // If there are more than one output paths, the stream will need to be seekable
  97. if (paths.Length > 1 && !source.CanSeek)
  98. {
  99. var memoryStream = new MemoryStream();
  100. using (source)
  101. {
  102. await source.CopyToAsync(memoryStream).ConfigureAwait(false);
  103. }
  104. memoryStream.Position = 0;
  105. source = memoryStream;
  106. }
  107. var currentPath = GetCurrentImagePath(item, type, index);
  108. using (source)
  109. {
  110. var isFirst = true;
  111. foreach (var path in paths)
  112. {
  113. // Seek back to the beginning
  114. if (!isFirst)
  115. {
  116. source.Position = 0;
  117. }
  118. await SaveImageToLocation(source, path, cancellationToken).ConfigureAwait(false);
  119. isFirst = false;
  120. }
  121. }
  122. // Set the path into the item
  123. SetImagePath(item, type, imageIndex, paths[0]);
  124. // Delete the current path
  125. if (!string.IsNullOrEmpty(currentPath) && !paths.Contains(currentPath, StringComparer.OrdinalIgnoreCase))
  126. {
  127. _libraryMonitor.ReportFileSystemChangeBeginning(currentPath);
  128. try
  129. {
  130. var currentFile = new FileInfo(currentPath);
  131. // This will fail if the file is hidden
  132. if (currentFile.Exists)
  133. {
  134. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  135. {
  136. currentFile.Attributes &= ~FileAttributes.Hidden;
  137. }
  138. currentFile.Delete();
  139. }
  140. }
  141. finally
  142. {
  143. _libraryMonitor.ReportFileSystemChangeComplete(currentPath, false);
  144. }
  145. }
  146. }
  147. /// <summary>
  148. /// Saves the image to location.
  149. /// </summary>
  150. /// <param name="source">The source.</param>
  151. /// <param name="path">The path.</param>
  152. /// <param name="cancellationToken">The cancellation token.</param>
  153. /// <returns>Task.</returns>
  154. private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken)
  155. {
  156. _logger.Debug("Saving image to {0}", path);
  157. var parentFolder = Path.GetDirectoryName(path);
  158. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  159. _libraryMonitor.ReportFileSystemChangeBeginning(parentFolder);
  160. try
  161. {
  162. Directory.CreateDirectory(Path.GetDirectoryName(path));
  163. // If the file is currently hidden we'll have to remove that or the save will fail
  164. var file = new FileInfo(path);
  165. // This will fail if the file is hidden
  166. if (file.Exists)
  167. {
  168. if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  169. {
  170. file.Attributes &= ~FileAttributes.Hidden;
  171. }
  172. }
  173. using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  174. {
  175. await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  176. }
  177. }
  178. finally
  179. {
  180. _libraryMonitor.ReportFileSystemChangeComplete(path, false);
  181. _libraryMonitor.ReportFileSystemChangeComplete(parentFolder, false);
  182. }
  183. }
  184. /// <summary>
  185. /// Gets the save paths.
  186. /// </summary>
  187. /// <param name="item">The item.</param>
  188. /// <param name="type">The type.</param>
  189. /// <param name="imageIndex">Index of the image.</param>
  190. /// <param name="mimeType">Type of the MIME.</param>
  191. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  192. /// <returns>IEnumerable{System.String}.</returns>
  193. private string[] GetSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  194. {
  195. if (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy || !saveLocally)
  196. {
  197. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
  198. }
  199. return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
  200. }
  201. /// <summary>
  202. /// Gets the current image path.
  203. /// </summary>
  204. /// <param name="item">The item.</param>
  205. /// <param name="type">The type.</param>
  206. /// <param name="imageIndex">Index of the image.</param>
  207. /// <returns>System.String.</returns>
  208. /// <exception cref="System.ArgumentNullException">
  209. /// imageIndex
  210. /// or
  211. /// imageIndex
  212. /// </exception>
  213. private string GetCurrentImagePath(IHasImages item, ImageType type, int imageIndex)
  214. {
  215. return item.GetImagePath(type, imageIndex);
  216. }
  217. /// <summary>
  218. /// Sets the image path.
  219. /// </summary>
  220. /// <param name="item">The item.</param>
  221. /// <param name="type">The type.</param>
  222. /// <param name="imageIndex">Index of the image.</param>
  223. /// <param name="path">The path.</param>
  224. /// <exception cref="System.ArgumentNullException">imageIndex
  225. /// or
  226. /// imageIndex</exception>
  227. private void SetImagePath(BaseItem item, ImageType type, int? imageIndex, string path)
  228. {
  229. item.SetImagePath(type, imageIndex ?? 0, new FileInfo(path));
  230. }
  231. /// <summary>
  232. /// Gets the save path.
  233. /// </summary>
  234. /// <param name="item">The item.</param>
  235. /// <param name="type">The type.</param>
  236. /// <param name="imageIndex">Index of the image.</param>
  237. /// <param name="mimeType">Type of the MIME.</param>
  238. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  239. /// <returns>System.String.</returns>
  240. /// <exception cref="System.ArgumentNullException">
  241. /// imageIndex
  242. /// or
  243. /// imageIndex
  244. /// </exception>
  245. private string GetStandardSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  246. {
  247. string filename;
  248. switch (type)
  249. {
  250. case ImageType.Art:
  251. filename = "clearart";
  252. break;
  253. case ImageType.BoxRear:
  254. filename = "back";
  255. break;
  256. case ImageType.Disc:
  257. filename = item is MusicAlbum ? "cdart" : "disc";
  258. break;
  259. case ImageType.Primary:
  260. filename = item is Episode ? Path.GetFileNameWithoutExtension(item.Path) : "folder";
  261. break;
  262. case ImageType.Backdrop:
  263. filename = GetBackdropSaveFilename(item.GetImages(type), "backdrop", "backdrop", imageIndex);
  264. break;
  265. case ImageType.Screenshot:
  266. filename = GetBackdropSaveFilename(item.GetImages(type), "screenshot", "screenshot", imageIndex);
  267. break;
  268. default:
  269. filename = type.ToString().ToLower();
  270. break;
  271. }
  272. var extension = mimeType.Split('/').Last();
  273. if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
  274. {
  275. extension = "jpg";
  276. }
  277. extension = "." + extension.ToLower();
  278. string path = null;
  279. if (saveLocally)
  280. {
  281. if (item is Episode)
  282. {
  283. path = Path.Combine(Path.GetDirectoryName(item.Path), "metadata", filename + extension);
  284. }
  285. else if (item.IsInMixedFolder)
  286. {
  287. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  288. }
  289. if (string.IsNullOrEmpty(path))
  290. {
  291. path = Path.Combine(item.ContainingFolderPath, filename + extension);
  292. }
  293. }
  294. // None of the save local conditions passed, so store it in our internal folders
  295. if (string.IsNullOrEmpty(path))
  296. {
  297. if (string.IsNullOrEmpty(filename))
  298. {
  299. filename = "folder";
  300. }
  301. path = Path.Combine(_config.ApplicationPaths.GetInternalMetadataPath(item.Id), filename + extension);
  302. }
  303. return path;
  304. }
  305. private string GetBackdropSaveFilename(IEnumerable<ItemImageInfo> images, string zeroIndexFilename, string numberedIndexPrefix, int? index)
  306. {
  307. if (index.HasValue && index.Value == 0)
  308. {
  309. return zeroIndexFilename;
  310. }
  311. var filenames = images.Select(i => Path.GetFileNameWithoutExtension(i.Path)).ToList();
  312. var current = 1;
  313. while (filenames.Contains(numberedIndexPrefix + current.ToString(UsCulture), StringComparer.OrdinalIgnoreCase))
  314. {
  315. current++;
  316. }
  317. return numberedIndexPrefix + current.ToString(UsCulture);
  318. }
  319. /// <summary>
  320. /// Gets the compatible save paths.
  321. /// </summary>
  322. /// <param name="item">The item.</param>
  323. /// <param name="type">The type.</param>
  324. /// <param name="imageIndex">Index of the image.</param>
  325. /// <param name="mimeType">Type of the MIME.</param>
  326. /// <returns>IEnumerable{System.String}.</returns>
  327. /// <exception cref="System.ArgumentNullException">imageIndex</exception>
  328. private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType)
  329. {
  330. var season = item as Season;
  331. var extension = mimeType.Split('/').Last();
  332. if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
  333. {
  334. extension = "jpg";
  335. }
  336. extension = "." + extension.ToLower();
  337. // Backdrop paths
  338. if (type == ImageType.Backdrop)
  339. {
  340. if (!imageIndex.HasValue)
  341. {
  342. throw new ArgumentNullException("imageIndex");
  343. }
  344. if (imageIndex.Value == 0)
  345. {
  346. if (item.IsInMixedFolder)
  347. {
  348. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart", extension) };
  349. }
  350. if (season != null && item.IndexNumber.HasValue)
  351. {
  352. var seriesFolder = season.SeriesPath;
  353. var seasonMarker = item.IndexNumber.Value == 0
  354. ? "-specials"
  355. : item.IndexNumber.Value.ToString("00", UsCulture);
  356. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  357. return new[] { Path.Combine(seriesFolder, imageFilename) };
  358. }
  359. return new[]
  360. {
  361. Path.Combine(item.ContainingFolderPath, "fanart" + extension)
  362. };
  363. }
  364. var outputIndex = imageIndex.Value;
  365. if (item.IsInMixedFolder)
  366. {
  367. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(UsCulture), extension) };
  368. }
  369. var extraFanartFilename = GetBackdropSaveFilename(item.GetImages(ImageType.Backdrop), "fanart", "fanart", outputIndex);
  370. return new[]
  371. {
  372. Path.Combine(item.ContainingFolderPath, "extrafanart", extraFanartFilename + extension),
  373. Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension)
  374. };
  375. }
  376. if (type == ImageType.Primary)
  377. {
  378. if (season != null && item.IndexNumber.HasValue)
  379. {
  380. var seriesFolder = season.SeriesPath;
  381. var seasonMarker = item.IndexNumber.Value == 0
  382. ? "-specials"
  383. : item.IndexNumber.Value.ToString("00", UsCulture);
  384. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  385. return new[] { Path.Combine(seriesFolder, imageFilename) };
  386. }
  387. if (item is Episode)
  388. {
  389. var seasonFolder = Path.GetDirectoryName(item.Path);
  390. var imageFilename = Path.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
  391. return new[] { Path.Combine(seasonFolder, imageFilename) };
  392. }
  393. if (item.IsInMixedFolder || item is MusicVideo)
  394. {
  395. return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
  396. }
  397. if (item is MusicAlbum || item is MusicArtist)
  398. {
  399. return new[] { Path.Combine(item.ContainingFolderPath, "folder" + extension) };
  400. }
  401. return new[] { Path.Combine(item.ContainingFolderPath, "poster" + extension) };
  402. }
  403. if (type == ImageType.Banner)
  404. {
  405. if (season != null && item.IndexNumber.HasValue)
  406. {
  407. var seriesFolder = season.SeriesPath;
  408. var seasonMarker = item.IndexNumber.Value == 0
  409. ? "-specials"
  410. : item.IndexNumber.Value.ToString("00", UsCulture);
  411. var imageFilename = "season" + seasonMarker + "-banner" + extension;
  412. return new[] { Path.Combine(seriesFolder, imageFilename) };
  413. }
  414. }
  415. if (type == ImageType.Thumb)
  416. {
  417. if (season != null && item.IndexNumber.HasValue)
  418. {
  419. var seriesFolder = season.SeriesPath;
  420. var seasonMarker = item.IndexNumber.Value == 0
  421. ? "-specials"
  422. : item.IndexNumber.Value.ToString("00", UsCulture);
  423. var imageFilename = "season" + seasonMarker + "-landscape" + extension;
  424. return new[] { Path.Combine(seriesFolder, imageFilename) };
  425. }
  426. if (item.IsInMixedFolder)
  427. {
  428. return new[] { GetSavePathForItemInMixedFolder(item, type, "landscape", extension) };
  429. }
  430. return new[] { Path.Combine(item.ContainingFolderPath, "landscape" + extension) };
  431. }
  432. // All other paths are the same
  433. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
  434. }
  435. /// <summary>
  436. /// Gets the save path for item in mixed folder.
  437. /// </summary>
  438. /// <param name="item">The item.</param>
  439. /// <param name="type">The type.</param>
  440. /// <param name="imageFilename">The image filename.</param>
  441. /// <param name="extension">The extension.</param>
  442. /// <returns>System.String.</returns>
  443. private string GetSavePathForItemInMixedFolder(IHasImages item, ImageType type, string imageFilename, string extension)
  444. {
  445. if (type == ImageType.Primary)
  446. {
  447. imageFilename = "poster";
  448. }
  449. var folder = Path.GetDirectoryName(item.Path);
  450. return Path.Combine(folder, Path.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
  451. }
  452. }
  453. }