«Aggiungi account» ha una sola casella: mentre Alberto scrive compaiono subito i suggerimenti locali, poi i profili di Instagram con la foto, come chiesto in #37. Il browser di Febe scrive nella casella «Cerca» di Instagram con tasti veri da una mappa chiusa (mai Invio, Tab o Esc), controlla prima il fuoco, legge la risposta della pagina e non clicca mai un risultato. La ricerca ha una categoria propria nel Governatore, con tetti larghi che non consumano quelli della raccolta, e si dà il turno con il motore sull'unica pagina; a fine sessione la pagina torna comunque al riposo. Le foto passano dal CDN con un permesso ciascuna e restano solo in memoria. Le risposte di Alberto del 15 novembre (controllo del fuoco, turni, evento requestWillBeSent, niente foto dei seguiti per ora) sono in §6.1 e in docs/decisioni.md. Su Instagram vero la ricerca parte quando i bersagli search-open e search-box saranno raccolti dal vivo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
202 lines
7.3 KiB
C#
202 lines
7.3 KiB
C#
using SkiaSharp;
|
|
|
|
namespace Febe.Core.Library;
|
|
|
|
/// <summary>
|
|
/// Thumbnails of the library (spec §8.4): 480 pixels on the long side, JPEG, generated once and kept under
|
|
/// <c>Dati/miniature</c>, in 256 shard folders named after the first two hex digits of the key. The key is the
|
|
/// SHA-256 of the library file, so identical files share one thumbnail. Videos use the cover given by the page or a
|
|
/// frame (<see cref="VideoFrameExtractor"/>); without either, the interface shows the neutral tile
|
|
/// (<see cref="NeutralVideoTile"/>).
|
|
/// </summary>
|
|
public sealed class ThumbnailStore
|
|
{
|
|
/// <summary>Long side of a thumbnail, in pixels.</summary>
|
|
public const int LongSide = 480;
|
|
|
|
/// <summary>JPEG quality of thumbnails.</summary>
|
|
public const int JpegQuality = 82;
|
|
|
|
/// <summary>File name of the neutral tile for videos without a cover.</summary>
|
|
public const string NeutralVideoTileName = "_video.jpg";
|
|
|
|
private readonly string _root;
|
|
|
|
public ThumbnailStore(string thumbnailsFolder)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(thumbnailsFolder);
|
|
_root = Path.GetFullPath(thumbnailsFolder);
|
|
}
|
|
|
|
/// <summary>The thumbnails folder.</summary>
|
|
public string Root => _root;
|
|
|
|
/// <summary>Path of the thumbnail of a key (lowercase hex SHA-256).</summary>
|
|
public string PathFor(string key)
|
|
{
|
|
ValidateKey(key);
|
|
var k = key.ToLowerInvariant();
|
|
return Path.Combine(_root, k[..2], k + ".jpg");
|
|
}
|
|
|
|
public bool Exists(string key) => File.Exists(PathFor(key));
|
|
|
|
/// <summary>
|
|
/// Creates the thumbnail of an encoded image (photo, or video cover). Does nothing when it already exists.
|
|
/// Returns false when the content cannot be decoded.
|
|
/// </summary>
|
|
public bool Create(string key, Stream encodedImage)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(encodedImage);
|
|
var target = PathFor(key);
|
|
if (File.Exists(target))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, LongSide);
|
|
if (bitmap is null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
WriteJpeg(target, Render(bitmap, LongSide));
|
|
return true;
|
|
}
|
|
|
|
/// <summary>Creates the thumbnail of an image file.</summary>
|
|
public bool CreateFromFile(string key, string imagePath)
|
|
{
|
|
using var stream = File.OpenRead(imagePath);
|
|
return Create(key, stream);
|
|
}
|
|
|
|
/// <summary>Removes a thumbnail (when no file of the library uses its key any more).</summary>
|
|
public bool Delete(string key)
|
|
{
|
|
var path = PathFor(key);
|
|
if (!File.Exists(path))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
File.Delete(path);
|
|
return true;
|
|
}
|
|
|
|
/// <summary>The neutral tile for videos without a cover, created on first use (grey, with a play sign).</summary>
|
|
public string NeutralVideoTile()
|
|
{
|
|
var path = Path.Combine(_root, NeutralVideoTileName);
|
|
if (File.Exists(path))
|
|
{
|
|
return path;
|
|
}
|
|
|
|
const int width = 270, height = LongSide; // 9:16, like stories and reels
|
|
using var surface = SKSurface.Create(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
|
var canvas = surface.Canvas;
|
|
canvas.Clear(new SKColor(0xE4, 0xE4, 0xE4));
|
|
using (var paint = new SKPaint { Color = new SKColor(0x9A, 0x9A, 0x9A), IsAntialias = true, Style = SKPaintStyle.Fill })
|
|
{
|
|
canvas.DrawCircle(width / 2f, height / 2f, 34, paint);
|
|
}
|
|
|
|
using (var paint = new SKPaint { Color = new SKColor(0xE4, 0xE4, 0xE4), IsAntialias = true, Style = SKPaintStyle.Fill })
|
|
{
|
|
// A play triangle drawn as three thin rectangles would be blurry; vertices keep it crisp.
|
|
var cx = width / 2f + 4;
|
|
var cy = height / 2f;
|
|
SKPoint[] triangle = [new(cx - 10, cy - 15), new(cx - 10, cy + 15), new(cx + 15, cy)];
|
|
canvas.DrawVertices(SKVertexMode.Triangles, triangle, null, null, paint);
|
|
}
|
|
|
|
using var image = surface.Snapshot();
|
|
using var bitmap = SKBitmap.FromImage(image);
|
|
WriteJpeg(path, bitmap.Copy());
|
|
return path;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Re-encodes an image to a small JPEG in memory (issue #37, photos of the profile search: never on disk). Returns
|
|
/// null when the content is not a decodable image.
|
|
/// </summary>
|
|
public static byte[]? EncodeSmallJpeg(Stream source, int longSide)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(source);
|
|
ArgumentOutOfRangeException.ThrowIfLessThan(longSide, 16);
|
|
using var decoded = ImageDecoding.DecodeUpright(source, longSide);
|
|
if (decoded is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
using var small = Render(decoded, longSide);
|
|
using var pixmap = small.PeekPixels();
|
|
if (pixmap is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
using var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality));
|
|
return data?.ToArray();
|
|
}
|
|
|
|
private static SKBitmap Render(SKBitmap source, int longSide)
|
|
{
|
|
var scale = Math.Min(1.0, (double)longSide / Math.Max(source.Width, source.Height));
|
|
var width = Math.Max(1, (int)Math.Round(source.Width * scale));
|
|
var height = Math.Max(1, (int)Math.Round(source.Height * scale));
|
|
var result = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
|
using var canvas = new SKCanvas(result);
|
|
canvas.Clear(SKColors.White); // JPEG has no alpha: transparent areas become white
|
|
using var image = SKImage.FromBitmap(source);
|
|
canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null);
|
|
return result;
|
|
}
|
|
|
|
private static void WriteJpeg(string target, SKBitmap bitmap)
|
|
{
|
|
using (bitmap)
|
|
{
|
|
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
|
var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp";
|
|
try
|
|
{
|
|
using (var pixmap = bitmap.PeekPixels() ?? throw new InvalidOperationException("Miniatura senza pixel."))
|
|
using (var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality))
|
|
?? throw new InvalidOperationException("Codifica JPEG della miniatura non riuscita."))
|
|
using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write))
|
|
{
|
|
data.SaveTo(file);
|
|
}
|
|
|
|
try
|
|
{
|
|
File.Move(temp, target, overwrite: false);
|
|
}
|
|
catch (IOException) when (File.Exists(target))
|
|
{
|
|
// Created meanwhile by another task: same content.
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
if (File.Exists(temp))
|
|
{
|
|
File.Delete(temp);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void ValidateKey(string key)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(key);
|
|
if (key.Length < 8 || !key.All(Uri.IsHexDigit))
|
|
{
|
|
throw new ArgumentException("La chiave di una miniatura è uno SHA-256 in esadecimale.", nameof(key));
|
|
}
|
|
}
|
|
}
|