Ricerca dei profili con suggerimenti e foto (#37)
verifica / controlli (push) Successful in 20s
verifica / prove (push) Failing after 19m40s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped

«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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 16:30:03 +01:00
1 parent 5e417c666d
commit 9941a2fa1f
98 files changed
+8021 -229

No files matched your search

+67 -8
View File
@@ -1,6 +1,7 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
@@ -150,8 +151,8 @@ public static class AccountsApi
return ApiHttp.Message("Aperto nel tuo browser.");
});
endpoints.MapGet("/api/following", async (IFebeStorage storage, IClock clock, CancellationToken ct) =>
ApiHttp.Json(await FollowingAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.FollowingDto));
endpoints.MapGet("/api/following", async (IFebeStorage storage, IClock clock, IProfileSearch search, CancellationToken ct) =>
ApiHttp.Json(await FollowingAsync(storage, clock, ct, search).ConfigureAwait(false), FebeJsonContext.Default.FollowingDto));
endpoints.MapPost("/api/following/read", async (IFebeStorage storage, IEngineControl engine, IClock clock, CancellationToken ct) =>
{
@@ -165,10 +166,10 @@ public static class AccountsApi
return ApiHttp.Json(await ParseAsync(storage, body.Text, ct).ConfigureAwait(false), FebeJsonContext.Default.ParseResultDto);
});
endpoints.MapPost("/api/accounts", async (HttpContext context, IFebeStorage storage, IEngineControl engine, LibraryChanges changes, IClock clock, CancellationToken ct) =>
endpoints.MapPost("/api/accounts", async (HttpContext context, IFebeStorage storage, IEngineControl engine, LibraryChanges changes, IClock clock, IProfileSearch search, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.AddAccountsRequest).ConfigureAwait(false);
var result = await AddAsync(storage, body, clock, ct).ConfigureAwait(false);
var result = await AddAsync(storage, body, clock, ct, search).ConfigureAwait(false);
if (result.Added > 0)
{
await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false);
@@ -403,7 +404,11 @@ public static class AccountsApi
// ------------------------------------------------------------------------------------------ following and adding
public static async Task<FollowingDto> FollowingAsync(IFebeStorage storage, IClock clock, CancellationToken ct)
/// <summary>
/// The profiles of the local suggestions (issue #37): the ones Alberto follows, then the accounts in Febe he does
/// not follow, with the library avatar and the search photo when Febe has one.
/// </summary>
public static async Task<FollowingDto> FollowingAsync(IFebeStorage storage, IClock clock, CancellationToken ct, IProfileSearch? search = null)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(clock);
@@ -415,6 +420,10 @@ public static class AccountsApi
var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false);
var byName = accounts.ToDictionary(a => a.Username, StringComparer.OrdinalIgnoreCase);
var byId = accounts.Where(a => a.InstagramId is not null).ToDictionary(a => a.InstagramId!, StringComparer.Ordinal);
var avatars = await AvatarsAsync(storage, ct).ConfigureAwait(false);
var listed = new HashSet<long>();
string? Photo(string? instagramId, string username) =>
search?.Known(username) is { PhotoReady: true, PhotoKey: { } key } hit && (instagramId is null || hit.InstagramId == instagramId) ? key : null;
var list = profiles.Select(p =>
{
Account? present = null;
@@ -427,15 +436,43 @@ public static class AccountsApi
present = b;
}
return new FollowingProfileDto(p.Username, p.DisplayName, p.IsPrivate, present?.Id);
if (present is not null)
{
listed.Add(present.Id);
}
return new FollowingProfileDto(
p.Username,
p.DisplayName,
p.IsPrivate,
present?.Id,
p.InstagramId ?? present?.InstagramId,
present is not null && avatars.TryGetValue(present.Id, out var avatar) ? avatar : null,
Photo(p.InstagramId, p.Username),
Followed: true);
}).ToList();
var total = list.Count;
// Accounts in Febe that Alberto does not follow (added by name): suggestions marked «Già in Febe».
list.AddRange(accounts
.Where(a => !listed.Contains(a.Id) && !a.IsMine)
.OrderBy(a => a.Username, StringComparer.Ordinal)
.Select(a => new FollowingProfileDto(
a.Username,
a.DisplayName,
a.IsPrivate,
a.Id,
a.InstagramId,
avatars.TryGetValue(a.Id, out var avatar) ? avatar : null,
Photo(a.InstagramId, a.Username),
Followed: false)));
var profile = (await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).EffectiveProfile;
return new FollowingDto(
lastRead?.ToUnixTimeMilliseconds(),
lastRead is { } l ? ApiMapping.Day(LocalCalendar.Today(l, clock.LocalZone)) : null,
pending || !string.IsNullOrEmpty(started),
read,
list.Count,
total,
list,
profile.BackfillPostsPerAccountPerDay);
}
@@ -459,7 +496,12 @@ public static class AccountsApi
}
/// <summary>Adds accounts with one of the three starting points of spec §4.2.</summary>
public static async Task<AddAccountsDto> AddAsync(IFebeStorage storage, AddAccountsRequest request, IClock clock, CancellationToken ct)
/// <remarks>
/// A name found by the profile search (issue #37) takes its identifier and full name from the result the server
/// holds (<see cref="IProfileSearch.Known"/>), never from the page. When an account with that identifier is already
/// in Febe under another name, nothing is added and the name is reported.
/// </remarks>
public static async Task<AddAccountsDto> AddAsync(IFebeStorage storage, AddAccountsRequest request, IClock clock, CancellationToken ct, IProfileSearch? search = null)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(request);
@@ -488,6 +530,7 @@ public static class AccountsApi
var zone = clock.LocalZone;
var added = 0;
var skipped = new List<string>();
var renamed = new List<string>();
foreach (var raw in request.Usernames.Distinct(StringComparer.OrdinalIgnoreCase))
{
var username = raw.Trim().TrimStart('@').ToLowerInvariant();
@@ -529,6 +572,18 @@ public static class AccountsApi
IsPrivate = f.IsPrivate ?? false,
};
}
else if (search?.Known(username) is { } hit)
{
account = account with { InstagramId = hit.InstagramId, DisplayName = hit.DisplayName };
}
if (account.InstagramId is { } instagramId && await storage.Accounts.FindByInstagramIdAsync(instagramId, ct).ConfigureAwait(false) is not null)
{
// The same profile is already in Febe under its old name.
renamed.Add(username);
skipped.Add(username);
continue;
}
try
{
@@ -544,6 +599,10 @@ public static class AccountsApi
var message = added == 0
? "Nessun account aggiunto: erano già tutti in Febe."
: $"{ItalianText.Count(added, "account aggiunto", "account aggiunti")}." + (skipped.Count > 0 ? $" {ItalianText.Count(skipped.Count, "era già presente", "erano già presenti o non validi")}." : string.Empty);
if (renamed.Count > 0)
{
message += $" Già in Febe (con un altro nome): {string.Join(", ", renamed)}.";
}
return new AddAccountsDto(added, skipped, message);
}
+47 -1
View File
@@ -214,11 +214,57 @@ public sealed record AddAccountsRequest(IReadOnlyList<string> Usernames, string
public sealed record AddAccountsDto(int Added, IReadOnlyList<string> Skipped, string Message);
public sealed record FollowingProfileDto(string Username, string? DisplayName, bool? IsPrivate, long? AccountId);
/// <summary>A profile for the local suggestions: one Alberto follows, or an account in Febe he does not follow.</summary>
/// <param name="InstagramId">The site's identifier, when known (to merge with the results of the search).</param>
/// <param name="Avatar">Thumbnail key of the newest profile picture in the library (<c>/api/thumbnails/{key}</c>).</param>
/// <param name="Photo">Key of a photo of the search in memory (<c>/api/ricerca/foto/{key}</c>).</param>
/// <param name="Followed">True when Alberto follows the profile (from the list of followed profiles).</param>
public sealed record FollowingProfileDto(string Username, string? DisplayName, bool? IsPrivate, long? AccountId, string? InstagramId = null, string? Avatar = null, string? Photo = null, bool Followed = true);
/// <param name="BackfillPerDay">Default «Storico, massimo al giorno» of the caution profile, for the note of the dialog.</param>
public sealed record FollowingDto(long? ReadAt, string? ReadDay, bool InProgress, int ReadSoFar, int Total, IReadOnlyList<FollowingProfileDto> Profiles, int BackfillPerDay);
// ---------------------------------------------------------------- profile search (issue #37)
/// <summary>The text of the search box of the dialog. <paramref name="Client"/> is a random id of the window (16 hex).</summary>
public sealed record ProfileSearchRequest(string Client, string? Text)
{
private bool PrintMembers(System.Text.StringBuilder builder)
{
builder.Append($"TextLength = {Text?.Length ?? 0}");
return true;
}
}
/// <summary>The dialog closed.</summary>
public sealed record ProfileSearchEndRequest(string Client);
/// <summary>
/// What the search shows. <paramref name="State"/> is one of
/// <c>idle|solo-locale|attesa|cerca|pronta|vuota|nessuna-risposta|non-possibile|fuori-fascia|ferma|non-pronto|da-configurare|rifiutata|errore</c>;
/// <paramref name="Mine"/> is true when the window that asks wrote the text.
/// </summary>
public sealed record ProfileSearchDto(long Version, bool Mine, string Text, string State, string? Message, long? RetryAfter, IReadOnlyList<ProfileSearchHitDto> Hits)
{
private bool PrintMembers(System.Text.StringBuilder builder)
{
builder.Append($"Version = {Version}, State = {State}, Hits = {Hits.Count}");
return true;
}
}
/// <summary>A profile found on the site, with what Febe knows of it (account, followed, private).</summary>
/// <param name="Photo">Key of its photo in memory, once <paramref name="PhotoReady"/>.</param>
/// <param name="Avatar">Thumbnail key of the account's newest profile picture in the library, when it is in Febe.</param>
public sealed record ProfileSearchHitDto(string InstagramId, string Username, string? DisplayName, bool? IsVerified, string? Photo, bool PhotoReady, long? AccountId, bool Followed, bool? IsPrivate, string? Avatar)
{
private bool PrintMembers(System.Text.StringBuilder builder)
{
builder.Append($"PhotoReady = {PhotoReady}, InFebe = {AccountId is not null}, Followed = {Followed}");
return true;
}
}
// ---------------------------------------------------------------- engine
/// <summary>The connected account at the bottom of the sidebar.</summary>
+3
View File
@@ -38,6 +38,9 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(ParseResultDto))]
[JsonSerializable(typeof(AddAccountsRequest))]
[JsonSerializable(typeof(AddAccountsDto))]
[JsonSerializable(typeof(ProfileSearchRequest))]
[JsonSerializable(typeof(ProfileSearchEndRequest))]
[JsonSerializable(typeof(ProfileSearchDto))]
[JsonSerializable(typeof(FollowingDto))]
[JsonSerializable(typeof(EngineDto))]
[JsonSerializable(typeof(ResumeDto))]
+183
View File
@@ -0,0 +1,183 @@
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;
}
}