using System.Text.RegularExpressions; using Febe.Core.Abstractions; using Febe.Core.Collection.Search; using Febe.Core.Storage; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; namespace Febe.Web.Api; /// /// The profile search of the «Aggiungi account» dialog (issue #37): the window sends what Alberto types (POST, so the /// Origin check applies and the text is never in an address), then polls the view. The photos come from Febe's /// memory, never from Instagram: the page never contacts the site. /// public static partial class SearchApi { /// Closed list of the states on the wire. public static string StateName(SearchState state) => state switch { SearchState.Idle => "idle", SearchState.LocalOnly => "solo-locale", SearchState.Waiting => "attesa", SearchState.Searching => "cerca", SearchState.Ready => "pronta", SearchState.Empty => "vuota", SearchState.NoAnswer => "nessuna-risposta", SearchState.NotPossible => "non-possibile", SearchState.OutsideWindow => "fuori-fascia", SearchState.Stopped => "ferma", SearchState.Unavailable => "non-pronto", SearchState.NotConfigured => "da-configurare", SearchState.Refused => "rifiutata", _ => "errore", }; public static void Map(IEndpointRouteBuilder endpoints) { endpoints.MapPost("/api/ricerca", async (HttpContext context, IProfileSearch search, IFebeStorage storage, CancellationToken ct) => { var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ProfileSearchRequest).ConfigureAwait(false); var client = CheckClient(body.Client); if (body.Text is { Length: > SearchText.MaxRawLength }) { throw new BadRequestException($"Testo troppo lungo: al massimo {SearchText.MaxRawLength} caratteri."); } var view = search.Update(client, body.Text ?? string.Empty); return ApiHttp.Json(await DtoAsync(view, client, storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ProfileSearchDto); }); endpoints.MapGet("/api/ricerca", async (string? client, IProfileSearch search, IFebeStorage storage, CancellationToken ct) => { var id = client is null ? string.Empty : CheckClient(client); return ApiHttp.Json(await DtoAsync(search.Current, id, storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ProfileSearchDto); }); endpoints.MapPost("/api/ricerca/fine", async (HttpContext context, IProfileSearch search) => { var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ProfileSearchEndRequest).ConfigureAwait(false); search.End(CheckClient(body.Client)); return Results.NoContent(); }); endpoints.MapGet("/api/ricerca/foto/{key}", (string key, HttpContext context, IProfileSearch search) => { if (!PhotoKey().IsMatch(key) || !search.TryOpenPhoto(key, out var stream)) { throw new NotFoundException("Foto non trovata: Febe tiene le foto della ricerca solo per poco, in memoria."); } // Memory only (SearchPhotoCache): the browser of the interface keeps no copy on its disk either. context.Response.Headers.CacheControl = "no-store"; return Results.Stream(stream, "image/jpeg"); }); } /// The view for the window , with what Febe knows of each profile. public static async Task DtoAsync(SearchView view, string client, IFebeStorage storage, CancellationToken ct) { ArgumentNullException.ThrowIfNull(view); ArgumentNullException.ThrowIfNull(storage); var hits = new List(view.Hits.Count); if (view.Hits.Count > 0) { var following = await storage.Following.ListAsync(ct).ConfigureAwait(false); var followedIds = following.Where(f => f.InstagramId is not null).Select(f => f.InstagramId!).ToHashSet(StringComparer.Ordinal); var followedNames = following.Select(f => f.Username).ToHashSet(StringComparer.OrdinalIgnoreCase); foreach (var hit in view.Hits) { // By identifier first: a renamed account comes back under its new name with the same identifier. var account = await storage.Accounts.FindByInstagramIdAsync(hit.InstagramId, ct).ConfigureAwait(false) ?? await storage.Accounts.FindByUsernameAsync(hit.Username, ct).ConfigureAwait(false); var avatar = account is null ? null : await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false); var followed = followedIds.Contains(hit.InstagramId) || followedNames.Contains(hit.Username) || account?.IsFollowed == true; hits.Add(new ProfileSearchHitDto( hit.InstagramId, hit.Username, hit.DisplayName ?? account?.DisplayName, hit.IsVerified, hit.PhotoReady ? hit.PhotoKey : null, hit.PhotoReady, account?.Id, followed, account?.IsPrivate, avatar)); } } return new ProfileSearchDto( view.Version, client.Length > 0 && string.Equals(view.Owner, client, StringComparison.Ordinal), view.Text, StateName(view.State), view.Message, view.RetryAfter?.ToUnixTimeMilliseconds(), hits); } private static string CheckClient(string? client) => client is not null && ClientId().IsMatch(client) ? client : throw new BadRequestException("Finestra della ricerca sconosciuta."); [GeneratedRegex("^[0-9a-f]{16}$", RegexOptions.CultureInvariant)] private static partial Regex ClientId(); [GeneratedRegex("^[0-9a-f]{32}$", RegexOptions.CultureInvariant)] private static partial Regex PhotoKey(); } /// The search when no engine runs (a configuration problem, the tests): local suggestions only. public sealed class OfflineProfileSearch : IProfileSearch { private readonly Lock _gate = new(); private SearchView _view = SearchView.Initial; public SearchView Current { get { lock (_gate) { return _view; } } } public SearchView Update(string client, string text) { var query = SearchText.Normalize(text); lock (_gate) { _view = query.Kind switch { SearchQueryKind.Empty => SearchView.Initial with { Version = _view.Version + 1, Owner = client }, SearchQueryKind.Typable => new SearchView(_view.Version + 1, client, query.Typed, SearchState.Unavailable, "Il motore non è avviato: per ora vedi solo i profili che segui.", [], null), SearchQueryKind.Refused => new SearchView(_view.Version + 1, client, string.Empty, SearchState.Refused, "Il testo contiene un carattere che Febe non scrive mai su Instagram.", [], null), _ => new SearchView(_view.Version + 1, client, string.Empty, SearchState.LocalOnly, null, [], null), }; return _view; } } public void End(string client) { lock (_gate) { if (_view.Owner == client) { _view = SearchView.Initial with { Version = _view.Version + 1, Owner = client }; } } } public SearchHit? Known(string username) => null; public bool TryOpenPhoto(string key, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out Stream? stream) { stream = null; return false; } }