SkiaSharp e SkiaSharp.NativeAssets.Linux.NoDependencies escono da Directory.Packages.props e da ogni progetto, per la regola «niente componenti esterni». Tutto ciò che leggeva, ridimensionava o disegnava immagini con Skia ora usa codice scritto in casa sulla BCL: - ImageResampler: Lanczos3 separabile o media per area, alfa premoltiplicata, luce lineare facoltativa; ImageGray per l'impronta. - Il lettore JPEG decodifica ridotto a 1/2, 1/4, 1/8; le miniature chiedono almeno il doppio del lato lungo, così l'ultimo passo resta a Lanczos e la miniatura resta uguale alla lettura intera. - ImageOrientation applica l'EXIF in un punto solo (miniature, impronte, anteprime, dimensioni mostrate). - ImageConverter cambia formato fra JPEG, PNG e WebP portando EXIF, ICC, XMP e testi, con l'etichetta d'orientamento e i pixel non ruotati; PngEncoder scrive anche i testi (tEXt o iTXt). - Febe.Core.Drawing: rasterizzatore con antialiasing (tracciati, riempimenti, tratti, gradienti) per icona, immagini dimostrative, riquadro neutro dei video, foto del sito di prova e prove. Febe.ico rigenerata. - ThumbnailStore legge anche i BMP a 24 bit, come quelli del decoder video del ramo funzione/decoder-h264. Le impronte salvate restano confrontabili (390 su 393 campioni identiche, le altre a distanza 2, soglia 6): nessun ricalcolo. Un PNG o JPEG troncato ora non ha miniatura né impronta. Documenti, elenco dei componenti della pagina «Informazioni» e decisioni aggiornati; nuove prove per ridimensionamento, orientamento, lettura ridotta, conversione con metadati, testi PNG e rasterizzatore. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
125 lines
5.6 KiB
C#
125 lines
5.6 KiB
C#
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;
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </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 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();
|
||
}
|
||
}
|
||
|
||
/// <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,
|
||
}
|