using System.Collections.Concurrent; using System.Net; using System.Text; using System.Text.Json; using Febe.Core.Alerts; using Febe.Web.Native; namespace Febe.Tests.Alerts.Support; /// A request that reached the fake Telegram. /// HTTP method. /// Full address (it contains the token: tests check it here, nowhere else). /// Media type of the body. /// The JSON body. internal sealed record TelegramRequest(HttpMethod Method, Uri Uri, string? ContentType, string Body) { public string ChatId => JsonDocument.Parse(Body).RootElement.GetProperty("chat_id").GetString()!; public string Text => JsonDocument.Parse(Body).RootElement.GetProperty("text").GetString()!; } /// /// Telegram's Bot API, faked: records every request and answers with (by default /// 200 {"ok":true}). Never touches the network: the real api.telegram.org is never contacted from tests. /// internal sealed class FakeTelegramHandler : HttpMessageHandler { private readonly ConcurrentQueue _requests = new(); public Func>? Respond { get; set; } public IReadOnlyList Requests => [.. _requests]; public static HttpResponseMessage Answer(HttpStatusCode status, string json) => new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; /// Answers with and the usual error body of the Bot API. public void Fail(HttpStatusCode status, string description) => Respond = (_, _) => Task.FromResult(Answer(status, $$"""{"ok":false,"error_code":{{(int)status}},"description":"{{description}}"}""")); protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var body = request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync(cancellationToken); var recorded = new TelegramRequest(request.Method, request.RequestUri!, request.Content?.Headers.ContentType?.MediaType, body); _requests.Enqueue(recorded); return Respond is { } respond ? await respond(recorded, cancellationToken) : Answer(HttpStatusCode.OK, """{"ok":true,"result":{"message_id":1}}"""); } } /// The desktop shell, faked: it can notify and records the notifications. internal sealed class FakeNativeShell(bool canNotify = true) : INativeShell { private readonly ConcurrentQueue<(string Title, string Message)> _notifications = new(); public IReadOnlyList<(string Title, string Message)> Notifications => [.. _notifications]; public bool Throws { get; set; } public bool CanPickFolder => false; public bool CanShowInFolder => false; public bool CanOpenUrl => false; public bool CanNotify { get; } = canNotify; public bool SupportsAutostart => false; public Task PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult(null); public Task ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(false); public Task OpenUrlAsync(Uri address, CancellationToken ct) => Task.FromResult(false); public Task NotifyAsync(string title, string message, CancellationToken ct) { if (Throws) { throw new InvalidOperationException("notifiche spente"); } _notifications.Enqueue((title, message)); return Task.CompletedTask; } public Task GetAutostartAsync(CancellationToken ct) => Task.FromResult(false); public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask; } /// Free space by folder, as the test decides. internal sealed class FakeFreeSpaceProbe : IFreeSpaceProbe { private readonly ConcurrentDictionary _spaces = new(StringComparer.Ordinal); public const long GB = 1024L * 1024 * 1024; public void Set(string folder, long availableBytes, long totalBytes) => _spaces[folder] = new FreeSpace(availableBytes, totalBytes); public void Unmeasurable(string folder) => _spaces[folder] = null; public FreeSpace? Measure(string folder) => _spaces.TryGetValue(folder, out var space) ? space : new FreeSpace(500 * GB, 1000 * GB); } /// The log lines of the alert service. internal sealed class AlertLogRecorder { private readonly ConcurrentQueue<(AlertLogLevel Level, string Message)> _lines = new(); public IReadOnlyList<(AlertLogLevel Level, string Message)> Lines => [.. _lines]; public string All => string.Join("\n", _lines.Select(l => l.Message)); public void Write(AlertLogLevel level, string message) => _lines.Enqueue((level, message)); }