ImageSaver.cs 20 KB

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