ImageSaver.cs 22 KB

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