«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>
184 lines
7.9 KiB
C#
184 lines
7.9 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public static partial class SearchApi
|
|
{
|
|
/// <summary>Closed list of the states on the wire.</summary>
|
|
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");
|
|
});
|
|
}
|
|
|
|
/// <summary>The view for the window <paramref name="client"/>, with what Febe knows of each profile.</summary>
|
|
public static async Task<ProfileSearchDto> DtoAsync(SearchView view, string client, IFebeStorage storage, CancellationToken ct)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(view);
|
|
ArgumentNullException.ThrowIfNull(storage);
|
|
var hits = new List<ProfileSearchHitDto>(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();
|
|
}
|
|
|
|
/// <summary>The search when no engine runs (a configuration problem, the tests): local suggestions only.</summary>
|
|
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;
|
|
}
|
|
}
|