ImageSaver.cs 22 KB

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