|
| 1 | +using System.Collections.Concurrent; |
| 2 | +using System.IO.Hashing; |
| 3 | +using System.Text; |
| 4 | +using NeoSolve.ImageSharp.AVIF; |
| 5 | +using SixLabors.ImageSharp; |
| 6 | +using SixLabors.ImageSharp.Formats.Webp; |
| 7 | +using SixLabors.ImageSharp.Processing; |
| 8 | +using SnapX.Core.Utils.Miscellaneous; |
| 9 | +using Xdg.Directories; |
| 10 | + |
| 11 | +namespace SnapX.Core.Media.Services; |
| 12 | + |
| 13 | +public static class ThumbnailService |
| 14 | +{ |
| 15 | + static ThumbnailService() |
| 16 | + { |
| 17 | + var imageConfig = Configuration.Default; |
| 18 | + imageConfig.ImageFormatsManager.SetEncoder(AVIFFormat.Instance, AVIFEncoder.Instance); |
| 19 | + imageConfig.ImageFormatsManager.SetDecoder(AVIFFormat.Instance, AVIFDecoder.Instance); |
| 20 | + imageConfig.ImageFormatsManager.AddImageFormatDetector(new PatchedAVIFImageFormatDetector()); |
| 21 | + } |
| 22 | + private static readonly ConcurrentDictionary<string, string> _pathCache = new(); |
| 23 | + private static readonly string CacheFolder = Path.Combine(BaseDirectory.CacheHome, SnapX.AppName, "Thumbnails"); |
| 24 | + private static readonly HttpClient _httpClient = HttpClientFactory.Get(); |
| 25 | + private static readonly SemaphoreSlim _processingSemaphore = new(3, 3); |
| 26 | + public static async Task<string> GetCompatibleSourceAsync(string? source) |
| 27 | + { |
| 28 | + if (string.IsNullOrEmpty(source)) return string.Empty; |
| 29 | + var result = await Task.Factory.StartNew(async () => |
| 30 | + { |
| 31 | + await _processingSemaphore.WaitAsync(); |
| 32 | + try |
| 33 | + { |
| 34 | + return await GenerateWebpThumbnail(source); |
| 35 | + } |
| 36 | + finally |
| 37 | + { |
| 38 | + _processingSemaphore.Release(); |
| 39 | + } |
| 40 | + }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap(); |
| 41 | + _pathCache.TryAdd(source, result); |
| 42 | + return result; |
| 43 | + |
| 44 | + } |
| 45 | + |
| 46 | + private static async Task<string> GenerateWebpThumbnail(string source) |
| 47 | + { |
| 48 | + if (_pathCache.TryGetValue(source, out var cachedPath)) |
| 49 | + { |
| 50 | + return cachedPath; |
| 51 | + } |
| 52 | + var isUrl = Uri.TryCreate(source, UriKind.Absolute, out var uri) |
| 53 | + && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps); |
| 54 | + Directory.CreateDirectory(CacheFolder); |
| 55 | + |
| 56 | + var sourceBytes = Encoding.UTF8.GetBytes(source); |
| 57 | + var hashBytes = XxHash64.Hash(sourceBytes); |
| 58 | + var hashName = Convert.ToHexString(hashBytes).Replace("-", "") + ".webp"; |
| 59 | + var cachePath = Path.Combine(CacheFolder, hashName); |
| 60 | + |
| 61 | + if (File.Exists(cachePath)) return cachePath; |
| 62 | + |
| 63 | + try |
| 64 | + { |
| 65 | + DebugHelper.Logger?.Debug($"ThumbnailService: Generating thumbnail for {(isUrl ? "URL" : "File")}: {source}"); |
| 66 | + |
| 67 | + await using var imageStream = await GetImageStreamAsync(source, isUrl); |
| 68 | + using var image = await Image.LoadAsync(imageStream); |
| 69 | + image.Mutate(x => x.Resize(new ResizeOptions |
| 70 | + { |
| 71 | + Size = new Size(200, 150), |
| 72 | + Mode = ResizeMode.Max |
| 73 | + })); |
| 74 | + // CPU time is precious |
| 75 | + await image.SaveAsWebpAsync(cachePath, new WebpEncoder() |
| 76 | + { |
| 77 | + Quality = 70, |
| 78 | + Method = WebpEncodingMethod.Fastest |
| 79 | + }); |
| 80 | + |
| 81 | + return cachePath; |
| 82 | + } |
| 83 | + catch (Exception ex) |
| 84 | + { |
| 85 | + DebugHelper.Logger?.Debug($"ThumbnailService: Error during conversion: {ex.Message}"); |
| 86 | + return source; |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + private static async Task<Stream> GetImageStreamAsync(string source, bool isUrl) |
| 91 | + { |
| 92 | + if (!isUrl) return File.OpenRead(source); |
| 93 | + using var request = new HttpRequestMessage(HttpMethod.Get, source); |
| 94 | + |
| 95 | + request.Headers.Accept.ParseAdd("image/avif,image/webp,image/apng,image/*,*/*;q=0.8"); |
| 96 | + |
| 97 | + request.Headers.ExpectContinue = true; |
| 98 | + |
| 99 | + var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); |
| 100 | + response.EnsureSuccessStatusCode(); |
| 101 | + |
| 102 | + return await response.Content.ReadAsStreamAsync(); |
| 103 | + |
| 104 | + } |
| 105 | +} |
0 commit comments