using Microsoft.Extensions.Options; namespace SlpModularCms.Core.Media; /// Why an upload was refused. The names are the stable codes the API returns (see ). public enum ImageRejection { TooLarge, UnsupportedFormat, Corrupt, TooManyPixels, Timeout, Busy, Unavailable, } /// A refused image. The message is technical English for logs; users see a text from the language files. public sealed class ImageRejectedException(ImageRejection reason, string message) : Exception(message) { public ImageRejection Reason { get; } = reason; /// A stable code for the API: too_large, unsupported_format, corrupt, too_many_pixels, timeout, busy, unavailable. public string Code => Reason switch { ImageRejection.TooLarge => "too_large", ImageRejection.UnsupportedFormat => "unsupported_format", ImageRejection.Corrupt => "corrupt", ImageRejection.TooManyPixels => "too_many_pixels", ImageRejection.Timeout => "timeout", ImageRejection.Busy => "busy", _ => "unavailable", }; } /// Settings of the media service (Media:*). public sealed class MediaOptions { public const string SectionName = "Media"; /// The directory outside the release where files are stored. Empty = uploads are unavailable. public string? Directory { get; set; } public long MaxUploadBytes { get; set; } = 10 * 1024 * 1024; public long MaxPixels { get; set; } = 64_000_000; public int MaxSide { get; set; } = 16_384; public int MaxParallelJobs { get; set; } = 2; public int DecodeTimeoutSeconds { get; set; } = 20; /// The time allowed to remove metadata from an upload (it decodes and writes the whole picture again). public int StripTimeoutSeconds { get; set; } = 60; /// /// The time allowed to cut ALL variants of one photo in the background (one decode, then every variant). Generous on /// purpose: a large photo on a Raspberry Pi needs minutes; a runaway job is stopped after this. /// public int RenderSetTimeoutSeconds { get; set; } = 600; /// How long a free processing slot is awaited before the answer is "busy". public int BusyWaitSeconds { get; set; } = 3; public long MaxTotalBytes { get; set; } = 2L * 1024 * 1024 * 1024; public int RetentionDays { get; set; } = 7; /// /// Whether photos that were uploaded but never used are removed automatically after . /// The media library keeps everything until a person removes it, so set this to false (Media__AutoCleanupUnattached=false) /// once the library can show and delete photos. Retired files of photos a person removed stay housekeeping either way. /// Default true keeps today's behaviour (assumption 3 of the media-library list). /// public bool AutoCleanupUnattached { get; set; } = true; } /// /// The image library behind one small interface. Implementations must apply the resource limits of /// , decode only the format the caller names (decided from the signature), never use a /// client file name and never write metadata into an output. /// public interface IImageProcessor { /// The formats it can decode. IReadOnlySet SupportedInput { get; } /// The formats it can write (WebP always; AVIF when the platform can). IReadOnlySet SupportedOutput { get; } /// Reads size (after orientation), frame count and whether metadata is present, without decoding the pixels. /// The data is not a decodable image of that format. Task InspectAsync(ReadOnlyMemory data, ImageFormat declared, CancellationToken cancellationToken); /// /// Decodes the first frame, applies the orientation, cuts the crop, resizes to the variant size (never above the /// crop), strips metadata and encodes in the variant's format and quality. /// Task RenderAsync(ReadOnlyMemory data, ImageFormat declared, VariantSpec variant, CancellationToken cancellationToken); /// /// Cuts all variants of a photo from ONE decode (the picture is decoded and oriented once, then every variant is /// cropped, resized and encoded from it). is called with (variants done, variants in total) /// after every variant. Stops between variants when cancelled. The result has the order of . /// Task> RenderSetAsync(ReadOnlyMemory data, ImageFormat declared, IReadOnlyList variants, Action? progress, CancellationToken cancellationToken); /// /// Removes metadata from an original that carries any, keeping the pixels as they are as far as the format /// allows. Returns null when there is nothing to remove (the original is stored as received). /// Task StripMetadataAsync(ReadOnlyMemory data, ImageFormat declared, CancellationToken cancellationToken); /// Encodes and decodes a tiny image in every supported format. Throws when the library does not work here. Task SelfTestAsync(CancellationToken cancellationToken); } /// What the start-up self-test found; uploads are refused while the processor is not available. public sealed class MediaStatus { private volatile bool _processorAvailable; private volatile bool _directoryWritable; public bool ProcessorAvailable => _processorAvailable; public bool DirectoryWritable => _directoryWritable; public bool UploadsAvailable => _processorAvailable && _directoryWritable; public IReadOnlySet AcceptedInput { get; private set; } = new HashSet(); public IReadOnlySet Output { get; private set; } = new HashSet(); public void SetProcessor(bool available, IReadOnlySet input, IReadOnlySet output) { AcceptedInput = input; Output = output; _processorAvailable = available; } public void SetDirectory(bool writable) => _directoryWritable = writable; } /// Limits how many images are processed at once; a full gate answers "busy" after a short wait. public sealed class MediaProcessingGate(IOptions options) { private readonly SemaphoreSlim _slots = new(Math.Max(1, options.Value.MaxParallelJobs)); private readonly TimeSpan _wait = TimeSpan.FromSeconds(Math.Max(0, options.Value.BusyWaitSeconds)); public async Task EnterAsync(CancellationToken cancellationToken) { if (!await _slots.WaitAsync(_wait, cancellationToken)) { throw new ImageRejectedException(ImageRejection.Busy, "All image processing slots are in use."); } return new Releaser(_slots); } private sealed class Releaser(SemaphoreSlim slots) : IDisposable { private int _released; public void Dispose() { if (Interlocked.Exchange(ref _released, 1) == 0) { slots.Release(); } } } }