Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
134 lines
6.0 KiB
C#
134 lines
6.0 KiB
C#
using System.Buffers.Binary;
|
||
using System.Collections.Concurrent;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using SkiaSharp;
|
||
|
||
namespace Febe.SitoDiProva;
|
||
|
||
/// <summary>
|
||
/// Generates the files the «CDN» serves: JPEG pictures drawn with SkiaSharp 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.
|
||
/// </summary>
|
||
public sealed class MediaFactory
|
||
{
|
||
private static readonly Lazy<byte[]> VideoWithAudio = new(() => ReadResource("filmato-con-audio.mp4"));
|
||
private static readonly Lazy<byte[]> VideoWithoutAudio = new(() => ReadResource("filmato-muto.mp4"));
|
||
|
||
private readonly ConcurrentDictionary<string, byte[]> _cache = new(StringComparer.Ordinal);
|
||
|
||
/// <summary>A JPEG of <paramref name="width"/>×<paramref name="height"/> for <paramref name="key"/>.</summary>
|
||
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)));
|
||
|
||
/// <summary>An MP4 for <paramref name="key"/>: with audio (complete) or video only.</summary>
|
||
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 bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
||
using (var canvas = new SKCanvas(bitmap))
|
||
{
|
||
SKColor RandomColor() => new((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256));
|
||
using (var background = new SKPaint())
|
||
{
|
||
background.Shader = SKShader.CreateLinearGradient(
|
||
new SKPoint(0, 0),
|
||
new SKPoint(width, height),
|
||
[RandomColor(), RandomColor(), RandomColor()],
|
||
null,
|
||
SKShaderTileMode.Clamp);
|
||
canvas.DrawRect(0, 0, width, height, background);
|
||
}
|
||
|
||
// Shapes in relative coordinates: every size shows the same picture.
|
||
using var paint = new SKPaint { IsAntialias = true };
|
||
var shapes = 8 + random.Next(8);
|
||
for (var i = 0; i < shapes; i++)
|
||
{
|
||
paint.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.DrawRect(x - (w / 2), y - (h / 2), w, h, paint);
|
||
}
|
||
else
|
||
{
|
||
canvas.DrawOval(new SKRect(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2)), paint);
|
||
}
|
||
}
|
||
}
|
||
|
||
using var image = SKImage.FromBitmap(bitmap);
|
||
using var data = image.Encode(SKEncodedImageFormat.Jpeg, 85);
|
||
return data.ToArray();
|
||
}
|
||
|
||
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();
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Signed, expiring CDN addresses (spec §6.5: «gli indirizzi scadono»): <c>/m/{key}/{w}x{h}.jpg?scad=…&firma=…</c>.
|
||
/// The signature is an HMAC of path and expiry with a key drawn at start-up; an address past its expiry gets 403.
|
||
/// </summary>
|
||
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)}";
|
||
}
|
||
|
||
/// <summary>Checks an address: <see cref="CdnCheck.Valid"/>, <see cref="CdnCheck.Expired"/> or <see cref="CdnCheck.Invalid"/>.</summary>
|
||
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,
|
||
}
|