ImageSaver.cs 21 KB

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