ImageSaver.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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.IO;
  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.Server.Implementations.Providers
  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 remote image cache
  31. /// </summary>
  32. private readonly FileSystemRepository _remoteImageCache;
  33. /// <summary>
  34. /// The _directory watchers
  35. /// </summary>
  36. private readonly IDirectoryWatchers _directoryWatchers;
  37. private readonly IFileSystem _fileSystem;
  38. private readonly ILogger _logger;
  39. /// <summary>
  40. /// Initializes a new instance of the <see cref="ImageSaver"/> class.
  41. /// </summary>
  42. /// <param name="config">The config.</param>
  43. /// <param name="directoryWatchers">The directory watchers.</param>
  44. public ImageSaver(IServerConfigurationManager config, IDirectoryWatchers directoryWatchers, IFileSystem fileSystem, ILogger logger)
  45. {
  46. _config = config;
  47. _directoryWatchers = directoryWatchers;
  48. _fileSystem = fileSystem;
  49. _logger = logger;
  50. _remoteImageCache = new FileSystemRepository(config.ApplicationPaths.DownloadedImagesDataPath);
  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="sourceUrl">The source URL.</param>
  61. /// <param name="cancellationToken">The cancellation token.</param>
  62. /// <returns>Task.</returns>
  63. /// <exception cref="System.ArgumentNullException">mimeType</exception>
  64. public async Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, string sourceUrl, CancellationToken cancellationToken)
  65. {
  66. if (string.IsNullOrEmpty(mimeType))
  67. {
  68. throw new ArgumentNullException("mimeType");
  69. }
  70. var saveLocally = _config.Configuration.SaveLocalMeta && item.Parent != null && !(item is Audio);
  71. if (item is IItemByName || item is User)
  72. {
  73. saveLocally = true;
  74. }
  75. if (type != ImageType.Primary && item is Episode)
  76. {
  77. saveLocally = false;
  78. }
  79. var locationType = item.LocationType;
  80. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  81. {
  82. saveLocally = false;
  83. var season = item as Season;
  84. // If season is virtual under a physical series, save locally if using compatible convention
  85. if (season != null && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Compatible)
  86. {
  87. var series = season.Series;
  88. if (series != null)
  89. {
  90. var seriesLocationType = series.LocationType;
  91. if (seriesLocationType == LocationType.FileSystem || seriesLocationType == LocationType.Offline)
  92. {
  93. saveLocally = true;
  94. }
  95. }
  96. }
  97. }
  98. if (type == ImageType.Backdrop && imageIndex == null)
  99. {
  100. imageIndex = item.BackdropImagePaths.Count;
  101. }
  102. else if (type == ImageType.Screenshot && imageIndex == null)
  103. {
  104. var hasScreenshots = (IHasScreenshots)item;
  105. imageIndex = hasScreenshots.ScreenshotImagePaths.Count;
  106. }
  107. var paths = GetSavePaths(item, type, imageIndex, mimeType, saveLocally);
  108. // If there are more than one output paths, the stream will need to be seekable
  109. if (paths.Length > 1 && !source.CanSeek)
  110. {
  111. var memoryStream = new MemoryStream();
  112. using (source)
  113. {
  114. await source.CopyToAsync(memoryStream).ConfigureAwait(false);
  115. }
  116. memoryStream.Position = 0;
  117. source = memoryStream;
  118. }
  119. var currentPath = GetCurrentImagePath(item, type, imageIndex);
  120. using (source)
  121. {
  122. var isFirst = true;
  123. foreach (var path in paths)
  124. {
  125. // Seek back to the beginning
  126. if (!isFirst)
  127. {
  128. source.Position = 0;
  129. }
  130. await SaveImageToLocation(source, path, cancellationToken).ConfigureAwait(false);
  131. isFirst = false;
  132. }
  133. }
  134. // Set the path into the BaseItem
  135. SetImagePath(item, type, imageIndex, paths[0], sourceUrl);
  136. // Delete the current path
  137. if (!string.IsNullOrEmpty(currentPath) && !paths.Contains(currentPath, StringComparer.OrdinalIgnoreCase))
  138. {
  139. _directoryWatchers.TemporarilyIgnore(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. currentFile.Delete();
  151. }
  152. }
  153. finally
  154. {
  155. _directoryWatchers.RemoveTempIgnore(currentPath);
  156. }
  157. }
  158. }
  159. /// <summary>
  160. /// Saves the image to location.
  161. /// </summary>
  162. /// <param name="source">The source.</param>
  163. /// <param name="path">The path.</param>
  164. /// <param name="cancellationToken">The cancellation token.</param>
  165. /// <returns>Task.</returns>
  166. private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken)
  167. {
  168. _logger.Debug("Saving image to {0}", path);
  169. var parentFolder = Path.GetDirectoryName(path);
  170. _directoryWatchers.TemporarilyIgnore(path);
  171. _directoryWatchers.TemporarilyIgnore(parentFolder);
  172. try
  173. {
  174. Directory.CreateDirectory(Path.GetDirectoryName(path));
  175. // If the file is currently hidden we'll have to remove that or the save will fail
  176. var file = new FileInfo(path);
  177. // This will fail if the file is hidden
  178. if (file.Exists)
  179. {
  180. if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  181. {
  182. file.Attributes &= ~FileAttributes.Hidden;
  183. }
  184. }
  185. using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  186. {
  187. await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  188. }
  189. }
  190. finally
  191. {
  192. _directoryWatchers.RemoveTempIgnore(path);
  193. _directoryWatchers.RemoveTempIgnore(parentFolder);
  194. }
  195. }
  196. /// <summary>
  197. /// Gets the save paths.
  198. /// </summary>
  199. /// <param name="item">The item.</param>
  200. /// <param name="type">The type.</param>
  201. /// <param name="imageIndex">Index of the image.</param>
  202. /// <param name="mimeType">Type of the MIME.</param>
  203. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  204. /// <returns>IEnumerable{System.String}.</returns>
  205. private string[] GetSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  206. {
  207. if (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy || !saveLocally)
  208. {
  209. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
  210. }
  211. return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
  212. }
  213. /// <summary>
  214. /// Gets the current image path.
  215. /// </summary>
  216. /// <param name="item">The item.</param>
  217. /// <param name="type">The type.</param>
  218. /// <param name="imageIndex">Index of the image.</param>
  219. /// <returns>System.String.</returns>
  220. /// <exception cref="System.ArgumentNullException">
  221. /// imageIndex
  222. /// or
  223. /// imageIndex
  224. /// </exception>
  225. private string GetCurrentImagePath(BaseItem item, ImageType type, int? imageIndex)
  226. {
  227. switch (type)
  228. {
  229. case ImageType.Screenshot:
  230. var hasScreenshots = (IHasScreenshots)item;
  231. if (!imageIndex.HasValue)
  232. {
  233. throw new ArgumentNullException("imageIndex");
  234. }
  235. return hasScreenshots.ScreenshotImagePaths.Count > imageIndex.Value ? hasScreenshots.ScreenshotImagePaths[imageIndex.Value] : null;
  236. case ImageType.Backdrop:
  237. if (!imageIndex.HasValue)
  238. {
  239. throw new ArgumentNullException("imageIndex");
  240. }
  241. return item.BackdropImagePaths.Count > imageIndex.Value ? item.BackdropImagePaths[imageIndex.Value] : null;
  242. default:
  243. return item.GetImage(type);
  244. }
  245. }
  246. /// <summary>
  247. /// Sets the image path.
  248. /// </summary>
  249. /// <param name="item">The item.</param>
  250. /// <param name="type">The type.</param>
  251. /// <param name="imageIndex">Index of the image.</param>
  252. /// <param name="path">The path.</param>
  253. /// <param name="sourceUrl">The source URL.</param>
  254. /// <exception cref="System.ArgumentNullException">imageIndex
  255. /// or
  256. /// imageIndex</exception>
  257. private void SetImagePath(BaseItem item, ImageType type, int? imageIndex, string path, string sourceUrl)
  258. {
  259. switch (type)
  260. {
  261. case ImageType.Screenshot:
  262. if (!imageIndex.HasValue)
  263. {
  264. throw new ArgumentNullException("imageIndex");
  265. }
  266. var hasScreenshots = (IHasScreenshots)item;
  267. if (hasScreenshots.ScreenshotImagePaths.Count > imageIndex.Value)
  268. {
  269. hasScreenshots.ScreenshotImagePaths[imageIndex.Value] = path;
  270. }
  271. else if (!hasScreenshots.ScreenshotImagePaths.Contains(path, StringComparer.OrdinalIgnoreCase))
  272. {
  273. hasScreenshots.ScreenshotImagePaths.Add(path);
  274. }
  275. break;
  276. case ImageType.Backdrop:
  277. if (!imageIndex.HasValue)
  278. {
  279. throw new ArgumentNullException("imageIndex");
  280. }
  281. if (item.BackdropImagePaths.Count > imageIndex.Value)
  282. {
  283. item.BackdropImagePaths[imageIndex.Value] = path;
  284. }
  285. else if (!item.BackdropImagePaths.Contains(path, StringComparer.OrdinalIgnoreCase))
  286. {
  287. item.BackdropImagePaths.Add(path);
  288. }
  289. if (string.IsNullOrEmpty(sourceUrl))
  290. {
  291. item.RemoveImageSourceForPath(path);
  292. }
  293. else
  294. {
  295. item.AddImageSource(path, sourceUrl);
  296. }
  297. break;
  298. default:
  299. item.SetImage(type, path);
  300. break;
  301. }
  302. }
  303. /// <summary>
  304. /// Gets the save path.
  305. /// </summary>
  306. /// <param name="item">The item.</param>
  307. /// <param name="type">The type.</param>
  308. /// <param name="imageIndex">Index of the image.</param>
  309. /// <param name="mimeType">Type of the MIME.</param>
  310. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  311. /// <returns>System.String.</returns>
  312. /// <exception cref="System.ArgumentNullException">
  313. /// imageIndex
  314. /// or
  315. /// imageIndex
  316. /// </exception>
  317. private string GetStandardSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  318. {
  319. string filename;
  320. switch (type)
  321. {
  322. case ImageType.Art:
  323. filename = "clearart";
  324. break;
  325. case ImageType.Disc:
  326. filename = item is MusicAlbum ? "cdart" : "disc";
  327. break;
  328. case ImageType.Primary:
  329. filename = item is Episode ? Path.GetFileNameWithoutExtension(item.Path) : "folder";
  330. break;
  331. case ImageType.Backdrop:
  332. if (!imageIndex.HasValue)
  333. {
  334. throw new ArgumentNullException("imageIndex");
  335. }
  336. filename = GetBackdropSaveFilename(item.BackdropImagePaths, "backdrop", "backdrop", imageIndex.Value);
  337. break;
  338. case ImageType.Screenshot:
  339. if (!imageIndex.HasValue)
  340. {
  341. throw new ArgumentNullException("imageIndex");
  342. }
  343. var hasScreenshots = (IHasScreenshots)item;
  344. filename = GetBackdropSaveFilename(hasScreenshots.ScreenshotImagePaths, "screenshot", "screenshot", imageIndex.Value);
  345. break;
  346. default:
  347. filename = type.ToString().ToLower();
  348. break;
  349. }
  350. var extension = mimeType.Split('/').Last();
  351. if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
  352. {
  353. extension = "jpg";
  354. }
  355. extension = "." + extension.ToLower();
  356. string path = null;
  357. if (saveLocally)
  358. {
  359. if (item.IsInMixedFolder && !(item is Episode))
  360. {
  361. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  362. }
  363. if (string.IsNullOrEmpty(path))
  364. {
  365. path = Path.Combine(item.MetaLocation, filename + extension);
  366. }
  367. }
  368. // None of the save local conditions passed, so store it in our internal folders
  369. if (string.IsNullOrEmpty(path))
  370. {
  371. path = _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Id, filename + extension);
  372. }
  373. return path;
  374. }
  375. private string GetBackdropSaveFilename(IEnumerable<string> images, string zeroIndexFilename, string numberedIndexPrefix, int index)
  376. {
  377. if (index == 0)
  378. {
  379. return zeroIndexFilename;
  380. }
  381. var filenames = images.Select(Path.GetFileNameWithoutExtension).ToList();
  382. var current = index;
  383. while (filenames.Contains(numberedIndexPrefix + current.ToString(UsCulture), StringComparer.OrdinalIgnoreCase))
  384. {
  385. current++;
  386. }
  387. return numberedIndexPrefix + current.ToString(UsCulture);
  388. }
  389. /// <summary>
  390. /// Gets the compatible save paths.
  391. /// </summary>
  392. /// <param name="item">The item.</param>
  393. /// <param name="type">The type.</param>
  394. /// <param name="imageIndex">Index of the image.</param>
  395. /// <param name="mimeType">Type of the MIME.</param>
  396. /// <returns>IEnumerable{System.String}.</returns>
  397. /// <exception cref="System.ArgumentNullException">imageIndex</exception>
  398. private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType)
  399. {
  400. var season = item as Season;
  401. var extension = mimeType.Split('/').Last();
  402. if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
  403. {
  404. extension = "jpg";
  405. }
  406. extension = "." + extension.ToLower();
  407. // Backdrop paths
  408. if (type == ImageType.Backdrop)
  409. {
  410. if (!imageIndex.HasValue)
  411. {
  412. throw new ArgumentNullException("imageIndex");
  413. }
  414. if (imageIndex.Value == 0)
  415. {
  416. if (item.IsInMixedFolder)
  417. {
  418. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart", extension) };
  419. }
  420. if (season != null && item.IndexNumber.HasValue)
  421. {
  422. var seriesFolder = season.SeriesPath;
  423. var seasonMarker = item.IndexNumber.Value == 0
  424. ? "-specials"
  425. : item.IndexNumber.Value.ToString("00", UsCulture);
  426. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  427. return new[] { Path.Combine(seriesFolder, imageFilename) };
  428. }
  429. return new[]
  430. {
  431. Path.Combine(item.MetaLocation, "fanart" + extension)
  432. };
  433. }
  434. var outputIndex = imageIndex.Value;
  435. if (item.IsInMixedFolder)
  436. {
  437. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(UsCulture), extension) };
  438. }
  439. var extraFanartFilename = GetBackdropSaveFilename(item.BackdropImagePaths, "fanart", "fanart", outputIndex);
  440. return new[]
  441. {
  442. Path.Combine(item.MetaLocation, "extrafanart", extraFanartFilename + extension),
  443. Path.Combine(item.MetaLocation, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension)
  444. };
  445. }
  446. if (type == ImageType.Primary)
  447. {
  448. if (season != null && item.IndexNumber.HasValue)
  449. {
  450. var seriesFolder = season.SeriesPath;
  451. var seasonMarker = item.IndexNumber.Value == 0
  452. ? "-specials"
  453. : item.IndexNumber.Value.ToString("00", UsCulture);
  454. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  455. return new[] { Path.Combine(seriesFolder, imageFilename) };
  456. }
  457. if (item is Episode)
  458. {
  459. var seasonFolder = Path.GetDirectoryName(item.Path);
  460. var imageFilename = Path.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
  461. return new[] { Path.Combine(seasonFolder, imageFilename) };
  462. }
  463. if (item.IsInMixedFolder || item is MusicVideo)
  464. {
  465. return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
  466. }
  467. if (item is MusicAlbum || item is MusicArtist)
  468. {
  469. return new[] { Path.Combine(item.MetaLocation, "folder" + extension) };
  470. }
  471. return new[] { Path.Combine(item.MetaLocation, "poster" + extension) };
  472. }
  473. if (type == ImageType.Banner)
  474. {
  475. if (season != null && item.IndexNumber.HasValue)
  476. {
  477. var seriesFolder = season.SeriesPath;
  478. var seasonMarker = item.IndexNumber.Value == 0
  479. ? "-specials"
  480. : item.IndexNumber.Value.ToString("00", UsCulture);
  481. var imageFilename = "season" + seasonMarker + "-banner" + extension;
  482. return new[] { Path.Combine(seriesFolder, imageFilename) };
  483. }
  484. }
  485. if (type == ImageType.Thumb)
  486. {
  487. if (season != null && item.IndexNumber.HasValue)
  488. {
  489. var seriesFolder = season.SeriesPath;
  490. var seasonMarker = item.IndexNumber.Value == 0
  491. ? "-specials"
  492. : item.IndexNumber.Value.ToString("00", UsCulture);
  493. var imageFilename = "season" + seasonMarker + "-landscape" + extension;
  494. return new[] { Path.Combine(seriesFolder, imageFilename) };
  495. }
  496. }
  497. // All other paths are the same
  498. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
  499. }
  500. /// <summary>
  501. /// Gets the save path for item in mixed folder.
  502. /// </summary>
  503. /// <param name="item">The item.</param>
  504. /// <param name="type">The type.</param>
  505. /// <param name="imageFilename">The image filename.</param>
  506. /// <param name="extension">The extension.</param>
  507. /// <returns>System.String.</returns>
  508. private string GetSavePathForItemInMixedFolder(BaseItem item, ImageType type, string imageFilename, string extension)
  509. {
  510. if (type == ImageType.Primary)
  511. {
  512. imageFilename = "poster";
  513. }
  514. var folder = Path.GetDirectoryName(item.Path);
  515. return Path.Combine(folder, Path.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
  516. }
  517. }
  518. }