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;
}
}
+6
View File
@@ -83,6 +83,12 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
details = ["Il motore non parte finché il problema di configurazione non è risolto."];
sidebar = "Problema di configurazione";
break;
case DemoScene.UserDriving:
mode = EngineMode.UserDriving;
headline = "Stai usando il browser";
details = ["Il motore resta fermo finché non hai finito."];
sidebar = "Stai usando il browser";
break;
case DemoScene.Disconnected:
mode = EngineMode.NotConnected;
headline = "Non collegato";
+1
View File
@@ -91,6 +91,7 @@ public sealed class DemoHost : IAsyncDisposable
services.AddSingleton<DemoEngine>();
services.AddSingleton<IEngineMonitor>(sp => sp.GetRequiredService<DemoEngine>());
services.AddSingleton<IEngineControl>(sp => sp.GetRequiredService<DemoEngine>());
services.AddSingleton<Febe.Core.Collection.Search.IProfileSearch>(sp => new DemoProfileSearch(db, clock, sp.GetRequiredService<IHttpContextAccessor>()));
services.AddSingleton(sp => new DemoShell(sp.GetRequiredService<IHttpContextAccessor>(), root));
services.AddSingleton<INativeShell>(sp => sp.GetRequiredService<DemoShell>());
services.AddSingleton<IBrowserWindow>(sp => sp.GetRequiredService<DemoShell>());
+263
View File
@@ -0,0 +1,263 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Search;
using Febe.Core.Storage;
using Microsoft.AspNetCore.Http;
namespace Febe.Web.Demo;
/// <summary>
/// The profile search of the demo (issue #37): no browser, no network. The same text rules as the real search
/// (<see cref="SearchText.Normalize"/>); after a short simulated wait, up to six profiles that depend only on the text —
/// demo accounts and followed profiles whose name contains it, then a few invented ones — with drawn portraits that
/// appear a moment later. The waits are computed from the clock at each poll: nothing runs in the background, so a
/// headless screenshot always ends.
/// </summary>
public sealed class DemoProfileSearch : IProfileSearch
{
/// <summary>Simulated time Instagram takes to answer.</summary>
public static readonly TimeSpan AnswerAfter = TimeSpan.FromMilliseconds(750);
/// <summary>Simulated time of the photos after the answer.</summary>
public static readonly TimeSpan PhotosAfter = TimeSpan.FromMilliseconds(300);
/// <summary>Portraits kept (the oldest go first; a later answer draws them again).</summary>
public const int MaxPhotos = 120;
/// <summary>Profiles of the answers kept for <see cref="Known"/> (the oldest go first).</summary>
public const int MaxKnown = 400;
private static readonly string[] Suffixes = ["_foto", ".viaggi", "_official"];
private readonly Lock _gate = new();
private readonly IFebeStorage _storage;
private readonly IClock _clock;
private readonly IHttpContextAccessor? _context;
private readonly OrderedDictionary<string, byte[]> _photos = new(StringComparer.Ordinal);
private readonly OrderedDictionary<string, SearchHit> _seen = new(StringComparer.OrdinalIgnoreCase);
private Task<IReadOnlyList<Profile>>? _known;
private string _owner = string.Empty;
private SearchQuery _query = new(SearchQueryKind.Empty, string.Empty, string.Empty);
private DateTimeOffset _at;
private long _version;
public DemoProfileSearch(IFebeStorage storage, IClock clock, IHttpContextAccessor? context = null)
{
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_context = context;
}
public SearchView Current
{
get
{
lock (_gate)
{
return ViewLocked();
}
}
}
public SearchView Update(string client, string text)
{
var query = SearchText.Normalize(text);
lock (_gate)
{
_known ??= LoadAsync();
_owner = client;
if (!(query.Kind == SearchQueryKind.Typable && _query.Kind == SearchQueryKind.Typable && query.Typed == _query.Typed))
{
_query = query;
_at = _clock.Now;
_version++;
}
return ViewLocked();
}
}
public void End(string client)
{
lock (_gate)
{
if (client != _owner)
{
return;
}
_query = new SearchQuery(SearchQueryKind.Empty, string.Empty, string.Empty);
_version++;
}
}
public SearchHit? Known(string username)
{
lock (_gate)
{
// Any profile of an answer shown in this run, not only the last one: one chosen earlier keeps its identifier.
var name = username?.Trim().TrimStart('@') ?? string.Empty;
return _seen.TryGetValue(name, out var hit) ? hit : null;
}
}
public bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream)
{
lock (_gate)
{
if (_photos.TryGetValue(key, out var jpeg))
{
stream = new MemoryStream(jpeg, writable: false);
return true;
}
}
stream = null;
return false;
}
private SearchView ViewLocked()
{
var phase = 0;
SearchView Make(SearchState state, string text, string? message, IReadOnlyList<SearchHit>? hits = null) =>
new((_version * 4) + phase, _owner, text, state, message, hits ?? [], null);
switch (_query.Kind)
{
case SearchQueryKind.Empty:
return Make(SearchState.Idle, string.Empty, null);
case SearchQueryKind.Refused:
return Make(SearchState.Refused, string.Empty, "Il testo contiene un carattere che Febe non scrive mai su Instagram.");
case SearchQueryKind.SeveralNames:
return Make(SearchState.LocalOnly, string.Empty, "Più nomi insieme: Febe li aggiunge all'elenco; su Instagram cerca un nome alla volta.");
case SearchQueryKind.LocalOnly:
return Make(SearchState.LocalOnly, string.Empty, SearchText.Fold(_query.Shown.TrimStart('@')).Length < SearchText.MinTyped
? "Scrivi almeno due lettere per cercare anche su Instagram."
: "Su Instagram Febe cerca solo con lettere, numeri, punto, trattino basso e spazi: per ora vedi i profili che segui.");
}
var text = _query.Typed;
switch (_context?.HttpContext is { } http ? DemoRequest.Scene(http) : DemoScene.Normal)
{
case DemoScene.Stopped:
return Make(SearchState.Stopped, text, "Instagram ha chiesto una verifica: la ricerca è ferma finché non la completi e premi «Riprendi».");
case DemoScene.Disconnected:
return Make(SearchState.Unavailable, text, "Il browser di Febe non è collegato a Instagram: per ora vedi solo i profili che segui.");
case DemoScene.UserDriving:
return Make(SearchState.NotPossible, text, "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito.");
}
var elapsed = _clock.Now - _at;
if (elapsed < AnswerAfter || _known is not { IsCompletedSuccessfully: true } known)
{
return Make(SearchState.Searching, text, null);
}
var photos = elapsed >= AnswerAfter + PhotosAfter;
phase = photos ? 2 : 1;
var hits = Hits(text, known.Result, photos);
foreach (var hit in hits)
{
_seen.Remove(hit.Username);
_seen.Add(hit.Username, hit);
}
while (_seen.Count > MaxKnown)
{
_seen.RemoveAt(0);
}
return hits.Count == 0 ? Make(SearchState.Empty, text, "Nessun profilo trovato su Instagram.") : Make(SearchState.Ready, text, null, hits);
}
private List<SearchHit> Hits(string text, IReadOnlyList<Profile> known, bool photos)
{
var folded = SearchText.Fold(text);
var found = known
.Where(k => k.Username.Contains(folded.Replace(' ', '.'), StringComparison.Ordinal) || k.Folded.Contains(folded, StringComparison.Ordinal) || k.Username.Contains(folded.Replace(" ", string.Empty, StringComparison.Ordinal), StringComparison.Ordinal))
.OrderBy(k => k.Username.StartsWith(folded, StringComparison.Ordinal) ? 0 : 1)
.ThenBy(k => k.Username, StringComparer.Ordinal)
.Take(3)
.ToList();
var stem = folded.Replace(' ', '.');
foreach (var suffix in Suffixes)
{
if (found.Count >= 6)
{
break;
}
var name = stem + suffix;
if (name.Length <= 30 && found.All(f => f.Username != name))
{
found.Add(new Profile(Id(name), name, Title(text), string.Empty));
}
}
var hits = new List<SearchHit>(found.Count);
for (var i = 0; i < found.Count; i++)
{
var k = found[i];
string? key = null;
if (photos)
{
key = PhotoKey(k.Username);
if (_photos.Remove(key, out var jpeg))
{
// Used again: it goes to the end, the last to be dropped.
_photos.Add(key, jpeg);
}
else
{
_photos.Add(key, DemoImages.Render(DemoSubject.Portrait, Seed(k.Username), 160, 160));
while (_photos.Count > MaxPhotos)
{
_photos.RemoveAt(0);
}
}
}
hits.Add(new SearchHit(i, k.InstagramId, k.Username, k.DisplayName, k.Username.EndsWith("_official", StringComparison.Ordinal), key, key is not null));
}
return hits;
}
private async Task<IReadOnlyList<Profile>> LoadAsync()
{
var list = new List<Profile>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var account in await _storage.Accounts.ListAsync().ConfigureAwait(false))
{
if (!account.IsMine && seen.Add(account.Username))
{
list.Add(new Profile(account.InstagramId ?? Id(account.Username), account.Username, account.DisplayName, SearchText.Fold((account.DisplayName ?? string.Empty).ToLowerInvariant())));
}
}
foreach (var profile in await _storage.Following.ListAsync().ConfigureAwait(false))
{
if (seen.Add(profile.Username))
{
list.Add(new Profile(profile.InstagramId ?? Id(profile.Username), profile.Username, profile.DisplayName, SearchText.Fold((profile.DisplayName ?? string.Empty).ToLowerInvariant())));
}
}
return list;
}
private static string Title(string text) =>
CultureInfo.GetCultureInfo("it-IT").TextInfo.ToTitleCase(text.Replace('.', ' ').Replace('_', ' '));
private static string Id(string username) =>
"9" + (BitConverter.ToUInt64(SHA256.HashData(Encoding.UTF8.GetBytes("demo:" + username)), 0) % 1_000_000_000_000UL).ToString("D12", CultureInfo.InvariantCulture);
private static string PhotoKey(string username) =>
Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("demo-foto:" + username)))[..32];
private static int Seed(string username) => BitConverter.ToInt32(SHA256.HashData(Encoding.UTF8.GetBytes(username)), 0) & 0x7fffffff;
private sealed record Profile(string InstagramId, string Username, string? DisplayName, string Folded);
}
+6 -1
View File
@@ -19,6 +19,9 @@ public enum DemoScene
/// <summary>«errore»: a configuration problem (missing password): the interface shows only the problem page.</summary>
Error,
/// <summary>«alvolante»: Alberto is using Febe's browser; the engine waits and the profile search stays local (issue #37).</summary>
UserDriving,
}
/// <summary>
@@ -36,7 +39,7 @@ public static class DemoRequest
private const string SceneItem = "febe.demo.scena";
private const string EditionItem = "febe.demo.veste";
public static IReadOnlyList<string> SceneNames { get; } = ["normale", "sessione", "fermo", "scollegato", "errore"];
public static IReadOnlyList<string> SceneNames { get; } = ["normale", "sessione", "fermo", "scollegato", "errore", "alvolante"];
public static DemoScene? ParseScene(string? text) => text?.Trim().ToLowerInvariant() switch
{
@@ -45,6 +48,7 @@ public static class DemoRequest
"fermo" => DemoScene.Stopped,
"scollegato" => DemoScene.Disconnected,
"errore" => DemoScene.Error,
"alvolante" => DemoScene.UserDriving,
_ => null,
};
@@ -54,6 +58,7 @@ public static class DemoRequest
DemoScene.Stopped => "fermo",
DemoScene.Disconnected => "scollegato",
DemoScene.Error => "errore",
DemoScene.UserDriving => "alvolante",
_ => "normale",
};
+1 -1
View File
@@ -105,7 +105,7 @@ public static class SnapshotParts
/// <summary>Every category in the order of the table of spec §7.5.</summary>
public static readonly ActionKind[] All =
[ActionKind.Home, ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.SinglePost, ActionKind.FollowingListPage, ActionKind.DataDownload];
[ActionKind.Home, ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.SinglePost, ActionKind.FollowingListPage, ActionKind.ProfileSearch, ActionKind.DataDownload];
/// <summary>A minimal snapshot: no sessions, empty budgets.</summary>
public static EngineSnapshot Build(IClock clock, EngineMode mode, string headline, IReadOnlyList<string> details, string sidebar, CautionProfile profile)
+2
View File
@@ -63,6 +63,7 @@ public static class FebeWeb
services.TryAddSingleton<OfflineEngine>();
services.TryAddSingleton<IEngineMonitor>(sp => sp.GetRequiredService<OfflineEngine>());
services.TryAddSingleton<IEngineControl>(sp => sp.GetRequiredService<OfflineEngine>());
services.TryAddSingleton<Febe.Core.Collection.Search.IProfileSearch, OfflineProfileSearch>();
services.TryAddSingleton<IEngineSettingsControl>(sp => new StoredEngineSettingsControl(sp.GetRequiredService<IFebeStorage>()));
services.TryAddSingleton<IConfigurationProblems, NoConfigurationProblems>();
services.TryAddSingleton<IConnectionService, UnavailableConnectionService>();
@@ -138,6 +139,7 @@ public static class FebeWeb
SettingsApi.Map(endpoints);
ImportApi.Map(endpoints);
DuplicatesApi.Map(endpoints);
SearchApi.Map(endpoints);
RemoteViewSocket.Map(endpoints);
HealthEndpoint.Map(endpoints);
+9 -4
View File
@@ -114,7 +114,8 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
| `GET /api/entries/{id}`, `POST /api/entries/delete`, `/export`, `/{id}/open-on-instagram`, `POST /api/media/show-in-folder` | Visualizzatore, eliminazione (`remember` o `allowReturn`), CSV (`{ ids }` per la selezione, `{ query }` per il filtro della pagina: «Esporta l'elenco» nella riga degli strumenti) |
| `GET /api/accounts`, `GET /api/accounts/{id}`, `GET /{id}/history` | Elenco con conteggi, scheda, cronologia |
| `POST /api/accounts/{id}/plan`, `PUT /{id}/settings`, `POST /{id}/keep-updated`, `/pause`, `/resume`, `/check-now`, `/remove`, `/pick-folder`, `/open-on-instagram` | Impostazioni dell'account e comandi |
| `GET /api/following`, `POST /api/following/read`, `POST /api/accounts/parse`, `POST /api/accounts` | Dialogo «Aggiungi account» |
| `GET /api/following`, `POST /api/following/read`, `POST /api/accounts/parse`, `POST /api/accounts` | Dialogo «Aggiungi account»: `/api/following` dà anche gli account in Febe non seguiti (`followed: false`) per i suggerimenti locali, con `instagramId`, `avatar` e `photo` |
| `POST /api/ricerca` (`{ client, text }`), `GET /api/ricerca?client=`, `POST /api/ricerca/fine`, `GET /api/ricerca/foto/{chiave}` | Ricerca dei profili mentre si scrive (#37, `Api/SearchApi.cs`): `client` di 16 cifre esadecimali, testo al più 60 caratteri, Origin dell'interfaccia; la finestra chiede lo stato ogni 400 ms (poi ogni 2 s) finché Febe cerca o mancano foto. Stati: `idle`, `solo-locale`, `attesa`, `cerca`, `pronta`, `vuota`, `nessuna-risposta`, `non-possibile`, `fuori-fascia`, `ferma`, `non-pronto`, `da-configurare`, `rifiutata`, `errore`. Le foto (JPEG 160 px) stanno solo in memoria |
| `GET /accesso`, `POST /api/accesso`, `POST /api/uscita` | Accesso con password |
| `GET /api/connection`, `POST /api/connection/begin` (`{ openLogin }`), `/finish`, `/cancel`, `/disconnect` | Collegamento a Instagram (`IConnectionService`, §6.4): stato `notConnected`, `connected`, `verificationRequired`, `browserUnavailable` |
| `GET /api/engine/incidents` | Incidenti degli ultimi 14 giorni (rallentamenti, verifiche, arresti), con un consiglio dopo 3 rallentamenti in 7 giorni |
@@ -228,13 +229,16 @@ virtualizzazione, selezione, nuovi elementi in cima senza spostare la vista), `p
cartella temporanea con dati e libreria finti (38 account, circa 18.000 elementi), cancellata alla chiusura. Non
scrive mai nella libreria vera e non usa la rete.
- Scene del motore: `?scena=normale|sessione|fermo|scollegato|errore` (`errore`: password mancante, pagina di errore
di configurazione); tema: `?tema=chiaro|scuro`; veste: `?veste=desktop|windows|docker`.
- Scene del motore: `?scena=normale|sessione|fermo|scollegato|errore|alvolante` (`errore`: password mancante, pagina
di errore di configurazione; `alvolante`: Alberto usa il browser, la ricerca dei profili resta locale); tema: `?tema=chiaro|scuro`; veste: `?veste=desktop|windows|docker`.
- Indirizzi diretti: `/account?dialogo=aggiungi`, `/account/3/impostazioni`, `/account/2?tipo=storie`,
`/importa?passo=3` (revisione di un'importazione già analizzata), `/doppioni`, `/impostazioni/collegamento?scena=scollegato&veste=docker`.
- Seconda parte (`Demo/DemoPart2.cs`, `Demo/DemoImport.cs`, `Demo/DemoDiagnostics.cs`): collegamento, anteprima del
browser, incidenti e rapporto di diagnostica secondo la scena; tre doppioni dopo uno scaricamento; una sorgente da importare generata in `importa/Backup del vecchio disco`
(copie identiche, varianti, cartelle senza account, file non riconosciuti) e già analizzata all'avvio.
- Ricerca dei profili (`Demo/DemoProfileSearch.cs`): nessun browser; dopo 750 ms profili dimostrativi il cui nome
contiene il testo e qualche nome inventato, con foto disegnate 300 ms dopo. Con `fermo`, `scollegato` e `alvolante`
risponde `ferma`, `non-pronto` e `non-possibile`.
- I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i
conti tornino.
@@ -250,5 +254,6 @@ rimaste dai mockup sono in `docs/schermate/differenze.md`.
`tests/Febe.Tests/Web/` avvia Kestrel vero su una porta libera di 127.0.0.1 (`Support/WebTestServer.cs`), con
archivio e libreria temporanei e orologio manuale; `DemoTests` avvia una dimostrazione intera una volta per classe.
Le prove della seconda parte (`ConnectionApiTests`, `SettingsApiTests`, `ActivityApiTests`, `ImportApiTests`,
`DemoPart2Tests`) usano gli aiuti di `Part2Support/`.
`DemoPart2Tests`) usano gli aiuti di `Part2Support/`. `InterfaceTests` e `ProfileSearchInterfaceTests` guidano
l'interfaccia in un Chromium senza finestra (solo Linux; su Windows risultano «Inconclusive»).
`dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Web"`.
+10 -8
View File
@@ -2,16 +2,18 @@ using System.Text.RegularExpressions;
namespace Febe.Web.Library;
/// <summary>A user name read from a line of the «Per nome utente» text area.</summary>
/// <summary>A user name read from the names pasted in «Aggiungi account»; <paramref name="Line"/> is its place (from 1).</summary>
public sealed record ParsedUsername(int Line, string Username);
/// <summary>A line that is not a user name, with the reason in Italian.</summary>
/// <summary>A pasted name that is not a user name, with its place and the reason in Italian.</summary>
public sealed record UsernameProblem(int Line, string Text, string Reason);
/// <summary>
/// «Per nome utente» (spec §4.2, mockup 04): one user name or profile address per line. Accepts «marta.demo»,
/// «@marta.demo», «instagram.com/marta.demo», «https://www.instagram.com/marta.demo/?hl=it». Refuses addresses of
/// posts, reels and other pages, and names Instagram would not accept. Names are compared and stored in lowercase.
/// The names pasted or chosen in «Aggiungi account» (spec §4.2, mockup 04, issue #37): the window sends one name per
/// line (it splits what Alberto pasted at line breaks, commas and semicolons). Accepts «marta.demo», «@marta.demo»,
/// «instagram.com/marta.demo», «https://www.instagram.com/marta.demo/?hl=it». Refuses addresses of posts, reels and
/// other pages, and names Instagram would not accept. Names are compared and stored in lowercase. The reasons speak
/// of «names», not lines: the window shows each as «n° nome».
/// </summary>
public static partial class UsernameParser
{
@@ -43,7 +45,7 @@ public static partial class UsernameParser
if (line.Length > 300)
{
problems.Add(new UsernameProblem(number, line[..60] + "…", "Riga troppo lunga per essere un nome utente."));
problems.Add(new UsernameProblem(number, line[..60] + "…", "Troppo lungo per essere un nome utente."));
continue;
}
@@ -56,7 +58,7 @@ public static partial class UsernameParser
if (seen.TryGetValue(candidate, out var first))
{
problems.Add(new UsernameProblem(number, line, $"Già scritto alla riga {first}."));
problems.Add(new UsernameProblem(number, line, $"Già scritto: è uguale al {first}° nome."));
continue;
}
@@ -104,7 +106,7 @@ public static partial class UsernameParser
text = text.Trim().TrimStart('@').ToLowerInvariant();
if (text.Contains(' ', StringComparison.Ordinal))
{
return (null, "Un nome utente non contiene spazi: uno per riga.");
return (null, "Un nome utente non contiene spazi: per cercare un nome e cognome scrivilo da solo nella casella.");
}
return IsValid(text)
+41 -6
View File
@@ -561,12 +561,39 @@ a.stato:hover{border-color:var(--bordo-forte)}
/* dialogo «Aggiungi account» */
.aggiungi{width:min(900px,calc(100vw - 32px));height:min(660px,calc(100vh - 32px))}
.aggiungi .linguette{padding:0 22px;margin-top:6px}
.aggiungi .corpo-dialogo{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr) 316px}
.aggiungi .sinistra{display:flex;flex-direction:column;min-height:0;padding:14px 18px 0 22px;border-right:1px solid var(--bordo)}
.aggiungi .corpo-dialogo{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr) 316px;border-top:1px solid var(--bordo)}
.aggiungi .sinistra{display:flex;flex-direction:column;min-height:0;padding:16px 18px 0 22px;border-right:1px solid var(--bordo)}
.aggiungi .destra-dialogo{padding:16px 18px;overflow:auto;background:var(--superficie)}
.aggiungi .cerca-riga{display:flex;gap:10px;margin-bottom:6px}
.aggiungi .cerca-riga .campo{flex:1}
/* ricerca unica con i suggerimenti mentre si scrive (#37) */
.aggiungi .cerca-zona{position:relative;flex:none;margin-bottom:12px}
.aggiungi .cerca-zona .campo{height:40px}
.aggiungi .suggerimenti{position:absolute;left:0;right:0;top:calc(100% + 4px);z-index:5;max-height:min(420px,60vh);overflow:auto;background:var(--superficie);border:1px solid var(--bordo);border-radius:var(--r-pannello);box-shadow:var(--ombra-menu);padding:4px 6px 6px}
.aggiungi .suggerimenti[hidden]{display:none}
.aggiungi .sezione-titolo{display:flex;gap:6px;align-items:baseline;padding:9px 8px 5px;font-size:12px;font-weight:600;color:var(--testo-3)}
.aggiungi .sezione-titolo .per{font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
.aggiungi .stato-remoto{display:flex;gap:8px;align-items:flex-start;padding:4px 8px 8px;font-size:12.5px;line-height:1.4;color:var(--testo-2)}
.aggiungi .stato-remoto .ic{flex:none;margin-top:1px}
.aggiungi .stato-remoto.allarme{color:var(--ambra)}
.aggiungi .opzione{display:flex;align-items:center;gap:12px;padding:6px 8px;border-radius:6px;cursor:pointer;min-height:52px}
.aggiungi .opzione:hover{background:var(--rialzo)}
.aggiungi .opzione[aria-selected=true]{background:var(--accento-tinta)}
.aggiungi .opzione.presente{cursor:default}
.aggiungi .opzione.presente .chi-nome,.aggiungi .opzione.presente .av{opacity:.6}
.aggiungi .opzione .chi-nome,.aggiungi .voce.scelto .chi-nome{flex:1;min-width:0}
.aggiungi .opzione b,.aggiungi .voce.scelto b{display:block;font-weight:600;font-size:13.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.aggiungi .opzione small,.aggiungi .voce.scelto small{display:block;color:var(--testo-2);font-size:12.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.aggiungi .opzione .verificato{display:inline-flex;vertical-align:-2px;margin-left:4px;color:var(--accento)}
.aggiungi .etichette{display:flex;gap:6px;flex:none}
.aggiungi .opzione .btn{flex:none;min-width:96px;justify-content:center}
.aggiungi .opzione .btn.scelto{background:var(--accento-tinta);border-color:var(--accento-bordo);color:var(--accento-scuro)}
.aggiungi .opzione.azione .av{color:var(--testo-2)}
.aggiungi .scelti-testa{display:flex;align-items:center;gap:10px;flex:none;padding:2px 0 6px;border-bottom:1px solid var(--bordo)}
.aggiungi .scelti-testa h3{margin:0;font-size:13.5px;font-weight:650;display:flex;gap:7px;align-items:baseline}
.aggiungi .scelti-testa h3 i{font-style:normal;font-size:12px;color:var(--testo-3);font-weight:500}
.aggiungi .scelti-testa > .btn.collegamento{margin-left:auto;font-size:13px}
.aggiungi .vuoto-scelti{display:flex;gap:10px;align-items:flex-start;padding:16px 2px;color:var(--testo-2);font-size:13px;line-height:1.45}
.aggiungi .vuoto-scelti .ic{flex:none;margin-top:2px}
.aggiungi .elenco .voce.scelto{cursor:default}
.aggiungi .elenco{flex:1;overflow:auto;margin:0 -18px 0 -4px;padding:0 18px 0 4px}
.aggiungi .elenco .voce{padding:9px 2px;border-bottom:1px solid var(--bordo);gap:12px}
.aggiungi .elenco .voce.presente{opacity:.5}
@@ -582,6 +609,7 @@ a.stato:hover{border-color:var(--bordo-forte)}
.aggiungi .partenza .tondo{margin-top:2px}
.aggiungi .problemi{margin-top:10px;font-size:12.5px;color:var(--rosso);display:flex;flex-direction:column;gap:3px}
.aggiungi .riconosciuti{margin-top:10px;font-size:12.5px;color:var(--testo-2)}
.aggiungi .riconosciuti:empty,.aggiungi .problemi:empty{display:none}
/* ==========================================================================
Parte 2 dell'interfaccia: Attività, Impostazioni, Collegamento, Browser,
@@ -970,8 +998,15 @@ input[type=range].cursore.lungo::-webkit-slider-thumb{border-color:var(--accento
.tabella-account .tab td.menu-riga{position:absolute;right:4px;top:12px;width:auto}
.tabella-account .nome .sotto{flex-wrap:wrap;white-space:normal}
.tipi{grid-template-columns:1fr 1fr}
.aggiungi .corpo-dialogo{grid-template-columns:1fr;overflow:auto}
.aggiungi .corpo-dialogo{grid-template-columns:minmax(0,1fr);overflow:auto}
.aggiungi footer{flex-wrap:wrap;row-gap:10px}
.aggiungi footer .destra{margin-left:auto}
.aggiungi .sinistra{border-right:0;min-height:320px}
.aggiungi .opzione{flex-wrap:wrap;row-gap:4px}
.aggiungi .opzione .chi-nome{flex:1 1 0}
.aggiungi .opzione .btn{min-width:0}
.aggiungi .opzione .etichette{order:3;flex-basis:100%;padding-left:52px;flex-wrap:wrap}
.aggiungi .opzione .etichette:empty{display:none}
.salva{padding:10px 16px;flex-wrap:wrap}
.brevi{bottom:72px}
}
+13 -1
View File
@@ -31,6 +31,8 @@ const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:n
/**
* Opens a modal dialog over the whole window. build(close) returns { header?, body, footer? } or a node; close(value)
* resolves the returned promise. Esc and the veil close with undefined. Focus is trapped and restored.
* build may also return onEscape (called first on Esc: returning true means the dialog handled it, say by closing a
* list of suggestions, and stays open) and onClose (called once, however the dialog closes).
*/
export function dialog({ title, className = '', build, labelledBy, dismissable = true }) {
return new Promise((resolve) => {
@@ -42,6 +44,13 @@ export function dialog({ title, className = '', build, labelledBy, dismissable =
closed = true;
veil.remove();
document.removeEventListener('keydown', onKey, true);
if (parts && typeof parts.onClose === 'function') {
try {
parts.onClose();
} catch (error) {
console.error(error);
}
}
if (opener && opener.focus && document.contains(opener)) opener.focus();
resolve(value);
};
@@ -61,7 +70,10 @@ export function dialog({ title, className = '', build, labelledBy, dismissable =
if (e.target === veil && dismissable) close(undefined);
});
const onKey = (e) => {
if (e.key === 'Escape' && dismissable) {
if (e.key === 'Escape' && parts && typeof parts.onEscape === 'function' && parts.onEscape()) {
e.stopPropagation();
e.preventDefault();
} else if (e.key === 'Escape' && dismissable) {
e.stopPropagation();
close(undefined);
} else if (e.key === 'Tab') {
+707 -101
View File
@@ -1,11 +1,16 @@
// «Aggiungi account» (mockup 04, spec §4.2): from the local copy of the list of followed profiles (with its reading
// date and progress; it is read again only on request) or by user name, one per line; the three starting points on
// the right; the button says how many accounts it adds.
// «Aggiungi account» (mockup 04, spec §4.2, issue #37): one search box. While Alberto types, the list under it shows
// at once the profiles he follows and the accounts already in Febe, then the profiles Instagram finds, with their
// photo, user name, full name and the labels «Seguito», «Privato», «Già in Febe». Febe's browser searches on the site
// and fetches the photos (the page asks only Febe: /api/ricerca, /api/ricerca/foto, /api/thumbnails). Several names or
// profile addresses can be pasted in the same box. The chosen profiles go to «Da aggiungere»; the three starting
// points stay on the right; the button says how many accounts it adds. «Scegli fra tutti i profili che segui» opens
// the whole list of followed profiles with check boxes.
import { api } from '../core/api.js';
import { h, icon, fill, later } from '../core/dom.js';
import { h, icon, fill, later, uid } from '../core/dom.js';
import { t, number, shortDay } from '../core/text.js';
import { caps } from '../core/context.js';
import { engineState, onEngine } from '../core/engine.js';
import { avatar, checkbox, dialog, label, showError, toast } from '../core/ui.js';
const STARTS = ['everything', 'newOnly', 'storiesOnly'];
@@ -17,6 +22,31 @@ const DEPTHS = [
{ key: 'year', depth: 'fromDate' },
];
/** Local suggestions shown at most. */
const MAX_LOCAL = 8;
/** Pause after the last key before the text goes to Febe (the local suggestions do not wait). */
const DEBOUNCE_MS = 150;
/** Asking for the results: often at first, then less. Never stops while Febe is still searching. */
const FAST_POLL_MS = 400;
const SLOW_POLL_MS = 2000;
const FAST_FOR_MS = 10000;
/** How long to keep asking only for photos still on their way. */
const PHOTOS_FOR_MS = 60000;
/** Longest text the server accepts (SearchText.MaxRawLength). */
const MAX_TEXT = 60;
/** States of the search while Febe still works on the text. */
const WORKING = ['attesa', 'cerca'];
/**
* States the search leaves by itself (Alberto lets go of the browser, the pause or the stop ends, the active window
* opens, the cap frees up): the window keeps asking, slowly, and at once when the engine changes.
*/
const RESUMING = ['non-possibile', 'fuori-fascia', 'ferma'];
/**
* First path segments of instagram.com that are pages, not profiles (UsernameParser.ReservedPaths, SearchText): an
* address of a post, a reel or a story is never taken for the account «p», «reel» or «stories».
*/
const RESERVED_PATHS = new Set(['p', 'reel', 'reels', 'tv', 'stories', 'explore', 'accounts', 'direct', 'about', 'legal', 'developer', 'web', 'challenge', 'emails', 'session']);
/** Opens the dialog; resolves to true when accounts were added. */
export function openAddAccounts() {
return dialog({
@@ -26,75 +56,594 @@ export function openAddAccounts() {
});
}
/** Lowercase text without accents (the server folds the same way, SearchText.Fold). */
export function fold(text) {
return String(text || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
}
/** True for an instagram.com address of a post, a reel, a story or another page that is not a profile. */
export function isPageAddress(raw) {
const address = /instagram\.com\/([^/?#\s]+)/i.exec(String(raw || ''));
return Boolean(address && RESERVED_PATHS.has(address[1].toLowerCase()));
}
/**
* What the box asks for: a profile address becomes its user name, a leading @ goes, single spaces. The address of a
* post or another page gives nothing: it is not a profile.
*/
export function searchTerm(raw) {
let text = String(raw || '').trim();
const address = /instagram\.com\/([^/?#\s]+)/i.exec(text);
if (address) {
if (RESERVED_PATHS.has(address[1].toLowerCase())) return '';
text = address[1];
}
return fold(text.replace(/^@/, '')).replace(/\s+/g, ' ').trim();
}
/** True for a text holding several names: a line break, a comma, a semicolon or more than one profile address. */
export function isSeveralNames(raw) {
const text = String(raw || '');
return /[\r\n,;]/.test(text) || (text.match(/instagram\.com\//gi) || []).length > 1;
}
/** One name per line, for /api/accounts/parse (which reads one per line). */
export function namesPerLine(raw) {
return String(raw || '')
.split(/[\r\n,;]+/)
.flatMap((part) => ((part.match(/instagram\.com\//gi) || []).length > 1 ? part.trim().split(/\s+/) : [part]))
.map((part) => part.trim())
.filter(Boolean)
.join('\n');
}
/** A user name Instagram accepts (UsernameParser.IsValid). */
function validName(name) {
return /^[a-z0-9._]{1,30}$/.test(name) && !name.startsWith('.') && !name.endsWith('.') && !name.includes('..');
}
/** A text Febe would type on the site (SearchText: letters, digits, «.», «_» and spaces, 2 to 40). */
function likelyTypable(term) {
return term.length >= 2 && term.length <= 40 && /^[a-z0-9._]+( [a-z0-9._]+)*$/.test(term);
}
function randomClient() {
const bytes = new Uint8Array(8);
crypto.getRandomValues(bytes);
return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
}
function photoOf(avatarKey, searchKey) {
if (avatarKey) return `/api/thumbnails/${avatarKey}`;
if (searchKey) return `/api/ricerca/foto/${searchKey}`;
return null;
}
function build(close) {
let tab = 'seguiti';
const client = randomClient();
const listId = uid('suggerimenti');
const aborter = new AbortController();
let closed = false;
let following = null;
let parsed = { names: [], problems: [] };
const chosen = new Set();
let byName = new Map();
let byId = new Map();
let view = 'scelti';
let open = false;
let options = [];
let active = -1;
let remote = null;
let lastVersion = -1;
let awaiting = false;
let pollTimer = 0;
let pollFrom = 0;
let photosFrom = 0;
let start = 'everything';
let depth = 'all';
let parsedNote = null;
/** username → { username, displayName, photo, followed, isPrivate } */
const chosen = new Map();
/** One avatar node per place, name and photo, moved from one drawing to the next so a photo never flickers. */
const faces = new Map();
const tabFollowed = h('button', { type: 'button', role: 'tab', class: 'qui', 'aria-selected': 'true' }, t('aggiungi.seguiti'), h('i'));
const tabNames = h('button', { type: 'button', role: 'tab', 'aria-selected': 'false' }, t('aggiungi.perNome'));
const tabs = h('div.linguette', { role: 'tablist' }, tabFollowed, tabNames);
const left = h('div.sinistra', { role: 'tabpanel' });
const right = h('div.destra-dialogo');
const footerLeft = h('div', { style: { display: 'flex', alignItems: 'center', gap: '12px', fontSize: '13px', color: 'var(--testo-2)' } });
const addButton = h('button.btn.primo', { type: 'button', disabled: true, onclick: submit });
// ---------------------------------------------------------------------------- left: followed profiles
const search = h('input', { type: 'search', placeholder: t('aggiungi.cerca'), 'aria-label': t('aggiungi.cerca') });
const allButton = h('button.btn', { type: 'button' }, t('aggiungi.selezionaTutti'));
const list = h('div.elenco', { role: 'group', 'aria-label': t('aggiungi.seguiti') });
const progress = h('div.avanzamento', { role: 'status' });
const followedPanel = h('div', { style: { display: 'contents' } }, h('div.cerca-riga', h('label.campo', icon('search'), search), allButton), list, progress);
// ---------------------------------------------------------------------------- left: the box and its list
const box = h('input', {
type: 'search', autocomplete: 'off', spellcheck: 'false', autocapitalize: 'off', maxlength: String(MAX_TEXT),
placeholder: t('aggiungi.cerca'), 'aria-label': t('aggiungi.cercaEtichetta'),
role: 'combobox', 'aria-expanded': 'false', 'aria-controls': listId, 'aria-autocomplete': 'list',
});
const suggestions = h('div.suggerimenti', { id: listId, role: 'listbox', 'aria-label': t('aggiungi.suggerimenti'), hidden: true });
const announce = h('div.vh', { role: 'status', 'aria-live': 'polite' });
const searchZone = h('div.cerca-zona', h('label.campo', icon('search'), box), suggestions, announce);
// ---------------------------------------------------------------------------- left: by user name
const area = h('textarea', { rows: '8', spellcheck: 'false', autocapitalize: 'off', 'aria-describedby': 'aiuto-nomi', placeholder: 'marta.demo\n@luca.viaggi.demo\ninstagram.com/studio.lumen.demo' });
const chosenTitle = h('h3');
const toFollowed = h('button.btn.collegamento', { type: 'button', onclick: () => setView(view === 'scelti' ? 'seguiti' : 'scelti') });
const chosenList = h('div.elenco.scelti', { role: 'list', 'aria-label': t('aggiungi.daAggiungere') });
const parsedInfo = h('div.riconosciuti', { role: 'status' });
const problems = h('div.problemi');
const namesPanel = h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px', paddingBottom: '14px', overflow: 'auto' } },
h('label.etichetta', t('aggiungi.area')),
h('label.campo.area', area),
h('p.aiuto', { id: 'aiuto-nomi' }, t('aggiungi.areaAiuto')),
parsedInfo, problems);
const allButton = h('button.btn.piccolo', { type: 'button' }, t('aggiungi.selezionaTutti'));
const followedList = h('div.elenco', { role: 'group', 'aria-label': t('aggiungi.seguiti') });
const progress = h('div.avanzamento', { role: 'status' });
const left = h('div.sinistra');
// ---------------------------------------------------------------------------- what Febe knows locally
function present(p) {
return p.accountId != null;
}
function drawList() {
if (!following) {
fill(list, h('div.caricamento', t('comune.caricamento')));
return;
function known(username, instagramId) {
return (instagramId && byId.get(instagramId)) || byName.get(username) || null;
}
/** Followed profiles and accounts in Febe whose name or full name holds the text: prefix first, then alphabetical. */
function localMatches(term) {
if (!following || !term) return [];
const dotted = term.replace(/ /g, '.');
const joined = term.replace(/ /g, '');
const found = [];
for (const p of following.profiles) {
const name = p.username;
const full = fold(p.displayName);
let rank = -1;
if (name.startsWith(term) || name.startsWith(dotted) || name.startsWith(joined)) rank = 0;
else if (full.startsWith(term) || full.split(/\s+/).some((w) => w.startsWith(term))) rank = 1;
else if (name.includes(term) || name.includes(dotted) || name.includes(joined) || full.includes(term)) rank = 2;
if (rank >= 0) found.push([rank, p]);
}
const term = search.value.trim().toLowerCase().replace(/^@/, '');
const shown = following.profiles.filter((p) => !term || p.username.includes(term) || (p.displayName || '').toLowerCase().includes(term));
if (!shown.length) {
fill(list, h('div.caricamento', following.profiles.length ? t('aggiungi.nessunSeguito') : t('aggiungi.maiLetto')));
return;
}
fill(list, shown.map((p) => {
const isPresent = present(p);
const box = checkbox({
checked: isPresent || chosen.has(p.username),
disabled: isPresent,
labelNode: h('span', { style: { display: 'contents' } },
avatar(p.username, 'm'),
h('span.chi-nome', h('b', `@${p.username}`), p.displayName ? h('small', p.displayName) : null),
isPresent ? label(t('aggiungi.giaPresente')) : p.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null),
onchange: (on) => {
if (on) chosen.add(p.username);
else chosen.delete(p.username);
drawRight();
},
});
box.classList.toggle('presente', isPresent);
return box;
found.sort((a, b) => a[0] - b[0] || a[1].username.localeCompare(b[1].username));
return found.slice(0, MAX_LOCAL).map(([, p]) => ({
username: p.username,
displayName: p.displayName,
followed: p.followed !== false,
isPrivate: p.isPrivate,
accountId: p.accountId,
instagramId: p.instagramId,
isVerified: null,
photo: photoOf(p.avatar, p.photo),
}));
}
/** The profiles of Instagram's answer that are not already among the local ones; the local ones take their photo. */
function mergeRemote(local, term) {
if (!remote || !remote.mine) return [];
const current = !awaiting || remote.text === term;
const extra = [];
for (const hit of remote.hits) {
// While a newer text is on its way, the older answer stays only where it still fits what is written.
if (!current && !(hit.username.includes(term.replace(/ /g, '.')) || hit.username.includes(term.replace(/ /g, '')) || fold(hit.displayName).includes(term))) continue;
const photo = photoOf(hit.avatar, hit.photoReady ? hit.photo : null);
const same = local.find((r) => (r.instagramId && r.instagramId === hit.instagramId) || r.username === hit.username);
if (same) {
same.photo = same.photo || photo;
same.displayName = same.displayName || hit.displayName;
same.isVerified = hit.isVerified;
continue;
}
const f = known(hit.username, hit.instagramId);
extra.push({
username: hit.username,
displayName: hit.displayName || (f && f.displayName),
followed: hit.followed || Boolean(f && f.followed !== false),
isPrivate: hit.isPrivate != null ? hit.isPrivate : f ? f.isPrivate : null,
accountId: hit.accountId != null ? hit.accountId : f ? f.accountId : null,
instagramId: hit.instagramId,
isVerified: hit.isVerified,
photo: photo || (f ? photoOf(f.avatar, f.photo) : null),
});
}
return extra;
}
// ---------------------------------------------------------------------------- the list under the box
function face(where, username, photo) {
const key = `${where}|${username}|${photo || ''}`;
let node = faces.get(key);
if (node) return node;
node = avatar(username, 'm');
if (photo) {
// The initials stay until the photo has arrived from Febe.
const img = h('img', { src: photo, alt: '', decoding: 'async' });
img.addEventListener('load', () => {
node.textContent = '';
node.append(img);
node.classList.add('con-foto');
}, { once: true });
}
faces.set(key, node);
return node;
}
function labelsOf(r) {
return h('span.etichette',
r.followed ? label(t('aggiungi.seguito'), '', 'user-check') : null,
r.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null,
present(r) ? label(t('aggiungi.giaPresente')) : null);
}
function optionRow(r, index) {
const isPresent = present(r);
const isChosen = chosen.has(r.username);
// The option itself says whether the profile is in «Da aggiungere» (aria-checked; aria-selected is the keyboard
// cursor): the children of an option are presentational, so the button below is only for the mouse.
const row = h(`div.opzione${isPresent ? '.presente' : ''}`, {
id: `${listId}-${index}`, role: 'option', 'aria-selected': String(index === active),
'aria-checked': isPresent ? null : String(isChosen),
'aria-disabled': isPresent ? 'true' : null,
onmousedown: (e) => e.preventDefault(),
onclick: () => activate(index),
},
face('lista', r.username, r.photo),
h('span.chi-nome',
h('b', `@${r.username}`, r.isVerified ? h('span.verificato', { title: t('aggiungi.verificato'), 'aria-label': t('aggiungi.verificato') }, icon('circle-check', 's')) : null),
r.displayName ? h('small', r.displayName) : null),
labelsOf(r),
isPresent ? null : h(`button.btn.piccolo${isChosen ? '.scelto' : ''}`, {
type: 'button', tabindex: '-1', 'aria-hidden': 'true',
onmousedown: (e) => e.preventDefault(),
onclick: (e) => {
e.stopPropagation();
activate(index);
},
}, isChosen ? [icon('check', 's'), t('aggiungi.aggiunto')] : [icon('plus', 's'), t('aggiungi.aggiungiUno')]));
return row;
}
function actionRow(o, index) {
return h('div.opzione.azione', {
id: `${listId}-${index}`, role: 'option', 'aria-selected': String(index === active),
onmousedown: (e) => e.preventDefault(),
onclick: () => activate(index),
},
h('span.av.m.segnaposto', { 'aria-hidden': 'true' }, icon(o.action === 'nomi' ? 'users' : 'at-sign')),
h('span.chi-nome', h('b', o.title), h('small', o.note)));
}
/** The status line of the Instagram part: searching, waiting for the page, or why Instagram is not searched. */
function remoteStatus(term, extraCount) {
const driving = (engineState() && engineState().snapshot && engineState().snapshot.mode) === 'UserDriving';
if (awaiting) {
if (!likelyTypable(term)) return null;
return driving ? { text: t('aggiungi.alVolante'), kind: 'info' } : { text: t('aggiungi.cercoSuInstagram'), kind: 'lavoro' };
}
if (!remote) return null;
if (!remote.mine) return { text: t('aggiungi.altraFinestra'), kind: 'info' };
switch (remote.state) {
case 'idle':
return null;
case 'cerca':
return { text: t('aggiungi.cercoSuInstagram'), kind: 'lavoro' };
case 'attesa':
return { text: remote.message || t('aggiungi.attesa'), kind: 'lavoro' };
case 'pronta':
return extraCount ? null : { text: t('aggiungi.nessunAltro'), kind: 'info' };
case 'non-possibile':
return { text: remote.message || t('aggiungi.alVolante'), kind: 'info' };
case 'ferma':
case 'errore':
case 'rifiutata':
return { text: remote.message || t('comune.errore'), kind: 'allarme' };
default:
return remote.message ? { text: remote.message, kind: 'info' } : null;
}
}
function drawSuggestions() {
const term = searchTerm(box.value);
const several = isSeveralNames(box.value);
const pageAddress = !several && isPageAddress(box.value);
const keep = active >= 0 && options[active] ? options[active].username || options[active].action : null;
options = [];
const parts = [];
if (!several && term) {
const local = localMatches(term);
const extra = mergeRemote(local, term);
if (local.length) {
const titleId = `${listId}-locali`;
parts.push(h('div', { role: 'group', 'aria-labelledby': titleId },
h('div.sezione-titolo', { id: titleId, 'aria-hidden': 'true' }, t('aggiungi.traSeguiti')),
local.map((r) => {
options.push(r);
return optionRow(r, options.length - 1);
})));
}
const status = remoteStatus(term, extra.length);
if (extra.length || status) {
const titleId = `${listId}-instagram`;
const shown = remote && remote.mine && remote.text ? remote.text : term;
parts.push(h('div', { role: 'group', 'aria-labelledby': titleId },
h('div.sezione-titolo', { id: titleId, 'aria-hidden': 'true' }, t('aggiungi.daInstagram'), h('span.per', t('aggiungi.perTesto', { testo: shown }))),
// The status is read out by the live region (announce): inside the list it is only seen.
status ? h(`div.stato-remoto.${status.kind}`, { 'aria-hidden': 'true' }, icon(status.kind === 'lavoro' ? 'hourglass' : status.kind === 'allarme' ? 'triangle-alert' : 'info', 's'), h('span', status.text)) : null,
extra.map((r) => {
options.push(r);
return optionRow(r, options.length - 1);
})));
}
if (validName(term) && !options.some((r) => r.username === term)) {
options.push({ action: 'nome', name: term, title: t('aggiungi.perNomeUtente', { nome: term }), note: t('aggiungi.perNomeSpiega') });
parts.push(actionRow(options[options.length - 1], options.length - 1));
}
if (!local.length && following && following.profiles.length && !extra.length) {
// Seen, not an option: hidden from the list's structure (the live region says how many were found).
parts.unshift(h('div', { 'aria-hidden': 'true' },
h('div.sezione-titolo', t('aggiungi.traSeguiti')),
h('div.stato-remoto.info', icon('info', 's'), h('span', t('aggiungi.nessunLocale')))));
}
announce.textContent = status ? status.text : t('aggiungi.trovati', { n: options.filter((o) => !o.action).length });
} else if (pageAddress) {
parts.push(h('div', { 'aria-hidden': 'true' }, h('div.stato-remoto.info', icon('info', 's'), h('span', t('aggiungi.nonProfilo')))));
announce.textContent = t('aggiungi.nonProfilo');
} else if (several) {
options.push({ action: 'nomi', title: t('aggiungi.piuNomi'), note: t('aggiungi.piuNomiSpiega') });
parts.push(actionRow(options[0], 0));
announce.textContent = t('aggiungi.piuNomi');
}
active = keep ? options.findIndex((o) => (o.username || o.action) === keep) : -1;
fill(suggestions, parts);
setOpen(view === 'scelti' && document.activeElement === box && options.length + parts.length > 0);
markActive();
}
function setOpen(value) {
open = value;
suggestions.hidden = !value;
box.setAttribute('aria-expanded', String(value));
if (!value) {
active = -1;
box.removeAttribute('aria-activedescendant');
}
}
function markActive() {
const rows = [...suggestions.querySelectorAll('[role=option]')];
rows.forEach((row, i) => row.setAttribute('aria-selected', String(i === active)));
if (active >= 0 && rows[active]) {
box.setAttribute('aria-activedescendant', rows[active].id);
rows[active].scrollIntoView({ block: 'nearest' });
} else {
box.removeAttribute('aria-activedescendant');
}
}
function move(step) {
if (!open) {
drawSuggestions();
if (!open) return;
}
if (!options.length) return;
active = active < 0 ? (step > 0 ? 0 : options.length - 1) : active + step;
if (active >= options.length || active < 0) active = -1;
markActive();
}
function activate(index) {
const o = options[index];
if (!o) return;
active = index;
if (o.action === 'nomi') {
addNames(box.value, true);
return;
}
if (o.action === 'nome') {
addNames(o.name, true);
return;
}
if (present(o)) return;
if (chosen.has(o.username)) chosen.delete(o.username);
else chosen.set(o.username, { username: o.username, displayName: o.displayName, photo: o.photo, followed: o.followed, isPrivate: o.isPrivate });
drawChosen();
drawSuggestions();
}
// ---------------------------------------------------------------------------- talking to Febe
const send = later(async () => {
if (closed) return;
pollFrom = Date.now();
photosFrom = 0;
let answer;
try {
answer = await api('/api/ricerca', { method: 'POST', body: { client, text: box.value.slice(0, MAX_TEXT) }, signal: aborter.signal });
} catch (error) {
if (error && error.name === 'AbortError') return;
awaiting = false;
remote = { version: lastVersion, mine: true, text: '', state: 'errore', message: error.message, hits: [] };
drawSuggestions();
return;
}
accept(answer, true);
}, DEBOUNCE_MS);
function accept(answer, fromSend) {
if (closed || !answer || answer.version < lastVersion) {
schedule();
return;
}
lastVersion = answer.version;
remote = answer;
if (fromSend) awaiting = false;
drawSuggestions();
schedule();
}
function needsPoll() {
if (!remote || !remote.mine || closed) return false;
if (WORKING.includes(remote.state) || RESUMING.includes(remote.state)) {
photosFrom = 0;
return true;
}
if (!remote.hits.some((hit) => !hit.photoReady && !hit.avatar)) return false;
photosFrom = photosFrom || Date.now();
return Date.now() - photosFrom < PHOTOS_FOR_MS;
}
function schedule() {
clearTimeout(pollTimer);
pollTimer = 0;
if (awaiting || !needsPoll()) return;
let wait = Date.now() - pollFrom < FAST_FOR_MS ? FAST_POLL_MS : SLOW_POLL_MS;
if (RESUMING.includes(remote.state)) {
// Febe resumes the search by itself: slowly, and right when the stop says it ends (retryAfter).
wait = SLOW_POLL_MS;
if (remote.retryAfter) wait = Math.max(FAST_POLL_MS, Math.min(wait, remote.retryAfter - Date.now() + 250));
}
pollTimer = setTimeout(poll, wait);
}
async function poll() {
pollTimer = 0;
try {
accept(await api(`/api/ricerca?client=${client}`, { signal: aborter.signal }), false);
} catch (error) {
if (error && error.name === 'AbortError') return;
schedule();
}
}
function onInput() {
if (view === 'seguiti') {
drawFollowed();
return;
}
awaiting = !isSeveralNames(box.value);
clearTimeout(pollTimer);
pollTimer = 0;
drawSuggestions();
if (isSeveralNames(box.value)) {
send.cancel();
return;
}
send();
}
async function addNames(raw, clearBox) {
const text = namesPerLine(raw);
if (!text) return;
let parsed;
try {
parsed = await api('/api/accounts/parse', { method: 'POST', body: { text }, signal: aborter.signal });
} catch (error) {
showError(error);
return;
}
let ready = 0;
let already = 0;
for (const n of parsed.names) {
if (n.present) {
already += 1;
continue;
}
ready += 1;
const f = byName.get(n.username);
chosen.set(n.username, {
username: n.username,
displayName: n.displayName || (f && f.displayName),
photo: f ? photoOf(f.avatar, f.photo) : null,
followed: n.followed,
isPrivate: n.isPrivate,
});
}
parsedNote = parsed.names.length > 1 || parsed.problems.length || already ? { ready, already, problems: parsed.problems } : null;
if (clearBox) {
box.value = '';
awaiting = false;
send();
}
drawChosen();
drawSuggestions();
// Pasted names went to «Da aggiungere»: the list under the box gives way, so the result shows.
if (!clearBox) setOpen(false);
if (view === 'seguiti') {
// «Da aggiungere» is not on screen in this view: the check boxes show the names, and a note says where they went.
drawFollowed();
if (ready) toast(t('aggiungi.incollatiSeguiti', { n: ready }));
}
}
// ---------------------------------------------------------------------------- left: «Da aggiungere»
function drawChosen() {
fill(chosenTitle, t('aggiungi.daAggiungere'), chosen.size ? h('i', number(chosen.size)) : null);
if (!chosen.size) {
fill(chosenList, h('div.vuoto-scelti', { role: 'listitem' }, icon('search', 's'), h('span', t('aggiungi.sceltiNessuno'))));
} else {
fill(chosenList, [...chosen.values()].map((c) => h('div.voce.scelto', { role: 'listitem' },
face('scelti', c.username, c.photo),
h('span.chi-nome', h('b', `@${c.username}`), c.displayName ? h('small', c.displayName) : null),
h('span.etichette', c.followed ? label(t('aggiungi.seguito'), '', 'user-check') : null, c.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null),
h('button.btn.nudo.solo', {
type: 'button', 'aria-label': t('aggiungi.togli', { nome: c.username }), title: t('aggiungi.togli', { nome: c.username }),
onclick: () => {
chosen.delete(c.username);
drawChosen();
box.focus();
},
}, icon('x', 's')))));
}
if (parsedNote) {
fill(parsedInfo, t('aggiungi.riconosciuti', { n: parsedNote.ready }), parsedNote.already ? ` · ${t('aggiungi.presenti', { n: parsedNote.already })}` : '');
fill(problems, parsedNote.problems.map((p) => h('div', t('aggiungi.riga', { n: p.line, motivo: `«${p.text}»: ${p.reason}` }))));
} else {
fill(parsedInfo);
fill(problems);
}
drawRight();
}
// ---------------------------------------------------------------------------- left: all followed profiles
function followedShown() {
const term = searchTerm(box.value);
return following.profiles.filter((p) => p.followed !== false && (!term || p.username.includes(term) || fold(p.displayName).includes(term)));
}
function drawFollowed() {
if (!following) {
fill(followedList, h('div.caricamento', t('comune.caricamento')));
return;
}
const shown = followedShown();
if (!shown.length) {
fill(followedList, h('div.caricamento', following.total ? t('aggiungi.nessunSeguito') : t('aggiungi.maiLetto')));
return;
}
fill(followedList, shown.map((p) => {
const isPresent = present(p);
const item = checkbox({
checked: isPresent || chosen.has(p.username),
disabled: isPresent,
labelNode: h('span', { style: { display: 'contents' } },
face('seguiti', p.username, photoOf(p.avatar, p.photo)),
h('span.chi-nome', h('b', `@${p.username}`), p.displayName ? h('small', p.displayName) : null),
isPresent ? label(t('aggiungi.giaPresente')) : p.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null),
onchange: (on) => {
if (on) chosen.set(p.username, { username: p.username, displayName: p.displayName, photo: photoOf(p.avatar, p.photo), followed: true, isPrivate: p.isPrivate });
else chosen.delete(p.username);
drawChosen();
},
});
item.classList.toggle('presente', isPresent);
return item;
}));
}
allButton.addEventListener('click', () => {
if (!following) return;
const shown = followedShown().filter((p) => !present(p));
const all = shown.every((p) => chosen.has(p.username));
for (const p of shown) {
if (all) chosen.delete(p.username);
else chosen.set(p.username, { username: p.username, displayName: p.displayName, photo: photoOf(p.avatar, p.photo), followed: true, isPrivate: p.isPrivate });
}
allButton.textContent = t(all ? 'aggiungi.selezionaTutti' : 'aggiungi.togliTutti');
drawFollowed();
drawChosen();
});
function drawProgress() {
fill(toFollowed, view === 'seguiti' ? t('aggiungi.chiudiSeguiti') : t('aggiungi.scegliTraSeguiti', { n: following ? following.total : 0 }));
if (!following) return;
progress.hidden = !following.inProgress;
fill(progress, following.inProgress
@@ -104,65 +653,111 @@ function build(close) {
h('span', following.readDay ? t('aggiungi.lettoIl', { giorno: shortDay(following.readDay, caps().today) }) : t('aggiungi.maiLetto')),
h('button.btn.collegamento', { type: 'button', disabled: following.inProgress, onclick: reread, title: t('aggiungi.rilettura') },
icon('refresh-cw', 's'), following.readDay ? t('aggiungi.rileggi') : t('aggiungi.leggi')));
const count = tabFollowed.querySelector('i');
count.textContent = number(following.total);
}
function setFollowing(value) {
following = value;
byName = new Map(following.profiles.map((p) => [p.username, p]));
byId = new Map(following.profiles.filter((p) => p.instagramId).map((p) => [p.instagramId, p]));
}
async function loadFollowing() {
try {
following = await api('/api/following');
setFollowing(await api('/api/following', { signal: aborter.signal }));
} catch (error) {
if (error && error.name === 'AbortError') return;
showError(error);
following = { profiles: [], total: 0, inProgress: false, readSoFar: 0, readDay: null, backfillPerDay: 300 };
setFollowing({ profiles: [], total: 0, inProgress: false, readSoFar: 0, readDay: null, backfillPerDay: 300 });
}
drawList();
drawProgress();
drawFollowed();
drawRight();
if (box.value) drawSuggestions();
}
async function reread() {
try {
following = await api('/api/following/read', { method: 'POST' });
setFollowing(await api('/api/following/read', { method: 'POST' }));
drawProgress();
drawList();
drawFollowed();
} catch (error) {
showError(error);
}
}
allButton.addEventListener('click', () => {
if (!following) return;
const term = search.value.trim().toLowerCase().replace(/^@/, '');
const shown = following.profiles.filter((p) => !present(p) && (!term || p.username.includes(term) || (p.displayName || '').toLowerCase().includes(term)));
const all = shown.every((p) => chosen.has(p.username));
for (const p of shown) {
if (all) chosen.delete(p.username);
else chosen.add(p.username);
function setView(value) {
view = value;
if (value === 'seguiti') {
setOpen(false);
send.cancel();
awaiting = false;
fill(left, searchZone,
h('div.scelti-testa', h('h3', t('aggiungi.seguiti')), allButton, toFollowed),
followedList, progress);
drawFollowed();
endRemote();
} else {
fill(left, searchZone,
h('div.scelti-testa', chosenTitle, toFollowed),
chosenList, parsedInfo, problems);
drawChosen();
}
allButton.textContent = t(all ? 'aggiungi.selezionaTutti' : 'aggiungi.togliTutti');
drawList();
drawRight();
});
search.addEventListener('input', later(drawList, 120));
drawProgress();
box.placeholder = value === 'seguiti' ? t('aggiungi.filtraSeguiti') : t('aggiungi.cerca');
box.focus();
if (value === 'scelti' && box.value) onInput();
}
const parse = later(async () => {
try {
parsed = await api('/api/accounts/parse', { method: 'POST', body: { text: area.value } });
} catch (error) {
showError(error);
return;
/** The window no longer searches on Instagram (closed, or the whole list is open). */
function endRemote() {
clearTimeout(pollTimer);
pollTimer = 0;
remote = null;
lastVersion = -1;
api('/api/ricerca/fine', { method: 'POST', body: { client }, keepalive: true }).catch(() => {});
}
// ---------------------------------------------------------------------------- the box
box.addEventListener('input', onInput);
box.addEventListener('focus', () => {
if (view === 'scelti' && box.value) drawSuggestions();
});
box.addEventListener('blur', () => setOpen(false));
// A press on the list (its scroll bar, a title) keeps the focus in the box, so the list stays open.
suggestions.addEventListener('mousedown', (e) => e.preventDefault());
box.addEventListener('paste', (e) => {
const text = e.clipboardData ? e.clipboardData.getData('text') : '';
if (!isSeveralNames(text)) return; // one name or address: it goes in the box and is searched
e.preventDefault();
addNames(text, false);
});
box.addEventListener('keydown', (e) => {
if (view !== 'scelti') return;
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault();
move(e.key === 'ArrowDown' ? 1 : -1);
} else if (e.key === 'Enter') {
e.preventDefault();
if (open && active >= 0) {
activate(active);
return;
}
if (isSeveralNames(box.value)) {
addNames(box.value, true);
return;
}
const name = searchTerm(box.value);
const exact = options.findIndex((o) => o.username === name);
if (exact >= 0) activate(exact);
else if (validName(name)) addNames(name, true);
} else if (e.key === 'Tab') {
setOpen(false);
}
const ready = parsed.names.filter((n) => !n.present);
const already = parsed.names.length - ready.length;
fill(parsedInfo, area.value.trim() ? [t('aggiungi.riconosciuti', { n: ready.length }), already ? ` · ${t('aggiungi.presenti', { n: already })}` : ''] : '');
fill(problems, parsed.problems.map((p) => h('div', t('aggiungi.riga', { n: p.line, motivo: `«${p.text}»: ${p.reason}` }))));
drawRight();
}, 250);
area.addEventListener('input', parse);
});
// ---------------------------------------------------------------------------- right: starting point
function selection() {
return tab === 'seguiti' ? [...chosen] : parsed.names.filter((n) => !n.present).map((n) => n.username);
return [...chosen.keys()];
}
function drawRight() {
@@ -208,26 +803,37 @@ function build(close) {
}
}
function setTab(value) {
tab = value;
tabFollowed.classList.toggle('qui', value === 'seguiti');
tabNames.classList.toggle('qui', value === 'nomi');
tabFollowed.setAttribute('aria-selected', String(value === 'seguiti'));
tabNames.setAttribute('aria-selected', String(value === 'nomi'));
fill(left, value === 'seguiti' ? followedPanel : namesPanel);
footerLeft.hidden = value !== 'seguiti';
drawRight();
(value === 'seguiti' ? search : area).focus();
}
tabFollowed.addEventListener('click', () => setTab('seguiti'));
tabNames.addEventListener('click', () => setTab('nomi'));
let engineMode = null;
const stopEngine = onEngine((state) => {
if (open) drawSuggestions();
const mode = state && state.snapshot ? state.snapshot.mode : null;
const changed = mode !== engineMode;
engineMode = mode;
// Alberto let go of the browser, «Riprendi»: the search resumes by itself, the window asks at once.
if (changed && remote && remote.mine && RESUMING.includes(remote.state) && !awaiting && !closed) {
clearTimeout(pollTimer);
pollTimer = setTimeout(poll, FAST_POLL_MS);
}
});
fill(left, followedPanel);
drawList();
box.setAttribute('autofocus', '');
setView('scelti');
drawRight();
loadFollowing();
return {
body: h('div', { style: { display: 'contents' } }, tabs, h('div.corpo-dialogo', left, right)),
body: h('div.corpo-dialogo', left, right),
footer: h('footer', footerLeft, h('div.destra', h('button.btn', { type: 'button', onclick: () => close(false) }, t('comune.annulla')), addButton)),
onEscape: () => {
if (!open) return false;
setOpen(false);
return true;
},
onClose: () => {
closed = true;
send.cancel();
stopEngine();
endRemote();
aborter.abort();
},
};
}
+31 -6
View File
@@ -313,9 +313,36 @@
},
"aggiungi": {
"titolo": "Aggiungi account",
"seguiti": "Dai profili che segui",
"perNome": "Per nome utente",
"cerca": "Cerca tra i profili che segui",
"seguiti": "Profili che segui",
"cerca": "Cerca un profilo per nome o nome utente, o incolla più nomi",
"cercaEtichetta": "Cerca un profilo da aggiungere",
"filtraSeguiti": "Filtra i profili che segui",
"suggerimenti": "Profili trovati",
"traSeguiti": "Profili che segui e account in Febe",
"nessunLocale": "Nessun profilo che segui ha questo nome.",
"nonProfilo": "È l'indirizzo di un post, di un reel o di un'altra pagina, non di un profilo: incolla l'indirizzo del profilo (instagram.com/nome.utente).",
"incollatiSeguiti": "1 nome aggiunto a «Da aggiungere»|{n} nomi aggiunti a «Da aggiungere»",
"daInstagram": "Da Instagram",
"perTesto": "per «{testo}»",
"cercoSuInstagram": "Cerco su Instagram…",
"attesa": "In attesa del turno: i risultati di Instagram arrivano appena il browser di Febe è libero.",
"nessunAltro": "Su Instagram nessun altro profilo oltre a questi.",
"alVolante": "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito. Intanto vedi i profili che segui.",
"altraFinestra": "La ricerca su Instagram è in uso da un'altra finestra di Febe: qui vedi solo i profili che segui.",
"trovati": "1 profilo trovato|{n} profili trovati",
"seguito": "Seguito",
"verificato": "Profilo verificato",
"aggiungiUno": "Aggiungi",
"aggiunto": "Aggiunto",
"perNomeUtente": "Aggiungi @{nome} per nome utente",
"perNomeSpiega": "Anche se non compare fra i risultati: Febe lo controlla alla prossima sessione",
"piuNomi": "Aggiungi all'elenco i nomi scritti",
"piuNomiSpiega": "Più nomi utente o indirizzi di profilo, separati da virgole",
"daAggiungere": "Da aggiungere",
"sceltiNessuno": "Cerca un profilo qui sopra e premi «Aggiungi», oppure incolla più nomi utente o indirizzi di profilo: uno per riga o separati da virgole.",
"togli": "Togli @{nome} dall'elenco",
"scegliTraSeguiti": "Scegli fra tutti i profili che segui ({n})",
"chiudiSeguiti": "Torna a «Da aggiungere»",
"selezionaTutti": "Seleziona tutti",
"togliTutti": "Togli tutti",
"giaPresente": "Già in Febe",
@@ -328,11 +355,9 @@
"inAttesa": "Lettura chiesta: comincia alla prossima sessione",
"rilettura": "Febe rilegge l'elenco a ritmo umano, dentro i tetti: può servire più di una sessione.",
"nessunSeguito": "Nessun profilo con questo nome nell'elenco.",
"area": "Nomi utente o indirizzi dei profili",
"areaAiuto": "Uno per riga: nome.utente, @nome.utente oppure instagram.com/nome.utente",
"riconosciuti": "1 nome pronto|{n} nomi pronti",
"presenti": "1 già in Febe|{n} già in Febe",
"riga": "Riga {n}: {motivo}",
"riga": "{n}° nome: {motivo}",
"perScelti": "Per l'account scelto|Per i {n} account scelti",
"perNessuno": "Scegli gli account a sinistra",
"potraiCambiare": "Potrai cambiare tutto dopo, account per account.",