ImageSaver.cs 19 KB

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