ImageSaver.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. _fileSystem.DeleteFile(currentFile.FullName);
  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)
  202. .ConfigureAwait(false);
  203. }
  204. if (_config.Configuration.SaveMetadataHidden)
  205. {
  206. file.Refresh();
  207. // Add back the attribute
  208. file.Attributes |= FileAttributes.Hidden;
  209. }
  210. }
  211. catch (UnauthorizedAccessException ex)
  212. {
  213. _logger.Error("Error saving image to {0}", ex, path);
  214. throw new Exception(string.Format("Error saving image to {0}", path), ex);
  215. }
  216. finally
  217. {
  218. _libraryMonitor.ReportFileSystemChangeComplete(path, false);
  219. _libraryMonitor.ReportFileSystemChangeComplete(parentFolder, false);
  220. }
  221. }
  222. /// <summary>
  223. /// Gets the save paths.
  224. /// </summary>
  225. /// <param name="item">The item.</param>
  226. /// <param name="type">The type.</param>
  227. /// <param name="imageIndex">Index of the image.</param>
  228. /// <param name="mimeType">Type of the MIME.</param>
  229. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  230. /// <returns>IEnumerable{System.String}.</returns>
  231. private string[] GetSavePaths(IHasImages item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  232. {
  233. if (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy || !saveLocally)
  234. {
  235. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
  236. }
  237. return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
  238. }
  239. /// <summary>
  240. /// Gets the current image 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. /// <returns>System.String.</returns>
  246. /// <exception cref="System.ArgumentNullException">
  247. /// imageIndex
  248. /// or
  249. /// imageIndex
  250. /// </exception>
  251. private string GetCurrentImagePath(IHasImages item, ImageType type, int imageIndex)
  252. {
  253. return item.GetImagePath(type, imageIndex);
  254. }
  255. /// <summary>
  256. /// Sets the image path.
  257. /// </summary>
  258. /// <param name="item">The item.</param>
  259. /// <param name="type">The type.</param>
  260. /// <param name="imageIndex">Index of the image.</param>
  261. /// <param name="path">The path.</param>
  262. /// <exception cref="System.ArgumentNullException">imageIndex
  263. /// or
  264. /// imageIndex</exception>
  265. private void SetImagePath(IHasImages item, ImageType type, int? imageIndex, string path)
  266. {
  267. item.SetImagePath(type, imageIndex ?? 0, new FileInfo(path));
  268. }
  269. /// <summary>
  270. /// Gets the save path.
  271. /// </summary>
  272. /// <param name="item">The item.</param>
  273. /// <param name="type">The type.</param>
  274. /// <param name="imageIndex">Index of the image.</param>
  275. /// <param name="mimeType">Type of the MIME.</param>
  276. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  277. /// <returns>System.String.</returns>
  278. /// <exception cref="System.ArgumentNullException">
  279. /// imageIndex
  280. /// or
  281. /// imageIndex
  282. /// </exception>
  283. private string GetStandardSavePath(IHasImages item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  284. {
  285. string filename;
  286. switch (type)
  287. {
  288. case ImageType.Art:
  289. filename = "clearart";
  290. break;
  291. case ImageType.BoxRear:
  292. filename = "back";
  293. break;
  294. case ImageType.Disc:
  295. filename = item is MusicAlbum ? "cdart" : "disc";
  296. break;
  297. case ImageType.Primary:
  298. filename = item is Episode ? _fileSystem.GetFileNameWithoutExtension(item.Path) : "folder";
  299. break;
  300. case ImageType.Backdrop:
  301. filename = GetBackdropSaveFilename(item.GetImages(type), "backdrop", "backdrop", imageIndex);
  302. break;
  303. case ImageType.Screenshot:
  304. filename = GetBackdropSaveFilename(item.GetImages(type), "screenshot", "screenshot", imageIndex);
  305. break;
  306. default:
  307. filename = type.ToString().ToLower();
  308. break;
  309. }
  310. var extension = mimeType.Split('/').Last();
  311. if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
  312. {
  313. extension = "jpg";
  314. }
  315. extension = "." + extension.ToLower();
  316. string path = null;
  317. if (saveLocally)
  318. {
  319. if (item is Episode)
  320. {
  321. path = Path.Combine(Path.GetDirectoryName(item.Path), "metadata", filename + extension);
  322. }
  323. else if (item.IsInMixedFolder)
  324. {
  325. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  326. }
  327. if (string.IsNullOrEmpty(path))
  328. {
  329. path = Path.Combine(item.ContainingFolderPath, filename + extension);
  330. }
  331. }
  332. // None of the save local conditions passed, so store it in our internal folders
  333. if (string.IsNullOrEmpty(path))
  334. {
  335. if (string.IsNullOrEmpty(filename))
  336. {
  337. filename = "folder";
  338. }
  339. path = Path.Combine(item.GetInternalMetadataPath(), filename + extension);
  340. }
  341. return path;
  342. }
  343. private string GetBackdropSaveFilename(IEnumerable<ItemImageInfo> images, string zeroIndexFilename, string numberedIndexPrefix, int? index)
  344. {
  345. if (index.HasValue && index.Value == 0)
  346. {
  347. return zeroIndexFilename;
  348. }
  349. var filenames = images.Select(i => _fileSystem.GetFileNameWithoutExtension(i.Path)).ToList();
  350. var current = 1;
  351. while (filenames.Contains(numberedIndexPrefix + current.ToString(UsCulture), StringComparer.OrdinalIgnoreCase))
  352. {
  353. current++;
  354. }
  355. return numberedIndexPrefix + current.ToString(UsCulture);
  356. }
  357. /// <summary>
  358. /// Gets the compatible save paths.
  359. /// </summary>
  360. /// <param name="item">The item.</param>
  361. /// <param name="type">The type.</param>
  362. /// <param name="imageIndex">Index of the image.</param>
  363. /// <param name="mimeType">Type of the MIME.</param>
  364. /// <returns>IEnumerable{System.String}.</returns>
  365. /// <exception cref="System.ArgumentNullException">imageIndex</exception>
  366. private string[] GetCompatibleSavePaths(IHasImages item, ImageType type, int? imageIndex, string mimeType)
  367. {
  368. var season = item as Season;
  369. var extension = MimeTypes.ToExtension(mimeType);
  370. // Backdrop paths
  371. if (type == ImageType.Backdrop)
  372. {
  373. if (!imageIndex.HasValue)
  374. {
  375. throw new ArgumentNullException("imageIndex");
  376. }
  377. if (imageIndex.Value == 0)
  378. {
  379. if (item.IsInMixedFolder)
  380. {
  381. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart", extension) };
  382. }
  383. if (season != null && season.IndexNumber.HasValue)
  384. {
  385. var seriesFolder = season.SeriesPath;
  386. var seasonMarker = season.IndexNumber.Value == 0
  387. ? "-specials"
  388. : season.IndexNumber.Value.ToString("00", UsCulture);
  389. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  390. return new[] { Path.Combine(seriesFolder, imageFilename) };
  391. }
  392. return new[]
  393. {
  394. Path.Combine(item.ContainingFolderPath, "fanart" + extension)
  395. };
  396. }
  397. var outputIndex = imageIndex.Value;
  398. if (item.IsInMixedFolder)
  399. {
  400. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(UsCulture), extension) };
  401. }
  402. var extraFanartFilename = GetBackdropSaveFilename(item.GetImages(ImageType.Backdrop), "fanart", "fanart", outputIndex);
  403. var list = new List<string>
  404. {
  405. Path.Combine(item.ContainingFolderPath, "extrafanart", extraFanartFilename + extension)
  406. };
  407. if (EnableExtraThumbsDuplication)
  408. {
  409. list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension));
  410. }
  411. return list.ToArray();
  412. }
  413. if (type == ImageType.Primary)
  414. {
  415. if (season != null && season.IndexNumber.HasValue)
  416. {
  417. var seriesFolder = season.SeriesPath;
  418. var seasonMarker = season.IndexNumber.Value == 0
  419. ? "-specials"
  420. : season.IndexNumber.Value.ToString("00", UsCulture);
  421. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  422. return new[] { Path.Combine(seriesFolder, imageFilename) };
  423. }
  424. if (item is Episode)
  425. {
  426. var seasonFolder = Path.GetDirectoryName(item.Path);
  427. var imageFilename = _fileSystem.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
  428. return new[] { Path.Combine(seasonFolder, imageFilename) };
  429. }
  430. if (item.IsInMixedFolder || item is MusicVideo)
  431. {
  432. return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
  433. }
  434. if (item is MusicAlbum || item is MusicArtist)
  435. {
  436. return new[] { Path.Combine(item.ContainingFolderPath, "folder" + extension) };
  437. }
  438. return new[] { Path.Combine(item.ContainingFolderPath, "poster" + extension) };
  439. }
  440. if (type == ImageType.Banner)
  441. {
  442. if (season != null && season.IndexNumber.HasValue)
  443. {
  444. var seriesFolder = season.SeriesPath;
  445. var seasonMarker = season.IndexNumber.Value == 0
  446. ? "-specials"
  447. : season.IndexNumber.Value.ToString("00", UsCulture);
  448. var imageFilename = "season" + seasonMarker + "-banner" + extension;
  449. return new[] { Path.Combine(seriesFolder, imageFilename) };
  450. }
  451. }
  452. if (type == ImageType.Thumb)
  453. {
  454. if (season != null && season.IndexNumber.HasValue)
  455. {
  456. var seriesFolder = season.SeriesPath;
  457. var seasonMarker = season.IndexNumber.Value == 0
  458. ? "-specials"
  459. : season.IndexNumber.Value.ToString("00", UsCulture);
  460. var imageFilename = "season" + seasonMarker + "-landscape" + extension;
  461. return new[] { Path.Combine(seriesFolder, imageFilename) };
  462. }
  463. if (item.IsInMixedFolder)
  464. {
  465. return new[] { GetSavePathForItemInMixedFolder(item, type, "landscape", extension) };
  466. }
  467. return new[] { Path.Combine(item.ContainingFolderPath, "landscape" + extension) };
  468. }
  469. // All other paths are the same
  470. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
  471. }
  472. private bool EnableExtraThumbsDuplication
  473. {
  474. get
  475. {
  476. var config = _config.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
  477. return config.EnableExtraThumbsDuplication;
  478. }
  479. }
  480. /// <summary>
  481. /// Gets the save path for item in mixed folder.
  482. /// </summary>
  483. /// <param name="item">The item.</param>
  484. /// <param name="type">The type.</param>
  485. /// <param name="imageFilename">The image filename.</param>
  486. /// <param name="extension">The extension.</param>
  487. /// <returns>System.String.</returns>
  488. private string GetSavePathForItemInMixedFolder(IHasImages item, ImageType type, string imageFilename, string extension)
  489. {
  490. if (type == ImageType.Primary)
  491. {
  492. imageFilename = "poster";
  493. }
  494. var folder = Path.GetDirectoryName(item.Path);
  495. return Path.Combine(folder, _fileSystem.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
  496. }
  497. }
  498. }