ImageSaver.cs 20 KB

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