using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace SlpModularCms.Core.Media; public static class MediaServiceCollectionExtensions { /// /// The general media service: options (Media:*), the processing gate, the status the admin reads, the upload /// guard and the start-up self-test. Safe to call from every module that needs it. An /// has to be registered separately (the Magick project does that); without one the status stays "unavailable". /// public static IServiceCollection AddCmsMedia(this IServiceCollection services) { services.AddOptions().Configure((options, configuration) => configuration.GetSection(MediaOptions.SectionName).Bind(options)); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); if (!services.Any(d => d.ImplementationType == typeof(ImageProcessorSelfTest))) { services.AddHostedService(); services.AddHostedService(); } return services; } /// Lets the /media endpoint serve the given area (for example hero). public static IServiceCollection AddCmsMediaArea(this IServiceCollection services, string area) { services.AddCmsMedia(); services.AddSingleton(new MediaAreaRegistration(area)); return services; } } /// A module declares the media area it owns; the host adds all of them to the at start-up. public sealed record MediaAreaRegistration(string Area); /// /// At start-up, proves that the media directory exists (creating it when needed) and is writable, fills the area /// registry and warns when the directory fills up. A failure only turns image uploads off; files that are already /// stored keep being served. /// public sealed class MediaDirectoryCheck( IMediaStore store, MediaStatus status, MediaAreaRegistry areas, IEnumerable registrations, Microsoft.Extensions.Options.IOptions options, ILogger logger) : IHostedService { /// The check in the background; completes when the status is known (tests await it). public Task Completion { get; private set; } = Task.CompletedTask; private readonly CancellationTokenSource _stopping = new(); public Task StartAsync(CancellationToken cancellationToken) { foreach (var registration in registrations) { areas.Add(registration.Area); } // Not awaited: a hosted service delays the moment the host starts listening, and a disk that is slow to answer must // never keep the website from coming up. Until it is done, uploads are simply not available yet. Completion = Task.Run(() => CheckAsync(_stopping.Token), CancellationToken.None); return Task.CompletedTask; } private async Task CheckAsync(CancellationToken cancellationToken) { try { if (string.IsNullOrWhiteSpace(options.Value.Directory)) { status.SetDirectory(false); logger.LogWarning("Media:Directory is not configured: image uploads are unavailable on this host."); return; } var writable = await store.ProbeAsync(cancellationToken); status.SetDirectory(writable); if (!writable) { logger.LogError("The media directory is missing or not writable: image uploads are unavailable until it is fixed."); return; } var total = await store.GetTotalBytesAsync(cancellationToken); if (options.Value.MaxTotalBytes > 0 && total > options.Value.MaxTotalBytes * 8 / 10) { logger.LogError("The media directory is over 80 percent of its safety limit ({Bytes} bytes).", total); } } catch (Exception exception) when (exception is not OperationCanceledException) { status.SetDirectory(false); logger.LogError(exception, "The media directory check failed: image uploads are unavailable on this host."); } } public async Task StopAsync(CancellationToken cancellationToken) { await _stopping.CancelAsync(); try { await Completion.WaitAsync(cancellationToken); } catch (OperationCanceledException) { // Shutting down. } } } /// /// At start-up, proves the image library works on this host (encodes and decodes a tiny image in every supported /// format) and publishes what it found. A failure only turns image uploads off: nothing else depends on it, and /// reading pages and media keeps working. /// public sealed class ImageProcessorSelfTest(IServiceProvider services, MediaStatus status, ILogger logger) : IHostedService { /// The self-test in the background; completes when the status is known (tests await it). public Task Completion { get; private set; } = Task.CompletedTask; private readonly CancellationTokenSource _stopping = new(); public Task StartAsync(CancellationToken cancellationToken) { // Not awaited: loading the native library and encoding a test image can take seconds on a small machine, and a // hosted service delays the moment the host starts listening (the health check of a deploy waits for it). Completion = Task.Run(() => TestAsync(_stopping.Token), CancellationToken.None); return Task.CompletedTask; } private async Task TestAsync(CancellationToken cancellationToken) { try { var processor = services.GetService(); if (processor is null) { status.SetProcessor(false, new HashSet(), new HashSet()); logger.LogWarning("No image processor is registered: image uploads are unavailable."); return; } await processor.SelfTestAsync(cancellationToken); status.SetProcessor(true, processor.SupportedInput, processor.SupportedOutput); } catch (Exception exception) when (exception is not OperationCanceledException) { status.SetProcessor(false, new HashSet(), new HashSet()); logger.LogError(exception, "The image library self-test failed: image uploads are unavailable on this host."); } } public async Task StopAsync(CancellationToken cancellationToken) { await _stopping.CancelAsync(); try { await Completion.WaitAsync(cancellationToken); } catch (OperationCanceledException) { // Shutting down. } } }