ImageSaver.cs 22 KB

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