2
0

ImageSaver.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Audio;
  5. using MediaBrowser.Controller.Entities.TV;
  6. using MediaBrowser.Controller.IO;
  7. using MediaBrowser.Model.Configuration;
  8. using MediaBrowser.Model.Entities;
  9. using System;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Server.Implementations.Providers
  16. {
  17. /// <summary>
  18. /// Class ImageSaver
  19. /// </summary>
  20. public class ImageSaver
  21. {
  22. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  23. /// <summary>
  24. /// The _config
  25. /// </summary>
  26. private readonly IServerConfigurationManager _config;
  27. /// <summary>
  28. /// The remote image cache
  29. /// </summary>
  30. private readonly FileSystemRepository _remoteImageCache;
  31. /// <summary>
  32. /// The _directory watchers
  33. /// </summary>
  34. private readonly IDirectoryWatchers _directoryWatchers;
  35. private readonly IFileSystem _fileSystem;
  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="directoryWatchers">The directory watchers.</param>
  41. public ImageSaver(IServerConfigurationManager config, IDirectoryWatchers directoryWatchers, IFileSystem fileSystem)
  42. {
  43. _config = config;
  44. _directoryWatchers = directoryWatchers;
  45. _fileSystem = fileSystem;
  46. _remoteImageCache = new FileSystemRepository(config.ApplicationPaths.DownloadedImagesDataPath);
  47. }
  48. /// <summary>
  49. /// Saves the image.
  50. /// </summary>
  51. /// <param name="item">The item.</param>
  52. /// <param name="source">The source.</param>
  53. /// <param name="mimeType">Type of the MIME.</param>
  54. /// <param name="type">The type.</param>
  55. /// <param name="imageIndex">Index of the image.</param>
  56. /// <param name="sourceUrl">The source URL.</param>
  57. /// <param name="cancellationToken">The cancellation token.</param>
  58. /// <returns>Task.</returns>
  59. /// <exception cref="System.ArgumentNullException">mimeType</exception>
  60. public async Task SaveImage(BaseItem item, Stream source, string mimeType, ImageType type, int? imageIndex, string sourceUrl, CancellationToken cancellationToken)
  61. {
  62. if (string.IsNullOrEmpty(mimeType))
  63. {
  64. throw new ArgumentNullException("mimeType");
  65. }
  66. var saveLocally = _config.Configuration.SaveLocalMeta && item.Parent != null && !(item is Audio);
  67. if (item is IItemByName || item is User)
  68. {
  69. saveLocally = true;
  70. }
  71. if (type != ImageType.Primary && item is Episode)
  72. {
  73. saveLocally = false;
  74. }
  75. var locationType = item.LocationType;
  76. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  77. {
  78. saveLocally = false;
  79. }
  80. var paths = GetSavePaths(item, type, imageIndex, mimeType, saveLocally);
  81. // If there are more than one output paths, the stream will need to be seekable
  82. if (paths.Length > 1 && !source.CanSeek)
  83. {
  84. var memoryStream = new MemoryStream();
  85. using (source)
  86. {
  87. await source.CopyToAsync(memoryStream).ConfigureAwait(false);
  88. }
  89. memoryStream.Position = 0;
  90. source = memoryStream;
  91. }
  92. var currentPath = GetCurrentImagePath(item, type, imageIndex);
  93. using (source)
  94. {
  95. var isFirst = true;
  96. foreach (var path in paths)
  97. {
  98. // Seek back to the beginning
  99. if (!isFirst)
  100. {
  101. source.Position = 0;
  102. }
  103. await SaveImageToLocation(source, path, cancellationToken).ConfigureAwait(false);
  104. isFirst = false;
  105. }
  106. }
  107. // Set the path into the BaseItem
  108. SetImagePath(item, type, imageIndex, paths[0], sourceUrl);
  109. // Delete the current path
  110. if (!string.IsNullOrEmpty(currentPath) && !paths.Contains(currentPath, StringComparer.OrdinalIgnoreCase))
  111. {
  112. _directoryWatchers.TemporarilyIgnore(currentPath);
  113. try
  114. {
  115. var currentFile = new FileInfo(currentPath);
  116. // This will fail if the file is hidden
  117. if (currentFile.Exists)
  118. {
  119. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  120. {
  121. currentFile.Attributes &= ~FileAttributes.Hidden;
  122. }
  123. currentFile.Delete();
  124. }
  125. }
  126. finally
  127. {
  128. _directoryWatchers.RemoveTempIgnore(currentPath);
  129. }
  130. }
  131. }
  132. /// <summary>
  133. /// Saves the image to location.
  134. /// </summary>
  135. /// <param name="source">The source.</param>
  136. /// <param name="path">The path.</param>
  137. /// <param name="cancellationToken">The cancellation token.</param>
  138. /// <returns>Task.</returns>
  139. private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken)
  140. {
  141. _directoryWatchers.TemporarilyIgnore(path);
  142. try
  143. {
  144. Directory.CreateDirectory(Path.GetDirectoryName(path));
  145. // If the file is currently hidden we'll have to remove that or the save will fail
  146. var file = new FileInfo(path);
  147. // This will fail if the file is hidden
  148. if (file.Exists)
  149. {
  150. if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  151. {
  152. file.Attributes &= ~FileAttributes.Hidden;
  153. }
  154. }
  155. using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  156. {
  157. await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  158. }
  159. }
  160. finally
  161. {
  162. _directoryWatchers.RemoveTempIgnore(path);
  163. }
  164. }
  165. /// <summary>
  166. /// Gets the save paths.
  167. /// </summary>
  168. /// <param name="item">The item.</param>
  169. /// <param name="type">The type.</param>
  170. /// <param name="imageIndex">Index of the image.</param>
  171. /// <param name="mimeType">Type of the MIME.</param>
  172. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  173. /// <returns>IEnumerable{System.String}.</returns>
  174. private string[] GetSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  175. {
  176. if (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy || !saveLocally)
  177. {
  178. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
  179. }
  180. return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
  181. }
  182. /// <summary>
  183. /// Gets the current image path.
  184. /// </summary>
  185. /// <param name="item">The item.</param>
  186. /// <param name="type">The type.</param>
  187. /// <param name="imageIndex">Index of the image.</param>
  188. /// <returns>System.String.</returns>
  189. /// <exception cref="System.ArgumentNullException">
  190. /// imageIndex
  191. /// or
  192. /// imageIndex
  193. /// </exception>
  194. private string GetCurrentImagePath(BaseItem item, ImageType type, int? imageIndex)
  195. {
  196. switch (type)
  197. {
  198. case ImageType.Screenshot:
  199. if (!imageIndex.HasValue)
  200. {
  201. throw new ArgumentNullException("imageIndex");
  202. }
  203. return item.ScreenshotImagePaths.Count > imageIndex.Value ? item.ScreenshotImagePaths[imageIndex.Value] : null;
  204. case ImageType.Backdrop:
  205. if (!imageIndex.HasValue)
  206. {
  207. throw new ArgumentNullException("imageIndex");
  208. }
  209. return item.BackdropImagePaths.Count > imageIndex.Value ? item.BackdropImagePaths[imageIndex.Value] : null;
  210. default:
  211. return item.GetImage(type);
  212. }
  213. }
  214. /// <summary>
  215. /// Sets the image path.
  216. /// </summary>
  217. /// <param name="item">The item.</param>
  218. /// <param name="type">The type.</param>
  219. /// <param name="imageIndex">Index of the image.</param>
  220. /// <param name="path">The path.</param>
  221. /// <param name="sourceUrl">The source URL.</param>
  222. /// <exception cref="System.ArgumentNullException">imageIndex
  223. /// or
  224. /// imageIndex</exception>
  225. private void SetImagePath(BaseItem item, ImageType type, int? imageIndex, string path, string sourceUrl)
  226. {
  227. switch (type)
  228. {
  229. case ImageType.Screenshot:
  230. if (!imageIndex.HasValue)
  231. {
  232. throw new ArgumentNullException("imageIndex");
  233. }
  234. if (item.ScreenshotImagePaths.Count > imageIndex.Value)
  235. {
  236. item.ScreenshotImagePaths[imageIndex.Value] = path;
  237. }
  238. else
  239. {
  240. item.ScreenshotImagePaths.Add(path);
  241. }
  242. break;
  243. case ImageType.Backdrop:
  244. if (!imageIndex.HasValue)
  245. {
  246. throw new ArgumentNullException("imageIndex");
  247. }
  248. if (item.BackdropImagePaths.Count > imageIndex.Value)
  249. {
  250. item.BackdropImagePaths[imageIndex.Value] = path;
  251. }
  252. else
  253. {
  254. item.BackdropImagePaths.Add(path);
  255. }
  256. if (string.IsNullOrEmpty(sourceUrl))
  257. {
  258. item.RemoveImageSourceForPath(path);
  259. }
  260. else
  261. {
  262. item.AddImageSource(path, sourceUrl);
  263. }
  264. break;
  265. default:
  266. item.SetImage(type, path);
  267. break;
  268. }
  269. }
  270. /// <summary>
  271. /// Gets the save path.
  272. /// </summary>
  273. /// <param name="item">The item.</param>
  274. /// <param name="type">The type.</param>
  275. /// <param name="imageIndex">Index of the image.</param>
  276. /// <param name="mimeType">Type of the MIME.</param>
  277. /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
  278. /// <returns>System.String.</returns>
  279. /// <exception cref="System.ArgumentNullException">
  280. /// imageIndex
  281. /// or
  282. /// imageIndex
  283. /// </exception>
  284. private string GetStandardSavePath(BaseItem item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
  285. {
  286. string filename;
  287. switch (type)
  288. {
  289. case ImageType.Art:
  290. filename = "clearart";
  291. break;
  292. case ImageType.Primary:
  293. filename = item is Episode ? Path.GetFileNameWithoutExtension(item.Path) : "folder";
  294. break;
  295. case ImageType.Backdrop:
  296. if (!imageIndex.HasValue)
  297. {
  298. throw new ArgumentNullException("imageIndex");
  299. }
  300. filename = imageIndex.Value == 0 ? "backdrop" : "backdrop" + imageIndex.Value.ToString(UsCulture);
  301. break;
  302. case ImageType.Screenshot:
  303. if (!imageIndex.HasValue)
  304. {
  305. throw new ArgumentNullException("imageIndex");
  306. }
  307. filename = imageIndex.Value == 0 ? "screenshot" : "screenshot" + imageIndex.Value.ToString(UsCulture);
  308. break;
  309. default:
  310. filename = type.ToString().ToLower();
  311. break;
  312. }
  313. var extension = mimeType.Split('/').Last();
  314. if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
  315. {
  316. extension = "jpg";
  317. }
  318. extension = "." + extension.ToLower();
  319. string path = null;
  320. if (saveLocally)
  321. {
  322. if (item.IsInMixedFolder && !(item is Episode))
  323. {
  324. path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
  325. }
  326. if (string.IsNullOrEmpty(path))
  327. {
  328. path = Path.Combine(item.MetaLocation, 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. path = _remoteImageCache.GetResourcePath(item.GetType().FullName + item.Id, filename + extension);
  335. }
  336. return path;
  337. }
  338. /// <summary>
  339. /// Gets the compatible save paths.
  340. /// </summary>
  341. /// <param name="item">The item.</param>
  342. /// <param name="type">The type.</param>
  343. /// <param name="imageIndex">Index of the image.</param>
  344. /// <param name="mimeType">Type of the MIME.</param>
  345. /// <returns>IEnumerable{System.String}.</returns>
  346. /// <exception cref="System.ArgumentNullException">imageIndex</exception>
  347. private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int? imageIndex, string mimeType)
  348. {
  349. var extension = mimeType.Split('/').Last();
  350. if (string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase))
  351. {
  352. extension = "jpg";
  353. }
  354. extension = "." + extension.ToLower();
  355. // Backdrop paths
  356. if (type == ImageType.Backdrop)
  357. {
  358. if (!imageIndex.HasValue)
  359. {
  360. throw new ArgumentNullException("imageIndex");
  361. }
  362. if (imageIndex.Value == 0)
  363. {
  364. if (item is Season && item.IndexNumber.HasValue)
  365. {
  366. var seriesFolder = Path.GetDirectoryName(item.Path);
  367. var seasonMarker = item.IndexNumber.Value == 0
  368. ? "-specials"
  369. : item.IndexNumber.Value.ToString("00", UsCulture);
  370. var imageFilename = "season" + seasonMarker + "-fanart" + extension;
  371. return new[] { Path.Combine(seriesFolder, imageFilename) };
  372. }
  373. return new[]
  374. {
  375. Path.Combine(item.MetaLocation, "fanart" + extension)
  376. };
  377. }
  378. var outputIndex = imageIndex.Value;
  379. return new[]
  380. {
  381. Path.Combine(item.MetaLocation, "extrafanart", "fanart" + outputIndex.ToString(UsCulture) + extension),
  382. Path.Combine(item.MetaLocation, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension)
  383. };
  384. }
  385. if (type == ImageType.Primary)
  386. {
  387. if (item is Season && item.IndexNumber.HasValue)
  388. {
  389. var seriesFolder = Path.GetDirectoryName(item.Path);
  390. var seasonMarker = item.IndexNumber.Value == 0
  391. ? "-specials"
  392. : item.IndexNumber.Value.ToString("00", UsCulture);
  393. var imageFilename = "season" + seasonMarker + "-poster" + extension;
  394. return new[] { Path.Combine(seriesFolder, imageFilename) };
  395. }
  396. if (item is Episode)
  397. {
  398. var seasonFolder = Path.GetDirectoryName(item.Path);
  399. var imageFilename = Path.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
  400. return new[] { Path.Combine(seasonFolder, imageFilename) };
  401. }
  402. if (item.IsInMixedFolder)
  403. {
  404. return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
  405. }
  406. var filename = "poster" + extension;
  407. return new[] { Path.Combine(item.MetaLocation, filename) };
  408. }
  409. if (type == ImageType.Banner)
  410. {
  411. if (item is Season && item.IndexNumber.HasValue)
  412. {
  413. var seriesFolder = Path.GetDirectoryName(item.Path);
  414. var seasonMarker = item.IndexNumber.Value == 0
  415. ? "-specials"
  416. : item.IndexNumber.Value.ToString("00", UsCulture);
  417. var imageFilename = "season" + seasonMarker + "-banner" + extension;
  418. return new[] { Path.Combine(seriesFolder, imageFilename) };
  419. }
  420. }
  421. if (type == ImageType.Thumb)
  422. {
  423. if (item is Season && item.IndexNumber.HasValue)
  424. {
  425. var seriesFolder = Path.GetDirectoryName(item.Path);
  426. var seasonMarker = item.IndexNumber.Value == 0
  427. ? "-specials"
  428. : item.IndexNumber.Value.ToString("00", UsCulture);
  429. var imageFilename = "season" + seasonMarker + "-landscape" + extension;
  430. return new[] { Path.Combine(seriesFolder, imageFilename) };
  431. }
  432. }
  433. // All other paths are the same
  434. return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
  435. }
  436. /// <summary>
  437. /// Gets the save path for item in mixed folder.
  438. /// </summary>
  439. /// <param name="item">The item.</param>
  440. /// <param name="type">The type.</param>
  441. /// <param name="imageFilename">The image filename.</param>
  442. /// <param name="extension">The extension.</param>
  443. /// <returns>System.String.</returns>
  444. private string GetSavePathForItemInMixedFolder(BaseItem item, ImageType type, string imageFilename, string extension)
  445. {
  446. if (type == ImageType.Primary)
  447. {
  448. imageFilename = "poster";
  449. }
  450. var folder = Path.GetDirectoryName(item.Path);
  451. return Path.Combine(folder, Path.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
  452. }
  453. }
  454. }