ImageSaver.cs 21 KB

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