ImageSaver.cs 21 KB

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