Ricerca dei profili con suggerimenti e foto (#37)
«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:
1 parent
5e417c666d
commit
9941a2fa1f
98 files changed
+8021
-229
No files matched your search
@@ -6,7 +6,8 @@ namespace Febe.SitoDiProva;
|
||||
/// <summary>
|
||||
/// The JSON the pages fetch, in the site's own synthetic format (LEGGIMI.md). It is what the response tap captures
|
||||
/// and what the readers of <c>lettori.prova.json</c> read. Keys are Italian and the shape is ours: it does not
|
||||
/// imitate Instagram.
|
||||
/// imitate Instagram. One exception: the answer of the search box (<see cref="Search"/>) has the shape of the cleaned
|
||||
/// Instagram sample, so the search of Febe is exercised end to end on the real format (issue #37).
|
||||
/// </summary>
|
||||
public sealed class DataApi(World world, CdnSigner signer, SiteControl control, Func<string> cdnBase, TimeProvider time)
|
||||
{
|
||||
@@ -168,6 +169,87 @@ public sealed class DataApi(World world, CdnSigner signer, SiteControl control,
|
||||
|
||||
public static string Cursor(int offset) => "c" + offset.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>
|
||||
/// The answer of the search box: up to <see cref="SearchSize"/> profiles whose name or display name contains the text
|
||||
/// (accents folded), the ones that start with it first. The shape and keys are those of the cleaned Instagram sample
|
||||
/// «ricerca-profili» (PolarisSearchBoxRefetchableQuery), and only keys present there: no «is_private», no
|
||||
/// «friendship_status», no echo of the text.
|
||||
/// </summary>
|
||||
public JsonObject Search(string text)
|
||||
{
|
||||
var wanted = Fold(text.Trim());
|
||||
var users = new JsonArray();
|
||||
if (wanted.Length > 0)
|
||||
{
|
||||
var found = world.Accounts
|
||||
.Where(a => !a.IsViewer)
|
||||
.Select(a => (Account: a, Name: Fold(a.Username), Display: Fold(a.DisplayName)))
|
||||
.Where(x => x.Name.Contains(wanted, StringComparison.Ordinal) || x.Display.Contains(wanted, StringComparison.Ordinal))
|
||||
.OrderBy(x => x.Name.StartsWith(wanted, StringComparison.Ordinal) || x.Display.StartsWith(wanted, StringComparison.Ordinal) ? 0 : 1)
|
||||
.ThenBy(x => x.Name, StringComparer.Ordinal)
|
||||
.Take(SearchSize)
|
||||
.ToList();
|
||||
var position = 0;
|
||||
foreach (var (account, _, _) in found)
|
||||
{
|
||||
var small = Version(account.PictureKey, 150, 150, video: false)["indirizzo"]!.GetValue<string>();
|
||||
var large = Version(account.PictureKey, 320, 320, video: false)["indirizzo"]!.GetValue<string>();
|
||||
users.Add(new JsonObject
|
||||
{
|
||||
["position"] = position++,
|
||||
["user"] = new JsonObject
|
||||
{
|
||||
["username"] = account.Username,
|
||||
["is_verified"] = false,
|
||||
["full_name"] = account.DisplayName,
|
||||
["pk"] = account.Id,
|
||||
["profile_pic_url"] = small,
|
||||
["hd_profile_pic_url_info"] = new JsonObject { ["url"] = large },
|
||||
["id"] = account.Id,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return new JsonObject
|
||||
{
|
||||
["data"] = new JsonObject
|
||||
{
|
||||
["xdt_api__v1__fbsearch__topsearch_connection"] = new JsonObject
|
||||
{
|
||||
["hashtags"] = new JsonArray(),
|
||||
["places"] = new JsonArray(),
|
||||
["users"] = users,
|
||||
},
|
||||
},
|
||||
["extensions"] = new JsonObject { ["is_final"] = true },
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The «ricerche recenti» shown when the search panel opens: the site's own format, never read by Febe.</summary>
|
||||
public JsonObject RecentSearches(IReadOnlyList<string> names) => new()
|
||||
{
|
||||
["recenti"] = new JsonArray([.. names.Select(n => (JsonNode)new JsonObject { ["voce"] = n })]),
|
||||
};
|
||||
|
||||
/// <summary>Profiles in one search answer.</summary>
|
||||
public const int SearchSize = 8;
|
||||
|
||||
private static string Fold(string text)
|
||||
{
|
||||
var decomposed = text.ToLowerInvariant().Normalize(System.Text.NormalizationForm.FormD);
|
||||
var builder = new System.Text.StringBuilder(decomposed.Length);
|
||||
foreach (var c in decomposed)
|
||||
{
|
||||
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
|
||||
{
|
||||
builder.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static JsonObject Page(int total, int offset, int size)
|
||||
{
|
||||
var more = offset + size < total;
|
||||
|
||||
@@ -53,6 +53,7 @@ storie attive di Marta è anche nella raccolta «Estate», con lo **stesso ident
|
||||
| `/post/{codice}/` | pagina di un post, con tutti i file |
|
||||
| `/verifica` | pagina di verifica, semplice testo |
|
||||
| `/sessione-scaduta` | pagina di sessione terminata, semplice testo (non è un modulo di accesso) |
|
||||
| pulsante «Cerca» (in ogni pagina) | apre il pannello di ricerca (bersagli `search-open` e `search-box`): a ogni tasto la pagina chiede `/dati/cerca` e mostra i profili trovati; con la casella vuota mostra le ricerche recenti. Premere Invio o aprire un risultato scrive una «ricerca recente» (`POST /dati/ricerche-recenti`), cosa che Febe non deve fare mai (issue #37) |
|
||||
| `/benvenuto` | quella che Febe apre come «pagina di accesso» del sito di prova (Collegamento): semplice testo, nessun modulo; la visita apre la sessione, come ogni pagina |
|
||||
|
||||
La mappa dei bersagli di queste pagine è `src/Febe.Core/Config/bersagli.prova.json` (copiata accanto al programma
|
||||
@@ -74,6 +75,8 @@ di Instagram (regola 10). Il vocabolario che lo descrive ai lettori è `src/Febe
|
||||
| `/dati/storie/{nome}` | `{ autore, storie: [contenuto], successivo }`: tutte le storie attive arrivano subito |
|
||||
| `/dati/evidenza/{id}` | `{ raccolta: { numero, titolo, autore, contenuti }, successiva }` |
|
||||
| `/dati/seguiti?dopo=` | `{ seguiti: [profilo], pagina }` |
|
||||
| `/dati/cerca?testo=` | **eccezione**: le chiavi del campione ripulito `000002-ricerca-profili` di Instagram (`data.xdt_api__v1__fbsearch__topsearch_connection.users[].user`), al più 8 profili, mai l'account collegato, prima quelli il cui nome comincia con il testo; maiuscole, accenti e spazi ai lati non contano |
|
||||
| `/dati/ricerche-recenti` | GET: le ricerche recenti; POST: ne scrive una (conta in `/_controllo/ricerca/recenti`) |
|
||||
|
||||
Oggetti:
|
||||
|
||||
@@ -116,6 +119,10 @@ Dentro il processo: `site.Control` (`SiteControl`). Da fuori: `/_controllo/...`
|
||||
| `/_controllo/rinomina?da=&a=` | un account cambia nome (stesso numero) |
|
||||
| `/_controllo/ritratto?nome=` | nuova foto del profilo |
|
||||
| `/_controllo/pubblica?nome=&tipo=foto\|video\|serie` | nuovo post in cima |
|
||||
| `/_controllo/ricerca/ritardo?ms=` | ritardo di ogni risposta della ricerca |
|
||||
| `/_controllo/ricerca/disordine?valore=si\|no` | le risposte ai testi più corti arrivano più tardi (fuori ordine) |
|
||||
| `/_controllo/ricerca/memoria?valore=si\|no` | il pannello ricorda il testo quando si richiude, come Instagram |
|
||||
| `/_controllo/ricerca/recenti` | quante ricerche recenti sono state scritte |
|
||||
| `/_controllo/stato` | modo attuale e numero di richieste di dati |
|
||||
|
||||
Il sito non ha pagine di accesso: la sessione (cookie `sessione_prova`) nasce alla prima visita di una pagina.
|
||||
@@ -88,7 +88,12 @@ internal static class Pages
|
||||
<html lang="it">
|
||||
<head><meta charset="utf-8"><title>{Html(title)} · Sito di prova</title><link rel="stylesheet" href="/risorse/sito.css"></head>
|
||||
<body data-pagina="{page}" {attributes}>
|
||||
<header class="sito"><strong>Sito di prova di Febe</strong><a href="/">Inizio</a><a href="/profilo/alberto.prova/seguiti/">Seguiti</a></header>
|
||||
<header class="sito"><strong>Sito di prova di Febe</strong><a href="/">Inizio</a><a href="/profilo/alberto.prova/seguiti/">Seguiti</a><button type="button" id="apri-cerca" aria-label="Cerca" aria-expanded="false">Cerca</button></header>
|
||||
<section id="pannello-cerca" class="pannello-cerca" hidden aria-label="Pannello di ricerca">
|
||||
<input type="search" id="casella-cerca" aria-label="Cerca" placeholder="Cerca" autocomplete="off">
|
||||
<ul id="recenti-cerca" aria-label="Ricerche recenti"></ul>
|
||||
<ul id="risultati-cerca" aria-label="Risultati"></ul>
|
||||
</section>
|
||||
<main>
|
||||
{main}
|
||||
</main>
|
||||
|
||||
@@ -37,3 +37,12 @@ body.visualizzatore { background: #111; color: #eee; overflow: hidden; }
|
||||
.chi { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); z-index: 3; font-size: 13px; }
|
||||
button.zona-avanti { position: fixed; top: 60px; bottom: 60px; left: 50%; right: 80px; background: transparent; border: 0; z-index: 2; cursor: pointer; }
|
||||
button.chiudi { position: fixed; top: 16px; right: 24px; z-index: 4; background: #333; color: #eee; border: 1px solid #777; width: 44px; height: 44px; font-size: 20px; cursor: pointer; }
|
||||
|
||||
/* Pannello di ricerca (issue #37 di Febe). */
|
||||
header.sito button#apri-cerca { margin-left: auto; font: inherit; padding: 4px 10px; }
|
||||
.pannello-cerca { max-width: 640px; margin: 8px auto; padding: 8px; border: 1px solid #ccc; background: #fff; }
|
||||
.pannello-cerca input { width: 100%; font: inherit; padding: 6px; box-sizing: border-box; }
|
||||
.pannello-cerca ul { list-style: none; margin: 6px 0 0; padding: 0; }
|
||||
.pannello-cerca li a { display: flex; align-items: center; gap: 8px; padding: 4px 0; color: inherit; text-decoration: none; }
|
||||
.pannello-cerca li img { width: 32px; height: 32px; border-radius: 50%; }
|
||||
.pannello-cerca .esteso { color: #666; }
|
||||
@@ -234,6 +234,73 @@
|
||||
mostra();
|
||||
}
|
||||
|
||||
// Il pannello «Cerca» della colonna laterale, come la casella di ricerca di un sito vero (issue #37 di Febe). Le
|
||||
// risposte di /dati/cerca hanno la forma del campione ripulito di Instagram. Aprire il pannello chiede le ricerche
|
||||
// recenti; cliccare un risultato o premere Invio nella casella ne scrive una, come Instagram registra una ricerca:
|
||||
// Febe non deve mai farlo.
|
||||
function ricerca() {
|
||||
const bottone = document.getElementById('apri-cerca');
|
||||
const pannello = document.getElementById('pannello-cerca');
|
||||
const casella = document.getElementById('casella-cerca');
|
||||
const risultati = document.getElementById('risultati-cerca');
|
||||
const recenti = document.getElementById('recenti-cerca');
|
||||
if (!bottone || !pannello || !casella || !risultati || !recenti) return;
|
||||
const memoria = new Map();
|
||||
const conMemoria = corpo.dataset.memoriaRicerca === 'si';
|
||||
let attesa = null;
|
||||
|
||||
function registra() {
|
||||
return fetch('/dati/ricerche-recenti', { method: 'POST', credentials: 'same-origin' }).catch(() => {});
|
||||
}
|
||||
|
||||
function mostra(utenti) {
|
||||
risultati.replaceChildren(...utenti.map((voce) => {
|
||||
const u = voce.user || {};
|
||||
return el('li', {}, el('a', { href: '/profilo/' + encodeURIComponent(u.username || '') + '/' },
|
||||
u.profile_pic_url ? el('img', { src: u.profile_pic_url, alt: '' }) : null,
|
||||
el('span', { class: 'nome', testo: u.username || '' }),
|
||||
el('span', { class: 'esteso', testo: u.full_name || '' })));
|
||||
}));
|
||||
}
|
||||
|
||||
async function cerca(testo) {
|
||||
if (conMemoria && memoria.has(testo)) { mostra(memoria.get(testo)); return; }
|
||||
try {
|
||||
const dati = await carica('/dati/cerca?testo=' + encodeURIComponent(testo));
|
||||
const radice = (dati && dati.data && dati.data.xdt_api__v1__fbsearch__topsearch_connection) || {};
|
||||
const utenti = radice.users || [];
|
||||
memoria.set(testo, utenti);
|
||||
if (casella.value.trim() === testo) mostra(utenti);
|
||||
} catch { /* la pagina resta com'è */ }
|
||||
}
|
||||
|
||||
bottone.addEventListener('click', async () => {
|
||||
const apri = pannello.hidden;
|
||||
pannello.hidden = !apri;
|
||||
bottone.setAttribute('aria-expanded', apri ? 'true' : 'false');
|
||||
if (!apri) return;
|
||||
try {
|
||||
const dati = await carica('/dati/ricerche-recenti');
|
||||
recenti.replaceChildren(...((dati && dati.recenti) || []).map((r) => el('li', { testo: r.voce })));
|
||||
} catch { /* niente ricerche recenti */ }
|
||||
});
|
||||
casella.addEventListener('input', () => {
|
||||
clearTimeout(attesa);
|
||||
const testo = casella.value.trim();
|
||||
if (!testo) { risultati.replaceChildren(); return; }
|
||||
attesa = setTimeout(() => { cerca(testo); }, 200);
|
||||
});
|
||||
casella.addEventListener('keydown', (e) => { if (e.key === 'Enter') registra(); });
|
||||
risultati.addEventListener('click', (e) => {
|
||||
const collegamento = e.target.closest('a');
|
||||
if (!collegamento) return;
|
||||
e.preventDefault();
|
||||
registra().finally(() => { location.href = percorsoSicuro(collegamento.getAttribute('href')); });
|
||||
});
|
||||
}
|
||||
|
||||
ricerca();
|
||||
|
||||
const avvio = {
|
||||
inizio,
|
||||
profilo,
|
||||
|
||||
@@ -56,6 +56,25 @@ public sealed class SiteControl
|
||||
private int _cdnFiles;
|
||||
private int _cdnExpired;
|
||||
private int _cdnThrottled;
|
||||
private int _recentSearchWrites;
|
||||
|
||||
/// <summary>Extra wait before every answer of the search box (slow answers).</summary>
|
||||
public TimeSpan SearchDelay { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The search box answers shorter texts later than longer ones, so an earlier prefix arrives last (answers out of
|
||||
/// order, as on a slow network).
|
||||
/// </summary>
|
||||
public bool SearchDisorder { get; set; }
|
||||
|
||||
/// <summary>The page sends no request for a text it already searched, as a page with its own memory does.</summary>
|
||||
public bool SearchMemory { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Number of «ricerche recenti» the page wrote: clicking a result or pressing Enter in the search box writes one,
|
||||
/// as Instagram registers a search. Febe must never cause one.
|
||||
/// </summary>
|
||||
public int RecentSearchWrites => _recentSearchWrites;
|
||||
|
||||
public StopMode Mode
|
||||
{
|
||||
@@ -91,6 +110,10 @@ public sealed class SiteControl
|
||||
StoryDuration = TimeSpan.FromSeconds(5);
|
||||
AddressLifetime = TimeSpan.FromHours(6);
|
||||
CdnTooManyRequests = false;
|
||||
SearchDelay = TimeSpan.Zero;
|
||||
SearchDisorder = false;
|
||||
SearchMemory = false;
|
||||
Interlocked.Exchange(ref _recentSearchWrites, 0);
|
||||
Interlocked.Exchange(ref _cdnFiles, 0);
|
||||
Interlocked.Exchange(ref _cdnExpired, 0);
|
||||
Interlocked.Exchange(ref _cdnThrottled, 0);
|
||||
@@ -116,6 +139,8 @@ public sealed class SiteControl
|
||||
|
||||
internal void OnCdnServed() => Interlocked.Increment(ref _cdnFiles);
|
||||
|
||||
internal void OnRecentSearchWritten() => Interlocked.Increment(ref _recentSearchWrites);
|
||||
|
||||
internal void OnCdnExpired() => Interlocked.Increment(ref _cdnExpired);
|
||||
|
||||
internal void OnCdnThrottled() => Interlocked.Increment(ref _cdnThrottled);
|
||||
|
||||
@@ -251,6 +251,11 @@ public sealed class TestSite : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
if (Control.SearchMemory)
|
||||
{
|
||||
html = html.Replace("<body ", "<body data-memoria-ricerca=\"si\" ", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
await HtmlAsync(context, status, html).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -279,6 +284,32 @@ public sealed class TestSite : IAsyncDisposable
|
||||
}
|
||||
|
||||
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
|
||||
if (segments is ["dati", "cerca"])
|
||||
{
|
||||
await SearchAsync(context, query["testo"].ToString()).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (segments is ["dati", "ricerche-recenti"])
|
||||
{
|
||||
if (HttpMethods.IsPost(context.Request.Method))
|
||||
{
|
||||
// The analogue of Instagram registering a search in the recent ones: a write Febe must never cause.
|
||||
Control.OnRecentSearchWritten();
|
||||
await JsonAsync(context, 200, new JsonObject { ["ok"] = true }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
JsonObject recent;
|
||||
lock (World.Gate)
|
||||
{
|
||||
recent = Api.RecentSearches([.. World.Following.Take(3).Select(a => a.Username)]);
|
||||
}
|
||||
|
||||
await JsonAsync(context, 200, recent).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var tab = query["scheda"].ToString() switch { "reel" => ProfileTab.Reels, "taggati" => ProfileTab.Tagged, _ => ProfileTab.Posts };
|
||||
var after = query["dopo"].ToString();
|
||||
JsonObject? result;
|
||||
@@ -308,6 +339,29 @@ public sealed class TestSite : IAsyncDisposable
|
||||
await JsonAsync(context, 200, result).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The answer of the search box, after the waits the control asks for (slow, out of order).</summary>
|
||||
private async Task SearchAsync(HttpContext context, string text)
|
||||
{
|
||||
var delay = Control.SearchDelay;
|
||||
if (Control.SearchDisorder)
|
||||
{
|
||||
delay += TimeSpan.FromMilliseconds(Math.Max(0, 8 - text.Trim().Length) * 250);
|
||||
}
|
||||
|
||||
if (delay > TimeSpan.Zero)
|
||||
{
|
||||
await Task.Delay(delay, context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
JsonObject answer;
|
||||
lock (World.Gate)
|
||||
{
|
||||
answer = Api.Search(text);
|
||||
}
|
||||
|
||||
await JsonAsync(context, 200, answer).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ServeCdnAsync(HttpContext context)
|
||||
{
|
||||
var path = context.Request.Path.Value ?? string.Empty;
|
||||
@@ -381,6 +435,18 @@ public sealed class TestSite : IAsyncDisposable
|
||||
case "durata-storie":
|
||||
Control.StoryDuration = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture));
|
||||
break;
|
||||
case "ricerca/ritardo":
|
||||
Control.SearchDelay = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture));
|
||||
break;
|
||||
case "ricerca/disordine":
|
||||
Control.SearchDisorder = q["valore"].ToString() is not ("no" or "false");
|
||||
break;
|
||||
case "ricerca/memoria":
|
||||
Control.SearchMemory = q["valore"].ToString() is not ("no" or "false");
|
||||
break;
|
||||
case "ricerca/recenti":
|
||||
answer["scritte"] = Control.RecentSearchWrites;
|
||||
break;
|
||||
case "cdn-troppe-richieste":
|
||||
Control.CdnTooManyRequests = q["valore"].ToString() is "si" or "sì" or "true";
|
||||
break;
|
||||
|
||||
Reference in new issue
Block a user