2
0

ImageSaver.cs 22 KB

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