using System.Security.Cryptography; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SlpModularCms.Core.Hosting.Website; using SlpModularCms.Core.Media; using SlpModularCms.Core.Media.Library; using SlpModularCms.Modules.Hero.Data.Entities; using SlpModularCms.Modules.Hero.Models; using SlpModularCms.Modules.Hero.Repositories; namespace SlpModularCms.Modules.Hero.Services; /// The image is still used by a slide (the administrator gets a 409 and a message). public sealed class HeroImageInUseException() : Exception("The image is still used by a slide."); /// Cutting the variants of one image failed; the id tells the background renderer which image to give up on after a few tries. public sealed class HeroImageRenderException(Guid imageId, Exception inner) : Exception("Cutting the variants of a hero image failed.", inner) { public Guid ImageId { get; } = imageId; } public sealed class HeroImageNotFoundException() : Exception("The image does not exist."); /// There is not enough room in the media directory for the image. public sealed class MediaStorageFullException() : Exception("The media directory is full."); public interface IHeroImageService { /// /// Admits and stores an uploaded image and returns at once: the variants are cut afterwards by the background renderer /// (), so a slow machine never holds the request open. The same photo twice is one /// image. Until its set exists the image has no variants and is not published. /// /// The upload is refused; see the code. Task UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken, string? originalFileName = null); /// How many images exist, how many wait for their variants and how many only lack the full-frame preview (for the log). Task<(int Total, int NeedRender, int NeedPreview)> GetRenderBacklogAsync(CancellationToken cancellationToken); /// /// Records a changed focus (general and optionally per ratio) on a tracked image. Nothing is cut here: the caller saves /// the image together with the hero and then calls ; the background renderer cuts the new set /// into NEW files and only then switches the image to it (so the old set stays live until the new one is complete). /// void ApplyFocus(HeroImage image, HeroFocusRequest request); /// The variant the renderer is busy with: (done, total), or null when the image is not being cut right now. (int Done, int Total)? RenderProgress(Guid imageId); /// /// Applies a new crop to an image at once, WITHOUT saving the hero (Bryan, 2026-11-17: a new crop must not need another /// click on Save). The new set is cut in the background and the image switches to it when it is complete, so what is live /// changes only then. Returns the image as the admin sees it now (processing), or null when there is no such image. /// Task SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken); /// /// A crop for ONE slide (crop per use): the same photo can have another crop on another slide. Applied at once, without /// saving the hero; the slide's own set is cut in the background and the slide switches to it when it is complete (until /// then it shows the photo's set). Returns the slide as the admin sees it (processing), or null when there is no such slide. /// Task SetSlideFocusAsync(Guid slideId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken); /// Takes the slide's own crop away: it uses the photo's crop and set again. Null when there is no such slide. Task ResetSlideFocusAsync(Guid slideId, Guid callerId, CancellationToken cancellationToken); /// One image as the admin sees it now (including whether it is still being prepared). Null when there is no such image. Task GetImageAsync(Guid imageId, CancellationToken cancellationToken); /// True when the background renderer gave up on the image after a few failed tries (until a retry or a restart). bool IsRenderFailed(Guid imageId); /// Lets the background renderer try an image it gave up on again. /// There is no such image. Task RetryRenderAsync(Guid imageId, CancellationToken cancellationToken); /// Wakes the background renderer: there is an image whose set is missing or does not match its focus. void NotifyPending(); /// /// Cuts the set of the oldest image that needs one (new upload, repair or changed focus), skipping the given ids, and /// switches the image to it. Returns the id of the image handled, or null when nothing is pending. /// Task RenderNextPendingAsync(IReadOnlySet skip, CancellationToken cancellationToken); /// Removes an image nothing uses; its files go after the retention time. Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken); /// /// Moves an image to the trash: the slides that use it are removed from the hero (and remember the moment as its last use), /// it disappears from the hero and its files stay for the trash period. Returns how many slides were removed. /// /// There is no such image outside the trash. Task TrashAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken); /// Takes an image out of the trash again. False when it is not in the trash. Task RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken); /// /// Removes an image that is in the trash FOR GOOD: its original and its set (a file another image shares stays) and the /// record. Refused when the image is not in the trash or a slide uses it after all. /// Task PurgeAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken); } public class HeroImageService( IMediaUploadGuard guard, IImageProcessor processor, IMediaStore store, MediaProcessingGate gate, IHeroRepository repository, IOptions mediaOptions, ILogger logger, TimeProvider? time = null, IIndexHtmlCache? indexCache = null, HeroRenderSignal? signal = null) : IHeroImageService { private readonly TimeProvider _time = time ?? TimeProvider.System; public async Task UploadAsync(Stream upload, long declaredLength, Guid callerId, CancellationToken cancellationToken, string? originalFileName = null) { using var admitted = await guard.AdmitAsync(upload, declaredLength, cancellationToken); var sha = Convert.ToHexStringLower(SHA256.HashData(admitted.Bytes)); // The same photo again is the same image. When its files are gone (a lost or restored media directory) the upload // repairs them from the file that was just sent. var existing = await repository.GetImageBySha256Async(sha, cancellationToken); var fileName = HeroFileNames.Clean(originalFileName); // The same photo uploaded again also brings it back from the trash. if (existing is not null) { existing.DeletedAt = null; existing.OriginalFileName ??= fileName; } if (existing is not null && await FilesExistAsync(existing, cancellationToken)) { await repository.SaveChangesAsync(cancellationToken); // The same photo again also gives up the failed state: the renderer tries it again when it is still pending. signal?.Reset(existing.Id); signal?.Notify(); return HeroMapping.ToImageDto(existing) with { Reused = true }; } await EnsureRoomAsync(admitted.Bytes.Length, cancellationToken); // The original is kept without metadata (GPS and the like); formats that cannot be written back (HEIC) become JPEG. var format = admitted.Info.Format; var stripped = await processor.StripMetadataAsync(admitted.Bytes, format, cancellationToken); var original = stripped ?? admitted.Bytes; var storedFormat = stripped is not null && format == ImageFormat.Heic ? ImageFormat.Jpeg : format; var image = existing ?? new HeroImage { Id = Guid.NewGuid(), OriginalSha256 = sha, OriginalKey = $"originals/{sha}.{storedFormat.Extension()}", SourceFormat = storedFormat.Extension(), Width = admitted.Info.Width, Height = admitted.Info.Height, Bytes = original.Length, CreatedAt = _time.GetUtcNow(), CreatedByUserId = callerId, OriginalFileName = fileName, }; // The files first, the row last: an aborted request leaves at most an original nobody refers to (the clean-up // removes it) and a repeated upload simply does it again. The set is cut afterwards by the background renderer. await store.PutAsync(image.OriginalKey, original, cancellationToken); image.SetHash = string.Empty; image.Variants = []; if (existing is null) { repository.AddImage(image); } await repository.SaveChangesAsync(cancellationToken); signal?.Notify(); logger.LogInformation("Hero image {ImageId} {Action} by user {UserId} ({Width}x{Height}); its variants are cut in the background", image.Id, existing is null ? "uploaded" : "repaired", callerId, image.Width, image.Height); return HeroMapping.ToImageDto(image); } private async Task FilesExistAsync(HeroImage image, CancellationToken cancellationToken) { if (!await store.ExistsAsync(image.OriginalKey, cancellationToken)) { return false; } foreach (var variant in image.Variants) { if (!await store.ExistsAsync($"{HeroMapping.Area}/{image.SetHash}/{variant.FileName}", cancellationToken)) { return false; } } return true; } public void ApplyFocus(HeroImage image, HeroFocusRequest request) { var general = request.Focus.ToSetting().Normalize(); image.FocusX = general.X; image.FocusY = general.Y; image.Zoom = general.Zoom; Apply(request.Wide, v => (image.WideFocusX, image.WideFocusY, image.WideZoom) = v); Apply(request.Tall, v => (image.TallFocusX, image.TallFocusY, image.TallZoom) = v); } public void NotifyPending() => signal?.Notify(); public async Task SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken) { var image = await repository.GetImageAsync(imageId, cancellationToken); if (image is null) { return null; } ApplyFocus(image, request); await repository.SaveChangesAsync(cancellationToken); signal?.Reset(imageId); signal?.Notify(); logger.LogInformation("Hero image {ImageId} got a new crop from user {UserId}; its variants are cut in the background", imageId, callerId); return await GetImageAsync(imageId, cancellationToken); } public async Task SetSlideFocusAsync(Guid slideId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken) { var slide = await repository.GetSlideAsync(slideId, cancellationToken); if (slide is null) { return null; } var general = request.Focus.ToSetting().Normalize(); (slide.FocusX, slide.FocusY, slide.Zoom) = (general.X, general.Y, general.Zoom); Apply(request.Wide, v => (slide.WideFocusX, slide.WideFocusY, slide.WideZoom) = v); Apply(request.Tall, v => (slide.TallFocusX, slide.TallFocusY, slide.TallZoom) = v); await repository.SaveChangesAsync(cancellationToken); signal?.Reset(slideId); signal?.Notify(); logger.LogInformation("Hero slide {SlideId} got a crop of its own from user {UserId}; its variants are cut in the background", slideId, callerId); return await GetSlideAsync(slideId, cancellationToken); } public async Task ResetSlideFocusAsync(Guid slideId, Guid callerId, CancellationToken cancellationToken) { var slide = await repository.GetSlideAsync(slideId, cancellationToken); if (slide is null) { return null; } var oldSet = slide.SetHash; slide.ClearOwnCrop(); if (!string.IsNullOrEmpty(oldSet) && oldSet != slide.Image!.SetHash) { repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() }); } await repository.SaveChangesAsync(cancellationToken); signal?.Reset(slideId); indexCache?.Invalidate(); logger.LogInformation("Hero slide {SlideId} uses the crop of its photo again (reset by user {UserId})", slideId, callerId); return await GetSlideAsync(slideId, cancellationToken); } private async Task GetSlideAsync(Guid slideId, CancellationToken cancellationToken) { var slide = await repository.GetSlideFreshAsync(slideId, cancellationToken); if (slide is null) { return null; } var dto = HeroMapping.ToSlideAdmin(slide); if (!slide.HasOwnCrop) { return dto; } var progress = RenderProgress(slideId); return dto with { Image = dto.Image with { Failed = IsRenderFailed(slideId), RenderDone = progress?.Done, RenderTotal = progress?.Total } }; } public async Task GetImageAsync(Guid imageId, CancellationToken cancellationToken) { var image = await repository.GetImageFreshAsync(imageId, cancellationToken); if (image is null) { return null; } var failed = IsRenderFailed(imageId); var progress = RenderProgress(imageId); return HeroMapping.ToImageDto(image) with { Failed = failed, RenderDone = progress?.Done, RenderTotal = progress?.Total }; } public bool IsRenderFailed(Guid imageId) => signal?.IsGivenUp(imageId) ?? false; public (int Done, int Total)? RenderProgress(Guid imageId) => signal?.GetProgress(imageId); public async Task RetryRenderAsync(Guid imageId, CancellationToken cancellationToken) { // The id is a photo's or the id of a slide with a crop of its own (both are renderer keys). if (await repository.GetImageAsync(imageId, cancellationToken) is null && await repository.GetSlideAsync(imageId, cancellationToken) is null) { throw new HeroImageNotFoundException(); } signal?.Reset(imageId); signal?.Notify(); } public async Task<(int Total, int NeedRender, int NeedPreview)> GetRenderBacklogAsync(CancellationToken cancellationToken) => (await repository.CountImagesAsync(cancellationToken), (await repository.GetImagesNeedingRenderAsync(cancellationToken)).Count + (await repository.GetSlidesNeedingRenderAsync(cancellationToken)).Count, (await repository.GetImagesNeedingPreviewAsync(cancellationToken)).Count); public async Task RenderNextPendingAsync(IReadOnlySet skip, CancellationToken cancellationToken) { var image = (await repository.GetImagesNeedingRenderAsync(cancellationToken)).FirstOrDefault(i => !skip.Contains(i.Id)); if (image is null) { // Then the slides that have a crop of their own. var slide = (await repository.GetSlidesNeedingRenderAsync(cancellationToken)).FirstOrDefault(s => !skip.Contains(s.Id)); if (slide is not null) { try { return await RenderSlideAsync(slide, cancellationToken); } catch (Exception exception) when (exception is not OperationCanceledException) { logger.LogError(exception, "Hero slide {SlideId}: cutting the variants failed.", slide.Id); throw new HeroImageRenderException(slide.Id, exception); } finally { signal?.ClearProgress(slide.Id); } } // Nothing to cut: add the full-frame preview to complete sets that were made before it existed. var old = (await repository.GetImagesNeedingPreviewAsync(cancellationToken)).FirstOrDefault(i => !skip.Contains(i.Id)); return old is null ? null : await AddPreviewAsync(old, cancellationToken); } try { return await RenderAsync(image, cancellationToken); } catch (Exception exception) when (exception is not OperationCanceledException) { logger.LogError(exception, "Hero image {ImageId}: cutting the variants failed.", image.Id); throw new HeroImageRenderException(image.Id, exception); } finally { signal?.ClearProgress(image.Id); } } /// Makes only the preview file of a complete set (one decode, one resize) and adds it to the set where it already is. private async Task AddPreviewAsync(HeroImage image, CancellationToken cancellationToken) { try { using (await gate.EnterAsync(cancellationToken)) { var file = await store.OpenReadAsync(image.OriginalKey, cancellationToken) ?? throw new ImageRejectedException(ImageRejection.Unavailable, "The stored original is missing."); using var memory = new MemoryStream(); await using (file.Content) { await file.Content.CopyToAsync(memory, cancellationToken); } var storedFormat = ImageFormatExtensions.FromExtension(Path.GetExtension(image.OriginalKey).TrimStart('.')); var spec = VariantPlanner.Preview(image.Width, image.Height, processor.SupportedOutput); var rendered = (await processor.RenderSetAsync(memory.ToArray(), storedFormat, [spec], null, cancellationToken))[0]; var name = MediaPaths.FileName(spec.Ratio.Name, spec.Width, spec.Format); await store.PutAsync($"{HeroMapping.Area}/{image.SetHash}/{name}", rendered.Bytes, cancellationToken); image.Variants = [.. image.Variants, new HeroVariant(spec.Ratio.Name, rendered.Width, rendered.Height, spec.Format.MimeType(), name, rendered.Bytes.LongLength)]; } await repository.SaveChangesAsync(cancellationToken); logger.LogInformation("Hero image {ImageId}: the full-frame preview was added to its set.", image.Id); return image.Id; } catch (Exception exception) when (exception is not OperationCanceledException) { logger.LogError(exception, "Hero image {ImageId}: adding the preview failed.", image.Id); throw new HeroImageRenderException(image.Id, exception); } } /// Cuts the set of a slide's own crop. A crop equal to the photo's own crop shares the photo's set (same hash, no cutting). private async Task RenderSlideAsync(HeroSlide slide, CancellationToken cancellationToken) { var photo = slide.Image!; var effective = HeroMapping.Effective(slide)!; var target = HeroMapping.TargetSetHash(effective); var oldSet = slide.SetHash ?? string.Empty; if (target == photo.SetHash && photo.Variants.Count > 0) { slide.SetHash = target; slide.Variants = [.. photo.Variants]; await repository.SaveChangesAsync(cancellationToken); indexCache?.Invalidate(); logger.LogInformation("Hero slide {SlideId}: its crop equals the crop of its photo, so it shares the photo's set.", slide.Id); return slide.Id; } var watch = System.Diagnostics.Stopwatch.StartNew(); logger.LogInformation("Hero slide {SlideId}: cutting the variants of its own crop starts ({Width}x{Height}).", slide.Id, photo.Width, photo.Height); Dictionary files; List variants; using (await gate.EnterAsync(cancellationToken)) { var file = await store.OpenReadAsync(photo.OriginalKey, cancellationToken) ?? throw new ImageRejectedException(ImageRejection.Unavailable, "The stored original is missing."); using var memory = new MemoryStream(); await using (file.Content) { await file.Content.CopyToAsync(memory, cancellationToken); } var storedFormat = ImageFormatExtensions.FromExtension(Path.GetExtension(photo.OriginalKey).TrimStart('.')); (files, variants) = await RenderSetAsync(effective, memory.ToArray(), storedFormat, (done, total) => signal?.SetProgress(slide.Id, done, total), cancellationToken); } await store.PutSetAsync(HeroMapping.Area, target, files, cancellationToken); // The crop may have changed (or the slide may be gone) while the set was cut: then it stays pending at the newest crop. var current = await repository.GetSlideFreshAsync(slide.Id, cancellationToken); if (current is null || !current.HasOwnCrop || HeroMapping.TargetSetHash(HeroMapping.Effective(current)!) != target) { logger.LogInformation("Hero slide {SlideId}: recut superseded, its crop changed while its variants were being cut.", slide.Id); return slide.Id; } slide.SetHash = target; slide.Variants = variants; if (oldSet.Length > 0 && oldSet != target) { repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() }); } await repository.SaveChangesAsync(cancellationToken); indexCache?.Invalidate(); logger.LogInformation("Hero slide {SlideId}: {Variants} variants cut in {Seconds:0.0} s", slide.Id, variants.Count, watch.Elapsed.TotalSeconds); return slide.Id; } private async Task RenderAsync(HeroImage image, CancellationToken cancellationToken) { var target = HeroMapping.TargetSetHash(image); var oldSet = image.SetHash; Dictionary files; List variants; var watch = System.Diagnostics.Stopwatch.StartNew(); logger.LogInformation("Hero image {ImageId}: cutting the variants starts ({Width}x{Height}, {Bytes} bytes, {Reason}).", image.Id, image.Width, image.Height, image.Bytes, image.Variants.Count == 0 ? "new" : "focus changed"); using (await gate.EnterAsync(cancellationToken)) { var file = await store.OpenReadAsync(image.OriginalKey, cancellationToken) ?? throw new ImageRejectedException(ImageRejection.Unavailable, "The stored original is missing."); using var memory = new MemoryStream(); await using (file.Content) { await file.Content.CopyToAsync(memory, cancellationToken); } var storedFormat = ImageFormatExtensions.FromExtension(Path.GetExtension(image.OriginalKey).TrimStart('.')); var lastStep = watch.Elapsed; (files, variants) = await RenderSetAsync(image, memory.ToArray(), storedFormat, (done, total) => { signal?.SetProgress(image.Id, done, total); logger.LogInformation("Hero image {ImageId}: variant {Done} of {Total} in {Milliseconds:0} ms.", image.Id, done, total, (watch.Elapsed - lastStep).TotalMilliseconds); lastStep = watch.Elapsed; }, cancellationToken); } await store.PutSetAsync(HeroMapping.Area, target, files, cancellationToken); // The focus may have been changed while the set was being cut: then this set is not the one that is wanted and the // image stays pending (the next round cuts the right one; this set is cleaned up as an unreferenced set). var current = await repository.GetImageFreshAsync(image.Id, cancellationToken); if (current is null || HeroMapping.TargetSetHash(current) != target) { logger.LogInformation("Hero image {ImageId}: recut superseded, the focus changed while its variants were being cut; the finished set is dropped and the image is cut again at the newest focus.", image.Id); return image.Id; } image.SetHash = target; image.Variants = variants; if (oldSet.Length > 0 && oldSet != target) { repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() }); } await repository.SaveChangesAsync(cancellationToken); indexCache?.Invalidate(); logger.LogInformation("Hero image {ImageId}: {Variants} variants cut in {Seconds:0.0} s", image.Id, variants.Count, watch.Elapsed.TotalSeconds); return image.Id; } public async Task DeleteAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken) { var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException(); if (await repository.ImageInUseAsync(imageId, cancellationToken)) { throw new HeroImageInUseException(); } var now = _time.GetUtcNow(); repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = image.SetHash, RetiredAt = now }); repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "original", Key = image.OriginalKey, RetiredAt = now }); repository.RemoveImage(image); await repository.SaveChangesAsync(cancellationToken); logger.LogInformation("Hero image {ImageId} removed by user {UserId}", imageId, callerId); } public async Task TrashAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken) { var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException(); var now = _time.GetUtcNow(); // A slide cannot exist without its image, so the slides that use it go with it; the moment counts as its last use. var slides = await repository.GetSlidesOfImageAsync(imageId, cancellationToken); foreach (var slide in slides) { repository.RemoveSlide(slide); } if (slides.Count > 0) { image.LastUsedAt = now; } image.DeletedAt = now; await repository.SaveChangesAsync(cancellationToken); indexCache?.Invalidate(); logger.LogInformation("Hero image {ImageId} moved to the trash by user {UserId} ({Slides} slides removed)", imageId, callerId, slides.Count); return slides.Count; } public async Task PurgeAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken) { var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken); if (image is null || image.DeletedAt is null) { return MediaPurgeOutcome.NotInTrash; } if (await repository.ImageInUseAsync(imageId, cancellationToken)) { return MediaPurgeOutcome.InUse; } // The row first (nothing refers to it any more), then the files; a file another image still shares stays. var (setShared, originalShared) = await repository.FilesSharedWithOthersAsync(imageId, image.SetHash, image.OriginalKey, cancellationToken); var (setHash, originalKey) = (image.SetHash, image.OriginalKey); repository.RemoveImage(image); await repository.SaveChangesAsync(cancellationToken); if (setHash.Length > 0 && !setShared) { await store.DeleteSetAsync(HeroMapping.Area, setHash, cancellationToken); } if (!originalShared) { await store.DeleteAsync(originalKey, cancellationToken); } indexCache?.Invalidate(); logger.LogInformation("Hero image {ImageId} removed for good by user {UserId}", imageId, callerId); return MediaPurgeOutcome.Purged; } public async Task RestoreAsync(Guid imageId, Guid callerId, CancellationToken cancellationToken) { var image = await repository.GetImageIncludingTrashedAsync(imageId, cancellationToken); if (image is null || image.DeletedAt is null) { return false; } image.DeletedAt = null; await repository.SaveChangesAsync(cancellationToken); signal?.Notify(); logger.LogInformation("Hero image {ImageId} restored from the trash by user {UserId}", imageId, callerId); return true; } private static void Apply(FocusDto? value, Action<(double?, double?, double?)> assign) { if (value is null) { assign((null, null, null)); return; } var f = value.ToSetting().Normalize(); assign((f.X, f.Y, f.Zoom)); } /// Cuts and encodes every planned variant of the image at its current focus (one decode for the whole set). private async Task<(Dictionary Files, List Variants)> RenderSetAsync(HeroImage image, byte[] original, ImageFormat storedFormat, Action? progress, CancellationToken cancellationToken) { var ratios = new[] { Ratio.Wide, Ratio.Tall } .Select(r => new RatioPlan(r, image.FocusFor(r.Name), VariantPlanner.DefaultWidths(r))) .ToList(); var specs = VariantPlanner.Plan(image.Width, image.Height, ratios, processor.SupportedOutput).ToList(); // The whole picture, for the focus dialog of the admin (never published to a website). specs.Add(VariantPlanner.Preview(image.Width, image.Height, processor.SupportedOutput)); progress?.Invoke(0, specs.Count); var rendered = await processor.RenderSetAsync(original, storedFormat, specs, progress, cancellationToken); var files = new Dictionary(); var variants = new List(); for (var i = 0; i < specs.Count; i++) { var spec = specs[i]; var name = MediaPaths.FileName(spec.Ratio.Name, spec.Width, spec.Format); files[name] = rendered[i].Bytes; variants.Add(new HeroVariant(spec.Ratio.Name, rendered[i].Width, rendered[i].Height, spec.Format.MimeType(), name, rendered[i].Bytes.LongLength)); } return (files, variants); } private async Task EnsureRoomAsync(long incomingBytes, CancellationToken cancellationToken) { var limits = mediaOptions.Value; // A set is a few times the size of the original at most; keep a margin so the write cannot fill the disk. var needed = incomingBytes * 4; var total = await store.GetTotalBytesAsync(cancellationToken); if (limits.MaxTotalBytes > 0 && total + needed > limits.MaxTotalBytes) { throw new MediaStorageFullException(); } if (store.GetFreeBytes() is { } free && free < needed + 64L * 1024 * 1024) { throw new MediaStorageFullException(); } } } /// The file name of an upload as it is shown in the library: cleaned, for display only, never part of a path. public static class HeroFileNames { public const int MaxLength = 200; public static string? Clean(string? name) { if (string.IsNullOrWhiteSpace(name)) { return null; } var last = name[(name.LastIndexOfAny(['/', '\\']) + 1)..]; var cleaned = new string(last.Where(c => !char.IsControl(c)).ToArray()).Trim(); if (cleaned.Length > MaxLength) { cleaned = cleaned[..MaxLength]; } return cleaned.Length == 0 ? null : cleaned; } }