using System.Buffers.Binary; using System.Numerics; using Febe.Core.Abstractions; using Febe.Core.Codecs.Images; using Febe.Core.Domain; using Febe.Core.Drawing; using Febe.Data; 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, drawn and encoded /// with Febe's own code (Drawing, Codecs/Images). /// internal static class TestImages { public static RgbaImage Scene(int seed, int width = 1200, int height = 900) { var random = new Random(seed); 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 angle = random.NextDouble() * Math.PI * 2; var dx = (float)Math.Cos(angle) * width / 2; var dy = (float)Math.Sin(angle) * height / 2; var background = new LinearGradientBrush( new Vector2((width / 2f) - dx, (height / 2f) - dy), new Vector2((width / 2f) + dx, (height / 2f) + dy), [RandomColor(), RandomColor(), RandomColor()]); canvas.FillRect(0, 0, width, height, background); var shapes = 10 + random.Next(10); for (var i = 0; i < shapes; i++) { var color = RandomColor().WithAlpha((byte)(160 + random.Next(96))); var stroke = random.Next(4) == 0; float 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: if (stroke) { canvas.StrokeRect(x - (w / 2), y - (h / 2), w, h, strokeWidth, color); } else { canvas.FillRect(x - (w / 2), y - (h / 2), w, h, color); } break; case 1: if (stroke) { canvas.StrokeCircle(x, y, Math.Min(w, h) / 2, strokeWidth, color); } else { canvas.FillCircle(x, y, Math.Min(w, h) / 2, color); } break; case 2: if (stroke) { canvas.StrokeEllipse(x, y, w / 2, h / 2, strokeWidth, color); } else { canvas.FillEllipse(x, y, w / 2, h / 2, color); } break; default: strokeWidth = 6 + random.Next(20); canvas.DrawLine(x, y, (float)(random.NextDouble() * width), (float)(random.NextDouble() * height), strokeWidth, color); break; } } // Fine grain, as in a photo. for (var i = 0; i < width * height / 60; i++) { var v = (byte)random.Next(256); canvas.BlendPixel(random.Next(width), random.Next(height), new Color(v, v, v, 28)); } return image; } public static byte[] Jpeg(RgbaImage image, int quality = 90) => JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = quality }); public static byte[] Png(RgbaImage image) => PngEncoder.Encode(image); public static RgbaImage Resize(RgbaImage source, int width, int height) => ImageResampler.Resize(source, width, height); /// The pixels of × from (, ). public static RgbaImage Crop(RgbaImage source, int left, int top, int width, int height) { var result = new RgbaImage(width, height); for (var y = 0; y < height; y++) { source.GetRow(top + y).Slice(left * 4, width * 4).CopyTo(result.GetRow(y)); } return result; } /// Decodes a JPEG/PNG back to pixels (as stored: the orientation is not applied). public static RgbaImage Decode(byte[] encoded) => ImageDecoder.Decode(encoded); /// Rotates pixels 90° counter-clockwise (what a camera stores before tagging orientation 6). public static RgbaImage RotateCounterClockwise(RgbaImage source) { var result = new RgbaImage(source.Height, source.Width); for (var y = 0; y < result.Height; y++) { var row = result.GetRow(y); for (var x = 0; x < result.Width; x++) { // Target (x, y) shows source (w − 1 − y, x). var (r, g, b, a) = source.GetPixel(source.Width - 1 - y, x); row[x * 4] = r; row[(x * 4) + 1] = g; row[(x * 4) + 2] = b; row[(x * 4) + 3] = a; } } 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)]; } }