«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>
161 lines
6.3 KiB
C#
161 lines
6.3 KiB
C#
using System.Globalization;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace Febe.Core.Collection.Search;
|
|
|
|
/// <summary>What the normalized text of the search box is good for.</summary>
|
|
public enum SearchQueryKind
|
|
{
|
|
/// <summary>Nothing to search.</summary>
|
|
Empty,
|
|
|
|
/// <summary>Febe may type it into the site's search box.</summary>
|
|
Typable,
|
|
|
|
/// <summary>Several names or addresses: they go to the list, Febe does not search them on the site.</summary>
|
|
SeveralNames,
|
|
|
|
/// <summary>A character Febe never types (a control character other than a line break).</summary>
|
|
Refused,
|
|
|
|
/// <summary>Too short, too long, or other characters: local suggestions only.</summary>
|
|
LocalOnly,
|
|
}
|
|
|
|
/// <summary>The search text after <see cref="SearchText.Normalize"/>. Never printed with the text.</summary>
|
|
/// <param name="Kind">What it is good for.</param>
|
|
/// <param name="Typed">The text Febe types (lowercase, no accents, single spaces); empty unless <see cref="SearchQueryKind.Typable"/>.</param>
|
|
/// <param name="Shown">The cleaned text, for the local suggestions and the label of the results.</param>
|
|
public sealed record SearchQuery(SearchQueryKind Kind, string Typed, string Shown)
|
|
{
|
|
private bool PrintMembers(StringBuilder builder)
|
|
{
|
|
builder.Append($"Kind = {Kind}, Length = {Typed.Length}");
|
|
return true;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The rules of what the profile search may type (issue #37), decided here in Core and not in the interface: a line
|
|
/// break, a tab or any control character is never typed (so nothing can ever press Enter on the site); several names
|
|
/// stay local; a profile address becomes its user name; accents are removed; only letters, digits, «.», «_» and single
|
|
/// spaces are typed, from 2 to 40 characters.
|
|
/// </summary>
|
|
public static partial class SearchText
|
|
{
|
|
/// <summary>Longest text the interface may send (characters, before cleaning).</summary>
|
|
public const int MaxRawLength = 60;
|
|
|
|
/// <summary>Shortest text Febe types on the site.</summary>
|
|
public const int MinTyped = 2;
|
|
|
|
/// <summary>Longest text Febe types on the site.</summary>
|
|
public const int MaxTyped = 40;
|
|
|
|
/// <summary>First path segments of Instagram that are pages, not profiles.</summary>
|
|
private static readonly HashSet<string> Reserved = new(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
"p", "reel", "reels", "tv", "stories", "explore", "accounts", "direct", "about", "legal", "developer", "web", "challenge", "emails", "session",
|
|
};
|
|
|
|
public static SearchQuery Normalize(string? raw)
|
|
{
|
|
if (string.IsNullOrEmpty(raw))
|
|
{
|
|
return new SearchQuery(SearchQueryKind.Empty, string.Empty, string.Empty);
|
|
}
|
|
|
|
// 1. Control characters: a line break means several names, any other is refused. Never typed.
|
|
foreach (var c in raw)
|
|
{
|
|
if (c is '\r' or '\n')
|
|
{
|
|
return new SearchQuery(SearchQueryKind.SeveralNames, string.Empty, string.Empty);
|
|
}
|
|
|
|
if (char.IsControl(c) || char.GetUnicodeCategory(c) is UnicodeCategory.Format or UnicodeCategory.LineSeparator or UnicodeCategory.ParagraphSeparator)
|
|
{
|
|
return new SearchQuery(SearchQueryKind.Refused, string.Empty, string.Empty);
|
|
}
|
|
}
|
|
|
|
// 2. Trim and single spaces.
|
|
var text = Spaces().Replace(raw.Trim(), " ");
|
|
if (text.Length == 0)
|
|
{
|
|
return new SearchQuery(SearchQueryKind.Empty, string.Empty, string.Empty);
|
|
}
|
|
|
|
// 4. Several names: only an explicit separator or more than one profile address.
|
|
if (text.Contains(',', StringComparison.Ordinal) || text.Contains(';', StringComparison.Ordinal) || Addresses().Count(text) > 1)
|
|
{
|
|
return new SearchQuery(SearchQueryKind.SeveralNames, string.Empty, text);
|
|
}
|
|
|
|
// 3. A profile address becomes its user name; a leading @ goes.
|
|
if (text.Contains("instagram.com", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
if (ProfileName(text) is not { } name)
|
|
{
|
|
return new SearchQuery(SearchQueryKind.LocalOnly, string.Empty, text);
|
|
}
|
|
|
|
text = name;
|
|
}
|
|
|
|
text = text.TrimStart('@').Trim();
|
|
|
|
// 5. Lowercase, letters with diacritics folded to their base letter.
|
|
var typed = Fold(text.ToLowerInvariant());
|
|
var shown = text;
|
|
|
|
// 6. Only the closed set of characters, 2 to 40 of them.
|
|
if (typed.Length < MinTyped || typed.Length > MaxTyped || !Typable().IsMatch(typed))
|
|
{
|
|
return new SearchQuery(SearchQueryKind.LocalOnly, string.Empty, shown);
|
|
}
|
|
|
|
return new SearchQuery(SearchQueryKind.Typable, typed, shown);
|
|
}
|
|
|
|
/// <summary>Lowercase text without diacritics, for comparing names (local suggestions use the same rule).</summary>
|
|
public static string Fold(string text)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(text);
|
|
var decomposed = text.Normalize(NormalizationForm.FormD);
|
|
var builder = new StringBuilder(decomposed.Length);
|
|
foreach (var c in decomposed)
|
|
{
|
|
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
|
|
{
|
|
builder.Append(c);
|
|
}
|
|
}
|
|
|
|
return builder.ToString().Normalize(NormalizationForm.FormC);
|
|
}
|
|
|
|
private static string? ProfileName(string text)
|
|
{
|
|
var address = text.Contains("://", StringComparison.Ordinal) ? text : "https://" + text;
|
|
if (!Uri.TryCreate(address, UriKind.Absolute, out var uri)
|
|
|| !(uri.Host.Equals("instagram.com", StringComparison.OrdinalIgnoreCase) || uri.Host.EndsWith(".instagram.com", StringComparison.OrdinalIgnoreCase)))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var segments = uri.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
|
return segments.Length == 0 || Reserved.Contains(segments[0]) ? null : Uri.UnescapeDataString(segments[0]);
|
|
}
|
|
|
|
[GeneratedRegex(@"\s+", RegexOptions.CultureInvariant)]
|
|
private static partial Regex Spaces();
|
|
|
|
[GeneratedRegex("instagram\\.com/", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)]
|
|
private static partial Regex Addresses();
|
|
|
|
[GeneratedRegex("^[a-z0-9._]+( [a-z0-9._]+)*$", RegexOptions.CultureInvariant)]
|
|
private static partial Regex Typable();
|
|
}
|