using System.Buffers.Binary; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Data; using SkiaSharp; namespace Febe.Tests.Support; /// A temporary folder removed at the end of a test. internal sealed class TempFolder : IDisposable { public TempFolder(string prefix = "febe") { Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "febe-prove", prefix + "-" + Guid.NewGuid().ToString("N")[..10]); Directory.CreateDirectory(Path); } public string Path { get; } public string Combine(params string[] parts) => System.IO.Path.Combine([Path, .. parts]); public void Dispose() { try { Directory.Delete(Path, recursive: true); } catch (IOException) { } catch (UnauthorizedAccessException) { } } } /// A clock moved by hand, in Alberto's zone. internal sealed class ManualClock(DateTimeOffset start, TimeZoneInfo? zone = null) : IClock { public DateTimeOffset Now { get; set; } = start; public TimeZoneInfo LocalZone { get; } = zone ?? TestZones.Rome; public Task Delay(TimeSpan time, CancellationToken ct) { Now += time; return Task.CompletedTask; } } internal static class TestZones { /// Europe/Rome, or an equivalent custom zone when the system has no time zone data. public static TimeZoneInfo Rome { get; } = LoadRome(); private static TimeZoneInfo LoadRome() { foreach (var id in new[] { "Europe/Rome", "W. Europe Standard Time" }) { try { return TimeZoneInfo.FindSystemTimeZoneById(id); } catch (TimeZoneNotFoundException) { } catch (InvalidTimeZoneException) { } } var start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 5, DayOfWeek.Sunday); var end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 10, 5, DayOfWeek.Sunday); var rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue.Date, DateTime.MaxValue.Date, TimeSpan.FromHours(1), start, end); return TimeZoneInfo.CreateCustomTimeZone("Europe/Rome", TimeSpan.FromHours(1), "Europe/Rome", "CET", "CEST", [rule]); } } /// Builders of domain records for tests. internal static class Make { public static readonly DateTimeOffset T0 = new(2026, 10, 13, 8, 0, 0, TimeSpan.Zero); public static Account Account(string username, string? instagramId = null, bool mine = false) => Core.Domain.Account.Create(username, StartingPoint.EverythingAndKeepUpdated, T0, TestZones.Rome, isMine: mine) with { InstagramId = instagramId ?? ((uint)username.GetHashCode(StringComparison.Ordinal)).ToString(System.Globalization.CultureInfo.InvariantCulture), }; public static Entry Entry(long accountId, string instagramId, DateTimeOffset publishedAt, EntryKind kind = EntryKind.Post, string? caption = null) => new() { AccountId = accountId, Kind = kind, InstagramId = instagramId, Code = "C" + instagramId, PublishedAt = publishedAt, Caption = caption, DiscoveredAt = T0, }; public static Media Photo(int position = 1, MediaState state = MediaState.ToDownload) => new() { Position = position, Kind = MediaKind.Photo, State = state, Width = 1080, Height = 1350 }; public static Media Video(int position = 1, MediaState state = MediaState.ToDownload) => new() { Position = position, Kind = MediaKind.Video, State = state, Width = 1080, Height = 1920, Duration = TimeSpan.FromSeconds(15) }; public static Media Stored(Media media, string sha, string path) => media with { State = MediaState.Downloaded, Sha256 = sha, RelativePath = path, Bytes = 1000 }; public static string Sha(int n) => n.ToString("x64", System.Globalization.CultureInfo.InvariantCulture); } /// Opens test databases. internal static class TestDatabase { public static Task OpenAsync(TempFolder folder, string name = "dati") => FebeDatabase.OpenAsync(folder.Combine(name)); } /// Generated images: «photos» made of gradients, shapes, lines and grain, reproducible from a seed. internal static class TestImages { public static SKBitmap Scene(int seed, int width = 1200, int height = 900) { var random = new Random(seed); 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()) { var angle = random.NextDouble() * Math.PI * 2; var dx = (float)Math.Cos(angle) * width / 2; var dy = (float)Math.Sin(angle) * height / 2; background.Shader = SKShader.CreateLinearGradient( new SKPoint((width / 2f) - dx, (height / 2f) - dy), new SKPoint((width / 2f) + dx, (height / 2f) + dy), [RandomColor(), RandomColor(), RandomColor()], null, SKShaderTileMode.Clamp); canvas.DrawRect(0, 0, width, height, background); } using var paint = new SKPaint { IsAntialias = true }; var shapes = 10 + random.Next(10); for (var i = 0; i < shapes; i++) { paint.Color = RandomColor().WithAlpha((byte)(160 + random.Next(96))); paint.Style = random.Next(4) == 0 ? SKPaintStyle.Stroke : SKPaintStyle.Fill; paint.StrokeWidth = 4 + random.Next(30); var x = (float)(random.NextDouble() * width); var y = (float)(random.NextDouble() * height); var w = (float)((0.05 + (random.NextDouble() * 0.4)) * width); var h = (float)((0.05 + (random.NextDouble() * 0.4)) * height); switch (random.Next(4)) { case 0: canvas.DrawRect(x - (w / 2), y - (h / 2), w, h, paint); break; case 1: canvas.DrawCircle(x, y, Math.Min(w, h) / 2, paint); break; case 2: canvas.DrawOval(new SKRect(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2)), paint); break; default: paint.StrokeWidth = 6 + random.Next(20); canvas.DrawLine(x, y, (float)(random.NextDouble() * width), (float)(random.NextDouble() * height), paint); break; } } // Fine grain, as in a photo. using var grain = new SKPaint { IsAntialias = false }; for (var i = 0; i < width * height / 60; i++) { var v = (byte)random.Next(256); grain.Color = new SKColor(v, v, v, 28); canvas.DrawPoint(random.Next(width), random.Next(height), grain); } return bitmap; } public static byte[] Jpeg(SKBitmap bitmap, int quality = 90) { using var image = SKImage.FromBitmap(bitmap); using var data = image.Encode(SKEncodedImageFormat.Jpeg, quality); return data.ToArray(); } public static byte[] Png(SKBitmap bitmap) { using var image = SKImage.FromBitmap(bitmap); using var data = image.Encode(SKEncodedImageFormat.Png, 100); return data.ToArray(); } public static SKBitmap Resize(SKBitmap source, int width, int height) { var result = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); using var canvas = new SKCanvas(result); using var image = SKImage.FromBitmap(source); canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null); return result; } public static SKBitmap Crop(SKBitmap source, SKRectI area) { var result = new SKBitmap(new SKImageInfo(area.Width, area.Height, SKColorType.Rgba8888, SKAlphaType.Premul)); using var canvas = new SKCanvas(result); using var image = SKImage.FromBitmap(source); canvas.DrawImage(image, area, new SKRect(0, 0, area.Width, area.Height), new SKSamplingOptions(SKFilterMode.Nearest), null); return result; } /// Decodes a JPEG/PNG back to a bitmap. public static SKBitmap Decode(byte[] encoded) => SKBitmap.Decode(encoded) ?? throw new InvalidOperationException("decode"); /// Rotates pixels 90° counter-clockwise (what a camera stores before tagging orientation 6). public static SKBitmap RotateCounterClockwise(SKBitmap source) { var result = new SKBitmap(new SKImageInfo(source.Height, source.Width, SKColorType.Rgba8888, SKAlphaType.Premul)); using var canvas = new SKCanvas(result); canvas.Translate(0, source.Width); canvas.RotateDegrees(-90); canvas.DrawBitmap(source, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null); return result; } /// Inserts an EXIF APP1 segment with the given orientation right after the SOI marker of a JPEG. public static byte[] WithExifOrientation(byte[] jpeg, ushort orientation) { if (jpeg.Length < 2 || jpeg[0] != 0xFF || jpeg[1] != 0xD8) { throw new ArgumentException("Not a JPEG.", nameof(jpeg)); } var app1 = new byte[36]; app1[0] = 0xFF; app1[1] = 0xE1; BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(2), 34); // length, including these two bytes "Exif\0\0"u8.CopyTo(app1.AsSpan(4)); "MM\0*"u8.CopyTo(app1.AsSpan(10)); // TIFF header, big endian BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(14), 8); // offset of IFD0 BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(18), 1); // one entry BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(20), 0x0112); // Orientation BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(22), 3); // SHORT BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(24), 1); // count BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(28), orientation); BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(32), 0); // no next IFD return [.. jpeg.AsSpan(0, 2), .. app1, .. jpeg.AsSpan(2)]; } }