ImageSaver.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Extensions;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Entities.Audio;
  15. using MediaBrowser.Controller.IO;
  16. using MediaBrowser.Controller.Library;
  17. using MediaBrowser.Model.Configuration;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.IO;
  20. using MediaBrowser.Model.Net;
  21. using Microsoft.Extensions.Logging;
  22. using Episode = MediaBrowser.Controller.Entities.TV.Episode;
  23. using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
  24. using Person = MediaBrowser.Controller.Entities.Person;
  25. using Season = MediaBrowser.Controller.Entities.TV.Season;
  26. namespace MediaBrowser.Providers.Manager
  27. {
  28. /// <summary>
  29. /// Class ImageSaver.
  30. /// </summary>
  31. public class ImageSaver
  32. {
  33. /// <summary>
  34. /// The _config.
  35. /// </summary>
  36. private readonly IServerConfigurationManager _config;
  37. /// <summary>
  38. /// The _directory watchers.
  39. /// </summary>
  40. private readonly ILibraryMonitor _libraryMonitor;
  41. private readonly IFileSystem _fileSystem;
  42. private readonly ILogger _logger;
  43. /// <summary>
  44. /// Initializes a new instance of the <see cref="ImageSaver" /> class.
  45. /// </summary>
  46. /// <param name="config">The config.</param>
  47. /// <param name="libraryMonitor">The directory watchers.</param>
  48. /// <param name="fileSystem">The file system.</param>
  49. /// <param name="logger">The logger.</param>
  50. public ImageSaver(IServerConfigurationManager config, ILibraryMonitor libraryMonitor, IFileSystem fileSystem, ILogger logger)
  51. {
  52. _config = config;
  53. _libraryMonitor = libraryMonitor;
  54. _fileSystem = fileSystem;
  55. _logger = logger;
  56. }
  57. private bool EnableExtraThumbsDuplication
  58. {
  59. get
  60. {
  61. var config = _config.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
  62. return config.EnableExtraThumbsDuplication;
  63. }
  64. }
  65. /// <summary>
  66. /// Saves the image.
  67. /// </summary>
  68. /// <param name="item">The item.</param>
  69. /// <param name="source">The source.</param>
  70. /// <param name="mimeType">Type of the MIME.</param>
  71. /// <param name="type">The type.</param>
  72. /// <param name="imageIndex">Index of the image.</param>
  73. /// <param name="cancellationToken">The cancellation token.</param>
  74. /// <returns>Task.</returns>
  75. /// <exception cref="ArgumentNullException">mimeType.</exception>
  76. public Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
  77. {
  78. return SaveImage(item, source, mimeType, type, imageIndex, null, cancellationToken);
  79. }
  80. public async Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, bool? saveLocallyWithMedia, CancellationToken cancellationToken)
  81. {
  82. ArgumentException.ThrowIfNullOrEmpty(mimeType);
  83. var saveLocally = item.SupportsLocalMetadata && item.IsSaveLocalMetadataEnabled() && !item.ExtraType.HasValue && item is not Audio;
  84. if (type != ImageType.Primary && item is Episode)
  85. {
  86. saveLocally = false;
  87. }
  88. if (!item.IsFileProtocol)
  89. {
  90. saveLocally = false;
  91. // If season is virtual under a physical series, save locally
  92. if (item is Season season)
  93. {
  94. var series = season.Series;
  95. if (series is not null && series.SupportsLocalMetadata && series.IsSaveLocalMetadataEnabled())
  96. {
  97. saveLocally = true;
  98. }
  99. }
  100. }
  101. if (saveLocallyWithMedia.HasValue && !saveLocallyWithMedia.Value)
  102. {
  103. saveLocally = saveLocallyWithMedia.Value;
  104. }
  105. if (!imageIndex.HasValue && item.AllowsMultipleImages(type))
  106. {
  107. imageIndex = item.GetImages(type).Count();
  108. }
  109. var index = imageIndex ?? 0;
  110. var paths = GetSavePaths(item, type, imageIndex, mimeType, saveLocally);
  111. string[] retryPaths = [];
  112. if (saveLocally)
  113. {
  114. retryPaths = GetSavePaths(item, type, imageIndex, mimeType, false);
  115. }
  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. await using (source.ConfigureAwait(false))
  121. {
  122. await source.CopyToAsync(memoryStream, cancellationToken).ConfigureAwait(false);
  123. }
  124. source = memoryStream;
  125. }
  126. var currentImage = GetCurrentImage(item, type, index);
  127. var currentImageIsLocalFile = currentImage is not null && currentImage.IsLocalFile;
  128. var currentImagePath = currentImage?.Path;
  129. var savedPaths = new List<string>();
  130. await using (source.ConfigureAwait(false))
  131. {
  132. for (int i = 0; i < paths.Length; i++)
  133. {
  134. if (i != 0)
  135. {
  136. source.Position = 0;
  137. }
  138. string retryPath = null;
  139. if (paths.Length == retryPaths.Length)
  140. {
  141. retryPath = retryPaths[i];
  142. }
  143. var savedPath = await SaveImageToLocation(source, paths[i], retryPath, cancellationToken).ConfigureAwait(false);
  144. savedPaths.Add(savedPath);
  145. }
  146. }
  147. // Set the path into the item
  148. SetImagePath(item, type, imageIndex, savedPaths[0]);
  149. // Delete the current path
  150. if (currentImageIsLocalFile
  151. && !savedPaths.Contains(currentImagePath, StringComparison.OrdinalIgnoreCase)
  152. && (saveLocally || currentImagePath.Contains(_config.ApplicationPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase)))
  153. {
  154. var currentPath = currentImagePath;
  155. _logger.LogInformation("Deleting previous image {0}", currentPath);
  156. _libraryMonitor.ReportFileSystemChangeBeginning(currentPath);
  157. try
  158. {
  159. _fileSystem.DeleteFile(currentPath);
  160. // Remove local episode metadata directory if it exists and is empty
  161. var directory = Path.GetDirectoryName(currentPath);
  162. if (item is Episode && directory.Equals("metadata", StringComparison.Ordinal))
  163. {
  164. var parentDirectoryPath = Directory.GetParent(currentPath).FullName;
  165. if (_fileSystem.DirectoryExists(parentDirectoryPath) && !_fileSystem.GetFiles(parentDirectoryPath).Any())
  166. {
  167. try
  168. {
  169. _logger.LogInformation("Deleting empty local metadata folder {Folder}", parentDirectoryPath);
  170. Directory.Delete(parentDirectoryPath);
  171. }
  172. catch (UnauthorizedAccessException ex)
  173. {
  174. _logger.LogError(ex, "Error deleting directory {Path}", parentDirectoryPath);
  175. }
  176. catch (IOException ex)
  177. {
  178. _logger.LogError(ex, "Error deleting directory {Path}", parentDirectoryPath);
  179. }
  180. }
  181. }
  182. }
  183. catch (FileNotFoundException)
  184. {
  185. }
  186. finally
  187. {
  188. _libraryMonitor.ReportFileSystemChangeComplete(currentPath, false);
  189. }
  190. }
  191. }
  192. public async Task SaveImage(Stream source, string path)
  193. {
  194. await SaveImageToLocation(source, path, path, CancellationToken.None).ConfigureAwait(false);
  195. }
  196. private async Task<string> SaveImageToLocation(Stream source, string path, string retryPath, CancellationToken cancellationToken)
  197. {
  198. try
  199. {
  200. await SaveImageToLocation(source, path, cancellationToken).ConfigureAwait(false);
  201. return path;
  202. }
  203. catch (UnauthorizedAccessException)
  204. {
  205. var retry = !string.IsNullOrWhiteSpace(retryPath) &&
  206. !string.Equals(path, retryPath, StringComparison.OrdinalIgnoreCase);
  207. if (retry)
  208. {
  209. _logger.LogError("UnauthorizedAccessException - Access to path {0} is denied. Will retry saving to {1}", path, retryPath);
  210. }
  211. else
  212. {
  213. throw;
  214. }
  215. }
  216. catch (IOException ex)
  217. {
  218. var retry = !string.IsNullOrWhiteSpace(retryPath) &&
  219. !string.Equals(path, retryPath, StringComparison.OrdinalIgnoreCase);
  220. if (retry)
  221. {
  222. _logger.LogError(ex, "IOException saving to {0}. Will retry saving to {1}", path, retryPath);
  223. }
  224. else
  225. {
  226. throw;
  227. }
  228. }
  229. await SaveImageToLocation(source, retryPath, cancellationToken).ConfigureAwait(false);
  230. return retryPath;
  231. }
  232. /// <summary>
  233. /// Saves the image to location.
  234. /// </summary>
  235. /// <param name="source">The source.</param>
  236. /// <param name="path">The path.</param>
  237. /// <param name="cancellationToken">The cancellation token.</param>
  238. /// <returns>Task.</returns>
  239. private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken)
  240. {
  241. _logger.LogDebug("Saving image to {0}", path);
  242. var parentFolder = Path.GetDirectoryName(path);
  243. try
  244. {
  245. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  246. _libraryMonitor.ReportFileSystemChangeBeginning(parentFolder);
  247. Directory.CreateDirectory(Path.GetDirectoryName(path));
  248. _fileSystem.SetAttributes(path, false, false);
  249. var fileStreamOptions = AsyncFile.WriteOptions;
  250. fileStreamOptions.Mode = FileMode.Create;
  251. fileStreamOptions.Options = FileOptions.WriteThrough;
  252. if (source.CanSeek)
  253. {
  254. fileStreamOptions.PreallocationSize = source.Length;
  255. }
  256. var fs = new FileStream(path, fileStreamOptions);
  257. await using (fs.ConfigureAwait(false))
  258. {
  259. await source.CopyToAsync(fs, cancellationToken).ConfigureAwait(false);
  260. }
  261. if (_config.Configuration.SaveMetadataHidden)
  262. {
  263. SetHidden(path, true);
  264. }
  265. }
  266. finally
  267. {
  268. _libraryMonitor.ReportFileSystemChangeComplete(path, false);
  269. _libraryMonitor.ReportFileSystemChangeComplete(parentFolder, false);
  270. }
  271. }
  272. private void SetHidden(string path, bool hidden)
  273. {
  274. try
  275. {
  276. _fileSystem.SetHidden(path, hidden);
  277. }
  278. catch (Exception ex)
  279. {
  280. _logger.LogError(ex, "Error setting hidden attribute on {0}", path);
  281. }
  282. }
  283. /// <summary>
  284. /// Gets the save paths.
  285. /// </summary>
  286. /// <param name="item">The item.</param>
  287. /// <param name="type">The type.</param>
  288. /// <param name="imageIndex">Index of the image.</param>
  289. /// <param name="mimeType">Type of the MIME.</param>
  290. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  291. /// <returns>IEnumerable{System.String}.</returns>
  292. private string[] GetSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  293. {
  294. if (!saveLocally || (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy))
  295. {
  296. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
  297. }
  298. return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
  299. }
  300. /// <summary>
  301. /// Gets the current image path.
  302. /// </summary>
  303. /// <param name="item">The item.</param>
  304. /// <param name="type">The type.</param>
  305. /// <param name="imageIndex">Index of the image.</param>
  306. /// <returns>System.String.</returns>
  307. /// <exception cref="ArgumentNullException">
  308. /// imageIndex
  309. /// or
  310. /// imageIndex.
  311. /// </exception>
  312. private ItemImageInfo GetCurrentImage(BaseItem item, ImageType type, int imageIndex)
  313. {
  314. return item.GetImageInfo(type, imageIndex);
  315. }
  316. /// <summary>
  317. /// Sets the image path.
  318. /// </summary>
  319. /// <param name="item">The item.</param>
  320. /// <param name="type">The type.</param>
  321. /// <param name="imageIndex">Index of the image.</param>
  322. /// <param name="path">The path.</param>
  323. /// <exception cref="ArgumentNullException">imageIndex
  324. /// or
  325. /// imageIndex.
  326. /// </exception>
  327. private void SetImagePath(BaseItem item, ImageType type, int? imageIndex, string path)
  328. {
  329. item.SetImagePath(type, imageIndex ?? 0, _fileSystem.GetFileInfo(path));
  330. }
  331. /// <summary>
  332. /// Gets the save path.
  333. /// </summary>
  334. /// <param name="item">The item.</param>
  335. /// <param name="type">The type.</param>
  336. /// <param name="imageIndex">Index of the image.</param>
  337. /// <param name="mimeType">Type of the MIME.</param>
  338. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  339. /// <returns>System.String.</returns>
  340. /// <exception cref="ArgumentNullException">
  341. /// imageIndex
  342. /// or
  343. /// imageIndex.
  344. /// </exception>
  345. private string GetStandardSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  346. {
  347. var season = item as Season;
  348. var extension = MimeTypes.ToExtension(mimeType);
  349. if (string.IsNullOrWhiteSpace(extension))
  350. {
  351. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unable to determine image file extension from mime type {0}", mimeType));
  352. }
  353. if (string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase))
  354. {
  355. extension = ".jpg";
  356. }
  357. extension = extension.ToLowerInvariant();
  358. if (type == ImageType.Primary && saveLocally)
  359. {
  360. if (season is not null && season.IndexNumber.HasValue)
  361. {
  362. var seriesFolder = season.SeriesPath;
  363. var seasonMarker = season.IndexNumber.Value == 0
  364. ? "-specials"
  365. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  366. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  367. return Path.Combine(seriesFolder, imageFilename);
  368. }
  369. }
  370. if (type == ImageType.Backdrop && saveLocally)
  371. {
  372. if (season is not null
  373. && season.IndexNumber.HasValue
  374. && (imageIndex is null || imageIndex == 0))
  375. {
  376. var seriesFolder = season.SeriesPath;
  377. var seasonMarker = season.IndexNumber.Value == 0
  378. ? "-specials"
  379. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  380. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  381. return Path.Combine(seriesFolder, imageFilename);
  382. }
  383. }
  384. if (type == ImageType.Thumb && saveLocally)
  385. {
  386. if (season is not null && season.IndexNumber.HasValue)
  387. {
  388. var seriesFolder = season.SeriesPath;
  389. var seasonMarker = season.IndexNumber.Value == 0
  390. ? "-specials"
  391. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  392. var imageFilename = "season" + seasonMarker + "-landscape" + extension;
  393. return Path.Combine(seriesFolder, imageFilename);
  394. }
  395. if (item.IsInMixedFolder)
  396. {
  397. return GetSavePathForItemInMixedFolder(item, type, "landscape", extension);
  398. }
  399. return Path.Combine(item.ContainingFolderPath, "landscape" + extension);
  400. }
  401. if (type == ImageType.Banner && saveLocally)
  402. {
  403. if (season is not null && season.IndexNumber.HasValue)
  404. {
  405. var seriesFolder = season.SeriesPath;
  406. var seasonMarker = season.IndexNumber.Value == 0
  407. ? "-specials"
  408. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  409. var imageFilename = "season" + seasonMarker + "-banner" + extension;
  410. return Path.Combine(seriesFolder, imageFilename);
  411. }
  412. }
  413. if (type == ImageType.Logo && saveLocally)
  414. {
  415. if (season is not 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", CultureInfo.InvariantCulture);
  421. var imageFilename = "season" + seasonMarker + "-logo" + extension;
  422. return Path.Combine(seriesFolder, imageFilename);
  423. }
  424. }
  425. string filename;
  426. var folderName = item is MusicAlbum ||
  427. item is MusicArtist ||
  428. item is PhotoAlbum ||
  429. item is Person ||
  430. (saveLocally && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy) ?
  431. "folder" :
  432. "poster";
  433. switch (type)
  434. {
  435. case ImageType.Art:
  436. filename = "clearart";
  437. break;
  438. case ImageType.BoxRear:
  439. filename = "back";
  440. break;
  441. case ImageType.Thumb:
  442. filename = "landscape";
  443. break;
  444. case ImageType.Disc:
  445. filename = item is MusicAlbum ? "cdart" : "disc";
  446. break;
  447. case ImageType.Primary:
  448. filename = saveLocally && item is Episode ? Path.GetFileNameWithoutExtension(item.Path) : folderName;
  449. break;
  450. case ImageType.Backdrop:
  451. filename = GetBackdropSaveFilename(item.GetImages(type), "backdrop", "backdrop", imageIndex);
  452. break;
  453. default:
  454. filename = type.ToString().ToLowerInvariant();
  455. break;
  456. }
  457. string path = null;
  458. if (saveLocally)
  459. {
  460. if (type == ImageType.Primary && item is Episode)
  461. {
  462. path = Path.Combine(Path.GetDirectoryName(item.Path), filename + "-thumb" + extension);
  463. }
  464. else if (item.IsInMixedFolder)
  465. {
  466. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  467. }
  468. if (string.IsNullOrEmpty(path))
  469. {
  470. path = Path.Combine(item.ContainingFolderPath, filename + extension);
  471. }
  472. }
  473. // None of the save local conditions passed, so store it in our internal folders
  474. if (string.IsNullOrEmpty(path))
  475. {
  476. if (string.IsNullOrEmpty(filename))
  477. {
  478. filename = folderName;
  479. }
  480. path = Path.Combine(item.GetInternalMetadataPath(), filename + extension);
  481. }
  482. return path;
  483. }
  484. private string GetBackdropSaveFilename(IEnumerable<ItemImageInfo> images, string zeroIndexFilename, string numberedIndexPrefix, int? index)
  485. {
  486. if (index.HasValue && index.Value == 0)
  487. {
  488. return zeroIndexFilename;
  489. }
  490. var filenames = images.Select(i => Path.GetFileNameWithoutExtension(i.Path)).ToList();
  491. var current = 1;
  492. while (filenames.Contains(numberedIndexPrefix + current.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase))
  493. {
  494. current++;
  495. }
  496. return numberedIndexPrefix + current.ToString(CultureInfo.InvariantCulture);
  497. }
  498. /// <summary>
  499. /// Gets the compatible save paths.
  500. /// </summary>
  501. /// <param name="item">The item.</param>
  502. /// <param name="type">The type.</param>
  503. /// <param name="imageIndex">Index of the image.</param>
  504. /// <param name="mimeType">Type of the MIME.</param>
  505. /// <returns>IEnumerable{System.String}.</returns>
  506. /// <exception cref="ArgumentNullException">imageIndex.</exception>
  507. private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType)
  508. {
  509. var season = item as Season;
  510. var extension = MimeTypes.ToExtension(mimeType);
  511. // Backdrop paths
  512. if (type == ImageType.Backdrop)
  513. {
  514. if (!imageIndex.HasValue)
  515. {
  516. throw new ArgumentNullException(nameof(imageIndex));
  517. }
  518. if (imageIndex.Value == 0)
  519. {
  520. if (item.IsInMixedFolder)
  521. {
  522. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart", extension) };
  523. }
  524. if (season is not null && season.IndexNumber.HasValue)
  525. {
  526. var seriesFolder = season.SeriesPath;
  527. var seasonMarker = season.IndexNumber.Value == 0
  528. ? "-specials"
  529. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  530. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  531. return new[] { Path.Combine(seriesFolder, imageFilename) };
  532. }
  533. return new[]
  534. {
  535. Path.Combine(item.ContainingFolderPath, "fanart" + extension)
  536. };
  537. }
  538. var outputIndex = imageIndex.Value;
  539. if (item.IsInMixedFolder)
  540. {
  541. return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(CultureInfo.InvariantCulture), extension) };
  542. }
  543. var extraFanartFilename = GetBackdropSaveFilename(item.GetImages(ImageType.Backdrop), "fanart", "fanart", outputIndex);
  544. var list = new List<string>
  545. {
  546. Path.Combine(item.ContainingFolderPath, "extrafanart", extraFanartFilename + extension)
  547. };
  548. if (EnableExtraThumbsDuplication)
  549. {
  550. list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(CultureInfo.InvariantCulture) + extension));
  551. }
  552. return list.ToArray();
  553. }
  554. if (type == ImageType.Primary)
  555. {
  556. if (season is not null && season.IndexNumber.HasValue)
  557. {
  558. var seriesFolder = season.SeriesPath;
  559. var seasonMarker = season.IndexNumber.Value == 0
  560. ? "-specials"
  561. : season.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  562. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  563. return new[] { Path.Combine(seriesFolder, imageFilename) };
  564. }
  565. if (item is Episode)
  566. {
  567. var seasonFolder = Path.GetDirectoryName(item.Path);
  568. var imageFilename = Path.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
  569. return new[] { Path.Combine(seasonFolder, imageFilename) };
  570. }
  571. if (item.IsInMixedFolder || item is MusicVideo)
  572. {
  573. return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
  574. }
  575. if (item is MusicAlbum || item is MusicArtist)
  576. {
  577. return new[] { Path.Combine(item.ContainingFolderPath, "folder" + extension) };
  578. }
  579. return new[] { Path.Combine(item.ContainingFolderPath, "poster" + extension) };
  580. }
  581. // All other paths are the same
  582. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
  583. }
  584. /// <summary>
  585. /// Gets the save path for item in mixed folder.
  586. /// </summary>
  587. /// <param name="item">The item.</param>
  588. /// <param name="type">The type.</param>
  589. /// <param name="imageFilename">The image filename.</param>
  590. /// <param name="extension">The extension.</param>
  591. /// <returns>System.String.</returns>
  592. private string GetSavePathForItemInMixedFolder(BaseItem item, ImageType type, string imageFilename, string extension)
  593. {
  594. if (type == ImageType.Primary)
  595. {
  596. imageFilename = "poster";
  597. }
  598. var folder = Path.GetDirectoryName(item.Path);
  599. return Path.Combine(folder, Path.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
  600. }
  601. }
  602. }