ImageSaver.cs 22 KB

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