ImageSaver.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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 System;
  10. using System.Collections.Generic;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using MediaBrowser.Model.Logging;
  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. }
  84. if (type == ImageType.Backdrop && imageIndex == null)
  85. {
  86. imageIndex = item.BackdropImagePaths.Count;
  87. }
  88. else if (type == ImageType.Screenshot && imageIndex == null)
  89. {
  90. imageIndex = item.ScreenshotImagePaths.Count;
  91. }
  92. var paths = GetSavePaths(item, type, imageIndex, mimeType, saveLocally);
  93. // If there are more than one output paths, the stream will need to be seekable
  94. if (paths.Length > 1 && !source.CanSeek)
  95. {
  96. var memoryStream = new MemoryStream();
  97. using (source)
  98. {
  99. await source.CopyToAsync(memoryStream).ConfigureAwait(false);
  100. }
  101. memoryStream.Position = 0;
  102. source = memoryStream;
  103. }
  104. var currentPath = GetCurrentImagePath(item, type, imageIndex);
  105. using (source)
  106. {
  107. var isFirst = true;
  108. foreach (var path in paths)
  109. {
  110. // Seek back to the beginning
  111. if (!isFirst)
  112. {
  113. source.Position = 0;
  114. }
  115. await SaveImageToLocation(source, path, cancellationToken).ConfigureAwait(false);
  116. isFirst = false;
  117. }
  118. }
  119. // Set the path into the BaseItem
  120. SetImagePath(item, type, imageIndex, paths[0], sourceUrl);
  121. // Delete the current path
  122. if (!string.IsNullOrEmpty(currentPath) && !paths.Contains(currentPath, StringComparer.OrdinalIgnoreCase))
  123. {
  124. _directoryWatchers.TemporarilyIgnore(currentPath);
  125. try
  126. {
  127. var currentFile = new FileInfo(currentPath);
  128. // This will fail if the file is hidden
  129. if (currentFile.Exists)
  130. {
  131. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  132. {
  133. currentFile.Attributes &= ~FileAttributes.Hidden;
  134. }
  135. currentFile.Delete();
  136. }
  137. }
  138. finally
  139. {
  140. _directoryWatchers.RemoveTempIgnore(currentPath);
  141. }
  142. }
  143. }
  144. /// <summary>
  145. /// Saves the image to location.
  146. /// </summary>
  147. /// <param name="source">The source.</param>
  148. /// <param name="path">The path.</param>
  149. /// <param name="cancellationToken">The cancellation token.</param>
  150. /// <returns>Task.</returns>
  151. private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken)
  152. {
  153. _logger.Debug("Saving image to {0}", path);
  154. var parentFolder = Path.GetDirectoryName(path);
  155. _directoryWatchers.TemporarilyIgnore(path);
  156. _directoryWatchers.TemporarilyIgnore(parentFolder);
  157. try
  158. {
  159. Directory.CreateDirectory(Path.GetDirectoryName(path));
  160. // If the file is currently hidden we'll have to remove that or the save will fail
  161. var file = new FileInfo(path);
  162. // This will fail if the file is hidden
  163. if (file.Exists)
  164. {
  165. if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  166. {
  167. file.Attributes &= ~FileAttributes.Hidden;
  168. }
  169. }
  170. using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  171. {
  172. await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  173. }
  174. }
  175. finally
  176. {
  177. _directoryWatchers.RemoveTempIgnore(path);
  178. _directoryWatchers.RemoveTempIgnore(parentFolder);
  179. }
  180. }
  181. /// <summary>
  182. /// Gets the save paths.
  183. /// </summary>
  184. /// <param name="item">The item.</param>
  185. /// <param name="type">The type.</param>
  186. /// <param name="imageIndex">Index of the image.</param>
  187. /// <param name="mimeType">Type of the MIME.</param>
  188. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  189. /// <returns>IEnumerable{System.String}.</returns>
  190. private string[] GetSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  191. {
  192. if (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy || !saveLocally)
  193. {
  194. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
  195. }
  196. return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
  197. }
  198. /// <summary>
  199. /// Gets the current image path.
  200. /// </summary>
  201. /// <param name="item">The item.</param>
  202. /// <param name="type">The type.</param>
  203. /// <param name="imageIndex">Index of the image.</param>
  204. /// <returns>System.String.</returns>
  205. /// <exception cref="System.ArgumentNullException">
  206. /// imageIndex
  207. /// or
  208. /// imageIndex
  209. /// </exception>
  210. private string GetCurrentImagePath(BaseItem item, ImageType type, int? imageIndex)
  211. {
  212. switch (type)
  213. {
  214. case ImageType.Screenshot:
  215. if (!imageIndex.HasValue)
  216. {
  217. throw new ArgumentNullException("imageIndex");
  218. }
  219. return item.ScreenshotImagePaths.Count > imageIndex.Value ? item.ScreenshotImagePaths[imageIndex.Value] : null;
  220. case ImageType.Backdrop:
  221. if (!imageIndex.HasValue)
  222. {
  223. throw new ArgumentNullException("imageIndex");
  224. }
  225. return item.BackdropImagePaths.Count > imageIndex.Value ? item.BackdropImagePaths[imageIndex.Value] : null;
  226. default:
  227. return item.GetImage(type);
  228. }
  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. if (item.ScreenshotImagePaths.Count > imageIndex.Value)
  251. {
  252. item.ScreenshotImagePaths[imageIndex.Value] = path;
  253. }
  254. else if (!item.ScreenshotImagePaths.Contains(path, StringComparer.OrdinalIgnoreCase))
  255. {
  256. item.ScreenshotImagePaths.Add(path);
  257. }
  258. break;
  259. case ImageType.Backdrop:
  260. if (!imageIndex.HasValue)
  261. {
  262. throw new ArgumentNullException("imageIndex");
  263. }
  264. if (item.BackdropImagePaths.Count > imageIndex.Value)
  265. {
  266. item.BackdropImagePaths[imageIndex.Value] = path;
  267. }
  268. else if (!item.BackdropImagePaths.Contains(path, StringComparer.OrdinalIgnoreCase))
  269. {
  270. item.BackdropImagePaths.Add(path);
  271. }
  272. if (string.IsNullOrEmpty(sourceUrl))
  273. {
  274. item.RemoveImageSourceForPath(path);
  275. }
  276. else
  277. {
  278. item.AddImageSource(path, sourceUrl);
  279. }
  280. break;
  281. default:
  282. item.SetImage(type, path);
  283. break;
  284. }
  285. }
  286. /// <summary>
  287. /// Gets the save path.
  288. /// </summary>
  289. /// <param name="item">The item.</param>
  290. /// <param name="type">The type.</param>
  291. /// <param name="imageIndex">Index of the image.</param>
  292. /// <param name="mimeType">Type of the MIME.</param>
  293. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  294. /// <returns>System.String.</returns>
  295. /// <exception cref="System.ArgumentNullException">
  296. /// imageIndex
  297. /// or
  298. /// imageIndex
  299. /// </exception>
  300. private string GetStandardSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  301. {
  302. string filename;
  303. switch (type)
  304. {
  305. case ImageType.Art:
  306. filename = "clearart";
  307. break;
  308. case ImageType.Primary:
  309. filename = item is Episode ? Path.GetFileNameWithoutExtension(item.Path) : "folder";
  310. break;
  311. case ImageType.Backdrop:
  312. if (!imageIndex.HasValue)
  313. {
  314. throw new ArgumentNullException("imageIndex");
  315. }
  316. filename = GetBackdropSaveFilename(item.BackdropImagePaths, "backdrop", "backdrop", imageIndex.Value);
  317. break;
  318. case ImageType.Screenshot:
  319. if (!imageIndex.HasValue)
  320. {
  321. throw new ArgumentNullException("imageIndex");
  322. }
  323. filename = GetBackdropSaveFilename(item.ScreenshotImagePaths, "screenshot", "screenshot", imageIndex.Value);
  324. break;
  325. default:
  326. filename = type.ToString().ToLower();
  327. break;
  328. }
  329. var extension = mimeType.Split('/').Last();
  330. if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
  331. {
  332. extension = "jpg";
  333. }
  334. extension = "." + extension.ToLower();
  335. string path = null;
  336. if (saveLocally)
  337. {
  338. if (item.IsInMixedFolder && !(item is Episode))
  339. {
  340. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  341. }
  342. if (string.IsNullOrEmpty(path))
  343. {
  344. path = Path.Combine(item.MetaLocation, filename + extension);
  345. }
  346. }
  347. // None of the save local conditions passed, so store it in our internal folders
  348. if (string.IsNullOrEmpty(path))
  349. {
  350. path = _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Id, filename + extension);
  351. }
  352. return path;
  353. }
  354. private string GetBackdropSaveFilename(List<string> images, string zeroIndexFilename, string numberedIndexPrefix, int index)
  355. {
  356. if (index == 0)
  357. {
  358. return zeroIndexFilename;
  359. }
  360. var filenames = images.Select(Path.GetFileNameWithoutExtension).ToList();
  361. var current = index;
  362. while (filenames.Contains(numberedIndexPrefix + current.ToString(UsCulture), StringComparer.OrdinalIgnoreCase))
  363. {
  364. current++;
  365. }
  366. return numberedIndexPrefix + current.ToString(UsCulture);
  367. }
  368. /// <summary>
  369. /// Gets the compatible save paths.
  370. /// </summary>
  371. /// <param name="item">The item.</param>
  372. /// <param name="type">The type.</param>
  373. /// <param name="imageIndex">Index of the image.</param>
  374. /// <param name="mimeType">Type of the MIME.</param>
  375. /// <returns>IEnumerable{System.String}.</returns>
  376. /// <exception cref="System.ArgumentNullException">imageIndex</exception>
  377. private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType)
  378. {
  379. var extension = mimeType.Split('/').Last();
  380. if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
  381. {
  382. extension = "jpg";
  383. }
  384. extension = "." + extension.ToLower();
  385. // Backdrop paths
  386. if (type == ImageType.Backdrop)
  387. {
  388. if (!imageIndex.HasValue)
  389. {
  390. throw new ArgumentNullException("imageIndex");
  391. }
  392. if (imageIndex.Value == 0)
  393. {
  394. if (item is Season && item.IndexNumber.HasValue)
  395. {
  396. var seriesFolder = Path.GetDirectoryName(item.Path);
  397. var seasonMarker = item.IndexNumber.Value == 0
  398. ? "-specials"
  399. : item.IndexNumber.Value.ToString("00", UsCulture);
  400. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  401. return new[] { Path.Combine(seriesFolder, imageFilename) };
  402. }
  403. return new[]
  404. {
  405. Path.Combine(item.MetaLocation, "fanart" + extension)
  406. };
  407. }
  408. var outputIndex = imageIndex.Value;
  409. var extraFanartFilename = GetBackdropSaveFilename(item.BackdropImagePaths, "fanart", "fanart", outputIndex);
  410. return new[]
  411. {
  412. Path.Combine(item.MetaLocation, "extrafanart", extraFanartFilename + extension),
  413. Path.Combine(item.MetaLocation, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension)
  414. };
  415. }
  416. if (type == ImageType.Primary)
  417. {
  418. if (item is Season && item.IndexNumber.HasValue)
  419. {
  420. var seriesFolder = Path.GetDirectoryName(item.Path);
  421. var seasonMarker = item.IndexNumber.Value == 0
  422. ? "-specials"
  423. : item.IndexNumber.Value.ToString("00", UsCulture);
  424. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  425. return new[] { Path.Combine(seriesFolder, imageFilename) };
  426. }
  427. if (item is Episode)
  428. {
  429. var seasonFolder = Path.GetDirectoryName(item.Path);
  430. var imageFilename = Path.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
  431. return new[] { Path.Combine(seasonFolder, imageFilename) };
  432. }
  433. if (item.IsInMixedFolder)
  434. {
  435. return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
  436. }
  437. var filename = "poster" + extension;
  438. return new[] { Path.Combine(item.MetaLocation, filename) };
  439. }
  440. if (type == ImageType.Banner)
  441. {
  442. if (item is Season && item.IndexNumber.HasValue)
  443. {
  444. var seriesFolder = Path.GetDirectoryName(item.Path);
  445. var seasonMarker = item.IndexNumber.Value == 0
  446. ? "-specials"
  447. : item.IndexNumber.Value.ToString("00", UsCulture);
  448. var imageFilename = "season" + seasonMarker + "-banner" + extension;
  449. return new[] { Path.Combine(seriesFolder, imageFilename) };
  450. }
  451. }
  452. if (type == ImageType.Thumb)
  453. {
  454. if (item is Season && item.IndexNumber.HasValue)
  455. {
  456. var seriesFolder = Path.GetDirectoryName(item.Path);
  457. var seasonMarker = item.IndexNumber.Value == 0
  458. ? "-specials"
  459. : item.IndexNumber.Value.ToString("00", UsCulture);
  460. var imageFilename = "season" + seasonMarker + "-landscape" + extension;
  461. return new[] { Path.Combine(seriesFolder, imageFilename) };
  462. }
  463. }
  464. // All other paths are the same
  465. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
  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(BaseItem 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, Path.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
  483. }
  484. }
  485. }