using System.Buffers.Binary; using System.Collections.Concurrent; using System.Security.Cryptography; using System.Numerics; using System.Text; using Febe.Core.Codecs.Images; using Febe.Core.Drawing; namespace Febe.SitoDiProva; /// /// Generates the files the «CDN» serves: JPEG pictures drawn with Febe's own canvas and JPEG writer from the media key (same key, same /// picture at every size) and short MP4 videos made unique with a trailing «free» box. Results are cached. /// public sealed class MediaFactory { private static readonly Lazy VideoWithAudio = new(() => ReadResource("filmato-con-audio.mp4")); private static readonly Lazy VideoWithoutAudio = new(() => ReadResource("filmato-muto.mp4")); private readonly ConcurrentDictionary _cache = new(StringComparer.Ordinal); /// A JPEG of × for . public byte[] Picture(string key, int width, int height) => _cache.GetOrAdd($"p|{key}|{width}|{height}", _ => DrawPicture(key, Math.Clamp(width, 16, 2048), Math.Clamp(height, 16, 2048))); /// An MP4 for : with audio (complete) or video only. public byte[] Video(string key, int width, int height, bool withAudio) => _cache.GetOrAdd($"v|{key}|{width}|{height}|{withAudio}", _ => { var template = withAudio ? VideoWithAudio.Value : VideoWithoutAudio.Value; var payload = Encoding.ASCII.GetBytes($"febe-sito-di-prova {key} {width}x{height} {(withAudio ? "audio" : "muto")}"); var result = new byte[template.Length + 8 + payload.Length]; template.CopyTo(result, 0); BinaryPrimitives.WriteUInt32BigEndian(result.AsSpan(template.Length), (uint)(8 + payload.Length)); "free"u8.CopyTo(result.AsSpan(template.Length + 4)); payload.CopyTo(result, template.Length + 8); return result; }); private static byte[] DrawPicture(string key, int width, int height) { var seed = BinaryPrimitives.ReadInt32LittleEndian(SHA256.HashData(Encoding.UTF8.GetBytes(key))); var random = new Random(seed); using var image = new RgbaImage(width, height); using (var canvas = new Canvas(image)) { Color RandomColor() => new((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256)); var background = new LinearGradientBrush(new Vector2(0, 0), new Vector2(width, height), [RandomColor(), RandomColor(), RandomColor()]); canvas.FillRect(0, 0, width, height, background); // Shapes in relative coordinates: every size shows the same picture. var shapes = 8 + random.Next(8); for (var i = 0; i < shapes; i++) { var color = RandomColor().WithAlpha((byte)(150 + random.Next(100))); var x = (float)(random.NextDouble() * width); var y = (float)(random.NextDouble() * height); var w = (float)((0.08 + (random.NextDouble() * 0.35)) * width); var h = (float)((0.08 + (random.NextDouble() * 0.35)) * height); if (random.Next(2) == 0) { canvas.FillRect(x - (w / 2), y - (h / 2), w, h, color); } else { canvas.FillEllipse(x, y, w / 2, h / 2, color); } } } return JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = 85 }); } private static byte[] ReadResource(string name) { using var stream = typeof(MediaFactory).Assembly.GetManifestResourceStream($"Febe.SitoDiProva.Risorse.{name}") ?? throw new FileNotFoundException($"Risorsa mancante: {name}"); using var memory = new MemoryStream(); stream.CopyTo(memory); return memory.ToArray(); } } /// /// Signed, expiring CDN addresses (spec §6.5: «gli indirizzi scadono»): /m/{key}/{w}x{h}.jpg?scad=…&firma=…. /// The signature is an HMAC of path and expiry with a key drawn at start-up; an address past its expiry gets 403. /// public sealed class CdnSigner { private readonly byte[] _key = RandomNumberGenerator.GetBytes(32); public string Sign(string path, DateTimeOffset expiresAt) { var expiry = expiresAt.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture); return $"{path}?scad={expiry}&firma={Signature(path, expiry)}"; } /// Checks an address: , or . public CdnCheck Check(string path, string? expiry, string? signature, DateTimeOffset now) { if (string.IsNullOrEmpty(expiry) || string.IsNullOrEmpty(signature) || !long.TryParse(expiry, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var seconds)) { return CdnCheck.Invalid; } if (!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(Signature(path, expiry)), Encoding.ASCII.GetBytes(signature))) { return CdnCheck.Invalid; } return DateTimeOffset.FromUnixTimeSeconds(seconds) < now ? CdnCheck.Expired : CdnCheck.Valid; } private string Signature(string path, string expiry) => Convert.ToHexStringLower(HMACSHA256.HashData(_key, Encoding.UTF8.GetBytes(path + "|" + expiry)))[..24]; } public enum CdnCheck { Valid, Expired, Invalid, }