ImageSaver.cs 20 KB

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