ImageProcessor.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. using ImageMagickSharp;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Drawing;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Serialization;
  12. using System;
  13. using System.Collections.Concurrent;
  14. using System.Collections.Generic;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Server.Implementations.Drawing
  21. {
  22. /// <summary>
  23. /// Class ImageProcessor
  24. /// </summary>
  25. public class ImageProcessor : IImageProcessor, IDisposable
  26. {
  27. /// <summary>
  28. /// The us culture
  29. /// </summary>
  30. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  31. /// <summary>
  32. /// The _cached imaged sizes
  33. /// </summary>
  34. private readonly ConcurrentDictionary<Guid, ImageSize> _cachedImagedSizes;
  35. /// <summary>
  36. /// Gets the list of currently registered image processors
  37. /// Image processors are specialized metadata providers that run after the normal ones
  38. /// </summary>
  39. /// <value>The image enhancers.</value>
  40. public IEnumerable<IImageEnhancer> ImageEnhancers { get; private set; }
  41. /// <summary>
  42. /// The _logger
  43. /// </summary>
  44. private readonly ILogger _logger;
  45. private readonly IFileSystem _fileSystem;
  46. private readonly IJsonSerializer _jsonSerializer;
  47. private readonly IServerApplicationPaths _appPaths;
  48. public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem, IJsonSerializer jsonSerializer)
  49. {
  50. _logger = logger;
  51. _fileSystem = fileSystem;
  52. _jsonSerializer = jsonSerializer;
  53. _appPaths = appPaths;
  54. _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);
  55. Dictionary<Guid, ImageSize> sizeDictionary;
  56. try
  57. {
  58. sizeDictionary = jsonSerializer.DeserializeFromFile<Dictionary<Guid, ImageSize>>(ImageSizeFile) ??
  59. new Dictionary<Guid, ImageSize>();
  60. }
  61. catch (FileNotFoundException)
  62. {
  63. // No biggie
  64. sizeDictionary = new Dictionary<Guid, ImageSize>();
  65. }
  66. catch (DirectoryNotFoundException)
  67. {
  68. // No biggie
  69. sizeDictionary = new Dictionary<Guid, ImageSize>();
  70. }
  71. catch (Exception ex)
  72. {
  73. logger.ErrorException("Error parsing image size cache file", ex);
  74. sizeDictionary = new Dictionary<Guid, ImageSize>();
  75. }
  76. _cachedImagedSizes = new ConcurrentDictionary<Guid, ImageSize>(sizeDictionary);
  77. LogImageMagickVersionVersion();
  78. }
  79. private string ResizedImageCachePath
  80. {
  81. get
  82. {
  83. return Path.Combine(_appPaths.ImageCachePath, "resized-images");
  84. }
  85. }
  86. private string EnhancedImageCachePath
  87. {
  88. get
  89. {
  90. return Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
  91. }
  92. }
  93. private string CroppedWhitespaceImageCachePath
  94. {
  95. get
  96. {
  97. return Path.Combine(_appPaths.ImageCachePath, "cropped-images");
  98. }
  99. }
  100. public void AddParts(IEnumerable<IImageEnhancer> enhancers)
  101. {
  102. ImageEnhancers = enhancers.ToArray();
  103. }
  104. public async Task ProcessImage(ImageProcessingOptions options, Stream toStream)
  105. {
  106. var file = await ProcessImage(options).ConfigureAwait(false);
  107. using (var fileStream = _fileSystem.GetFileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, true))
  108. {
  109. await fileStream.CopyToAsync(toStream).ConfigureAwait(false);
  110. }
  111. }
  112. public ImageFormat[] GetSupportedImageOutputFormats()
  113. {
  114. if (_webpAvailable)
  115. {
  116. return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  117. }
  118. return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
  119. }
  120. private bool _webpAvailable = true;
  121. private void TestWebp()
  122. {
  123. try
  124. {
  125. var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp");
  126. Directory.CreateDirectory(Path.GetDirectoryName(tmpPath));
  127. using (var wand = new MagickWand(1, 1, new PixelWand("none", 1)))
  128. {
  129. wand.SaveImage(tmpPath);
  130. }
  131. }
  132. catch (Exception ex)
  133. {
  134. _logger.ErrorException("Error loading webp: ", ex);
  135. _webpAvailable = false;
  136. }
  137. }
  138. private void LogImageMagickVersionVersion()
  139. {
  140. try
  141. {
  142. _logger.Info("ImageMagick version: " + Wand.VersionString);
  143. }
  144. catch (Exception ex)
  145. {
  146. _logger.ErrorException("Error loading ImageMagick: ", ex);
  147. }
  148. TestWebp();
  149. }
  150. public async Task<string> ProcessImage(ImageProcessingOptions options)
  151. {
  152. if (options == null)
  153. {
  154. throw new ArgumentNullException("options");
  155. }
  156. var originalImagePath = options.Image.Path;
  157. if (options.HasDefaultOptions(originalImagePath) && options.Enhancers.Count == 0 && !options.CropWhiteSpace)
  158. {
  159. // Just spit out the original file if all the options are default
  160. return originalImagePath;
  161. }
  162. var dateModified = options.Image.DateModified;
  163. var length = options.Image.Length;
  164. if (options.CropWhiteSpace)
  165. {
  166. var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified, length).ConfigureAwait(false);
  167. originalImagePath = tuple.Item1;
  168. dateModified = tuple.Item2;
  169. length = tuple.Item3;
  170. }
  171. if (options.Enhancers.Count > 0)
  172. {
  173. var tuple = await GetEnhancedImage(new ItemImageInfo
  174. {
  175. Length = length,
  176. DateModified = dateModified,
  177. Type = options.Image.Type,
  178. Path = originalImagePath
  179. }, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);
  180. originalImagePath = tuple.Item1;
  181. dateModified = tuple.Item2;
  182. length = tuple.Item3;
  183. }
  184. var originalImageSize = GetImageSize(originalImagePath, dateModified);
  185. // Determine the output size based on incoming parameters
  186. var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight);
  187. if (options.HasDefaultOptionsWithoutSize(originalImagePath) && newSize.Equals(originalImageSize) && options.Enhancers.Count == 0)
  188. {
  189. // Just spit out the original file if the new size equals the old
  190. return originalImagePath;
  191. }
  192. var quality = options.Quality ?? 90;
  193. var outputFormat = GetOutputFormat(options.OutputFormat);
  194. var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, length, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor);
  195. var semaphore = GetLock(cacheFilePath);
  196. await semaphore.WaitAsync().ConfigureAwait(false);
  197. // Check again in case of lock contention
  198. try
  199. {
  200. if (File.Exists(cacheFilePath))
  201. {
  202. semaphore.Release();
  203. return cacheFilePath;
  204. }
  205. }
  206. catch
  207. {
  208. semaphore.Release();
  209. throw;
  210. }
  211. try
  212. {
  213. CheckDisposed();
  214. var newWidth = Convert.ToInt32(newSize.Width);
  215. var newHeight = Convert.ToInt32(newSize.Height);
  216. Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  217. if (string.IsNullOrWhiteSpace(options.BackgroundColor))
  218. {
  219. using (var originalImage = new MagickWand(originalImagePath))
  220. {
  221. originalImage.CurrentImage.ResizeImage(newWidth, newHeight);
  222. DrawIndicator(originalImage, newWidth, newHeight, options);
  223. originalImage.CurrentImage.CompressionQuality = quality;
  224. originalImage.SaveImage(cacheFilePath);
  225. }
  226. }
  227. else
  228. {
  229. using (var wand = new MagickWand(newWidth, newHeight, options.BackgroundColor))
  230. {
  231. using (var originalImage = new MagickWand(originalImagePath))
  232. {
  233. originalImage.CurrentImage.ResizeImage(newWidth, newHeight);
  234. wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
  235. DrawIndicator(wand, newWidth, newHeight, options);
  236. wand.CurrentImage.CompressionQuality = quality;
  237. wand.SaveImage(cacheFilePath);
  238. }
  239. }
  240. }
  241. }
  242. finally
  243. {
  244. semaphore.Release();
  245. }
  246. return cacheFilePath;
  247. }
  248. private ImageFormat GetOutputFormat(ImageFormat requestedFormat)
  249. {
  250. if (requestedFormat == ImageFormat.Webp && !_webpAvailable)
  251. {
  252. return ImageFormat.Png;
  253. }
  254. return requestedFormat;
  255. }
  256. /// <summary>
  257. /// Draws the indicator.
  258. /// </summary>
  259. /// <param name="wand">The wand.</param>
  260. /// <param name="imageWidth">Width of the image.</param>
  261. /// <param name="imageHeight">Height of the image.</param>
  262. /// <param name="options">The options.</param>
  263. private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
  264. {
  265. if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
  266. {
  267. return;
  268. }
  269. try
  270. {
  271. if (options.AddPlayedIndicator)
  272. {
  273. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  274. new PlayedIndicatorDrawer(_appPaths).DrawPlayedIndicator(wand, currentImageSize);
  275. }
  276. else if (options.UnplayedCount.HasValue)
  277. {
  278. var currentImageSize = new ImageSize(imageWidth, imageHeight);
  279. new UnplayedCountIndicator(_appPaths).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
  280. }
  281. if (options.PercentPlayed > 0)
  282. {
  283. new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
  284. }
  285. }
  286. catch (Exception ex)
  287. {
  288. _logger.ErrorException("Error drawing indicator overlay", ex);
  289. }
  290. }
  291. /// <summary>
  292. /// Crops whitespace from an image, caches the result, and returns the cached path
  293. /// </summary>
  294. private async Task<Tuple<string, DateTime, long>> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified, long length)
  295. {
  296. var name = originalImagePath;
  297. name += "datemodified=" + dateModified.Ticks;
  298. name += "length=" + length;
  299. var croppedImagePath = GetCachePath(CroppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
  300. var semaphore = GetLock(croppedImagePath);
  301. await semaphore.WaitAsync().ConfigureAwait(false);
  302. // Check again in case of contention
  303. if (File.Exists(croppedImagePath))
  304. {
  305. semaphore.Release();
  306. return GetResult(croppedImagePath);
  307. }
  308. try
  309. {
  310. Directory.CreateDirectory(Path.GetDirectoryName(croppedImagePath));
  311. using (var wand = new MagickWand(originalImagePath))
  312. {
  313. wand.CurrentImage.TrimImage(10);
  314. wand.SaveImage(croppedImagePath);
  315. }
  316. }
  317. catch (Exception ex)
  318. {
  319. // We have to have a catch-all here because some of the .net image methods throw a plain old Exception
  320. _logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
  321. return new Tuple<string, DateTime, long>(originalImagePath, dateModified, length);
  322. }
  323. finally
  324. {
  325. semaphore.Release();
  326. }
  327. return GetResult(croppedImagePath);
  328. }
  329. private Tuple<string, DateTime, long> GetResult(string path)
  330. {
  331. var file = new FileInfo(path);
  332. return new Tuple<string, DateTime, long>(path, _fileSystem.GetLastWriteTimeUtc(file), file.Length);
  333. }
  334. /// <summary>
  335. /// Increment this when there's a change requiring caches to be invalidated
  336. /// </summary>
  337. private const string Version = "3";
  338. /// <summary>
  339. /// Gets the cache file path based on a set of parameters
  340. /// </summary>
  341. private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, long length, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, string backgroundColor)
  342. {
  343. var filename = originalPath;
  344. filename += "width=" + outputSize.Width;
  345. filename += "height=" + outputSize.Height;
  346. filename += "quality=" + quality;
  347. filename += "datemodified=" + dateModified.Ticks;
  348. filename += "length=" + length;
  349. filename += "f=" + format;
  350. if (addPlayedIndicator)
  351. {
  352. filename += "pl=true";
  353. }
  354. if (percentPlayed > 0)
  355. {
  356. filename += "p=" + percentPlayed;
  357. }
  358. if (unwatchedCount.HasValue)
  359. {
  360. filename += "p=" + unwatchedCount.Value;
  361. }
  362. if (!string.IsNullOrEmpty(backgroundColor))
  363. {
  364. filename += "b=" + backgroundColor;
  365. }
  366. filename += "v=" + Version;
  367. return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLower());
  368. }
  369. /// <summary>
  370. /// Gets the size of the image.
  371. /// </summary>
  372. /// <param name="path">The path.</param>
  373. /// <returns>ImageSize.</returns>
  374. public ImageSize GetImageSize(string path)
  375. {
  376. return GetImageSize(path, File.GetLastWriteTimeUtc(path));
  377. }
  378. public ImageSize GetImageSize(ItemImageInfo info)
  379. {
  380. return GetImageSize(info.Path, info.DateModified);
  381. }
  382. /// <summary>
  383. /// Gets the size of the image.
  384. /// </summary>
  385. /// <param name="path">The path.</param>
  386. /// <param name="imageDateModified">The image date modified.</param>
  387. /// <returns>ImageSize.</returns>
  388. /// <exception cref="System.ArgumentNullException">path</exception>
  389. private ImageSize GetImageSize(string path, DateTime imageDateModified)
  390. {
  391. if (string.IsNullOrEmpty(path))
  392. {
  393. throw new ArgumentNullException("path");
  394. }
  395. var name = path + "datemodified=" + imageDateModified.Ticks;
  396. ImageSize size;
  397. var cacheHash = name.GetMD5();
  398. if (!_cachedImagedSizes.TryGetValue(cacheHash, out size))
  399. {
  400. size = GetImageSizeInternal(path);
  401. _cachedImagedSizes.AddOrUpdate(cacheHash, size, (keyName, oldValue) => size);
  402. }
  403. return size;
  404. }
  405. /// <summary>
  406. /// Gets the image size internal.
  407. /// </summary>
  408. /// <param name="path">The path.</param>
  409. /// <returns>ImageSize.</returns>
  410. private ImageSize GetImageSizeInternal(string path)
  411. {
  412. ImageSize size;
  413. try
  414. {
  415. size = ImageHeader.GetDimensions(path, _logger, _fileSystem);
  416. }
  417. catch
  418. {
  419. _logger.Info("Failed to read image header for {0}. Doing it the slow way.", path);
  420. CheckDisposed();
  421. using (var wand = new MagickWand())
  422. {
  423. wand.PingImage(path);
  424. var img = wand.CurrentImage;
  425. size = new ImageSize
  426. {
  427. Width = img.Width,
  428. Height = img.Height
  429. };
  430. }
  431. }
  432. StartSaveImageSizeTimer();
  433. return size;
  434. }
  435. private readonly Timer _saveImageSizeTimer;
  436. private const int SaveImageSizeTimeout = 5000;
  437. private readonly object _saveImageSizeLock = new object();
  438. private void StartSaveImageSizeTimer()
  439. {
  440. _saveImageSizeTimer.Change(SaveImageSizeTimeout, Timeout.Infinite);
  441. }
  442. private void SaveImageSizeCallback(object state)
  443. {
  444. lock (_saveImageSizeLock)
  445. {
  446. try
  447. {
  448. var path = ImageSizeFile;
  449. Directory.CreateDirectory(Path.GetDirectoryName(path));
  450. _jsonSerializer.SerializeToFile(_cachedImagedSizes, path);
  451. }
  452. catch (Exception ex)
  453. {
  454. _logger.ErrorException("Error saving image size file", ex);
  455. }
  456. }
  457. }
  458. private string ImageSizeFile
  459. {
  460. get
  461. {
  462. return Path.Combine(_appPaths.DataPath, "imagesizes.json");
  463. }
  464. }
  465. /// <summary>
  466. /// Gets the image cache tag.
  467. /// </summary>
  468. /// <param name="item">The item.</param>
  469. /// <param name="image">The image.</param>
  470. /// <returns>Guid.</returns>
  471. /// <exception cref="System.ArgumentNullException">item</exception>
  472. public string GetImageCacheTag(IHasImages item, ItemImageInfo image)
  473. {
  474. if (item == null)
  475. {
  476. throw new ArgumentNullException("item");
  477. }
  478. if (image == null)
  479. {
  480. throw new ArgumentNullException("image");
  481. }
  482. var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
  483. return GetImageCacheTag(item, image, supportedEnhancers.ToList());
  484. }
  485. /// <summary>
  486. /// Gets the image cache tag.
  487. /// </summary>
  488. /// <param name="item">The item.</param>
  489. /// <param name="image">The image.</param>
  490. /// <param name="imageEnhancers">The image enhancers.</param>
  491. /// <returns>Guid.</returns>
  492. /// <exception cref="System.ArgumentNullException">item</exception>
  493. public string GetImageCacheTag(IHasImages item, ItemImageInfo image, List<IImageEnhancer> imageEnhancers)
  494. {
  495. if (item == null)
  496. {
  497. throw new ArgumentNullException("item");
  498. }
  499. if (imageEnhancers == null)
  500. {
  501. throw new ArgumentNullException("imageEnhancers");
  502. }
  503. if (image == null)
  504. {
  505. throw new ArgumentNullException("image");
  506. }
  507. var originalImagePath = image.Path;
  508. var dateModified = image.DateModified;
  509. var imageType = image.Type;
  510. var length = image.Length;
  511. // Optimization
  512. if (imageEnhancers.Count == 0)
  513. {
  514. return (originalImagePath + dateModified.Ticks + string.Empty + length).GetMD5().ToString("N");
  515. }
  516. // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
  517. var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
  518. cacheKeys.Add(originalImagePath + dateModified.Ticks + string.Empty + length);
  519. return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N");
  520. }
  521. /// <summary>
  522. /// Gets the enhanced image.
  523. /// </summary>
  524. /// <param name="item">The item.</param>
  525. /// <param name="imageType">Type of the image.</param>
  526. /// <param name="imageIndex">Index of the image.</param>
  527. /// <returns>Task{System.String}.</returns>
  528. public async Task<string> GetEnhancedImage(IHasImages item, ImageType imageType, int imageIndex)
  529. {
  530. var enhancers = GetSupportedEnhancers(item, imageType).ToList();
  531. var imageInfo = item.GetImageInfo(imageType, imageIndex);
  532. var result = await GetEnhancedImage(imageInfo, item, imageIndex, enhancers);
  533. return result.Item1;
  534. }
  535. private async Task<Tuple<string, DateTime, long>> GetEnhancedImage(ItemImageInfo image,
  536. IHasImages item,
  537. int imageIndex,
  538. List<IImageEnhancer> enhancers)
  539. {
  540. var originalImagePath = image.Path;
  541. var dateModified = image.DateModified;
  542. var imageType = image.Type;
  543. var length = image.Length;
  544. try
  545. {
  546. var cacheGuid = GetImageCacheTag(item, image, enhancers);
  547. // Enhance if we have enhancers
  548. var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid).ConfigureAwait(false);
  549. // If the path changed update dateModified
  550. if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase))
  551. {
  552. return GetResult(ehnancedImagePath);
  553. }
  554. }
  555. catch (Exception ex)
  556. {
  557. _logger.Error("Error enhancing image", ex);
  558. }
  559. return new Tuple<string, DateTime, long>(originalImagePath, dateModified, length);
  560. }
  561. /// <summary>
  562. /// Gets the enhanced image internal.
  563. /// </summary>
  564. /// <param name="originalImagePath">The original image path.</param>
  565. /// <param name="item">The item.</param>
  566. /// <param name="imageType">Type of the image.</param>
  567. /// <param name="imageIndex">Index of the image.</param>
  568. /// <param name="supportedEnhancers">The supported enhancers.</param>
  569. /// <param name="cacheGuid">The cache unique identifier.</param>
  570. /// <returns>Task&lt;System.String&gt;.</returns>
  571. /// <exception cref="ArgumentNullException">
  572. /// originalImagePath
  573. /// or
  574. /// item
  575. /// </exception>
  576. private async Task<string> GetEnhancedImageInternal(string originalImagePath,
  577. IHasImages item,
  578. ImageType imageType,
  579. int imageIndex,
  580. IEnumerable<IImageEnhancer> supportedEnhancers,
  581. string cacheGuid)
  582. {
  583. if (string.IsNullOrEmpty(originalImagePath))
  584. {
  585. throw new ArgumentNullException("originalImagePath");
  586. }
  587. if (item == null)
  588. {
  589. throw new ArgumentNullException("item");
  590. }
  591. // All enhanced images are saved as png to allow transparency
  592. var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png");
  593. var semaphore = GetLock(enhancedImagePath);
  594. await semaphore.WaitAsync().ConfigureAwait(false);
  595. // Check again in case of contention
  596. if (File.Exists(enhancedImagePath))
  597. {
  598. semaphore.Release();
  599. return enhancedImagePath;
  600. }
  601. try
  602. {
  603. Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath));
  604. await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false);
  605. }
  606. finally
  607. {
  608. semaphore.Release();
  609. }
  610. return enhancedImagePath;
  611. }
  612. /// <summary>
  613. /// Executes the image enhancers.
  614. /// </summary>
  615. /// <param name="imageEnhancers">The image enhancers.</param>
  616. /// <param name="inputPath">The input path.</param>
  617. /// <param name="outputPath">The output path.</param>
  618. /// <param name="item">The item.</param>
  619. /// <param name="imageType">Type of the image.</param>
  620. /// <param name="imageIndex">Index of the image.</param>
  621. /// <returns>Task{EnhancedImage}.</returns>
  622. private async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, IHasImages item, ImageType imageType, int imageIndex)
  623. {
  624. // Run the enhancers sequentially in order of priority
  625. foreach (var enhancer in imageEnhancers)
  626. {
  627. var typeName = enhancer.GetType().Name;
  628. try
  629. {
  630. await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false);
  631. }
  632. catch (Exception ex)
  633. {
  634. _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name);
  635. throw;
  636. }
  637. // Feed the output into the next enhancer as input
  638. inputPath = outputPath;
  639. }
  640. }
  641. /// <summary>
  642. /// The _semaphoreLocks
  643. /// </summary>
  644. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  645. /// <summary>
  646. /// Gets the lock.
  647. /// </summary>
  648. /// <param name="filename">The filename.</param>
  649. /// <returns>System.Object.</returns>
  650. private SemaphoreSlim GetLock(string filename)
  651. {
  652. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  653. }
  654. /// <summary>
  655. /// Gets the cache path.
  656. /// </summary>
  657. /// <param name="path">The path.</param>
  658. /// <param name="uniqueName">Name of the unique.</param>
  659. /// <param name="fileExtension">The file extension.</param>
  660. /// <returns>System.String.</returns>
  661. /// <exception cref="System.ArgumentNullException">
  662. /// path
  663. /// or
  664. /// uniqueName
  665. /// or
  666. /// fileExtension
  667. /// </exception>
  668. public string GetCachePath(string path, string uniqueName, string fileExtension)
  669. {
  670. if (string.IsNullOrEmpty(path))
  671. {
  672. throw new ArgumentNullException("path");
  673. }
  674. if (string.IsNullOrEmpty(uniqueName))
  675. {
  676. throw new ArgumentNullException("uniqueName");
  677. }
  678. if (string.IsNullOrEmpty(fileExtension))
  679. {
  680. throw new ArgumentNullException("fileExtension");
  681. }
  682. var filename = uniqueName.GetMD5() + fileExtension;
  683. return GetCachePath(path, filename);
  684. }
  685. /// <summary>
  686. /// Gets the cache path.
  687. /// </summary>
  688. /// <param name="path">The path.</param>
  689. /// <param name="filename">The filename.</param>
  690. /// <returns>System.String.</returns>
  691. /// <exception cref="System.ArgumentNullException">
  692. /// path
  693. /// or
  694. /// filename
  695. /// </exception>
  696. public string GetCachePath(string path, string filename)
  697. {
  698. if (string.IsNullOrEmpty(path))
  699. {
  700. throw new ArgumentNullException("path");
  701. }
  702. if (string.IsNullOrEmpty(filename))
  703. {
  704. throw new ArgumentNullException("filename");
  705. }
  706. var prefix = filename.Substring(0, 1);
  707. path = Path.Combine(path, prefix);
  708. return Path.Combine(path, filename);
  709. }
  710. public IEnumerable<IImageEnhancer> GetSupportedEnhancers(IHasImages item, ImageType imageType)
  711. {
  712. return ImageEnhancers.Where(i =>
  713. {
  714. try
  715. {
  716. return i.Supports(item, imageType);
  717. }
  718. catch (Exception ex)
  719. {
  720. _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
  721. return false;
  722. }
  723. });
  724. }
  725. private bool _disposed;
  726. public void Dispose()
  727. {
  728. _disposed = true;
  729. Wand.CloseEnvironment();
  730. _saveImageSizeTimer.Dispose();
  731. }
  732. private void CheckDisposed()
  733. {
  734. if (_disposed)
  735. {
  736. throw new ObjectDisposedException(GetType().Name);
  737. }
  738. }
  739. }
  740. }