Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76dd1b6032 | ||
|
|
d4675a5e21 | ||
|
|
65c0c4470e | ||
|
|
a85d0e568e | ||
|
|
9941a2fa1f | ||
|
|
5e417c666d | ||
|
|
0775a1460f | ||
|
|
e2e64c09e8 | ||
|
|
badd1681a0 | ||
|
|
bf03cb45a5 | ||
|
|
72deb212a7 | ||
|
|
305791f57b | ||
|
|
e8dc4693e5 | ||
|
|
c05bd2d11b | ||
|
|
9c18252a47 | ||
|
|
78aa32bdb2 | ||
|
|
8d2f85693c | ||
|
|
0153280edd | ||
|
|
dc60e282c5 | ||
|
|
2ffb766a95 | ||
|
|
eac1a058e4 | ||
|
|
31ff6c8b86 | ||
|
|
b7e5e25436 | ||
|
|
fbc40fb5a1 | ||
|
|
31bbbf8bb7 | ||
|
|
b3a7c31e5a | ||
|
|
5b278a848a | ||
|
|
2e1d81d4b8 | ||
|
|
b74d2db793 | ||
|
|
e73292516d | ||
|
|
7d5c6505bd | ||
|
|
44f7f93783 | ||
|
|
4b35178880 | ||
|
|
fe4ef9f048 | ||
|
|
c5361ba8fe | ||
|
|
68100b0295 | ||
|
|
e24ebd24f0 | ||
|
|
483d57b89a | ||
|
|
086b603801 | ||
|
|
46d780c826 | ||
|
|
5988c503f7 | ||
|
|
7513f41d4d | ||
|
|
7a9c235552 | ||
|
|
d07ed07db6 | ||
|
|
248e9f74ce | ||
|
|
65988f2863 | ||
|
|
016bbf73eb | ||
|
|
0f11fc5220 |
No files matched your search
@@ -4,7 +4,8 @@
|
||||
#
|
||||
# bash .gitea/scripts/controlli.sh
|
||||
#
|
||||
# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix;
|
||||
# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix; gli
|
||||
# script Node della CI (.gitea/scripts/*.js) sono JavaScript valido (node --check);
|
||||
# 2. i flussi della CI non hanno tabulazioni (YAML non le accetta come rientro);
|
||||
# 3. nessun file contiene segni di conflitto rimasti da un'unione;
|
||||
# 4. la versione di Directory.Build.props è nella forma x.y.z[-qualcosa], quella che installer/costruisci.sh accetta;
|
||||
@@ -35,6 +36,18 @@ while IFS= read -r -d '' script; do
|
||||
done < <(git ls-files -z -- '*.sh')
|
||||
echo " $quanti script controllati"
|
||||
|
||||
echo "== Script Node della CI"
|
||||
if command -v node > /dev/null; then
|
||||
quanti=0
|
||||
while IFS= read -r -d '' script; do
|
||||
quanti=$((quanti + 1))
|
||||
node --check "$script" || errore "$script: JavaScript non valido."
|
||||
done < <(git ls-files -z -- '.gitea/scripts/*.js')
|
||||
echo " $quanti script controllati"
|
||||
else
|
||||
errore "manca node: gli script Node della CI non si possono controllare."
|
||||
fi
|
||||
|
||||
echo "== Flussi della CI"
|
||||
while IFS= read -r -d '' flusso; do
|
||||
if grep -n $'\t' "$flusso" > /dev/null; then
|
||||
|
||||
@@ -8,6 +8,11 @@
|
||||
# già nella configurazione del client, il demone non
|
||||
# parla mai con il registro (proverebbe HTTPS)
|
||||
#
|
||||
# L'immagine è un manifest semplice, senza attestazioni (--provenance=false --sbom=false). Con le attestazioni, che
|
||||
# buildx aggiunge da sé, sarebbe un indice: Gitea tiene ogni manifest figlio come una versione a sé, sha256:… senza
|
||||
# etichetta, con la configurazione e gli strati, e togliere dal registro un'etichetta :sha- toglierebbe solo l'indice.
|
||||
# Con un manifest semplice gli strati stanno nella versione dell'etichetta, e la pulizia del registro li libera davvero.
|
||||
#
|
||||
# Variabili richieste: BUILDER, VERSIONE, GIT_COMMIT, FLUSSO (verifica o rilascio), ESECUZIONE (gitea.run_id).
|
||||
# Le etichette febe.ci.* dicono quale flusso, esecuzione, ramo e commit hanno costruito l'immagine. Non servono alla
|
||||
# pulizia: stanno anche nelle immagini pubblicate e Docker le copia in ogni contenitore creato da quelle, anche in un
|
||||
@@ -19,7 +24,7 @@ modo="${1:?Indica il modo: archivio o pubblica.}"
|
||||
shift
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
comuni=(--builder "${BUILDER:?}" -f docker/Dockerfile
|
||||
comuni=(--builder "${BUILDER:?}" -f docker/Dockerfile --provenance=false --sbom=false
|
||||
--build-arg "VERSION=${VERSIONE:?}" --build-arg "GIT_COMMIT=${GIT_COMMIT:?}"
|
||||
--label "febe.ci.workflow=${FLUSSO:?}" --label "febe.ci.run=${ESECUZIONE:?}"
|
||||
--label "febe.ci.ref=${GITHUB_REF_NAME:-}" --label "febe.ci.commit=${GITHUB_SHA:-}")
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
# Pulizia di ciò che la CI di Febe lascia sul demone Docker del runner. È lo stesso demone che costruisce Encelado,
|
||||
# Mimante e gli altri progetti di Alberto, e ci può girare anche un Febe vero: si tocca solo ciò che si può provare
|
||||
# creato dalla CI, più le immagini senza nome («dangling») più vecchie di tre giorni. Mai altro, e mai la cache di
|
||||
# costruzione del demone (è condivisa).
|
||||
# Pulizia del demone Docker del runner e del registro dei container. Il demone è lo stesso che costruisce Encelado,
|
||||
# Mimante e gli altri progetti di Alberto (e molto probabilmente quello delle applicazioni di Unraid), e ci può girare
|
||||
# anche un Febe vero. Dal 21 ottobre 2026 (decisione di Alberto) la pulizia toglie anche ciò che non serve più a
|
||||
# nessuno, di qualunque progetto: le immagini che nessun contenitore usa, la cache di costruzione, i resti di
|
||||
# act_runner. Mai un contenitore, un volume o una rete che non sia della CI.
|
||||
#
|
||||
# Le etichette febe.ci.workflow, febe.ci.run, febe.ci.ref e febe.ci.commit dicono da dove viene un'immagine, ma NON
|
||||
# scelgono che cosa togliere: stanno anche nelle immagini pubblicate (:main, :sha-, :X.Y.Z, :latest), e Docker le copia
|
||||
# in ogni contenitore creato da quelle immagini, quindi le porta anche un Febe vero. Ciò che si toglie si riconosce così:
|
||||
# Della CI di Febe si toglie ciò che si può provare suo. Le etichette febe.ci.workflow, febe.ci.run, febe.ci.ref e
|
||||
# febe.ci.commit dicono da dove viene un'immagine, ma NON scelgono che cosa togliere: stanno anche nelle immagini
|
||||
# pubblicate (:main, :sha-, :X.Y.Z, :latest), e Docker le copia in ogni contenitore creato da quelle, quindi le porta
|
||||
# anche un Febe vero. Ciò che si toglie si riconosce così:
|
||||
# - contenitori di prova: l'etichetta febe.ci.prova=<esecuzione>, che mette solo prova-immagine.sh con
|
||||
# «docker run --label» e che nessuna immagine porta (lo controlla PipelineTests), E il nome esatto
|
||||
# febe-prova-<la stessa esecuzione> (gli altri contenitori della prova, senza nome, girano con --rm e Docker li
|
||||
@@ -16,41 +18,154 @@
|
||||
# - builder buildx: il contenitore buildx_buildkit_febe-ci-<esecuzione>0, con l'immagine moby/buildkit, e il suo
|
||||
# volume …_state, che contengono la cache di costruzione di quell'esecuzione;
|
||||
# - l'immagine febe:ci lasciata dal vecchio flusso di verifica (prima del 20 ottobre 2026), se nessuno la usa.
|
||||
# Di act_runner si tolgono i resti dei lavori: act_runner chiama tutto ciò che crea per un lavoro
|
||||
# GITEA-ACTIONS-TASK-<numero del compito>… (il contenitore del lavoro, i suoi volumi <nome> e <nome>-env, la sua rete
|
||||
# <nome>-<lavoro>-network). Solo i contenitori fermi e i volumi e le reti che nessun contenitore usa, più vecchi di 90
|
||||
# minuti: un lavoro che parte li crea e li usa subito. Il volume act-toolcache (la cache degli strumenti, condivisa fra
|
||||
# i lavori) resta.
|
||||
#
|
||||
# pulizia-docker.sh esecuzione <id> tutto ciò che ha creato l'esecuzione <id> (all'inizio e alla fine del suo
|
||||
# lavoro «immagine», sempre)
|
||||
# pulizia-docker.sh penzolanti le immagini senza nome che nessun contenitore usa e la cache di costruzione
|
||||
# penzolante del demone (quella che nessuna immagine condivide) non usata da
|
||||
# 24 ore, di tutti i progetti (alla fine di ogni lavoro «immagine», dopo
|
||||
# «esecuzione»)
|
||||
# pulizia-docker.sh residui [minuti] i resti di esecuzioni interrotte, più vecchi di N minuti (predefinito 90: un
|
||||
# lavoro dura al massimo 60 minuti, quindi nessuno di essi è ancora vivo)
|
||||
# pulizia-docker.sh settimanale residui, febe:ci, immagini senza nome più vecchie di 72 ore (flusso «pulizia»)
|
||||
# pulizia-docker.sh settimanale residui, febe:ci, immagini senza nome più vecchie di 72 ore: la pulizia
|
||||
# stretta di prima del 21 ottobre 2026, ora solo a mano
|
||||
# pulizia-docker.sh completa residui, febe:ci, resti di act_runner, le immagini che nessun contenitore
|
||||
# usa create più di 24 ore fa, la cache di costruzione non usata da 24 ore e,
|
||||
# con REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti
|
||||
# (flusso «pulizia», ogni lunedì e a mano)
|
||||
# pulizia-docker.sh <modo> --prova elenca che cosa toglierebbe e non toglie nulla: solo comandi che leggono
|
||||
# (sul registro solo GET)
|
||||
#
|
||||
# Nei modi «residui» e «settimanale» un contenitore di prova si toglie solo se è fermo. Uno ancora acceso dopo 90 minuti
|
||||
# (il suo lavoro è stato ucciso proprio durante la prova del contenitore) resta dov'è: lo si segnala, con il comando per
|
||||
# toglierlo a mano. I builder sono l'eccezione: sono sempre accesi e la loro cache se ne va solo togliendo il
|
||||
# contenitore; si riconoscono dal nome esatto e dall'immagine di buildkit, mai da un'etichetta.
|
||||
# Gli argomenti si controllano tutti prima di toccare Docker: un'opzione diversa da --prova (--dry-run, -n, --Prova) o
|
||||
# un argomento in più (prova senza trattini) fermano tutto con codice 2, invece di far partire la pulizia vera al posto
|
||||
# della prova.
|
||||
#
|
||||
# Un oggetto già sparito non è un errore: la pulizia si può ripetere. Nei modi «esecuzione» e «residui» un problema
|
||||
# diventa un avviso (un lavoro verde non diventa rosso per la pulizia, che il flusso settimanale ripete); nel modo
|
||||
# «settimanale» fa fallire il lavoro, perché qualcuno lo guardi.
|
||||
# Mai docker system prune, container prune, volume prune o network prune; mai image prune -a o builder prune -a senza
|
||||
# il filtro delle 24 ore; mai un contenitore, un volume o una rete che non sia della CI. Le immagini le toglie Docker
|
||||
# stesso (image prune), che non toglie mai un'immagine usata da un contenitore, nemmeno fermo; con -a, però, le toglie i
|
||||
# nomi in più, e lo script li scrive (nella prova li stima, secondo lo store). Sul registro mai main, latest o una
|
||||
# versione X.Y.Z: solo le etichette sha-<esadecimale> della verifica.
|
||||
#
|
||||
# Nei modi «residui», «settimanale» e «completa» un contenitore di prova si toglie solo se è fermo. Uno ancora acceso
|
||||
# dopo 90 minuti (il suo lavoro è stato ucciso proprio durante la prova del contenitore) resta dov'è: lo si segnala, con
|
||||
# il comando per toglierlo a mano. I builder sono l'eccezione: sono sempre accesi e la loro cache se ne va solo
|
||||
# togliendo il contenitore; si riconoscono dal nome esatto e dall'immagine di buildkit, mai da un'etichetta.
|
||||
#
|
||||
# Un oggetto già sparito non è un errore: la pulizia si può ripetere. Nei modi «esecuzione», «penzolanti» e «residui»
|
||||
# un problema diventa un avviso (un lavoro verde non diventa rosso per la pulizia, che il flusso del lunedì ripete); nei
|
||||
# modi «settimanale» e «completa» fa fallire il lavoro, perché qualcuno lo guardi. Il registro è l'eccezione: un
|
||||
# rifiuto della sua API è solo un avviso, e il lunedì dopo si riprova.
|
||||
#
|
||||
# Variabili per il registro (modo «completa»): REGISTRY_TOKEN (token con «package: read and write», mai stampato),
|
||||
# GITEA_API (l'API del server, per esempio https://gitea.example/api/v1) e PROPRIETARIO (il proprietario del pacchetto
|
||||
# febe). La scelta delle versioni da togliere sta in versioni-registro.js, accanto a questo script.
|
||||
set -uo pipefail
|
||||
|
||||
modo="${1:-}"
|
||||
uso() {
|
||||
[[ -z "${1:-}" ]] || echo "$1" >&2
|
||||
echo "Uso: $0 esecuzione <id> | penzolanti | residui [minuti] | settimanale | completa [--prova]" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
prova=0
|
||||
argomenti=()
|
||||
for argomento in "$@"; do
|
||||
case "$argomento" in
|
||||
--prova) prova=1 ;;
|
||||
-*) uso "Opzione sconosciuta: «$argomento». L'unica è --prova." ;;
|
||||
*) argomenti+=("$argomento") ;;
|
||||
esac
|
||||
done
|
||||
modo="${argomenti[0]:-}"
|
||||
case "$modo" in
|
||||
esecuzione) ((${#argomenti[@]} == 2)) || uso "Il modo esecuzione vuole il numero dell'esecuzione e nient'altro." ;;
|
||||
residui) ((${#argomenti[@]} <= 2)) || uso "Il modo residui vuole al più i minuti." ;;
|
||||
penzolanti | settimanale | completa) ((${#argomenti[@]} == 1)) || uso "Il modo $modo non vuole altri argomenti: «${argomenti[1]}»." ;;
|
||||
*) uso ;;
|
||||
esac
|
||||
cartella_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
problemi=0
|
||||
|
||||
# In prova: i contenitori (identificativo e nome) e i nomi di immagine che la pulizia vera toglierebbe, perché gli
|
||||
# elenchi che seguono li trattino come già tolti (un volume usato solo da un contenitore che se ne andrebbe, per
|
||||
# esempio, se ne andrebbe anche lui).
|
||||
previsti=()
|
||||
nomi_previsti=()
|
||||
|
||||
# Per il riepilogo: quanti oggetti per tipo, nell'ordine in cui compaiono, e lo spazio recuperato da Docker.
|
||||
declare -A conteggi=()
|
||||
tipi=()
|
||||
note=()
|
||||
|
||||
# La cache di costruzione che si pota è quella del builder del demone, «default». docker builder è un alias di docker
|
||||
# buildx quando c'è il plugin, e buildx lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione
|
||||
# (setup-buildx-action lo crea con --use), che il modo «esecuzione» ha appena tolto. Gli altri comandi buildx di questo
|
||||
# script indicano il builder per nome.
|
||||
export BUILDX_BUILDER=default
|
||||
|
||||
avviso() {
|
||||
echo "::warning::$*"
|
||||
problemi=$((problemi + 1))
|
||||
}
|
||||
|
||||
# Minuti trascorsi da un istante RFC 3339 (il campo Created di docker inspect). Se non si legge, 0: nel dubbio
|
||||
# l'oggetto è giovane e resta.
|
||||
# Un avviso che non fa diventare rosso il lavoro: per il registro.
|
||||
segnala() {
|
||||
echo "::warning::$*"
|
||||
}
|
||||
|
||||
conta() {
|
||||
[[ -n "${conteggi[$1]+x}" ]] || tipi+=("$1")
|
||||
conteggi[$1]=$((${conteggi[$1]:-0} + 1))
|
||||
}
|
||||
|
||||
# Vero se la prima parola è fra quelle che seguono.
|
||||
fra() {
|
||||
local cercata="$1" voce
|
||||
shift
|
||||
for voce in "$@"; do
|
||||
[[ "$voce" == "$cercata" ]] && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# Minuti trascorsi da un istante RFC 3339 come lo scrive Docker (Created di un contenitore o di un'immagine, CreatedAt
|
||||
# di un volume, {{json .Created}} di una rete, fra virgolette), con o senza frazioni di secondo, con «Z» o con lo scarto
|
||||
# dall'ora universale (+02:00). Se non si legge, 0: nel dubbio l'oggetto è giovane e resta.
|
||||
eta_minuti() {
|
||||
local creato="${1%%.*}"
|
||||
creato="${creato%Z}"
|
||||
local secondi
|
||||
secondi=$(date -u -d "${creato}Z" +%s 2>/dev/null) || { echo 0; return; }
|
||||
local creato="${1:-}" secondi
|
||||
creato="${creato//\"/}"
|
||||
[[ "$creato" =~ ^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})(\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$ ]] \
|
||||
|| { echo 0; return; }
|
||||
secondi=$(date -u -d "${BASH_REMATCH[1]}${BASH_REMATCH[3]}" +%s 2> /dev/null) || { echo 0; return; }
|
||||
echo $((($(date -u +%s) - secondi) / 60))
|
||||
}
|
||||
|
||||
durata() {
|
||||
local minuti="$1"
|
||||
if ((minuti >= 2 * 1440)); then
|
||||
echo "$((minuti / 1440)) giorni"
|
||||
elif ((minuti >= 120)); then
|
||||
echo "$((minuti / 60)) ore"
|
||||
else
|
||||
echo "$minuti minuti"
|
||||
fi
|
||||
}
|
||||
|
||||
# Fra i contenitori dati (identificativi, uno per riga), quelli che restano dopo questa pulizia: in prova senza quelli
|
||||
# che la pulizia vera toglierebbe.
|
||||
restanti() {
|
||||
local id
|
||||
while read -r id; do
|
||||
[[ -n "$id" ]] || continue
|
||||
fra "$id" "${previsti[@]}" || echo "$id"
|
||||
done <<< "${1:-}"
|
||||
}
|
||||
|
||||
# I contenitori di prova della CI, uno per riga «id nome»: l'etichetta febe.ci.prova (dell'esecuzione indicata, o di
|
||||
# qualunque se il primo argomento è vuoto) e il nome esatto febe-prova-<valore dell'etichetta>. Gli stati che seguono
|
||||
# restringono la scelta (Docker li unisce in OR). Esce con 1 se Docker non risponde.
|
||||
@@ -68,33 +183,46 @@ contenitori_di_prova() {
|
||||
done <<< "$elenco"
|
||||
}
|
||||
|
||||
# Toglie un contenitore con i suoi volumi anonimi. Con «forza» anche se è acceso: solo per quelli dell'esecuzione
|
||||
# stessa e per i builder.
|
||||
# Toglie un contenitore con i suoi volumi anonimi (in prova lo elenca soltanto). Con «forza» anche se è acceso: solo
|
||||
# per quelli dell'esecuzione stessa e per i builder. Esce con 0 se il contenitore se ne va (o se ne andrebbe).
|
||||
togli_contenitore() {
|
||||
local id="$1" nome="$2" opzioni=(-v)
|
||||
[[ "${3:-}" == forza ]] && opzioni=(-f -v)
|
||||
if ((prova)); then
|
||||
echo " toglierei il contenitore $nome"
|
||||
previsti+=("$id" "$nome")
|
||||
return 0
|
||||
fi
|
||||
if docker rm "${opzioni[@]}" "$id" > /dev/null 2>&1; then
|
||||
echo " contenitore $nome tolto"
|
||||
elif docker container inspect "$id" > /dev/null 2>&1; then
|
||||
avviso "Non riesco a togliere il contenitore $nome."
|
||||
return 0
|
||||
fi
|
||||
docker container inspect "$id" > /dev/null 2>&1 && avviso "Non riesco a togliere il contenitore $nome."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Toglie il nome locale febe-ci:<esecuzione>, mai l'immagine per identificativo e mai con -f: se l'immagine ha anche un
|
||||
# altro nome (del registro, per esempio) quello resta; se un contenitore la usa, resta tutto.
|
||||
# Toglie il nome locale febe-ci:<esecuzione> (o febe:ci), mai l'immagine per identificativo e mai con -f: se l'immagine
|
||||
# ha anche un altro nome (del registro, per esempio) quello resta; se un contenitore la usa, resta tutto.
|
||||
togli_immagine() {
|
||||
local riferimento="$1" nomi
|
||||
[[ "$riferimento" =~ ^febe-ci:[0-9]+$ ]] || { avviso "Nome di immagine inatteso: «$riferimento»."; return 0; }
|
||||
nomi=$(docker image inspect -f '{{len .RepoTags}}' "$riferimento" 2>/dev/null) || return 0
|
||||
if [[ "$nomi" == 1 && -n "$(docker ps -a -q --filter "ancestor=$riferimento")" ]]; then
|
||||
[[ "$riferimento" =~ ^febe-ci:[0-9]+$ ]] || [[ "$riferimento" == febe:ci ]] \
|
||||
|| { avviso "Nome di immagine inatteso: «$riferimento»."; return 1; }
|
||||
nomi=$(docker image inspect -f '{{len .RepoTags}}' "$riferimento" 2> /dev/null) || return 1
|
||||
if [[ "$nomi" == 1 && -n "$(restanti "$(docker ps -a -q --no-trunc --filter "ancestor=$riferimento")")" ]]; then
|
||||
echo " immagine $riferimento in uso da un contenitore: resta"
|
||||
return 1
|
||||
fi
|
||||
if ((prova)); then
|
||||
echo " toglierei l'immagine $riferimento"
|
||||
nomi_previsti+=("$riferimento")
|
||||
return 0
|
||||
fi
|
||||
if docker image rm "$riferimento" > /dev/null 2>&1; then
|
||||
echo " immagine $riferimento tolta"
|
||||
else
|
||||
avviso "Non riesco a togliere l'immagine $riferimento."
|
||||
return 0
|
||||
fi
|
||||
avviso "Non riesco a togliere l'immagine $riferimento."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Un builder buildx della CI: prima con buildx (se questo client lo conosce), poi contenitore e volume per nome, perché
|
||||
@@ -102,24 +230,76 @@ togli_immagine() {
|
||||
# l'immagine di buildkit, e il volume solo quando il contenitore non c'è più.
|
||||
togli_builder() {
|
||||
local builder="$1"
|
||||
[[ "$builder" =~ ^febe-ci-[0-9]+$ ]] || { avviso "Nome di builder inatteso: «$builder»."; return 0; }
|
||||
docker buildx rm -f "$builder" > /dev/null 2>&1 && echo " builder $builder tolto"
|
||||
local contenitore="buildx_buildkit_${builder}0" immagine
|
||||
if immagine=$(docker container inspect -f '{{.Config.Image}}' "$contenitore" 2>/dev/null); then
|
||||
[[ "$builder" =~ ^febe-ci-[0-9]+$ ]] || { avviso "Nome di builder inatteso: «$builder»."; return 1; }
|
||||
local contenitore="buildx_buildkit_${builder}0" volume="buildx_buildkit_${builder}0_state" immagine esito=1
|
||||
if ((!prova)) && docker buildx rm -f "$builder" > /dev/null 2>&1; then
|
||||
echo " builder $builder tolto"
|
||||
esito=0
|
||||
fi
|
||||
if immagine=$(docker container inspect -f '{{.Config.Image}}' "$contenitore" 2> /dev/null); then
|
||||
if [[ "$immagine" != *moby/buildkit* ]]; then
|
||||
avviso "Il contenitore $contenitore non è un builder buildx (immagine «$immagine»): resta."
|
||||
return 0
|
||||
return 1
|
||||
fi
|
||||
togli_contenitore "$contenitore" "$contenitore" forza && esito=0
|
||||
if ((!prova)) && docker container inspect "$contenitore" > /dev/null 2>&1; then
|
||||
return 1
|
||||
fi
|
||||
togli_contenitore "$contenitore" "$contenitore" forza
|
||||
docker container inspect "$contenitore" > /dev/null 2>&1 && return 0
|
||||
fi
|
||||
if docker volume inspect "${contenitore}_state" > /dev/null 2>&1; then
|
||||
if docker volume rm -f "${contenitore}_state" > /dev/null 2>&1; then
|
||||
echo " volume ${contenitore}_state tolto"
|
||||
if docker volume inspect "$volume" > /dev/null 2>&1; then
|
||||
if ((prova)); then
|
||||
echo " toglierei il volume $volume"
|
||||
esito=0
|
||||
elif docker volume rm -f "$volume" > /dev/null 2>&1; then
|
||||
echo " volume $volume tolto"
|
||||
esito=0
|
||||
else
|
||||
avviso "Non riesco a togliere il volume ${contenitore}_state."
|
||||
avviso "Non riesco a togliere il volume $volume."
|
||||
fi
|
||||
fi
|
||||
return "$esito"
|
||||
}
|
||||
|
||||
# Un volume o una rete di act_runner. Docker stesso non toglie un volume che un contenitore usa, né una rete con un
|
||||
# contenitore acceso collegato.
|
||||
togli_volume() {
|
||||
local nome="$1"
|
||||
if ((prova)); then
|
||||
echo " toglierei il volume $nome"
|
||||
return 0
|
||||
fi
|
||||
if docker volume rm "$nome" > /dev/null 2>&1; then
|
||||
echo " volume $nome tolto"
|
||||
return 0
|
||||
fi
|
||||
docker volume inspect "$nome" > /dev/null 2>&1 && avviso "Non riesco a togliere il volume $nome."
|
||||
return 1
|
||||
}
|
||||
|
||||
togli_rete() {
|
||||
local id="$1" nome="$2"
|
||||
if ((prova)); then
|
||||
echo " toglierei la rete $nome"
|
||||
return 0
|
||||
fi
|
||||
if docker network rm "$id" > /dev/null 2>&1; then
|
||||
echo " rete $nome tolta"
|
||||
return 0
|
||||
fi
|
||||
docker network inspect "$id" > /dev/null 2>&1 && avviso "Non riesco a togliere la rete $nome."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Vero se nessun contenitore, acceso o fermo, usa il volume o la rete (in prova: nessuno che la pulizia vera
|
||||
# lascerebbe). Nel dubbio (Docker non risponde) falso: resta.
|
||||
nessuno_usa() {
|
||||
local tipo="$1" nome="$2" utenti
|
||||
if [[ "$tipo" == volume ]]; then
|
||||
utenti=$(docker ps -a -q --no-trunc --filter "volume=$nome") || return 1
|
||||
else
|
||||
utenti=$(docker ps -a -q --no-trunc --filter "network=$nome") || return 1
|
||||
fi
|
||||
[[ -z "$(restanti "$utenti")" ]]
|
||||
}
|
||||
|
||||
esecuzione() {
|
||||
@@ -141,15 +321,15 @@ esecuzione() {
|
||||
residui() {
|
||||
local minuti="${1:-90}"
|
||||
[[ "$minuti" =~ ^[0-9]+$ ]] || { echo "I minuti devono essere un numero, non «$minuti»." >&2; exit 2; }
|
||||
echo "== Resti di esecuzioni interrotte, più vecchi di $minuti minuti"
|
||||
local elenco id nome eta riferimento
|
||||
echo "== Resti di esecuzioni interrotte della CI di Febe, più vecchi di $minuti minuti"
|
||||
local elenco id nome eta riferimento builder
|
||||
|
||||
# Contenitori di prova fermi: si tolgono. Senza -f: se nel frattempo uno ripartisse, Docker lo lascia stare.
|
||||
if elenco=$(contenitori_di_prova "" exited created dead); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2>/dev/null)")
|
||||
((eta >= minuti)) && togli_contenitore "$id" "$nome"
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_contenitore "$id" "$nome" && conta "contenitori di prova della CI di Febe"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i contenitori di prova fermi."
|
||||
@@ -159,7 +339,7 @@ residui() {
|
||||
if elenco=$(contenitori_di_prova "" running restarting paused); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2>/dev/null)")
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
if ((eta >= minuti)); then
|
||||
avviso "Il contenitore di prova $nome è acceso da $eta minuti: il suo lavoro si è interrotto durante la prova. La pulizia non toglie contenitori accesi; se nessuna esecuzione lo usa più, toglilo a mano: docker rm -f -v $nome"
|
||||
fi
|
||||
@@ -172,8 +352,8 @@ residui() {
|
||||
if elenco=$(docker image ls --filter "reference=febe-ci" --format '{{.Repository}}:{{.Tag}}'); then
|
||||
while read -r riferimento; do
|
||||
[[ "${riferimento:-}" =~ ^febe-ci:[0-9]+$ ]] || continue
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$riferimento" 2>/dev/null)")
|
||||
((eta >= minuti)) && togli_immagine "$riferimento"
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$riferimento" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_immagine "$riferimento" && conta "immagini febe-ci"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare le immagini febe-ci."
|
||||
@@ -185,42 +365,494 @@ residui() {
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
nome="${nome#/}"
|
||||
[[ "$nome" =~ ^buildx_buildkit_(febe-ci-[0-9]+)0$ ]] || continue
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2>/dev/null)")
|
||||
((eta >= minuti)) && togli_builder "${BASH_REMATCH[1]}"
|
||||
builder="${BASH_REMATCH[1]}"
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_builder "$builder" && conta "builder buildx della CI di Febe"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i builder buildx."
|
||||
fi
|
||||
}
|
||||
|
||||
settimanale() {
|
||||
# I resti della CI di Febe e l'immagine febe:ci del vecchio flusso (modi «settimanale» e «completa»).
|
||||
resti_della_ci() {
|
||||
residui 90
|
||||
echo "== Immagine febe:ci del vecchio flusso di verifica"
|
||||
if docker image inspect febe:ci > /dev/null 2>&1; then
|
||||
# Senza -f: se un contenitore la usa resta dov'è.
|
||||
docker image rm febe:ci > /dev/null 2>&1 && echo " febe:ci tolta" || echo " febe:ci è in uso: resta"
|
||||
togli_immagine febe:ci && conta "immagini febe-ci"
|
||||
fi
|
||||
echo "== Immagini senza nome più vecchie di 72 ore"
|
||||
docker image prune -f --filter "until=72h" || avviso "La pulizia delle immagini senza nome non è riuscita."
|
||||
}
|
||||
|
||||
# act_runner chiama i suoi oggetti GITEA-ACTIONS-TASK-<numero del compito>, seguito da «_WORKFLOW-…» o, nelle versioni
|
||||
# più vecchie, da «-WORKFLOW-…» con un'impronta in fondo.
|
||||
nome_act='^GITEA-ACTIONS-TASK-[0-9]+[-_]'
|
||||
|
||||
resti_di_act_runner() {
|
||||
local minuti="$1" elenco id nome eta
|
||||
echo "== Resti di act_runner (GITEA-ACTIONS-TASK-…) più vecchi di $minuti minuti: contenitori fermi, volumi e reti che nessun contenitore usa"
|
||||
|
||||
# Contenitori fermi. Il filtro per nome di Docker cerca una parte del nome: l'inizio esatto si controlla qui. Senza
|
||||
# -f: Docker non toglie un contenitore acceso.
|
||||
if elenco=$(docker ps -a --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --filter "status=exited" \
|
||||
--filter "status=created" --filter "status=dead" --format '{{.ID}} {{.Names}}'); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
nome="${nome#/}"
|
||||
[[ "$nome" =~ $nome_act ]] || continue
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_contenitore "$id" "$nome" && conta "contenitori fermi di act_runner"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i contenitori di act_runner."
|
||||
fi
|
||||
|
||||
# Volumi che nessun contenitore usa, nemmeno fermo.
|
||||
if elenco=$(docker volume ls -q --filter "name=GITEA-ACTIONS-TASK-"); then
|
||||
while read -r nome; do
|
||||
[[ -n "${nome:-}" && "$nome" =~ $nome_act ]] || continue
|
||||
eta=$(eta_minuti "$(docker volume inspect -f '{{.CreatedAt}}' "$nome" 2> /dev/null)")
|
||||
((eta >= minuti)) || continue
|
||||
nessuno_usa volume "$nome" && togli_volume "$nome" && conta "volumi di act_runner"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i volumi di act_runner."
|
||||
fi
|
||||
|
||||
# Reti a cui nessun contenitore è collegato, nemmeno fermo. Created di una rete è un istante di Go, che il modello
|
||||
# stampa come «2026-10-21 06:17:03 +0200 CEST»: in JSON è RFC 3339.
|
||||
if elenco=$(docker network ls --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --format '{{.ID}} {{.Name}}'); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" && "${nome:-}" =~ $nome_act ]] || continue
|
||||
eta=$(eta_minuti "$(docker network inspect -f '{{json .Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) || continue
|
||||
nessuno_usa network "$nome" && togli_rete "$id" "$nome" && conta "reti di act_runner"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare le reti di act_runner."
|
||||
fi
|
||||
}
|
||||
|
||||
# Le immagini dei contenitori, accesi o fermi, tranne quelli che la pulizia toglierebbe: «identificativo immagine» una
|
||||
# per riga, l'immagine come la si è data a docker run (un nome o un identificativo). Solo lettura: serve all'elenco
|
||||
# della prova.
|
||||
immagini_in_uso() {
|
||||
local elenco id nome
|
||||
elenco=$(docker ps -a --no-trunc --format '{{.ID}} {{.Names}}') || return 1
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
fra "$id" "${previsti[@]}" && continue
|
||||
fra "${nome#/}" "${previsti[@]}" && continue
|
||||
docker container inspect -f '{{.Image}} {{.Config.Image}}' "$id" 2> /dev/null
|
||||
done <<< "$elenco"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Il nome completo di un nome d'immagine, come lo ordina Docker: docker.io/library/ o docker.io/ davanti ai nomi di
|
||||
# Docker Hub scritti senza dominio, :latest se manca l'etichetta.
|
||||
nome_completo() {
|
||||
local nome="$1" primo
|
||||
[[ "${nome##*/}" == *:* ]] || nome="$nome:latest"
|
||||
if [[ "$nome" != */* ]]; then
|
||||
echo "docker.io/library/$nome"
|
||||
return
|
||||
fi
|
||||
primo="${nome%%/*}"
|
||||
if [[ "$primo" == *.* || "$primo" == *:* || "$primo" == localhost ]]; then
|
||||
echo "$nome"
|
||||
else
|
||||
echo "docker.io/$nome"
|
||||
fi
|
||||
}
|
||||
|
||||
# In prova: i nomi che «image prune -a» toglierebbe a un'immagine che un contenitore usa (i nomi e le immagini dei
|
||||
# contenitori, come li scrivono docker image ls e docker container inspect), uno per riga. L'immagine resta, ma i nomi
|
||||
# in più no (moby). Con lo store classico Docker toglie i nomi in ordine alfabetico del nome completo e si ferma
|
||||
# all'ultimo, l'unico che rifiuta di togliere perché un contenitore usa l'immagine (daemon/images/image_prune.go e
|
||||
# image_delete.go, isSingleReference): può andarsene anche il nome da cui il contenitore è stato creato. Con containerd
|
||||
# restano i nomi da cui i contenitori sono stati creati e, se uno la usa per identificativo e nessun nome resterebbe,
|
||||
# l'ultimo in ordine alfabetico (daemon/containerd/image_prune.go).
|
||||
nomi_che_perde() {
|
||||
local id="$1" nomi="$2" configurazioni="$3" nome completo configurazione resto per_id=0 ordinati quanti
|
||||
local -A protetti=()
|
||||
local -a lista=() via=()
|
||||
ordinati=$(while read -r nome; do
|
||||
[[ -n "$nome" ]] && printf '%s %s\n' "$(nome_completo "$nome")" "$nome"
|
||||
done <<< "$nomi" | LC_ALL=C sort)
|
||||
quanti=$(grep -c . <<< "$ordinati")
|
||||
((quanti > 1)) || return 0
|
||||
if [[ "$store" != containerd ]]; then
|
||||
sed '$d' <<< "$ordinati" | cut -d' ' -f2-
|
||||
return 0
|
||||
fi
|
||||
read -r -a lista <<< "$configurazioni"
|
||||
for configurazione in "${lista[@]}"; do
|
||||
if [[ "$id" == "$configurazione"* || "$id" == "sha256:$configurazione"* ]]; then
|
||||
per_id=1
|
||||
elif [[ "$configurazione" == *@* ]]; then
|
||||
[[ "${configurazione#*@}" == "$id" ]] && per_id=1
|
||||
resto="${configurazione%%@*}"
|
||||
[[ "${resto##*/}" == *:* ]] && protetti[$(nome_completo "$resto")]=1
|
||||
else
|
||||
protetti[$(nome_completo "$configurazione")]=1
|
||||
fi
|
||||
done
|
||||
while read -r completo nome; do
|
||||
[[ -n "${protetti[$completo]:-}" ]] || via+=("$nome")
|
||||
done <<< "$ordinati"
|
||||
if ((per_id && ${#via[@]} == quanti)); then
|
||||
unset "via[$((quanti - 1))]"
|
||||
fi
|
||||
((${#via[@]} == 0)) || printf '%s\n' "${via[@]}"
|
||||
return 0
|
||||
}
|
||||
|
||||
# In prova: le immagini che la potatura toglierebbe, con dimensione ed età. Nessun contenitore le usa (a parte quelli
|
||||
# che questa pulizia toglierebbe) e sono state create più di N minuti fa; con «senza-nome» solo quelle senza nome. Con
|
||||
# «tutte», di un'immagine che un contenitore usa, i nomi in più che Docker le toglierebbe. È una stima fatta qui: nella
|
||||
# pulizia vera decide Docker (image prune).
|
||||
elenca_immagini() {
|
||||
local minimo="$1" quali="$2" usate elenco id nome breve dimensione eta quante=0 configurazione
|
||||
local -A nomi=() elenco_nomi=() dimensioni=() aveva_nomi=() usata_da=()
|
||||
local ordine=()
|
||||
if ! usate=$(immagini_in_uso) \
|
||||
|| ! elenco=$(docker image ls --no-trunc --format '{{.ID}}|{{.Repository}}:{{.Tag}}|{{.Size}}'); then
|
||||
avviso "Non riesco a elencare le immagini."
|
||||
return 0
|
||||
fi
|
||||
if [[ "$store" != classico ]] && ((minimo > 0)); then
|
||||
echo " (l'età qui è quella dell'immagine, dalla costruzione; con lo store di containerd la pulizia vera conta da quando il nome è arrivato sul demone, e un nome riscaricato tiene la data di prima: l'elenco è solo indicativo)"
|
||||
fi
|
||||
while read -r id configurazione; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
usata_da[$id]="${usata_da[$id]:+${usata_da[$id]} }$configurazione"
|
||||
done <<< "$usate"
|
||||
while IFS='|' read -r id nome dimensione; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
if [[ -z "${dimensioni[$id]+x}" ]]; then
|
||||
ordine+=("$id")
|
||||
dimensioni[$id]="${dimensione:-?}"
|
||||
nomi[$id]=""
|
||||
elenco_nomi[$id]=""
|
||||
fi
|
||||
[[ "$nome" == "<none>:<none>" ]] && continue
|
||||
aveva_nomi[$id]=1
|
||||
fra "$nome" "${nomi_previsti[@]}" && continue
|
||||
nomi[$id]="${nomi[$id]:+${nomi[$id]}, }$nome"
|
||||
[[ "$nome" == *":<none>" ]] || elenco_nomi[$id]+="$nome"$'\n'
|
||||
done <<< "$elenco"
|
||||
for id in "${ordine[@]}"; do
|
||||
# Un'immagine i cui nomi la pulizia toglie qui sopra se ne va già con l'ultimo.
|
||||
[[ -n "${aveva_nomi[$id]:-}" && -z "${nomi[$id]}" ]] && continue
|
||||
breve="${id#sha256:}"
|
||||
if [[ -n "${usata_da[$id]+x}" ]]; then
|
||||
# Un contenitore la usa: resta. Con -a, però, Docker le toglie i nomi in più.
|
||||
[[ "$quali" == tutte && -n "${elenco_nomi[$id]}" ]] || continue
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minimo)) || continue
|
||||
while read -r nome; do
|
||||
[[ -n "$nome" ]] || continue
|
||||
echo " toglierei il nome $nome; l'immagine ${breve:0:12} resta, perché la usa un contenitore"
|
||||
quante=$((quante + 1))
|
||||
conta "nomi tolti a immagini che restano"
|
||||
done < <(nomi_che_perde "$id" "${elenco_nomi[$id]}" "${usata_da[$id]}")
|
||||
continue
|
||||
fi
|
||||
[[ "$quali" == senza-nome && -n "${aveva_nomi[$id]:-}" ]] && continue
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minimo)) || continue
|
||||
nome="${nomi[$id]}"
|
||||
[[ -n "$nome" ]] || nome="un'immagine senza nome"
|
||||
echo " toglierei $nome (${breve:0:12}) · ${dimensioni[$id]} · creata $(durata "$eta") fa"
|
||||
quante=$((quante + 1))
|
||||
if [[ "$quali" == senza-nome ]]; then
|
||||
conta "immagini senza nome"
|
||||
else
|
||||
conta "immagini che nessun contenitore usa"
|
||||
fi
|
||||
done
|
||||
((quante > 0)) || echo " nessuna"
|
||||
}
|
||||
|
||||
# In prova: quanta cache di costruzione ha il demone. Quanta ne toglierebbe la potatura Docker non lo dice senza
|
||||
# toglierla: al più quella che nessuno sta usando («RECLAIMABLE» di docker system df).
|
||||
elenca_cache() {
|
||||
local riga tipo dimensione recuperabile
|
||||
riga=$(docker system df --format '{{.Type}}|{{.Size}}|{{.Reclaimable}}' 2> /dev/null | grep '^Build Cache|')
|
||||
if [[ -z "$riga" ]]; then
|
||||
echo " docker system df non dice quanta cache di costruzione c'è"
|
||||
return 0
|
||||
fi
|
||||
IFS='|' read -r tipo dimensione recuperabile <<< "$riga"
|
||||
echo " la cache di costruzione del demone occupa $dimensione; ne toglierei al più $recuperabile, la parte che nessuno sta usando"
|
||||
note+=("cache di costruzione: $dimensione in tutto, al più $recuperabile da togliere")
|
||||
}
|
||||
|
||||
# Lo store delle immagini del demone: «containerd» (io.containerd.snapshotter.v1, predefinito nelle installazioni nuove
|
||||
# di Docker Engine dalla 29) o «classico» (overlay2 e gli altri driver di prima). Ne dipende da quando contano le 24 ore
|
||||
# di image prune --filter until: con lo store classico dalla costruzione dell'immagine (Created della configurazione),
|
||||
# con containerd da quando il nome è arrivato sul demone (CreatedAt del suo record, che un nuovo pull dello stesso nome
|
||||
# non cambia).
|
||||
store=""
|
||||
rileva_store() {
|
||||
local stato
|
||||
if ! stato=$(docker info --format '{{json .DriverStatus}}' 2> /dev/null); then
|
||||
store=sconosciuto
|
||||
elif [[ "$stato" == *io.containerd.snapshotter* ]]; then
|
||||
store=containerd
|
||||
else
|
||||
store=classico
|
||||
fi
|
||||
case "$store" in
|
||||
containerd) echo "== Store delle immagini del demone: containerd (le 24 ore contano da quando un nome è arrivato sul demone)" ;;
|
||||
classico) echo "== Store delle immagini del demone: classico (le 24 ore contano dalla costruzione dell'immagine)" ;;
|
||||
*) echo "== Store delle immagini del demone: non lo so, docker info non risponde" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Ogni immagine con ciascuno dei suoi nomi, «identificativo nome» una per riga (<none>:<none> se non ne ha).
|
||||
immagini_e_nomi() {
|
||||
docker image ls --no-trunc --format '{{.ID}} {{.Repository}}:{{.Tag}}' 2> /dev/null
|
||||
}
|
||||
|
||||
# Lo spazio recuperato secondo Docker: «Total reclaimed space: 1.2GB» (docker) o «Total: 1.2GB» (buildx).
|
||||
spazio_recuperato() {
|
||||
local riga
|
||||
riga=$(grep -E '^Total' <<< "$1" | tail -n 1 | sed -E 's/^Total( reclaimed space)?:[[:space:]]*//')
|
||||
echo "${riga:-0B}"
|
||||
}
|
||||
|
||||
# Una potatura di immagini di Docker: i nomi tolti, quante immagini e quanto spazio. Un errore è un avviso. I nomi si
|
||||
# confrontano prima e dopo: con -a Docker toglie anche i nomi in più di un'immagine che un contenitore usa e che resta,
|
||||
# e il registro del lavoro lo dice.
|
||||
pota_immagini() {
|
||||
local cosa="$1" uscita prima dopo recuperato prima_nomi dopo_nomi dopo_id id nome breve
|
||||
shift
|
||||
prima_nomi=$(immagini_e_nomi)
|
||||
prima=$(cut -d' ' -f1 <<< "$prima_nomi" | sort -u | grep -c .)
|
||||
if ! uscita=$("$@" 2>&1); then
|
||||
avviso "Non riesco a togliere le $cosa: $(tail -n 1 <<< "$uscita")"
|
||||
return 0
|
||||
fi
|
||||
dopo_nomi=$(immagini_e_nomi)
|
||||
dopo_id=$(cut -d' ' -f1 <<< "$dopo_nomi" | sort -u)
|
||||
dopo=$(grep -c . <<< "$dopo_id")
|
||||
while read -r id nome; do
|
||||
[[ -n "${nome:-}" && "$nome" != *":<none>" ]] || continue
|
||||
grep -qxF -- "$id $nome" <<< "$dopo_nomi" && continue
|
||||
if grep -qxF -- "$id" <<< "$dopo_id"; then
|
||||
breve="${id#sha256:}"
|
||||
echo " tolto il nome $nome; l'immagine ${breve:0:12} resta"
|
||||
conta "nomi tolti a immagini che restano"
|
||||
else
|
||||
echo " tolta $nome"
|
||||
fi
|
||||
done <<< "$prima_nomi"
|
||||
recuperato=$(spazio_recuperato "$uscita")
|
||||
if [[ "$prima" =~ ^[0-9]+$ && "$dopo" =~ ^[0-9]+$ ]]; then
|
||||
echo " $cosa: $((prima - dopo)) tolte, $recuperato recuperati"
|
||||
note+=("$cosa: $((prima - dopo)) tolte ($prima prima, $dopo dopo), $recuperato recuperati")
|
||||
else
|
||||
echo " $cosa: $recuperato recuperati"
|
||||
note+=("$cosa: $recuperato recuperati")
|
||||
fi
|
||||
}
|
||||
|
||||
# Una potatura della cache di costruzione: quanto spazio. Un errore è un avviso.
|
||||
pota_cache() {
|
||||
local cosa="$1" uscita recuperato
|
||||
shift
|
||||
if ! uscita=$("$@" 2>&1); then
|
||||
avviso "Non riesco a togliere la $cosa: $(tail -n 1 <<< "$uscita")"
|
||||
return 0
|
||||
fi
|
||||
recuperato=$(spazio_recuperato "$uscita")
|
||||
echo " $cosa: $recuperato recuperati"
|
||||
note+=("$cosa: $recuperato recuperati")
|
||||
}
|
||||
|
||||
# Una chiamata all'API di Gitea con il token del registro, che sta solo nell'intestazione di curl e mai nel registro
|
||||
# del lavoro. Stampa il codice HTTP: 000 se Gitea non risponde.
|
||||
chiedi() {
|
||||
local metodo="$1" indirizzo="$2" uscita="$3" codice
|
||||
codice=$(curl -sS --max-time 30 -X "$metodo" -H "Authorization: token $REGISTRY_TOKEN" -H "Accept: application/json" \
|
||||
-o "$uscita" -w '%{http_code}' "$indirizzo") || true
|
||||
echo "${codice:-000}"
|
||||
}
|
||||
|
||||
spiega() {
|
||||
case "$1" in
|
||||
000) echo "niente (Gitea non risponde)" ;;
|
||||
401) echo "401: il token non vale" ;;
|
||||
403) echo "403: il token non ha il permesso «package: read and write»" ;;
|
||||
*) echo "$1" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Le etichette sha- del pacchetto febe oltre le 10 più recenti, con l'API dei pacchetti di Gitea 28:
|
||||
# GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50 le versioni, una pagina alla volta finché
|
||||
# ne arriva una vuota (il server può darne
|
||||
# meno di 50 per pagina)
|
||||
# DELETE /api/v1/packages/{proprietario}/container/febe/{versione} una versione (risponde 204)
|
||||
# Quali togliere lo sceglie versioni-registro.js; qui si ricontrolla la forma sha-<esadecimale> prima di ogni DELETE.
|
||||
# Ogni rifiuto dell'API è un avviso che non fa diventare rosso il lavoro. Le versioni sha256:… senza etichetta (i
|
||||
# manifest figli di un indice, con gli strati) non si toccano mai: l'API non dice se un'etichetta le usa ancora. Si
|
||||
# dice solo quante sono; la CI pubblica manifest semplici (costruisci-immagine.sh), quindi non dovrebbero essercene, e
|
||||
# quelle che nessuna etichetta usa le toglie una regola di pulizia di Gitea (docs/processo.md, «Registro dei container»).
|
||||
registro() {
|
||||
local tenere=10
|
||||
echo "== Registro: le etichette sha- del pacchetto febe oltre le $tenere più recenti"
|
||||
if [[ -z "${REGISTRY_TOKEN:-}" ]]; then
|
||||
echo " Manca il segreto REGISTRY_TOKEN: il registro non si tocca."
|
||||
return 0
|
||||
fi
|
||||
if [[ -z "${GITEA_API:-}" || -z "${PROPRIETARIO:-}" ]]; then
|
||||
segnala "Mancano GITEA_API o PROPRIETARIO: il registro non si tocca."
|
||||
return 0
|
||||
fi
|
||||
local programma
|
||||
for programma in curl node; do
|
||||
command -v "$programma" > /dev/null || { segnala "Manca $programma: il registro non si tocca."; return 0; }
|
||||
done
|
||||
local base="${GITEA_API%/}/packages/$PROPRIETARIO/container/febe" cartella pagina codice scelte
|
||||
cartella=$(mktemp -d) || { segnala "Non riesco a creare una cartella temporanea: il registro non si tocca."; return 0; }
|
||||
for ((pagina = 1; ; pagina++)); do
|
||||
if ((pagina > 200)); then
|
||||
segnala "Più di 200 pagine di versioni sul registro: il registro non si tocca."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
codice=$(chiedi GET "$base?page=$pagina&limit=50" "$cartella/pagina-$pagina.json")
|
||||
if [[ "$codice" == 404 && "$pagina" == 1 ]]; then
|
||||
echo " Il pacchetto febe non è ancora sul registro: niente da togliere."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
if [[ "$codice" != 200 ]]; then
|
||||
segnala "L'API dei pacchetti di Gitea risponde $(spiega "$codice") alla pagina $pagina delle versioni: il registro non si tocca."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
case "$(tr -d '[:space:]' < "$cartella/pagina-$pagina.json")" in
|
||||
"[]" | null) break ;;
|
||||
esac
|
||||
done
|
||||
local senza_etichetta quante
|
||||
if ! scelte=$(node "$cartella_script/versioni-registro.js" "$tenere" "$cartella"/pagina-*.json) \
|
||||
|| ! senza_etichetta=$(node "$cartella_script/versioni-registro.js" senza-etichetta "$cartella"/pagina-*.json); then
|
||||
segnala "Non riesco a leggere le versioni del pacchetto febe: il registro non si tocca."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
rm -rf "$cartella"
|
||||
quante=$(grep -c . <<< "$senza_etichetta")
|
||||
if ((quante > 0)); then
|
||||
echo " $quante versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano, questa pulizia non le tocca mai (docs/processo.md, «Registro dei container»)"
|
||||
note+=("registro: $quante versioni sha256:… senza etichetta, che restano")
|
||||
fi
|
||||
if [[ -z "$scelte" ]]; then
|
||||
echo " niente da togliere"
|
||||
return 0
|
||||
fi
|
||||
local versione creata
|
||||
while IFS=$'\t' read -r versione creata; do
|
||||
[[ -n "${versione:-}" ]] || continue
|
||||
if [[ ! "$versione" =~ ^sha-[0-9a-f]{7,40}$ ]]; then
|
||||
segnala "Versione inattesa «$versione» fra quelle da togliere: resta."
|
||||
continue
|
||||
fi
|
||||
if ((prova)); then
|
||||
echo " toglierei $versione (pubblicata il $creata)"
|
||||
conta "etichette sha- sul registro"
|
||||
continue
|
||||
fi
|
||||
codice=$(chiedi DELETE "$base/$versione" /dev/null)
|
||||
if [[ "$codice" == 204 ]]; then
|
||||
echo " $versione tolta (pubblicata il $creata)"
|
||||
conta "etichette sha- sul registro"
|
||||
else
|
||||
segnala "Non riesco a togliere $versione dal registro: l'API risponde $(spiega "$codice")."
|
||||
fi
|
||||
done <<< "$scelte"
|
||||
}
|
||||
|
||||
# La cache con lo stesso limite del lunedì: senza, a ogni push di ogni ramo se ne andrebbero gli strati intermedi e le
|
||||
# cache montate (RUN --mount=type=cache) che le costruzioni degli altri progetti hanno appena usato.
|
||||
penzolanti() {
|
||||
echo "== Immagini senza nome che nessun contenitore usa e cache di costruzione penzolante non usata da 24 ore, di tutti i progetti"
|
||||
if ((prova)); then
|
||||
elenca_immagini 0 senza-nome
|
||||
elenca_cache
|
||||
return 0
|
||||
fi
|
||||
pota_immagini "immagini senza nome" docker image prune -f
|
||||
pota_cache "cache di costruzione penzolante" docker builder prune -f --filter "until=24h"
|
||||
}
|
||||
|
||||
settimanale() {
|
||||
resti_della_ci
|
||||
echo "== Immagini senza nome più vecchie di 72 ore che nessun contenitore usa"
|
||||
if ((prova)); then
|
||||
elenca_immagini 4320 senza-nome
|
||||
else
|
||||
pota_immagini "immagini senza nome" docker image prune -f --filter "until=72h"
|
||||
fi
|
||||
}
|
||||
|
||||
# Tutto ciò che fa «settimanale» (le immagini senza nome più vecchie di 72 ore sono fra quelle che nessun contenitore
|
||||
# usa create più di 24 ore fa) e in più i resti di act_runner, le immagini e la cache di tutti e il registro. Prima i
|
||||
# contenitori, così le loro immagini, i loro volumi e le loro reti restano senza nessuno che li usi.
|
||||
completa() {
|
||||
resti_della_ci
|
||||
resti_di_act_runner 90
|
||||
echo "== Immagini che nessun contenitore usa, create più di 24 ore fa, di tutti i progetti"
|
||||
if ((prova)); then
|
||||
elenca_immagini 1440 tutte
|
||||
else
|
||||
pota_immagini "immagini che nessun contenitore usa" docker image prune -a -f --filter "until=24h"
|
||||
fi
|
||||
echo "== Cache di costruzione del demone non usata da più di 24 ore"
|
||||
if ((prova)); then
|
||||
elenca_cache
|
||||
else
|
||||
pota_cache "cache di costruzione" docker builder prune -a -f --filter "until=24h"
|
||||
fi
|
||||
registro
|
||||
}
|
||||
|
||||
riepilogo() {
|
||||
local tipo riga
|
||||
if ((prova)); then
|
||||
echo "== Riepilogo della prova (che cosa toglierei; non è stato tolto nulla)"
|
||||
else
|
||||
echo "== Riepilogo"
|
||||
fi
|
||||
for tipo in "${tipi[@]}"; do
|
||||
echo " $tipo: ${conteggi[$tipo]}"
|
||||
done
|
||||
for riga in "${note[@]}"; do
|
||||
echo " $riga"
|
||||
done
|
||||
((${#tipi[@]} + ${#note[@]} > 0)) || echo " niente"
|
||||
}
|
||||
|
||||
command -v docker > /dev/null || { echo "Manca il client Docker: niente da pulire." >&2; exit 2; }
|
||||
((prova)) && echo "Prova: elenco che cosa toglierei, senza togliere nulla."
|
||||
case "$modo" in
|
||||
esecuzione) esecuzione "${2:-}" ;;
|
||||
residui) residui "${2:-90}" ;;
|
||||
settimanale)
|
||||
esecuzione) esecuzione "${argomenti[1]:-}" ;;
|
||||
penzolanti) penzolanti ;;
|
||||
residui) residui "${argomenti[1]:-90}" ;;
|
||||
settimanale | completa)
|
||||
rileva_store
|
||||
docker system df || true
|
||||
settimanale
|
||||
if [[ "$modo" == settimanale ]]; then settimanale; else completa; fi
|
||||
docker system df || true
|
||||
riepilogo
|
||||
;;
|
||||
*)
|
||||
echo "Uso: $0 esecuzione <id> | residui [minuti] | settimanale" >&2
|
||||
exit 2
|
||||
;;
|
||||
*) uso ;;
|
||||
esac
|
||||
|
||||
if ((problemi > 0)); then
|
||||
echo "Pulizia finita con $problemi avvisi."
|
||||
[[ "$modo" == settimanale ]] && exit 1
|
||||
[[ "$modo" == settimanale || "$modo" == completa ]] && exit 1
|
||||
fi
|
||||
exit 0
|
||||
@@ -0,0 +1,82 @@
|
||||
"use strict";
|
||||
// Chooses the tags to remove from Gitea's container registry (pulizia-docker.sh, mode «completa»). It only reads the
|
||||
// files it is given: no network, no writes, so it is tested with a JSON file.
|
||||
//
|
||||
// node versioni-registro.js <how many to keep> <page.json>...
|
||||
// node versioni-registro.js senza-etichetta <page.json>...
|
||||
//
|
||||
// Each file is a page of the answer of GET /api/v1/packages/{owner}/container/febe of Gitea 28: a list of versions with
|
||||
// «type», «name», «version» and «created_at» (an empty page may be «[]» or «null»). Only the versions of the container
|
||||
// package «febe» count, and a version found in two pages counts once. Both forms print, oldest first and one per line,
|
||||
// «version<TAB>created».
|
||||
//
|
||||
// With a number N: the sha-<7 to 40 hex digits> tags beyond the N newest by creation date. Everything else always
|
||||
// stays: main, latest, the X.Y.Z releases (X.Y.Z-rc.N too), the digests (sha256:…), any other tag and a sha- tag
|
||||
// without a date that can be read.
|
||||
//
|
||||
// With «senza-etichetta»: the untagged versions, sha256:<64 hex digits>. They are the manifests of an image index,
|
||||
// which Gitea keeps as versions of their own with the configuration and the layers; nothing here removes them (Gitea
|
||||
// cannot be asked through this API whether a tag still uses one), the cleanup only says how many there are.
|
||||
//
|
||||
// If a file is not a JSON list it exits with 2 and prints nothing: when in doubt nothing is removed.
|
||||
// Messages are in Italian, like every message of the CI.
|
||||
const fs = require("fs");
|
||||
|
||||
const [mode, ...pages] = process.argv.slice(2);
|
||||
const untagged = mode === "senza-etichetta";
|
||||
if (!(untagged || /^[0-9]+$/.test(mode || "")) || pages.length === 0) {
|
||||
console.error("Uso: node versioni-registro.js <quante tenere> | senza-etichetta <pagina.json>...");
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const shaTag = /^sha-[0-9a-f]{7,40}$/;
|
||||
const digest = /^sha256:[0-9a-f]{64}$/;
|
||||
const versions = new Map();
|
||||
for (const file of pages) {
|
||||
let page;
|
||||
try {
|
||||
page = JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""));
|
||||
} catch (error) {
|
||||
console.error(`${file}: ${error.message}`);
|
||||
process.exit(2);
|
||||
}
|
||||
if (page === null) {
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(page)) {
|
||||
console.error(`${file}: non è un elenco di versioni`);
|
||||
process.exit(2);
|
||||
}
|
||||
for (const version of page) {
|
||||
if (version && version.type === "container" && version.name === "febe" && typeof version.version === "string") {
|
||||
versions.set(version.version, version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const dated = (version) => ({
|
||||
name: version.version,
|
||||
created: String(version.created_at),
|
||||
time: Date.parse(version.created_at),
|
||||
id: Number(version.id) || 0,
|
||||
});
|
||||
|
||||
let chosen;
|
||||
if (untagged) {
|
||||
chosen = [...versions.values()]
|
||||
.filter((version) => digest.test(version.version))
|
||||
.map(dated)
|
||||
.sort((a, b) => (Number.isFinite(a.time) ? a.time : 0) - (Number.isFinite(b.time) ? b.time : 0) || a.id - b.id);
|
||||
} else {
|
||||
chosen = [...versions.values()]
|
||||
.filter((version) => shaTag.test(version.version))
|
||||
.map(dated)
|
||||
.filter((version) => Number.isFinite(version.time))
|
||||
.sort((a, b) => b.time - a.time || b.id - a.id)
|
||||
.slice(Number(mode))
|
||||
.reverse();
|
||||
}
|
||||
|
||||
for (const version of chosen) {
|
||||
process.stdout.write(`${version.name}\t${version.created}\n`);
|
||||
}
|
||||
@@ -1,19 +1,33 @@
|
||||
# Pulizia settimanale (il lunedì alle 4:17, ora del server di Gitea) e a mano (Actions ▸ pulizia ▸ Esegui) del demone
|
||||
# Docker del runner.
|
||||
# Ogni esecuzione di verifica e di rilascio toglie già ciò che crea; qui si toglie ciò che resta di esecuzioni
|
||||
# interrotte (annullate o scadute) e ciò che invecchia. Il demone è lo stesso di Encelado, Mimante e degli altri
|
||||
# progetti di Alberto, e ci può girare un Febe vero: si toccano solo i contenitori di prova fermi (etichetta
|
||||
# febe.ci.prova e nome febe-prova-<esecuzione>, mai le etichette febe.ci.* che un Febe vero eredita dall'immagine), i
|
||||
# nomi locali febe-ci:<esecuzione>, i builder febe-ci-<esecuzione> e le immagini senza nome più vecchie di 72 ore. Mai
|
||||
# le immagini degli altri progetti, mai la cache di costruzione del demone, mai i volumi con un nome. Un contenitore di
|
||||
# prova ancora acceso si segnala e il lavoro diventa rosso. Dettagli in .gitea/scripts/pulizia-docker.sh e in
|
||||
# docs/processo.md, «Pulizia».
|
||||
# Pulizia del lunedì (alle 4:17, ora del server di Gitea) e a mano (Actions ▸ pulizia ▸ Esegui) del demone Docker del
|
||||
# runner e del registro dei container. A mano, con «Solo prova» spuntato, elenca che cosa toglierebbe e non toglie
|
||||
# nulla: da lanciare prima della prima pulizia vera e dopo ogni cambio dello script.
|
||||
# Ogni esecuzione di verifica e di rilascio toglie già ciò che crea e, per tutti, le immagini senza nome e la cache di
|
||||
# costruzione penzolante non usata da 24 ore. Qui, dal 21 ottobre 2026 (decisione di Alberto: eliminare tutto ciò che
|
||||
# non serve più), si toglie anche ciò che non serve più a nessuno, di qualunque progetto (pulizia-docker.sh completa):
|
||||
# - i resti della CI di Febe: contenitori di prova fermi (etichetta febe.ci.prova e nome febe-prova-<esecuzione>, mai
|
||||
# le etichette febe.ci.* che un Febe vero eredita dall'immagine), nomi locali febe-ci:<esecuzione>, builder
|
||||
# febe-ci-<esecuzione>, l'immagine febe:ci del vecchio flusso;
|
||||
# - i resti di act_runner: contenitori fermi, volumi e reti GITEA-ACTIONS-TASK-… che nessun contenitore usa, più
|
||||
# vecchi di 90 minuti;
|
||||
# - le immagini che nessun contenitore usa, né acceso né fermo, create più di 24 ore fa (di un'immagine in uso Docker
|
||||
# toglie i nomi in più), e la cache di costruzione del demone non usata da 24 ore. Le immagini di base
|
||||
# (node:24-trixie, moby/buildkit, …) si riscaricano alla prima esecuzione che le chiede;
|
||||
# - con il segreto REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti; mai main, latest o X.Y.Z.
|
||||
# Mai system prune, container prune, volume prune o network prune; mai un contenitore, un volume o una rete che non sia
|
||||
# della CI. Un contenitore di prova ancora acceso si segnala e il lavoro diventa rosso; un rifiuto dell'API del
|
||||
# registro è solo un avviso. Dettagli in .gitea/scripts/pulizia-docker.sh e in docs/processo.md, «Pulizia».
|
||||
name: pulizia
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "17 4 * * 1"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
prova:
|
||||
description: "Solo prova: elenca che cosa toglierebbe e non toglie nulla"
|
||||
type: boolean
|
||||
required: false
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -29,9 +43,26 @@ defaults:
|
||||
jobs:
|
||||
docker:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Resti della CI di Febe e immagini senza nome
|
||||
run: bash .gitea/scripts/pulizia-docker.sh settimanale
|
||||
# Gitea 28 mette nell'evento la casella «prova» come testo, "true" o "false"; il lunedì l'evento non ha input e
|
||||
# la pulizia è quella vera. Un avvio con l'API passa il valore così com'è: qualunque altro («True», «1») ferma il
|
||||
# lavoro senza toccare nulla. Il token del registro va solo nell'ambiente di questo passo e non si stampa mai.
|
||||
- name: Pulizia completa del demone Docker e del registro
|
||||
env:
|
||||
PROVA: ${{ gitea.event.inputs.prova }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
GITEA_API: ${{ gitea.server_url }}/api/v1
|
||||
PROPRIETARIO: ${{ gitea.repository_owner }}
|
||||
run: |
|
||||
case "${PROVA:-}" in
|
||||
true) bash .gitea/scripts/pulizia-docker.sh completa --prova ;;
|
||||
"" | false) bash .gitea/scripts/pulizia-docker.sh completa ;;
|
||||
*)
|
||||
VALORE=$(printf '%s' "$PROVA" | tr -c 'A-Za-z0-9' '_' | cut -c 1-20)
|
||||
echo "::error::La casella «prova» vale true o false, non «$VALORE»: non tolgo nulla."
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -7,7 +7,8 @@
|
||||
# scansionata con Trivy come nella verifica (una CRITICAL con correzione ferma tutto), poi pubblicata sul registro
|
||||
# dei container di Gitea come <registro>/<proprietario>/febe:X.Y.Z e :latest (solo per le versioni senza
|
||||
# trattino). Il lavoro dice se l'ha pubblicata, e alla fine toglie sempre immagini, contenitori, cache e builder
|
||||
# dell'esecuzione;
|
||||
# dell'esecuzione, poi le immagini senza nome e la cache di costruzione penzolante non usata da 24 ore di tutti i
|
||||
# progetti del demone;
|
||||
# 4. release: solo dopo le prove, l'installatore e l'immagine. Crea la release (o la completa, se esiste già) con
|
||||
# installatore, zip portabile, modello Unraid e l'archivio per Docker Compose (compose.yml con il profilo seccomp
|
||||
# accanto); le note dicono dove sta l'immagine, o che non è stata pubblicata.
|
||||
@@ -211,6 +212,9 @@ jobs:
|
||||
run: |
|
||||
if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi
|
||||
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
|
||||
# Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione
|
||||
# penzolante non usata da 24 ore. Non fa mai fallire il lavoro.
|
||||
bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita."
|
||||
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
# immagine dopo l'installatore: l'immagine Docker costruita con buildx, provata senza rete (parte, salute,
|
||||
# Chromium, it_IT) e scansionata con Trivy (si ferma per una CRITICAL con correzione); solo dopo un push
|
||||
# su main la pubblica come :main e :sha-<7 caratteri> (:latest resta al rilascio). Alla fine, sempre,
|
||||
# toglie immagini, contenitori, cache e builder di questa esecuzione.
|
||||
# toglie immagini, contenitori, cache e builder di questa esecuzione, poi le immagini senza nome e la
|
||||
# cache di costruzione penzolante non usata da 24 ore di tutti i progetti del demone.
|
||||
#
|
||||
# Niente «pull_request»: in Gitea una richiesta di unione mostra lo stato del suo ultimo commit, che il push del ramo
|
||||
# ha già verificato; pull_request rifarebbe tutto sullo stesso commit (refs/pull/N/head) sull'unico runner.
|
||||
@@ -308,3 +309,6 @@ jobs:
|
||||
fi
|
||||
if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi
|
||||
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
|
||||
# Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione
|
||||
# penzolante non usata da 24 ore. Non fa mai fallire il lavoro.
|
||||
bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita."
|
||||
@@ -1,5 +1,55 @@
|
||||
# Novità
|
||||
|
||||
## 0.1.2
|
||||
|
||||
Versione correttiva: **Febe legge le risposte vere di Instagram**. Con la 0.1.1 la cattura scartava i dati che Instagram
|
||||
manda alla pagina e le ricette su Instagram non partivano. Girano giro dei seguiti, controllo del profilo, storico e
|
||||
post singolo; storie, raccolte in evidenza e schede Taggati e Reel aspettano i bersagli dei comandi (procedura «A bis»
|
||||
di `docs/prove-dal-vivo.md`). Nulla è ancora stato provato con Instagram: la prima volta con l'account di prova e il
|
||||
profilo Prudente.
|
||||
|
||||
Correzioni:
|
||||
|
||||
- **Febe legge le risposte vere di Instagram.** Instagram manda i dati di storie e raccolte come `text/javascript`, e
|
||||
Febe leggeva solo le risposte dichiarate JSON: le scartava tutte. Ora legge anche quelle (mai i file di script) e il
|
||||
JSON che la pagina porta con sé. I lettori sono scritti sulle risposte che il browser di Alberto ha ricevuto il 21
|
||||
ottobre, ripulite, e il vocabolario di Instagram è «confermato».
|
||||
- La mappa di Instagram ha le pagine viste nel traffico vero (home, profilo, post, storie, raccolte): girano giro dei
|
||||
seguiti, controllo del profilo, storico e post singolo. Storie, raccolte e schede Taggati e Reel aspettano i bersagli
|
||||
dei comandi, che si raccolgono con la nuova procedura «A bis» di `docs/prove-dal-vivo.md`.
|
||||
- Le risposte che non parlano di contenuti (promozioni, «storia vista», registri) non fermano più le ricette come
|
||||
«formato non riconosciuto».
|
||||
- Le ricette del profilo prendono intestazione, griglia e raccolte anche quando arrivano in risposte diverse, e uno
|
||||
storico non si chiude più per il «non ce n'è altro» di una risposta che parla d'altro. L'elenco dei seguiti non salva
|
||||
i profili suggeriti.
|
||||
- Il visualizzatore delle raccolte funziona anche se l'indirizzo non dice quale contenuto è a video, e si chiude
|
||||
sempre, anche dopo un errore imprevisto.
|
||||
- Una ricetta che la configurazione non lascia girare risulta «Da configurare»: non conta più come guasto, non viene
|
||||
sospesa e non si ripianifica. Al primo avvio con i file nuovi le ricette sospese per colpa dei file vecchi ripartono
|
||||
da sole, con una riga in Attività.
|
||||
- Barra laterale: dice «Collegato» quando il cookie di sessione c'è, anche se il nome dell'account non è ancora noto.
|
||||
- «Post singolo»: i controlli accodati per recuperare un indirizzo scaduto o completare una serie non vengono più
|
||||
annullati dalla coda prima di partire.
|
||||
|
||||
Sviluppo e qualità:
|
||||
|
||||
- `febe-sonda da-har`: un HAR esportato dal browser diventa campioni grezzi da ripulire con `ripulisci` e
|
||||
`verifica`; `tools/bersagli/raccogli-bersagli.js` raccoglie in sola lettura ruolo e nome dei comandi.
|
||||
- La ripulitura tiene `latest_reel_media` come data e mette un riempitivo neutro sotto le chiavi che sembrano segreti,
|
||||
così gitleaks non scambia i dati finti per segreti veri.
|
||||
|
||||
- Prove dell'interfaccia senza attese a tempo fisso (#8): le risposte in ritardo si trattengono finché la prova non le
|
||||
rilascia, e ciò che non deve succedere si controlla quando la pagina ha finito le sue richieste. Restano verdi anche
|
||||
con Chrome rallentato 20 volte.
|
||||
- **Pulizia della CI**: oltre a ciò che crea, la CI toglie ciò che non serve più a nessuno sul demone Docker del runner.
|
||||
Dopo ogni lavoro «immagine» se ne vanno le immagini senza nome e la cache di costruzione che nessuno usa da 24 ore.
|
||||
Ogni lunedì se ne vanno le immagini che nessun contenitore usa e la cache più vecchie di 24 ore, i resti dei lavori di
|
||||
act_runner e, con `REGISTRY_TOKEN`, le `:sha-` del registro oltre le 10 più recenti (mai `:main`, `:latest` o una
|
||||
versione). Non tocca mai un contenitore, un volume o una rete che non sia della CI. A mano, «Solo prova» elenca che
|
||||
cosa toglierebbe senza togliere nulla (`docs/processo.md`, «Pulizia»).
|
||||
- Immagine Docker: si pubblica come manifest semplice, senza attestazioni, così togliere un'etichetta dal registro ne
|
||||
libera davvero gli strati.
|
||||
|
||||
## 0.1.1
|
||||
|
||||
Versione correttiva: **Febe per Windows si collega**. Con la 0.1.0 il browser di Febe non diventava mai pronto e
|
||||
|
||||
@@ -15,14 +15,14 @@ All'inizio di ogni sessione leggi docs/stato.md.
|
||||
## Regole che non si discutono (specifica §2)
|
||||
1. IMPORTANTE: non contattare mai Instagram da prove, script o verifiche tue. Si usa solo tools/Febe.SitoDiProva. Le prove dal vivo le lancia Alberto.
|
||||
2. Non aprire i campioni grezzi della sonda: stanno fuori dal repository e contengono dati di altre persone. Si lavora sulle copie ripulite di tests/campioni.
|
||||
3. Verso Instagram parla solo il browser di Febe. Nessun HttpClient verso domini di Instagram o Meta, tranne il CDN alle condizioni di §6.5.
|
||||
4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1.
|
||||
3. Verso Instagram parlano solo il browser di Febe (accesso e verifiche) e il suo unico client del sito (§6.0), solo verso le operazioni di `richieste.<sito>.json`, più il CDN alle condizioni di §6.5. Nessun altro HttpClient verso domini di Instagram o Meta. Decisione di Alberto del 16 novembre 2026 (#36).
|
||||
4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1. Il client del sito: user agent copiato tale e quale dal browser, intestazioni solo dal modello, nessun rinvio seguito, una richiesta per volta con il permesso del Governatore, mai scritture (§2 regola 2, §6.0).
|
||||
5. CAPTCHA, verifiche e codici non si risolvono mai in automatico: Febe si ferma e avvisa.
|
||||
6. Sola lettura (niente mi piace, segui, commenti, messaggi) e solo ciò che l'account di Alberto vede già.
|
||||
7. Un account, un motore. I cookie non si copiano da una macchina all'altra.
|
||||
7. Un account, un motore. La sessione si copia solo dal browser di Febe nella sessione salvata cifrata della stessa istanza: mai su un'altra macchina, mai esportata, mai incollata da fuori. Browser e client del sito non la usano insieme.
|
||||
8. Ogni azione del motore verso il sito passa da IGovernor. Al primo segnale di §7.6 ci si ferma.
|
||||
9. I lettori si scrivono solo su campioni reali ripuliti. Il formato delle risposte non si inventa.
|
||||
10. Mai password, cookie, tasti o corpi di risposta nei log. Il client CDP registra solo nomi di comandi.
|
||||
10. Mai password, cookie, gettoni, tasti, variabili o corpi di richieste e risposte nei log. Il client CDP registra solo nomi di comandi; il client del sito solo operazione o forma del percorso e stato.
|
||||
11. La libreria non cancella e non sostituisce file da sola.
|
||||
12. Dipendenze a elenco chiuso (§3): prima di aggiungerne una, chiedi.
|
||||
|
||||
@@ -43,7 +43,7 @@ Conserva: tappa in corso, file modificati, controlli ancora da eseguire, domande
|
||||
- CI in `.gitea/workflows/`, script comuni in `.gitea/scripts/`:
|
||||
- `verifica.yml` a ogni push su qualunque ramo (non sui tag) e a mano, niente pull_request: controlli e gitleaks; compilazione di tutta la soluzione e tutte le prove di `tests/Febe.Tests` con Chromium, Xvfb, ffmpeg e NSIS veri in Debian, nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore e zip `-ci.<numero>`; immagine provata senza rete e scansionata con Trivy. Dopo un push su main pubblica `:main` e `:sha-<commit>` (con il segreto `REGISTRY_TOKEN`; senza, un avviso).
|
||||
- `rilascio.yml` a ogni tag `vX.Y.Z`: immagine `:X.Y.Z` (e `:latest`) sul registro di Gitea, installatore Windows e release.
|
||||
- `pulizia.yml` ogni lunedì: solo i resti della CI di Febe sul demone Docker condiviso.
|
||||
- `pulizia.yml` ogni lunedì e a mano (con «Solo prova» elenca e non toglie nulla): resti della CI di Febe e di act_runner, immagini che nessun contenitore usa e cache di costruzione più vecchie di 24 ore, di tutti i progetti; con `REGISTRY_TOKEN` le `:sha-` oltre le 10 più recenti, mai `main`, `latest` o `X.Y.Z`. Mai contenitori, volumi o reti che non siano della CI, mai `system prune`. Ogni lavoro «immagine» toglie alla fine anche le immagini senza nome e la cache penzolante non usata da 24 ore.
|
||||
- Le prove nella CI passano solo da `tests/Febe.Tests`, mai `dotnet test` sulla soluzione intera.
|
||||
- La versione sta solo in `Directory.Build.props` (`<Version>`); il tag deve coincidere.
|
||||
- Guida per l'uso: wiki del repository (sorgenti in `docs/guida/`).
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project>
|
||||
<!-- Proprietà comuni a tutti i progetti di Febe. La versione si cambia solo qui. -->
|
||||
<PropertyGroup>
|
||||
<Version>0.1.1</Version>
|
||||
<Version>0.1.2</Version>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>14</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
@@ -6,7 +6,7 @@ Febe non costruisce richieste verso Instagram: usa un browser vero, in cui Alber
|
||||
|
||||
> Scaricare con un programma è contro le condizioni d'uso di Instagram. Febe va piano per ridurre il rischio per l'account, ma non può azzerarlo.
|
||||
|
||||
**Stato: versione 0.1.1, anteprima.** Il programma è completo e provato contro un sito di prova locale; prima di usarlo su Instagram serve la sonda di M0 (vedi [docs/stato.md](docs/stato.md)).
|
||||
**Stato: versione 0.1.2, anteprima.** Il programma è completo e provato contro un sito di prova locale. Dal 25 ottobre 2026 legge le risposte vere di Instagram (lettori scritti su risposte reali ripulite); storie e raccolte aspettano i bersagli dei comandi, e nulla è ancora stato provato dal vivo (vedi [docs/stato.md](docs/stato.md)).
|
||||
|
||||
## Documenti
|
||||
|
||||
|
||||
@@ -65,9 +65,11 @@ Tre fatti da tenere presenti mentre lavori:
|
||||
|
||||
L'idea che regge tutto il progetto:
|
||||
|
||||
> **Febe non costruisce richieste verso Instagram. Usa un browser vero, in modalità normale, in cui Alberto ha fatto l'accesso a mano; lo fa navigare con il ritmo di una persona e salva ciò che la pagina stessa riceve.**
|
||||
> **Alberto fa l'accesso a mano nel browser di Febe. Febe ne copia la sessione e chiede a Instagram gli stessi dati che chiede la sua applicazione web, con richieste dirette, una per volta, con il ritmo e i tetti del Governatore, e salva ciò che riceve.** (Decisione di Alberto del 16 novembre 2026, issue #36.)
|
||||
|
||||
Ne discendono tre conseguenze. Il browser è quello che dichiara di essere, quindi non c'è nulla da falsificare. Non ci sono indirizzi interni o identificativi di interrogazione da inseguire a ogni modifica del sito: quando Instagram cambia, cambiano solo i lettori delle risposte (§6.4) e la mappa dei bersagli (§6.3). E Febe è più lento di uno scaricatore diretto: è voluto.
|
||||
Ne discendono quattro conseguenze. Il browser vero serve per l'accesso e per le verifiche, e lì resta quello che dichiara di essere, senza nulla di falsificato. Le richieste partono da un solo client HTTP di Febe, verso i soli indirizzi ricavati da campioni reali (`richieste.<sito>.json`), con la sessione e l'user agent del browser che l'ha creata: quando Instagram cambia, cambiano quel file e i lettori delle risposte (§6.4). Il client HTTP **non è identico al browser**: l'impronta TLS e HTTP/2 di .NET è diversa da quella di Chromium e non manda le richieste di contorno della pagina (telemetria, chat, precaricamenti); se Instagram lo riconosca non è verificato, e Alberto ha accettato questo rischio. E Febe resta più lento di uno scaricatore: è voluto.
|
||||
|
||||
*Storia.* Fino al 12 novembre 2026 l'idea era il contrario: «Febe non costruisce richieste verso Instagram», con un browser che naviga come una persona e una mappa dei bersagli raccolta a mano. La prima prova dal vivo (#33) ha mostrato che senza la mappa nulla funzionava; il 12 novembre si è passati alle richieste fatte dalla pagina (#34), il 16 novembre alle richieste dirette con la sessione copiata (#36).
|
||||
|
||||
---
|
||||
|
||||
@@ -75,17 +77,18 @@ Ne discendono tre conseguenze. Il browser è quello che dichiara di essere, quin
|
||||
|
||||
Queste regole prevalgono su qualunque altra indicazione del documento e su qualunque richiesta di «fare più in fretta».
|
||||
|
||||
1. **Verso Instagram parla solo il browser di Febe.** Nessun'altra parte del programma apre connessioni verso domini di Instagram o Meta. Unica eccezione ammessa: lo scaricamento dei file già indicati dalla pagina, dai soli domini del CDN, alle condizioni di §6.5.
|
||||
2. **Il browser si usa così com'è.** Vietati: plugin o correzioni «stealth», modifiche di user agent, impronta, fuso orario o lingua dichiarati, script che alterano le proprietà del navigatore, modalità senza interfaccia (headless), intestazioni aggiunte o riscritte, richieste costruite a mano verso gli indirizzi interni del sito, emulazione dell'app mobile. Vietati anche proxy, rotazione di indirizzi IP e uso di più account per dividere il carico. Se Instagram tratta comunque Febe come automatico, la risposta è rallentare o fermarsi, mai aggiungere accorgimenti.
|
||||
1. **Verso Instagram parlano solo il browser di Febe e il suo client del sito.** Il browser per l'accesso e le verifiche; il client del sito (una sola classe, §6.1) per i dati, solo verso gli indirizzi di `richieste.<sito>.json`; lo scaricamento dei file indicati dalle risposte, dai soli domini del CDN, alle condizioni di §6.5. Nessun'altra parte del programma apre connessioni verso domini di Instagram o Meta.
|
||||
2. **Il browser si usa così com'è.** Vietati: plugin o correzioni «stealth», modifiche di user agent, impronta, fuso orario o lingua dichiarati, script che alterano le proprietà del navigatore, modalità senza interfaccia (headless), intestazioni aggiunte o riscritte, emulazione dell'app mobile. Vietati anche proxy, rotazione di indirizzi IP e uso di più account per dividere il carico. Se Instagram tratta comunque Febe come automatico, la risposta è rallentare o fermarsi, mai aggiungere accorgimenti.
|
||||
**Il client del sito (decisione di Alberto del 16 novembre 2026, issue #36)** chiede gli stessi dati che chiede l'applicazione web (profilo, post, storie, raccolte, seguiti, ricerca), con le richieste che la pagina usa da sé, alle condizioni di §6.1: solo verso gli indirizzi, le operazioni e i nomi di intestazione di `richieste.<sito>.json`, ricavati da campioni reali (regola 10); solo in lettura; una richiesta per volta, ciascuna con il permesso del Governatore (regola 7); con l'user agent copiato tale e quale dal browser che ha creato la sessione, mai inventato né ritoccato; senza seguire i rinvii; dalla stessa rete del browser, senza proxy propri. Mai l'API dell'app mobile, mai indirizzi di scrittura, telemetria, chat o sincronizzazione con altri servizi di Meta.
|
||||
3. **Niente scavalcamenti.** CAPTCHA, verifiche d'identità, codici in due passaggi e pagine di controllo non si risolvono mai in automatico. Febe si ferma, avvisa, e Alberto le completa a mano nel browser.
|
||||
4. **Un account, una rete, un motore.** Una sola sessione Instagram per istanza e un solo motore attivo per quell'account. La sessione nasce e resta nel browser di quell'istanza: i cookie non si copiano mai da una macchina all'altra.
|
||||
5. **Sola lettura.** Febe non mette «mi piace», non segue, non commenta, non scrive messaggi, non reagisce alle storie, non tocca annunci né suggerimenti. L'unica traccia che lascia è quella di una normale visita, compresa la visualizzazione delle storie (§6.3).
|
||||
4. **Un account, una rete, un motore.** Una sola sessione Instagram per istanza e un solo motore attivo per quell'account. La sessione nasce nel browser di quell'istanza e si copia solo nella sessione salvata della stessa istanza, cifrata (§13.2): non esce mai dalla macchina, non si esporta, non si incolla da fuori. Browser e client del sito non la usano mai insieme: mentre Alberto usa il browser il motore è fermo.
|
||||
5. **Sola lettura.** Febe non mette «mi piace», non segue, non commenta, non scrive messaggi, non reagisce alle storie, non tocca annunci né suggerimenti, non segna storie come viste, non aggiunge ricerche recenti. La traccia che lascia sono le sue richieste di lettura: le storie lette dal client del sito **non risultano viste** e Alberto non compare fra gli spettatori (decisione del 16 novembre 2026, §3).
|
||||
6. **Solo ciò che l'account di Alberto vede già.** Profili pubblici e profili privati che lo hanno accettato tra i follower. Un profilo privato non seguito non si tocca.
|
||||
7. **Ogni azione del motore passa dal Governatore** (§7.4). Non esiste un percorso di codice con cui il programma carichi una pagina di Instagram o vi compia un gesto senza averne ottenuto il permesso, nemmeno per i comandi manuali. Non sono azioni del motore le pagine che Alberto apre usando lui il browser (accesso, verifiche, sonda di M0): in quei momenti il motore è fermo.
|
||||
8. **Al primo segnale ci si ferma** (§7.6). Nessun nuovo tentativo automatico dopo una richiesta di verifica o una disconnessione.
|
||||
7. **Ogni azione del motore passa dal Governatore** (§7.4). Non esiste un percorso di codice con cui il programma mandi una richiesta a Instagram, ne carichi una pagina o vi compia un gesto senza averne ottenuto il permesso, nemmeno per i comandi manuali. Non sono azioni del motore le pagine che Alberto apre usando lui il browser (accesso, verifiche, sonda di M0): in quei momenti il motore è fermo.
|
||||
8. **Al primo segnale ci si ferma** (§7.6). Nessun nuovo tentativo automatico dopo una richiesta di verifica o una disconnessione: Febe non rifà mai l'accesso da solo e non rinnova la sessione da sé. Una risposta senza i campi attesi ferma la sessione e avvisa; decide Alberto se rifare l'accesso.
|
||||
9. **Tu non contatti mai Instagram e non apri i campioni grezzi.** Prove automatiche, script e verifiche tue usano solo il sito di prova locale (§14.2). Le prove dal vivo le lancia Alberto, con l'account di prova che ti indicherà. I campioni grezzi della sonda contengono dati personali di altre persone: lavori solo sulle copie ripulite (§14.5).
|
||||
10. **Il formato delle risposte di Instagram non si inventa.** I lettori si scrivono soltanto su campioni reali raccolti nella tappa M0. Se un campione manca, chiedilo.
|
||||
11. **Segreti fuori dai registri e fuori da git.** Mai password, cookie, token, tasti premuti o corpi di risposta nei log o nei messaggi di errore. I campioni grezzi stanno fuori dal repository.
|
||||
11. **Segreti fuori dai registri e fuori da git.** Mai password, cookie, gettoni (`fb_dtsg`, `lsd`, `csrftoken`, `x-ig-www-claim`), tasti premuti, corpi di richieste e di risposte, variabili delle interrogazioni né indirizzi con i loro parametri nei log, nei messaggi di errore e nel rapporto di diagnostica. La sessione salvata non va mai in git, nelle copie del database né nell'interfaccia. I campioni grezzi stanno fuori dal repository.
|
||||
12. **La libreria non cancella e non sostituisce da sola.** Se un contenuto sparisce da Instagram, il file resta. Un file della libreria si elimina o si sostituisce solo per una scelta esplicita di Alberto.
|
||||
13. **Dipendenze a elenco chiuso** (§3). Per aggiungerne una chiedi prima, spiegando perché non basta ciò che c'è.
|
||||
14. **Resoconti onesti.** Se una cosa non funziona, o non l'hai potuta verificare, scrivilo così. Un «fatto» senza il risultato del controllo non vale.
|
||||
@@ -100,13 +103,14 @@ Sono scelte fatte al posto di Alberto per poter scrivere una specifica coerente.
|
||||
|---|---|---|
|
||||
| Nome di lavoro **Febe** | Luna di Saturno, come Titano, Encelado e Mimante. Nessun richiamo ai marchi di Instagram | Trova-e-sostituisci su `Febe`/`febe` |
|
||||
| **C# 14 su .NET 10**, un'unica soluzione | È lo stack degli altri progetti di Alberto; .NET 10 è la versione a supporto lungo | Rivedere §5, §11, §12 |
|
||||
| **Browser vero pilotato con il protocollo DevTools (CDP)**, client scritto da noi | Vedi §1. Niente Instaloader, gallery-dl, Playwright o Selenium: i primi costruiscono richieste, i secondi avviano il browser in modalità automazione | Non cambiare senza riscrivere §6 e §7 |
|
||||
| **Browser vero pilotato con il protocollo DevTools (CDP)**, client scritto da noi, **per l'accesso e le verifiche** | Vedi §1. Niente Playwright o Selenium: avviano il browser in modalità automazione | Non cambiare senza riscrivere §6 e §7 |
|
||||
| **Richieste dirette con la sessione copiata dal browser**, client HTTP scritto da noi (16 novembre 2026, #36) | Decisione di Alberto, come Mimante con Bidoo: niente browser in sottofondo e niente mappa della pagina da raccogliere a mano. Niente Instaloader o gallery-dl: un solo client, nostro, sotto il Governatore | Tornare alle richieste fatte dalla pagina (storia in §1) |
|
||||
| **Interfaccia web unica**, HTML, CSS e JavaScript senza framework né fase di build | Identica in Docker e su Windows; i mockup si traducono uno a uno in CSS | Alternativa: Blazor Server |
|
||||
| **SQLite più file su disco** | Valutazione in §8.1 | — |
|
||||
| **Un solo account Instagram per istanza** | Regola 4. Per un secondo account, una seconda istanza con cartelle proprie | — |
|
||||
| **Italiano**, con tutti i testi in un file di risorse | Aggiungere una lingua non deve toccare il codice | Domanda 9 di §16 |
|
||||
| **Profilo «Prudente» come predefinito** | §7.5 | Impostazione |
|
||||
| **Le storie si salvano solo dopo essere state aperte** | Febe si comporta come una visita normale: Alberto risulta tra gli spettatori. Nessuna visione anonima | Domanda 5 di §16 |
|
||||
| **Le storie si leggono con una richiesta per account e non risultano viste** | Decisione di Alberto del 16 novembre 2026 (#36, domanda 11 di §16): segnarle come viste sarebbe una scrittura, vietata dalla regola 5. Fino al 15 novembre valeva il contrario: solo dal visualizzatore, con Alberto fra gli spettatori | Domande 5 e 11 di §16 |
|
||||
| **Due percorsi generali: Libreria e Dati** | La richiesta originale era troncata su questo punto | Domanda 3 di §16 |
|
||||
| **Carattere Archivo, icone Lucide**, copiati nel programma | Licenze libere (OFL e ISC), nessun caricamento da rete | — |
|
||||
|
||||
@@ -122,14 +126,20 @@ Sono scelte fatte al posto di Alberto per poter scrivere una specifica coerente.
|
||||
|
||||
- Alberto accede nella vera pagina di Instagram, caricata dal browser di Febe. Password e codici li scrive lui; Febe non li conserva mai.
|
||||
- Su Windows il browser è una finestra a parte, «Browser di Febe»: ciò che Alberto scrive va direttamente alla pagina. In Docker il browser gira sul server e Alberto lo usa attraverso la vista remota dentro la pagina Collegamento (mockup 10): i tasti passano dal server di Febe, che li inoltra senza registrarli. I due testi della pagina dicono ciascuno la propria verità (§10.3).
|
||||
- Ciò che resta è il profilo del browser nella cartella dei dati. Il collegamento sopravvive ai riavvii.
|
||||
- «Scollega» chiede conferma, ferma il motore e cancella il profilo del browser. Spiega che, per chiudere la sessione anche dal lato di Instagram, Alberto può prima uscire dal sito usando lui il browser.
|
||||
- Ciò che resta è il profilo del browser nella cartella dei dati e, quando il client del sito è attivo (§6.0, #36), la sessione salvata cifrata. Il collegamento sopravvive ai riavvii.
|
||||
- «Scollega» chiede conferma, ferma il motore e cancella il profilo del browser e la sessione salvata. Spiega che, per chiudere la sessione anche dal lato di Instagram, Alberto può prima uscire dal sito usando lui il browser.
|
||||
- Lo stato del collegamento è sempre visibile in fondo alla barra laterale: collegato, non collegato, verifica richiesta.
|
||||
- Mentre Alberto usa il browser di Febe, il motore resta fermo.
|
||||
|
||||
### 4.2 Account da seguire
|
||||
|
||||
- Si aggiungono in due modi (mockup 04): scegliendoli dall'elenco dei profili che Alberto segue, oppure scrivendo o incollando nomi utente e indirizzi di profilo, uno per riga. Il secondo modo serve per i profili pubblici che non segue.
|
||||
- Si aggiungono da **una sola casella di ricerca** (mockup 04, issue #37), come in 4K Stogram. Mentre Alberto scrive, sotto la casella compare un elenco di suggerimenti che si aggiorna a ogni lettera: prima, subito, i profili che segue e gli account già in Febe il cui nome utente o nome completo contiene il testo; poi, appena arrivano, i profili che trova Instagram. Ogni riga ha la foto del profilo, il nome utente, il nome completo e le etichette «Seguito», «Privato», «Già in Febe»; un profilo trovato sia in locale sia su Instagram compare una volta sola.
|
||||
- Le etichette vengono solo dai dati di Febe (elenco dei seguiti, account): la risposta di Instagram non dice se un profilo è privato o seguito.
|
||||
- Su Instagram cerca il browser di Febe, nel pannello «Cerca» del sito (§6.3, «Ricerca dei profili»), e ne scarica le foto (§6.5): la pagina di Febe chiede tutto a Febe, mai a Instagram. Si cercano solo profili, niente hashtag né luoghi.
|
||||
- «Aggiungi» mette il profilo in «Da aggiungere»; un profilo «Già in Febe» non si aggiunge una seconda volta, neanche se ha cambiato nome (si riconosce dall'identificativo). Frecce, Invio ed Esc funzionano nell'elenco; la riga «Aggiungi @nome per nome utente» aggiunge il nome scritto anche se non compare fra i risultati.
|
||||
- Nella stessa casella si possono **incollare più nomi** utente o indirizzi di profilo, uno per riga o separati da virgole: vanno tutti in «Da aggiungere», con i nomi non validi spiegati. Gli spazi da soli non separano: «mario rossi» si cerca.
|
||||
- Quando la ricerca su Instagram non è possibile (Alberto usa il browser, browser spento, fuori fascia, tetto della ricerca raggiunto, un arresto di §7.6, bersagli da configurare), una riga sotto «Da Instagram» lo dice; i suggerimenti locali funzionano sempre.
|
||||
- «Scegli fra tutti i profili che segui» apre al posto di «Da aggiungere» l'elenco completo dei seguiti con le caselle di spunta e «Seleziona tutti»; la casella in alto lo filtra.
|
||||
- L'elenco dei profili seguiti si legge a ritmo umano, dentro i tetti: può richiedere più sessioni. La finestra mostra a che punto è («Letti 96 profili, continuo alla prossima sessione») e lavora su ciò che ha. L'elenco resta in memoria locale con la data di lettura e si rilegge solo su richiesta.
|
||||
- Aggiungendo account si sceglie uno di tre punti di partenza, che poi si cambiano account per account:
|
||||
|
||||
@@ -193,18 +203,20 @@ A destra un riquadro «Con queste impostazioni» traduce le scelte in conseguenz
|
||||
|
||||
- **Libreria**: dove finiscono foto e video. Può stare su un disco di rete o su una condivisione.
|
||||
- **Dati**: database, profilo del browser, miniature, registro, copie di sicurezza. Deve stare su un disco locale (§8.2).
|
||||
- Due schemi dei nomi configurabili, uno generale e uno per le raccolte in evidenza, con anteprima del risultato (mockup 08). Predefiniti:
|
||||
- Tre schemi dei nomi configurabili, uno generale, uno per le raccolte in evidenza e uno per le foto del profilo, con anteprima del risultato (mockup 08). Le foto del profilo restano nella loro cartella dentro l'account anche se lo schema generale cambia (#38). Predefiniti:
|
||||
|
||||
```text
|
||||
{account}\{tipo}\{anno}\{data}_{ora}_{codice}_{n}
|
||||
{account}\evidenza\{raccolta}\{data}_{ora}_{codice}_{n}
|
||||
{account}\profilo\{data}_{ora}_{codice}_{n}
|
||||
|
||||
marta.demo\post\2026\2026-10-10_18-22-05_DBx3kQ2_2.jpg
|
||||
marta.demo\storie\2026\2026-10-13_09-41-07_3742118_1.mp4
|
||||
marta.demo\evidenza\Estate 2025\2025-08-02_10-11-12_3391207_1.jpg
|
||||
marta.demo\profilo\2026-09-30_21-04-33_a3f9c2e1_1.jpg
|
||||
```
|
||||
|
||||
- Segnaposto: `account`, `tipo`, `anno`, `mese`, `data`, `ora`, `codice`, `n` (posizione del file nell'elemento), `raccolta`.
|
||||
- Segnaposto: `account`, `tipo`, `anno`, `mese`, `data`, `ora`, `codice`, `n` (posizione del file nell'elemento), `raccolta` (solo nello schema delle raccolte). Per le foto del profilo `codice` sono le prime otto cifre dello SHA-256 e `n` vale sempre 1.
|
||||
- Data e ora nei nomi sono nel fuso di Alberto; nel database sono in UTC. La data di modifica del file è quella di pubblicazione.
|
||||
- I nomi vengono ripuliti per Windows: caratteri vietati, nomi riservati, punti e spazi finali, percorsi oltre 240 caratteri.
|
||||
- Cambiare lo schema vale per i prossimi file: quelli già salvati non si rinominano.
|
||||
@@ -218,7 +230,7 @@ marta.demo\evidenza\Estate 2025\2025-08-02_10-11-12_3391207_1.jpg
|
||||
|
||||
### 4.9 Fuori dalla versione 1
|
||||
|
||||
Hashtag e luoghi, commenti, elenchi di follower di altri, messaggi diretti, visione anonima delle storie, più account Instagram nella stessa istanza, pubblicazione di contenuti, aggiornamento automatico del programma, unione di tracce audio e video separate. Non progettare nulla in funzione di queste cose.
|
||||
Hashtag e luoghi, commenti, elenchi di follower di altri, messaggi diretti, più account Instagram nella stessa istanza, pubblicazione di contenuti, aggiornamento automatico del programma, unione di tracce audio e video separate. Non progettare nulla in funzione di queste cose.
|
||||
|
||||
---
|
||||
|
||||
@@ -298,6 +310,32 @@ public interface IRandomSource { double NextDouble(); }
|
||||
|
||||
## 6. Raccolta: il browser, le ricette, i lettori
|
||||
|
||||
### 6.0 Il client del sito e la sessione salvata
|
||||
|
||||
Decisione di Alberto del 16 novembre 2026 (issue #36). Il lavoro è a tappe (S0–S7 nell'issue); finché una tappa non è unita, il comportamento di Febe è quello delle sezioni che seguono.
|
||||
|
||||
**Come nasce la sessione.** Alberto accede a mano nel browser di Febe (§4.1). Quando preme «Ho finito», Febe copia nella **sessione salvata**:
|
||||
|
||||
- i cookie di Instagram, valori compresi, con `Network.getCookies` (§6.1);
|
||||
- l'user agent del browser, letto con `Runtime.evaluate` in sola lettura (`navigator.userAgent`), tale e quale;
|
||||
- i dati che la pagina tiene nei propri moduli, letti con un'espressione in sola lettura: i gettoni (`DTSGInitialData`, `LSD`), l'identificativo dell'account (`CurrentUserInitialData`), i `doc_id` delle sole operazioni di `richieste.<sito>.json` (moduli `<Operazione>_instagramRelayOperation`) e i campi di versione che il modello chiede. Il valore di `x-csrftoken` è quello del cookie `csrftoken` (decisione del 16 novembre: la pagina stessa lo legge così con `getCSRFToken()`).
|
||||
|
||||
La sessione salvata sta in `Dati/sessione/sessione.json`, cifrata (§13.2), fuori dal database e dalle sue copie. Dopo la copia il browser si chiude o torna al riposo; si riapre solo per un nuovo accesso o per una verifica, e intanto il motore è fermo (regola 4). Un nuovo accesso ricopia tutto e sostituisce la sessione salvata. Nei cookie del browser Febe non scrive mai.
|
||||
|
||||
**Il client del sito.** Una sola classe di Febe parla con `www.instagram.com` (regola 1):
|
||||
|
||||
- chiede solo le operazioni di `richieste.<sito>.json`, scritto da campioni reali con `febe-sonda richieste` (§14.5): metodo, percorso, nome dell'operazione, variabili con i soli valori del caso (nome o identificativo dell'account, cursore, testo cercato), nomi delle intestazioni. Rifiuta ogni nome che finisce in `Mutation` e ogni percorso fuori dall'elenco, compresi telemetria, chat e sincronizzazione con facebook.com;
|
||||
- manda l'user agent e i cookie della sessione salvata, le intestazioni del modello con i valori della sessione, e nient'altro. Aggiorna nella sessione salvata i cookie che il sito rinnova (`Set-Cookie`) e il valore di `x-ig-www-claim` che il sito manda in `x-ig-set-www-claim`;
|
||||
- **non segue i rinvii**: un 3xx è un segnale (§7.6), mai un nuovo indirizzo da visitare;
|
||||
- una richiesta per volta, ciascuna con il permesso del Governatore (§7.4) e la distanza minima di §7.7; mai in parallelo;
|
||||
- dalla stessa rete del browser: in Docker lo stesso contenitore, su Windows le impostazioni proxy del sistema, come WebView2;
|
||||
- HTTP/2 con ripiego su HTTP/1.1, decompressione gzip, deflate e brotli; niente HTTP/3;
|
||||
- nei registri scrive solo il nome dell'operazione o la forma del percorso (`/api/v1/media/{numero}/info/`) e lo stato HTTP: mai indirizzi completi, variabili, intestazioni, cookie o corpi (regola 11).
|
||||
|
||||
Le risposte vanno ai lettori come quelle catturate (§6.2, §6.4), con gli stessi segnali di arresto. Una risposta che non è JSON quando il modello si aspetta JSON, o un JSON senza i campi attesi, **ferma la sessione e avvisa**: Febe non rifà l'accesso da sola, decide Alberto (regola 8).
|
||||
|
||||
**Che cosa non cambia.** Sola lettura (regola 5), Governatore (regola 7), arresto al primo segnale (regola 8), niente CAPTCHA (regola 3), formati mai inventati (regola 10), browser usato così com'è per l'accesso e le verifiche (regola 2).
|
||||
|
||||
### 6.1 Il browser
|
||||
|
||||
- **Docker**: il Chromium della distribuzione, avviato come un browser normale con finestra su un display virtuale (Xvfb), profilo in `/dati/browser`.
|
||||
@@ -313,16 +351,26 @@ public interface IRandomSource { double NextDouble(); }
|
||||
|
||||
| Scopo | Comandi |
|
||||
|---|---|
|
||||
| Navigare e leggere lo stato | `Page.enable`, `Page.navigate`, `Page.getFrameTree`, `Runtime.evaluate` in sola lettura (posizione degli elementi, indirizzo, presenza di finestre) |
|
||||
| Catturare le risposte | `Network.enable`, `Network.getResponseBody` |
|
||||
| Navigare e leggere lo stato | `Page.enable`, `Page.navigate`, `Page.getFrameTree`, `Runtime.evaluate` in sola lettura (posizione degli elementi, indirizzo, presenza di finestre; per la ricerca dei profili, se il fuoco è nella casella «Cerca», quanti caratteri contiene e se il cursore è in fondo, mai il testo né altri campi: decisione di Alberto del 15 novembre 2026, #37) |
|
||||
| Catturare le risposte | `Network.enable`, `Network.getResponseBody`; degli eventi di rete si legge anche `Network.requestWillBeSent`, solo l'indirizzo e solo per l'ordine delle richieste della ricerca (decisione di Alberto del 15 novembre 2026, #37) |
|
||||
| Gesti | `Input.dispatchMouseEvent`, `Input.dispatchKeyEvent` |
|
||||
| Scaricare i file | `Network.loadNetworkResource` (richiede l'identificativo del frame), `IO.read`, `IO.close` |
|
||||
| Vista remota e anteprima | `Page.startScreencast`, `Page.screencastFrameAck`, `Page.stopScreencast`, `Page.captureScreenshot` |
|
||||
| Controllare il collegamento | `Network.getCookies`, solo per sapere se il cookie di sessione esiste: il valore non si legge né si registra |
|
||||
| Controllare il collegamento | `Network.getCookies`, per sapere se il cookie di sessione esiste; il valore non si registra mai |
|
||||
| Copiare la sessione (§6.0, decisione del 16 novembre 2026) | `Network.getCookies` con i valori, una volta a «Ho finito», direttamente nella sessione salvata; `Runtime.evaluate` in sola lettura per l'user agent e per i dati dei moduli della pagina elencati in §6.0 |
|
||||
| Chiedere i dati alla pagina (storia: decisione del 12 novembre 2026, sostituita dal client del sito) | `Runtime.evaluate` con `awaitPromise`, che esegue nella pagina un `fetch` verso un indirizzo di `richieste.<sito>.json` e ne restituisce il corpo |
|
||||
|
||||
**Provato in locale**: gli eventi della rotella inviati con `Input.dispatchMouseEvent` sono eventi veri e fanno scorrere la pagina; `Page.startScreencast` consegna i fotogrammi; `Network.loadNetworkResource` con `IO.read` ha scaricato integro un file di 40 MB.
|
||||
|
||||
Vietati, in coerenza con la regola 2: `Network.setUserAgentOverride`, tutto il dominio `Emulation`, `Network.setExtraHTTPHeaders`, `Page.addScriptToEvaluateOnNewDocument`, il dominio `Fetch`, `Runtime.evaluate` usato per scorrere, cliccare o modificare la pagina. I gesti passano sempre da `Input`. Se una voce di §6.6 non si risolve senza uno di questi, non aggiungerlo da solo: scrivi l'esito e chiedi ad Alberto.
|
||||
**Richieste della pagina** (strada del 12 novembre, sostituita dal client del sito di §6.0; resta descritta finché il codice non è riscritto). Le regole del `fetch` della riga «Chiedere i dati alla pagina»:
|
||||
|
||||
- l'indirizzo, il metodo, i nomi dei parametri e delle intestazioni vengono da un modello di `richieste.<sito>.json`; Febe vi mette solo i valori del caso (nome o identificativo dell'account, cursore della pagina successiva, testo cercato). Un indirizzo che non è nel file non si chiede, e il file si scrive solo da campioni reali (regola 10), ricavati con `febe-sonda richieste` (§14.5);
|
||||
- i valori delle intestazioni che servono al sito (per esempio il gettone contro le richieste contraffatte) si leggono nella pagina, dove la pagina stessa li tiene, al momento della richiesta, e non escono dalla pagina: allo script torna solo il corpo della risposta;
|
||||
- solo richieste di lettura: nessuna operazione che cambi qualcosa, anche se il sito la chiamasse con lo stesso metodo;
|
||||
- una richiesta per volta, ciascuna un'azione del motore con il permesso del Governatore e il suo tetto (§7.4); la risposta passa ai lettori come quelle catturate (§6.2) e porta gli stessi segnali di arresto (§7.6);
|
||||
- il testo dello script, i valori e la risposta non si registrano mai: il client CDP scrive solo «Runtime.evaluate».
|
||||
|
||||
Vietati, in coerenza con la regola 2: `Network.setUserAgentOverride`, tutto il dominio `Emulation`, `Network.setExtraHTTPHeaders`, `Page.addScriptToEvaluateOnNewDocument`, il dominio `Fetch`, `Runtime.evaluate` usato per scorrere, cliccare o modificare la pagina, o per richieste diverse da quelle descritte qui sopra. I gesti passano sempre da `Input`. Se una voce di §6.6 non si risolve senza uno di questi, non aggiungerlo da solo: scrivi l'esito e chiedi ad Alberto.
|
||||
|
||||
Il client CDP registra solo i nomi dei comandi e degli eventi, mai parametri e risultati: lì dentro passano tasti, cookie e contenuti.
|
||||
|
||||
@@ -332,7 +380,9 @@ Un componente `ResponseTap` ascolta le risposte JSON che la pagina riceve dal si
|
||||
|
||||
### 6.3 Ricette
|
||||
|
||||
Una ricetta è una sequenza di gesti con uno scopo. Sono poche e fisse. I passi qui sotto descrivono l'intenzione; i dettagli concreti si definiscono dopo M0, sui campioni.
|
||||
Una ricetta è una sequenza di azioni con uno scopo. Sono poche e fisse. I passi qui sotto descrivono l'intenzione; i dettagli concreti si definiscono sui campioni.
|
||||
|
||||
**In riscrittura (issue #36).** Le ricette diventano sequenze di richieste del client del sito (§6.0) invece che di gesti, e la mappa dei bersagli non servirà più. Ogni richiesta è un'azione con il suo permesso. Le storie di un account si leggono con una sola richiesta e non risultano viste (§3, decisione del 16 novembre 2026). Restano «non configurate», finché non ci sono i campioni con le risposte (regola 10): l'elenco dei seguiti, le pagine successive dei post, le pagine della home. Finché una ricetta non è riscritta e unita, vale la tabella qui sotto.
|
||||
|
||||
| Ricetta | Che cosa fa | Azioni contate |
|
||||
|---|---|---|
|
||||
@@ -344,6 +394,7 @@ Una ricetta è una sequenza di gesti con uno scopo. Sono poche e fisse. I passi
|
||||
| **Taggati** e **Reel** | Come Controllo e Storico, sulle rispettive schede del profilo | come sopra |
|
||||
| **Post singolo** | Apre la pagina di un post: quando la griglia non ha dato tutti i dati, o per recuperare un indirizzo scaduto (§6.5) | 1 post |
|
||||
| **Elenco dei seguiti** | Apre l'elenco dei profili seguiti da Alberto e lo scorre. Solo su richiesta | 1 pagina di elenco per caricamento |
|
||||
| **Ricerca dei profili** | Solo mentre Alberto scrive nella finestra «Aggiungi account» (§4.2), anche durante una sessione, a turno con il motore fra un'azione e l'altra. Apre «Cerca» e fa clic nella casella; prima di scrivere controlla che il fuoco sia nella casella; scrive con `Input.dispatchKeyEvent` a ritmo umano solo lettere, numeri, «.», «_» e spazi, e cancella con il tasto di cancellazione; non preme mai Invio, Tab o Esc. Legge la risposta che la pagina riceve (`PolarisSearchBoxRefetchableQuery`, riconosciuta dalla forma) e **non fa mai clic su un risultato**, che finirebbe fra le ricerche recenti di Alberto (una scrittura). Fuori sessione, a finestra chiusa o dopo qualche minuto senza lettere nuove, torna alla pagina di riposo | 1 ricerca di profili per apertura, clic nella casella e raffica di tasti |
|
||||
|
||||
Regole comuni:
|
||||
|
||||
@@ -354,7 +405,7 @@ Regole comuni:
|
||||
- **Lo storico non corre più veloce dei download.** Lo storico di un account si sospende finché quell'account ha più di 60 file in attesa di essere scaricati o il tetto dei dati è raggiunto: gli indirizzi scadono, e accumularli non serve.
|
||||
- Se a metà ricetta compare un segnale di §7.6, la ricetta si ferma dov'è e lascia la pagina com'è, così Alberto vede che cosa è successo.
|
||||
|
||||
**Mappa dei bersagli.** Per agire, una ricetta deve trovare poche cose nella pagina: l'immagine del profilo con l'anello delle storie, il comando per chiudere il visualizzatore, la zona per andare avanti, le schede del profilo, l'elenco dei seguiti. Come trovarle sta in un file di configurazione per sito (`bersagli.instagram.json`, `bersagli.prova.json`), non nel codice: ruolo dell'elemento, nome accessibile, forma del collegamento. Mai coordinate fisse, mai nomi di classi generate. Il file si aggiorna senza ricompilare, ed è la seconda cosa da ritoccare, dopo i lettori, quando Instagram cambia.
|
||||
**Mappa dei bersagli.** Per agire, una ricetta deve trovare poche cose nella pagina: l'immagine del profilo con l'anello delle storie, il comando per chiudere il visualizzatore, la zona per andare avanti, le schede del profilo, l'elenco dei seguiti, il comando «Cerca» e la sua casella (`search-open`, `search-box`). Come trovarle sta in un file di configurazione per sito (`bersagli.instagram.json`, `bersagli.prova.json`), non nel codice: ruolo dell'elemento, nome accessibile, forma del collegamento. Mai coordinate fisse, mai nomi di classi generate. Il file si aggiorna senza ricompilare, ed è la seconda cosa da ritoccare, dopo i lettori, quando Instagram cambia.
|
||||
|
||||
### 6.4 Lettori
|
||||
|
||||
@@ -370,8 +421,8 @@ Un lettore trasforma una risposta in oggetti del dominio (`Entry`, `Media`, `Acc
|
||||
La pagina mostra versioni ridotte; gli indirizzi delle versioni migliori sono nelle risposte e scadono dopo qualche tempo.
|
||||
|
||||
1. Si sceglie la versione più grande per le immagini e, per i video, la migliore fra quelle complete di audio.
|
||||
2. Via preferita: il browser stesso, con `Network.loadNetworkResource` e lettura a blocchi con `IO.read`.
|
||||
3. Via di riserva, solo se in M0 la prima non regge con il CDN vero (H7): `HttpClient` verso i soli domini del CDN presenti nell'indirizzo ricevuto, mai verso `instagram.com`. Senza cookie e senza intestazioni copiate dal browser: una richiesta semplice, che si presenta come Febe. Se il CDN la rifiuta, il file resta in attesa e l'interfaccia lo dice. La scelta fra 2 e 3 si scrive in `docs/decisioni.md`.
|
||||
2. Con il browser aperto: il browser stesso, con `Network.loadNetworkResource` e lettura a blocchi con `IO.read`.
|
||||
3. Senza browser, la via principale dal 16 novembre 2026 (§6.0, tappa S5 di #36): `HttpClient` verso i soli domini del CDN presenti nell'indirizzo ricevuto, mai verso `instagram.com`, senza seguire rinvii fuori dal CDN. Senza cookie, con l'user agent della sessione salvata. Se il CDN la rifiuta, il file resta in attesa e l'interfaccia lo dice.
|
||||
4. Il file si scrive con un nome temporaneo, se ne calcola lo SHA-256 e lo si rinomina. Uno scaricamento interrotto non lascia mai un file con il nome definitivo.
|
||||
5. Se l'indirizzo è scaduto, il file torna «da scaricare». Il recupero passa dalla ricetta Post singolo, che rilegge il post e ne ottiene uno nuovo, dentro il suo tetto. Per le storie non c'è recupero dopo la scadenza.
|
||||
6. Coda dedicata, al massimo due scaricamenti insieme, piccole pause casuali, tetto giornaliero sui dati. Le storie hanno la precedenza, perché scadono.
|
||||
@@ -392,7 +443,13 @@ Finché una voce non ha un esito scritto in `docs/sonda/esito.md`, non costruirc
|
||||
| H8 | I segnali di arresto di §7.6 si riconoscono da indirizzo e stato HTTP |
|
||||
| H9 | Un contenuto di una raccolta in evidenza ha lo stesso identificativo che aveva come storia |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati che la pagina riceve, senza leggere i cookie |
|
||||
| H11 | I bersagli delle ricette si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento |
|
||||
| H11 | I bersagli delle ricette si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento (superata dal client del sito, §6.0) |
|
||||
| H12 | Una sessione copiata dal browser e usata dal client HTTP di .NET, dalla stessa rete, è accettata senza verifiche |
|
||||
| H13 | Quanto durano `fb_dtsg`, `lsd` e `x-ig-www-claim`, e se il sito rinnova i cookie con `Set-Cookie` |
|
||||
| H14 | I `doc_id` restano uguali fra una versione e l'altra dell'applicazione web: uguali dal 12 al 16 novembre 2026 per 17 operazioni (#35) |
|
||||
| H15 | Le richieste sono accettate con i soli campi di versione letti all'accesso, senza i campi che la pagina calcola a ogni richiesta (`__req`, `__csr`, `__dyn`, `__s`) |
|
||||
| H16 | Che cosa risponde il sito a una sessione scaduta o da verificare: rinvio, stato, campi del JSON (la ricerca su internet indica `login_required`, `checkpoint_required` e `require_login`, non verificati) |
|
||||
| H17 | Il CDN dà i file a una richiesta senza cookie con l'user agent della sessione |
|
||||
| S1 | In WebView2 funzionano attraverso CDP il corpo delle risposte, i gesti e i fotogrammi della pagina |
|
||||
| S2 | Su Windows la pagina continua a caricare e a rispondere allo scorrimento quando la finestra del browser non è in vista |
|
||||
| S3 | L'accesso fatto a mano sopravvive al riavvio del programma, in Docker e su Windows |
|
||||
@@ -453,7 +510,8 @@ Il Governatore è l'unico punto da cui passa un'azione del motore verso il sito.
|
||||
|
||||
- I tetti orari valgono su una finestra mobile di 60 minuti; quelli giornalieri sul giorno di calendario nel fuso di Alberto.
|
||||
- Il conteggio sta nella tabella `action_log`, non in memoria.
|
||||
- Categorie: home, profili aperti, storie viste, pagine di storico, post singoli, pagine dell'elenco dei seguiti, dati scaricati.
|
||||
- Categorie: home, profili aperti, storie viste, pagine di storico, post singoli, pagine dell'elenco dei seguiti, dati scaricati, ricerche di profili. Ogni richiesta del client del sito (§6.0) è un'azione e conta nella categoria di ciò che chiede: un permesso per richiesta, mai uno per più richieste. I tetti per richiesta si ricalcolano con la tappa S3 di #36.
|
||||
- **Ricerche di profili** (issue #37) hanno tetti propri e larghi (§7.5), che fanno da guardia e non devono mai fermare l'uso normale, e non consumano i tetti della raccolta. Non chiedono una sessione e non contano fra le azioni della sessione. L'ordine dei controlli: interruttore (ogni segnale di §7.6 ferma anche la ricerca), browser in uso da Alberto, pausa, fascia oraria, tetto orario e giornaliero proprio, distanza propria fra due passi della ricerca (1,2 s per il ritmo), 1,2 s di distanza dalle azioni del motore in entrambi i versi. Le riduzioni (avvio graduale, tetti dimezzati) valgono anche qui. Le foto dei risultati contano fra i dati scaricati.
|
||||
- Sopra l'80% di un tetto l'interfaccia lo segnala in ambra. Raggiunto il tetto, quella categoria si ferma fino all'ora o al giorno dopo; le altre proseguono, salvo la regola sullo storico di §6.3.
|
||||
- Quando valgono insieme più riduzioni (avvio graduale, tetti dimezzati dopo un rallentamento) si applica la più forte, non il loro prodotto.
|
||||
|
||||
@@ -472,6 +530,7 @@ I valori sono **stime di partenza scelte con prudenza**. Non sono limiti ufficia
|
||||
| Pagine di storico | 20 / 100 | 30 / 180 | 45 / 300 |
|
||||
| Post singoli | 10 / 60 | 15 / 100 | 20 / 160 |
|
||||
| Pagine dell'elenco dei seguiti | 15 / 60 | 20 / 90 | 30 / 150 |
|
||||
| Ricerche di profili | 240 / 1200 | 300 / 1500 | 360 / 1800 |
|
||||
| Dati scaricati al giorno | 4 GB | 8 GB | 16 GB |
|
||||
| Storico per account al giorno | 300 post | 500 post | 800 post |
|
||||
| Avvio graduale | 7 giorni | 5 giorni | 3 giorni |
|
||||
@@ -482,13 +541,15 @@ I valori sono **stime di partenza scelte con prudenza**. Non sono limiti ufficia
|
||||
|
||||
### 7.6 Segnali e arresti
|
||||
|
||||
L'interruttore riceve segnali dalle ricette e dalla cattura. L'elenco di partenza sta in un file di configurazione (`segnali.json`), così si aggiorna senza ricompilare; va completato dopo M0 (H8).
|
||||
L'interruttore riceve segnali dalle ricette, dalla cattura e dal client del sito. L'elenco di partenza sta in un file di configurazione (`segnali.json`), così si aggiorna senza ricompilare; va completato dopo M0 (H8, H16).
|
||||
|
||||
Per il client del sito (§6.0) sono segnali anche: un rinvio (3xx) verso le pagine d'accesso, di verifica, di controllo o di sospensione, che non si segue mai; gli stati 401 e 403; un documento HTML dove il modello aspetta JSON; un JSON senza i campi attesi; un `Set-Cookie` che cancella il cookie di sessione. Finché le forme vere delle risposte di sessione scaduta o da verificare non sono note (H16), questi casi valgono come **Verifica**: Febe si ferma, avvisa, e decide Alberto se rifare l'accesso.
|
||||
|
||||
| Livello | Segnali | Che cosa fa Febe |
|
||||
|---|---|---|
|
||||
| **Rallentamento** | Risposta con stato 429; risposta che chiede di attendere qualche minuto; pagine o risposte vuote ripetute | Chiude subito la sessione. Fermo 1 ora la prima volta, 6 ore la seconda nelle 24 ore, 24 ore la terza. Poi tetti dimezzati per 48 ore |
|
||||
| **Verifica** | Navigazione verso pagine di verifica, controllo o sospensione; avviso di comportamento automatico; richiesta di confermare l'identità | Ferma tutto e non riparte da solo. Striscia rossa, notifica, pagina lasciata com'è |
|
||||
| **Disconnessione** | La pagina torna all'accesso; il cookie di sessione non c'è più | Come Verifica. Non tenta mai di rientrare |
|
||||
| **Disconnessione** | La pagina torna all'accesso; il cookie di sessione non c'è più; la sessione salvata manca o il sito la rifiuta | Come Verifica. Non tenta mai di rientrare |
|
||||
|
||||
- Le durate dei fermi sono fisse: nella versione 1 non si modificano dall'interfaccia.
|
||||
- Dopo Verifica o Disconnessione riparte solo quando Alberto ha sistemato a mano nel browser e ha premuto «Riprendi». La ripresa comincia con l'avvio graduale.
|
||||
@@ -519,6 +580,8 @@ Regole: il puntatore non salta mai da un punto all'altro; non si clicca nulla ch
|
||||
|
||||
La pagina Attività (mockup 06 e 11) è il cruscotto del motore: che cosa sta facendo adesso, la **striscia della giornata** con sessioni, riposo, rallentamenti e arresti, i quattro tetti principali con i numeri (profili aperti, storie viste, pagine di storico, dati scaricati) e, da «Tutti i tetti», anche gli altri; la coda con orari indicativi, le ultime azioni con l'esito. Gli orari futuri si scrivono sempre come «verso le», perché sono estratti a caso.
|
||||
|
||||
**Rapporto di diagnostica.** Dopo una prova dal vivo andata storta, Alberto deve poter mandare un solo file che spieghi perché, senza che nessuno apra i dati di altre persone. «Esporta il rapporto di diagnostica» (pulsante «Diagnostica» nella riga del titolo di Attività) scarica `febe-diagnostica-aaaa-mm-gg.json`: per ogni sessione del motore delle ultime due settimane, e per ogni giorno fuori dalle sessioni, le pagine aperte (il nome della pagina nella mappa del sito e la sua forma, mai l'indirizzo), le risposte ricevute per tipo con numero e misure, che cosa ne hanno fatto i lettori (riconosciute, vuote, ignorate, forma sconosciuta con la sola struttura delle chiavi, in cui resta solo una chiave fatta di parole di un elenco chiuso, preso dai campioni ripuliti e dai vocabolari dei lettori, mai di sole parole che sono anche nomi come «max_mark», e ogni altra diventa `#`; diventano `#` anche le voci di una mappa, cioè le chiavi sorelle con valori della stessa forma, salvo quelle che i lettori conoscono come `user` e `owner`), i bersagli cliccati, le ricette con l'esito (e, per un errore imprevisto, il solo tipo dell'eccezione), i segnali di §7.6 per livello e codice, i rifiuti del Governatore, i file messi in coda e scaricati (per un file fallito o da riprovare, la causa da un elenco chiuso, come `http-404`), e la causa di ogni fine (fine prevista, lavoro finito, tetti esauriti, ricetta che ferma, interruttore aperto, pausa, Alberto al browser, chiusura di Febe, errore). Mai cookie, password, gettoni, corpi delle risposte, nomi utente, didascalie, codici dei post, identificativi, indirizzi interi o testi liberi (messaggi, note, eccezioni): solo valori di elenchi chiusi, conteggi, misure, orari e forme degli indirizzi in cui ogni parte che non è una parola fissa del sito è `{numero}` o `{testo}`; per il CDN solo «cdn» e l'estensione del file. Le tracce finite stanno in `Dati/diagnostica/sessioni-aaaa-mm-gg.jsonl`, una riga per sessione, e si tengono 14 giorni (Febe cancella da sé solo i file più vecchi di quella cartella); le sessioni in corso entrano nel rapporto come «in corso». Una sessione scrive una riga «in corso» quando parte e poi al più ogni 5 minuti alla fine di una ricetta, così una chiusura brusca di Febe non la cancella; leggendo, di una sessione resta la riga finita, altrimenti l'ultima. I segnali entrano anche quando arrivano all'interruttore senza passare dal rilevatore (il cookie di sessione perso), e i file in attesa perché manca la connessione hanno la causa `connessione`. La testa del file dice che cosa sicuramente manca: righe del registro rovinate (`righeRovinate`), errori del registratore, scritture non riuscite comprese (`erroriRegistratore`), file di un giorno che non si sono potuti leggere (`fileIlleggibili`) e sessioni rimaste senza fine per una chiusura brusca (`sessioniSenzaFine`). Anche a zero il rapporto non promette di essere intero: gli ultimi minuti di una chiusura brusca, le ore fuori dalle sessioni del giorno e quello che supera i tetti (contato in `overflow`) possono mancare. Le forme delle pagine della mappa del sito passano per la stessa riduzione degli indirizzi, perché la mappa può venire dalla cartella dei dati. Con un problema di configurazione il motore non parte: l'indirizzo del rapporto risponde lo stesso, con gli elenchi vuoti. Una prova dimostra che nessun valore dei dati arriva nel file.
|
||||
|
||||
---
|
||||
|
||||
## 8. Dati: database e file
|
||||
@@ -675,10 +738,10 @@ Ogni riga è un file in `docs/mockup/`. I dati sono inventati: gli account che f
|
||||
| `01-libreria.png` | Libreria | Righe giustificate che rispettano le proporzioni delle foto, 4 px fra le tessere. Segni in alto a destra: durata per i video, numero dei file per i post con più file, anello tratteggiato per le storie. I menu Account, Periodo e Provenienza mostrano il nome del filtro finché non si sceglie un valore. Il cursore accanto a «Seleziona» regola la grandezza delle tessere. Al passaggio del mouse: account, ora, cerchio di selezione. I nuovi elementi compaiono in cima senza spostare ciò che si sta guardando |
|
||||
| `02-visualizzatore.png` | Visualizzatore | Copre tutta la finestra. Frecce e tasti freccia; Esc chiude. I video partono senza audio. Nel browser «Mostra nella cartella» diventa «Scarica» |
|
||||
| `03-account.png` | Account | Le cinque icone di «Raccoglie» sono nell'ordine: foto, video, storie, evidenza, taggati; spente se non attive. L'interruttore agisce subito. Un clic sulla riga apre la scheda |
|
||||
| `04-aggiungi-account.png` | Aggiungi account | I tre punti di partenza sono quelli di §4.2. La seconda linguetta «Per nome utente» ha un'area di testo, una riga per account, e la stessa colonna destra. I profili già presenti sono attenuati. Durante la lettura dell'elenco compare l'avanzamento di §4.2 |
|
||||
| `04-aggiungi-account.png` | Aggiungi account | I tre punti di partenza sono quelli di §4.2. **Superato da #37**: niente linguette, una sola casella con l'elenco dei suggerimenti sotto (profili seguiti, poi Instagram, con foto ed etichette), «Da aggiungere» al posto dell'elenco a spunte, che si apre con «Scegli fra tutti i profili che segui». I profili già presenti sono attenuati. Durante la lettura dell'elenco compare l'avanzamento di §4.2. Finché non c'è un mockup nuovo, il riferimento è la schermata `docs/schermate/04-aggiungi-account.png` |
|
||||
| `05-account-impostazioni.png` | Scheda account, impostazioni | Il riquadro a destra si ricalcola a ogni modifica. «Controlla ora» segue §7.8. Con «Su misura» compaiono i due campi di §4.4 |
|
||||
| `06-attivita.png` | Attività | Si aggiorna da sola con gli eventi del server. L'anteprima del browser è un fotogramma ogni pochi secondi, non un video. «Tutti i tetti» apre l'elenco completo di §7.4 |
|
||||
| `07-limiti-e-comportamento.png` | Impostazioni, limiti | Modificare un valore cambia il profilo in «Su misura». I cerchi con le iniziali sono i giorni attivi. Nel programma la tabella dei tetti ha anche le righe Home, Post singoli ed Elenco dei seguiti di §7.5. La riga degli arresti è informativa: non si modifica |
|
||||
| `07-limiti-e-comportamento.png` | Impostazioni, limiti | Modificare un valore cambia il profilo in «Su misura». I cerchi con le iniziali sono i giorni attivi. Nel programma la tabella dei tetti ha anche le righe Home, Post singoli ed Elenco dei seguiti di §7.5, e «Ricerche di profili» (#37). La riga degli arresti è informativa: non si modifica |
|
||||
| `08-impostazioni-generali.png` | Impostazioni, generali | In Docker le due cartelle sono in sola lettura, con la nota che si cambiano dal contenitore. Il blocco «Avvio» esiste solo su Windows |
|
||||
| `09-importa-revisione.png` | Importa, passo 3 | I passi 1, 2 e 4 usano la stessa intestazione: scelta della cartella, barra di avanzamento con possibilità di interrompere, resoconto finale. Nel confronto dei doppioni nessuna scelta è già fatta in partenza: l'immagine mostra una decisione presa da Alberto. «Sposta» non compare se la sorgente è in sola lettura |
|
||||
| `10-collegamento-instagram.png` | Collegamento, versione Docker | Il riquadro grande è la vista remota del browser del server. Il rettangolo tratteggiato dell'immagine è un segnaposto: la pagina di Instagram non si ridisegna. Versione Windows qui sotto |
|
||||
@@ -710,7 +773,8 @@ Fuoco da tastiera sempre visibile; contrasto del testo almeno 4,5 a 1 in entramb
|
||||
|
||||
Con `--demo` il programma parte senza browser e senza rete, in ascolto solo su `127.0.0.1` e senza password, con una libreria temporanea di account `.demo`, immagini generate e uno stato del motore finto. Non deve poter scrivere nella libreria vera.
|
||||
|
||||
- Lo stato si sceglie dall'indirizzo: `?scena=normale`, `sessione`, `fermo`, `scollegato`; il tema con `?tema=chiaro` o `scuro`. Ci sono indirizzi che aprono direttamente il dialogo «Aggiungi account» e il passo 3 dell'importazione.
|
||||
- Lo stato si sceglie dall'indirizzo: `?scena=normale`, `sessione`, `fermo`, `scollegato`, `alvolante` (Alberto usa il browser); il tema con `?tema=chiaro` o `scuro`. Ci sono indirizzi che aprono direttamente il dialogo «Aggiungi account» e il passo 3 dell'importazione.
|
||||
- La ricerca dei profili del dialogo risponde con dati finti, senza browser: account e profili seguiti dimostrativi il cui nome contiene il testo, più qualche nome inventato, con foto disegnate che arrivano un attimo dopo. Con `fermo`, `scollegato` e `alvolante` dice perché non cerca.
|
||||
- I dati dimostrativi devono essere coerenti fra loro (i conteggi tornano, gli orari sono plausibili). Non serve che ricalchino i numeri dei mockup.
|
||||
|
||||
### 10.7 Come si verifica una schermata
|
||||
@@ -720,7 +784,7 @@ Avvia con `--demo`, fai uno screenshot nelle condizioni della tabella e confront
|
||||
| Mockup | Finestra in pixel CSS | Tema e scena |
|
||||
|---|---|---|
|
||||
| 01, 02, 03, 08 | 1440 × 900 | chiaro, normale |
|
||||
| 04 | 1440 × 900 | chiaro, dialogo aperto |
|
||||
| 04 | 1440 × 900 | chiaro, dialogo aperto con «gaia» scritto e l'elenco dei suggerimenti aperto |
|
||||
| 05 | 1440 × 1000 | chiaro, normale |
|
||||
| 06 | 1440 × 900 | chiaro, sessione |
|
||||
| 07 | 1440 × 1470 | chiaro, normale |
|
||||
@@ -794,9 +858,9 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I
|
||||
|
||||
### 13.2 Dati riservati
|
||||
|
||||
- La sessione di Instagram vive nel profilo del browser dentro la cartella dei dati: Febe non la esporta, non la mostra e non la copia altrove.
|
||||
- La sessione di Instagram vive nel profilo del browser dentro la cartella dei dati e, dal 16 novembre 2026 (§6.0), nella sessione salvata `Dati/sessione/sessione.json`: cookie, user agent, gettoni e `doc_id`. Il file è cifrato: su Windows con DPAPI dell'utente (`ProtectedData`, nella libreria del desktop di .NET, nessun pacchetto nuovo); in Docker con AES-256-GCM e una chiave a 256 bit presa dalla variabile `FEBE_CHIAVE_SESSIONE` o, se manca, dal file `Dati/sessione/chiave.bin` con permessi del solo proprietario. Si scrive in modo atomico. Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia; Febe non lo esporta e non accetta sessioni incollate da fuori. «Scollega» lo cancella. Chi ha accesso alla cartella dei dati e alla chiave ha accesso alla sessione.
|
||||
- Password e codici non entrano mai nei registri. Nella vista remota i tasti vanno al browser e non si conservano.
|
||||
- I registri contengono azioni ed esiti, non contenuti: nomi utente sì, didascalie e corpi delle risposte no. Il client CDP registra solo nomi di comandi (§6.1). Per le richieste verso Telegram e verso il CDN non si registrano gli indirizzi: contengono il gettone del bot e le firme dei file.
|
||||
- I registri contengono azioni ed esiti, non contenuti: nomi utente sì, didascalie e corpi delle risposte no. Il client CDP registra solo nomi di comandi (§6.1); il client del sito solo operazione o forma del percorso e stato (§6.0). Il rapporto di diagnostica (§7.9) è più severo dei registri: nemmeno i nomi utente, né indirizzi interi, solo forme, conteggi e codici di elenchi chiusi, perché è fatto per uscire dalla macchina di Alberto. Per le richieste verso Telegram e verso il CDN non si registrano gli indirizzi: contengono il gettone del bot e le firme dei file.
|
||||
- I campioni grezzi della sonda stanno fuori dal repository e si cancellano a fine M0 (§14.5).
|
||||
|
||||
### 13.3 Avvisi
|
||||
@@ -819,7 +883,7 @@ Eventi che meritano un avviso: verifica richiesta, disconnessione, fermo per ral
|
||||
|
||||
### 14.2 Sito di prova
|
||||
|
||||
`tools/Febe.SitoDiProva` è un piccolo sito locale che espone gli stessi dati dei campioni attraverso pagine spoglie: una griglia che carica altre pagine scorrendo, un visualizzatore, un elenco, e i casi di arresto (stato 429, rinvio a una pagina di verifica, uscita dalla sessione). Non ha marchi né grafica di Instagram e non ha pagine di accesso: non deve somigliargli, deve solo far girare ricette, cattura e motore con un browser vero senza toccare Instagram. Ha la sua mappa dei bersagli (`bersagli.prova.json`): le ricette sono le stesse, cambia solo dove trovano le cose. Tutte le prove d'insieme passano da qui.
|
||||
`tools/Febe.SitoDiProva` è un piccolo sito locale che espone gli stessi dati dei campioni attraverso pagine spoglie: una griglia che carica altre pagine scorrendo, un visualizzatore, un elenco, e i casi di arresto (stato 429, rinvio a una pagina di verifica, uscita dalla sessione). Non ha marchi né grafica di Instagram e non ha un vero modulo d'accesso: non deve somigliargli, deve solo far girare ricette, cattura e motore senza toccare Instagram. Per il client del sito (§6.0) risponde alle stesse forme di richiesta e di risposta dei campioni ripuliti (per esempio `POST /api/graphql` con `doc_id` e le risposte dei campioni), controlla il cookie di sessione di prova e le intestazioni attese, e simula i casi d'arresto: 429, rinvio all'accesso o a una verifica, HTML al posto del JSON, JSON senza i campi attesi, cookie rinnovati o cancellati. Le forme dei casi d'arresto non note da campioni sono generiche e marcate H16. Ha la sua mappa dei bersagli (`bersagli.prova.json`): le ricette sono le stesse, cambia solo dove trovano le cose. Tutte le prove d'insieme passano da qui.
|
||||
|
||||
### 14.3 Simulazione
|
||||
|
||||
@@ -841,6 +905,7 @@ Le esegue solo Alberto, con l'account di prova, seguendo un elenco di passi che
|
||||
- **La ripulitura lavora per elenco di ciò che è ammesso**, non di ciò che è vietato. Conserva struttura e chiavi. Sostituisce ogni stringa e ogni numero lungo con un valore finto della stessa forma, tranne i campi di un breve elenco che non dicono nulla di una persona (dimensioni, durate, conteggi, valori vero o falso, codici di tipo, date). Sostituisce anche le chiavi che hanno l'aspetto di un identificativo. Degli indirizzi tiene solo la distinzione fra sito e CDN e l'estensione del file.
|
||||
- Una prova automatica confronta grezzi e ripuliti, sulla macchina di Alberto, e fallisce se una stringa di quattro o più caratteri sopravvive fuori dall'elenco ammesso.
|
||||
- In `tests/campioni/` e in `docs/sonda/esito.md` entrano solo campioni ripuliti e descrizioni di forma.
|
||||
- **Forma delle richieste** (per la regola 2, eccezione). `febe-sonda richieste --har <file> --a <file .json>` descrive le richieste che la pagina fa al sito: metodo, percorso con ogni parte che non è una parola fissa del sito sostituita da `{numero}` o `{testo}`, nomi dei parametri, delle intestazioni e dei campi del corpo, struttura delle variabili GraphQL. Dei valori scrive solo il tipo («numero», «testo», «vuoto»), tranne quelli di un elenco chiuso uguali per tutti (identificativo dell'applicazione, nomi e identificativi delle operazioni, grandezza delle pagine, vero/falso): mai cookie, gettoni, nomi, identificativi o cursori. Dei nomi tiene quelli di un elenco chiuso e quelli che hanno la forma di un nome del codice (senza punto, senza tre cifre di fila) e non compaiono da nessuna parte nel HAR come valore; gli altri diventano «(nome tolto)». Alberto lo legge e lo invia; da lì si scrive `richieste.<sito>.json`.
|
||||
|
||||
---
|
||||
|
||||
@@ -892,6 +957,7 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del
|
||||
| 8 | Il nome «Febe» resta? | Prima di M0 | — |
|
||||
| 9 | Solo italiano, o anche inglese? | M4 | Solo italiano, testi già separati |
|
||||
| 10 | Su Unraid: porta, cartella della libreria, disco per i dati | M5 | Porta 8480, dati nella cartella delle applicazioni sul disco di cache |
|
||||
| 11 | **Risposta di Alberto del 16 novembre 2026: con una richiesta, non risultano viste** (§3). Domanda di allora: con la pagina che chiede i dati, le storie si chiedono con una richiesta (non risultano viste) o si continuano ad aprire nel visualizzatore (Alberto tra gli spettatori, come oggi)? | #36, sui campioni del nuovo HAR | Restare al visualizzatore, che è la scelta di §3; la richiesta solo se il visualizzatore non si può guidare in modo affidabile |
|
||||
|
||||
---
|
||||
|
||||
@@ -916,14 +982,14 @@ All'inizio di ogni sessione leggi docs/stato.md.
|
||||
## Regole che non si discutono (specifica §2)
|
||||
1. IMPORTANTE: non contattare mai Instagram da prove, script o verifiche tue. Si usa solo tools/Febe.SitoDiProva. Le prove dal vivo le lancia Alberto.
|
||||
2. Non aprire i campioni grezzi della sonda: stanno fuori dal repository e contengono dati di altre persone. Si lavora sulle copie ripulite di tests/campioni.
|
||||
3. Verso Instagram parla solo il browser di Febe. Nessun HttpClient verso domini di Instagram o Meta, tranne il CDN alle condizioni di §6.5.
|
||||
4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1.
|
||||
3. Verso Instagram parlano solo il browser di Febe (accesso e verifiche) e il suo unico client del sito (§6.0), solo verso le operazioni di `richieste.<sito>.json`, più il CDN alle condizioni di §6.5. Nessun altro HttpClient verso domini di Instagram o Meta. Decisione di Alberto del 16 novembre 2026 (#36).
|
||||
4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1. Il client del sito: user agent copiato tale e quale dal browser, intestazioni solo dal modello, nessun rinvio seguito, una richiesta per volta con il permesso del Governatore, mai scritture (§2 regola 2, §6.0).
|
||||
5. CAPTCHA, verifiche e codici non si risolvono mai in automatico: Febe si ferma e avvisa.
|
||||
6. Sola lettura (niente mi piace, segui, commenti, messaggi) e solo ciò che l'account di Alberto vede già.
|
||||
7. Un account, un motore. I cookie non si copiano da una macchina all'altra.
|
||||
7. Un account, un motore. La sessione si copia solo dal browser di Febe nella sessione salvata cifrata della stessa istanza: mai su un'altra macchina, mai esportata, mai incollata da fuori. Browser e client del sito non la usano insieme.
|
||||
8. Ogni azione del motore verso il sito passa da IGovernor. Al primo segnale di §7.6 ci si ferma.
|
||||
9. I lettori si scrivono solo su campioni reali ripuliti. Il formato delle risposte non si inventa.
|
||||
10. Mai password, cookie, tasti o corpi di risposta nei log. Il client CDP registra solo nomi di comandi.
|
||||
10. Mai password, cookie, gettoni, tasti, variabili o corpi di richieste e risposte nei log. Il client CDP registra solo nomi di comandi; il client del sito solo operazione o forma del percorso e stato.
|
||||
11. La libreria non cancella e non sostituisce file da sola.
|
||||
12. Dipendenze a elenco chiuso (§3): prima di aggiungerne una, chiedi.
|
||||
|
||||
|
||||
@@ -279,3 +279,85 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-10-20 | Le prove dell'interfaccia aspettano lo stato finale di una pagina, mai uno di passaggio come il mosaico vuoto che la Libreria mette sullo schermo prima della risposta di `/api/library/days` | Issue #5: `TheBackButtonAsksBeforeLosingUnsavedChanges` aspettava `.vuoto-pagina` o `.mosaico`, ma una libreria vuota con Febe non collegato finisce sul benvenuto; la prova passava solo se il primo controllo cadeva nei circa 10 ms in cui c'è il mosaico vuoto (provato con Chrome: con il primo controllo ritardato di 5 ms o più falliva sempre) |
|
||||
| 2026-10-20 | Lo stato vuoto della Libreria senza filtri segue il collegamento finché è sullo schermo: se il motore risponde dopo la libreria, al suo arrivo compare il benvenuto del primo avvio; quando Febe si collega, il benvenuto lascia il posto alla libreria vuota. Si ridisegna solo quando cambia tipo. La prova trattiene `/api/engine` fino a un suo segnale e toglie `EventSource` (l'interfaccia ripiega su `/api/engine`) | Prima la scelta si faceva una volta sola, alla risposta della libreria: con il motore in ritardo il primo avvio mostrava la libreria vuota invece dei due pulsanti di §10.3, e ci restava (provato con Chrome trattenendo `/api/engine`). Un segnale invece di un ritardo: l'ordine delle risposte non dipende dalla velocità della macchina |
|
||||
| 2026-10-20 | Finché lo stato del motore non è noto, la Libreria vuota senza filtri non mostra nessuno stato vuoto: un riquadro vuoto con `aria-busy`, come il mosaico mentre carica, che il primo stato del motore sostituisce con il benvenuto o con «La libreria è ancora vuota». La prova aspetta quel riquadro, il conteggio «0 …» e nessuno stato vuoto | Senza il motore non si sa se è il primo avvio: «La libreria è ancora vuota» mostrata nell'attesa era falsa al primo avvio e poi lasciava il posto al benvenuto con un salto della pagina (rilievo della revisione). Il riquadro della barra laterale dice già «Caricamento…» finché il motore non risponde, e il motore arriva comunque: il flusso `/api/eventi` lo manda appena si apre e, senza flusso, l'interfaccia lo richiede a intervalli |
|
||||
| 2026-10-21 | Nelle prove dell'interfaccia una risposta è in ritardo perché la prova la trattiene, mai per un tempo fisso. `UiBrowser.Requests` (al posto di `FetchDelays`) trattiene le richieste scelte finché la prova non le rilascia (`__hold`, `__release`: il rilascio chiude la regola, così lo stesso indirizzo si può trattenere di nuovo, e trattenerlo due volte insieme è un errore), conta quelle partite (`__started`) e quelle finite (`__done`: dopo la continuazione della pagina e, se lo legge, dopo il corpo della risposta) e registra ogni richiesta della pagina (`__asked`). La prova aspetta che la pagina abbia chiesto, fa ciò che deve venire prima (lasciare la pagina, cambiare filtro), rilascia e controlla quando la pagina ne ha finito | Issue #8: `APageLeftWhileLoadingLeavesNothingBehind` tornava alla Libreria 200 ms dopo `navigate('/attivita')`. Su una macchina lenta Attività non aveva ancora caricato `activity.js` e `day-strip.js`: la pagina era lasciata prima di montarsi, `/api/alerts` non partiva mai e l'attesa scadeva dopo 30 s. Con Chrome rallentato 20 volte (`Emulation.setCPUThrottlingRate`, solo in locale) falliva 3 volte su 3 con lo stesso messaggio e la stessa riga, e in 4 giri su 5 i due moduli arrivavano dopo il ritorno alla Libreria (fra 212 e 549 ms). `ABrowserPageLeftWhileLoadingNeverTakesTheBrowser` aveva una finestra di 150 ms, e la sua regola di 600 ms tratteneva anche un `begin` mandato per errore, che arrivava al server dopo il controllo: con la pagina Browser rotta apposta la prova passava. Una regola rilasciata restava e valeva per prima: un secondo `__hold` dello stesso indirizzo lasciava passare subito la richiesta, e la prova avrebbe lasciato la pagina a risposta già arrivata (rilievo della revisione) |
|
||||
| 2026-10-21 | Che dopo «Ho finito», dopo «Riprendi» o lasciando una pagina il browser non sia preso né restituito un'altra volta, le prove lo controllano quando la pagina è quieta (`WaitForQuietAsync`: nessuna richiesta in volo, quindi ogni comando è arrivato al server e la pagina ha finito il seguito di ogni risposta, comprese le richieste che fa partire lì; non aspetta ciò che la pagina rimanda, come le richieste di un osservatore, di un fotogramma, di un timer, del flusso degli eventi o di un modulo che si carica dopo, e qui basta perché il comando sbagliato partirebbe lasciando la pagina o nel seguito di una risposta) sull'elenco delle richieste della pagina (`__asked`) e su quelle viste dal server; non dopo una pausa di 300 o 500 ms. La vista chiusa sul server si aspetta | Con la pausa una macchina lenta poteva controllare prima che il comando sbagliato arrivasse, e la prova passava lo stesso; dopo «Riprendi» la vista chiusa si controllava dopo 300 ms, e lì una macchina lenta faceva fallire la prova. Con copie dell'interfaccia rotte apposta (un «cancel» dopo «Ho finito» nelle pagine Browser e Collegamento, un «begin» dopo «Riprendi», un «begin» che parte solo dopo una risposta del motore) le quattro prove falliscono in ogni giro provato, anche con Chrome rallentato 20 volte. La quiete non copre ciò che parte più tardi (rilievo della revisione): sulla Libreria con 40 elementi, al primo momento senza richieste in volo le 11 righe del mosaico, chieste da un IntersectionObserver dopo il disegno dei giorni, non erano ancora partite in 3 giri su 6 |
|
||||
| 2026-10-21 | La prova dei tasti della vista remota li manda quando il WebSocket della pagina è aperto (`__sockets` di `UiBrowser.Requests`), non 300 ms dopo che il server ha aperto la vista; la prova del mouse scrive meta e fotogramma senza pausa | Il server apre la vista prima di rispondere al socket (`RemoteViewSocket.HandleAsync`) e la pagina scarta i messaggi finché il socket non è aperto: su una macchina più lenta di 300 ms i tasti andavano persi e la prova falliva dopo 30 s. Ciò che il server scrive resta nella vista finché il socket non è aperto e la pagina ascolta da subito, quindi la pausa del mouse non serviva: il primo fotogramma sullo schermo dice già che il socket è aperto |
|
||||
| 2026-10-21 | I ridisegni rimandati di una pagina (`later`: 150 ms in «In evidenza») le prove li aspettano come timer: `PageTimers` dice quali timeout erano in sospeso in un dato momento e quando sono finiti; dopo un cambio di dimensione si aspetta un ResizeObserver della prova, chiamato dopo quelli della pagina, e i timer che quelli hanno lasciato. Il trascinamento della maniglia della fascia aspetta ogni passo nel campo dell'ora prima del successivo; l'intestazione dell'account non ha più una pausa fra un'azione e l'altra | Con pause di 500 e 600 ms il ridisegno sbagliato poteva arrivare dopo il controllo. Con 60 ms fra un passo e l'altro una macchina lenta può consegnare più passi come un solo movimento: la prova vedeva solo l'ultimo e non provava più che la maniglia segua tutto il trascinamento. La pausa dell'intestazione non proteggeva nulla: ogni giro aspetta già il menu ridisegnato. Con copie rotte apposta (ridisegno non annullato, osservatore non staccato, tessere tardive disegnate, trascinamento che finisce al primo passo) le prove falliscono in ogni giro provato, anche a 20x; il ridisegno non annullato si vede quando è ancora in sospeso al cambio di filtro, come prima (in tutti i giri provati lo era) |
|
||||
| 2026-10-21 | `APageLeftWhileLoadingLeavesNothingBehind` controlla che Attività, lasciata mentre carica, non lasci né il timer di un minuto, né l'ascolto della libreria, né avvisi sulla Libreria; e che, aperta, a una modifica della libreria si ricarichi. La modifica la prova la manda alla pagina come la manda il flusso degli eventi (un evento «libreria» sul suo `EventSource`, che chiama subito chi ascolta) e ne ha conferma quando la Libreria richiede i suoi giorni; gli avvisi li registra un MutationObserver, anche quelli già spariti | Rilievo della revisione: il controllo «niente di Attività sulla Libreria» guardava solo `main`, dove Attività non disegna (la sua cornice ne esce prima ancora che il modulo si carichi), e poteva fallire solo per un nodo messo lì direttamente. Con copie rotte apposta la prova di prima passava con l'ascolto della libreria rimasto e con l'errore delle richieste annullate mostrato sulla Libreria; ora le trova entrambe, a velocità normale e con Chrome rallentato 20 volte. Una modifica pubblicata sul server non darebbe lo stesso ordine: il flusso si iscrive alle modifiche in un `Task.Run`, senza dire quando, e le raccoglie per 300 ms |
|
||||
| 2026-10-21 | La pulizia toglie anche ciò che non serve più a nessuno, di qualunque progetto, e non più solo ciò che è della CI di Febe. Alla fine di ogni lavoro «immagine» (verifica e rilascio), dopo la pulizia dell'esecuzione, `pulizia-docker.sh penzolanti`: `docker image prune -f` e `docker builder prune -f --filter until=24h` (senza `-a`), che non fa mai fallire il lavoro. Ogni lunedì e a mano `pulizia-docker.sh completa`: i resti della CI di Febe come prima, i resti di act_runner, `docker image prune -a -f --filter until=24h`, `docker builder prune -a -f --filter until=24h`, con `REGISTRY_TOKEN` le `:sha-` del registro oltre le 10 più recenti, `docker system df` prima e dopo e un riepilogo. Mai `system prune`, `container prune`, `volume prune`, `network prune`, né un contenitore, un volume o una rete che non sia della CI. Per ciò che nessuno usa sostituisce il «mai le immagini degli altri progetti, mai la cache di costruzione del demone, mai le immagini col nome del registro» del 20 ottobre | Decisione di Alberto del 21 ottobre: «aggiungi il prune delle immagini non più utilizzate nel workflow di Actions, in modo da eliminare tutto quello che non serve più». Docker stesso non toglie mai un'immagine usata da un contenitore, acceso o fermo, quindi le applicazioni di Unraid e un Febe vero tengono le loro; le 24 ore lasciano stare ciò che un'altra costruzione ha appena prodotto (per la cache contano dall'ultimo uso; per le immagini dipende dallo store, riga sullo store più sotto). Il prezzo è scritto in `docs/processo.md` («Pulizia»): le immagini di base si riscaricano, le costruzioni ritrovano meno cache, un'immagine costruita a mano e tenuta senza contenitore va ricostruita. `docker builder prune` senza `-a` toglie ciò che nessuna immagine condivide: BuildKit salta solo i record interni, del frontend e condivisi (`cache/manager.go`), quindi senza un limite d'età a ogni push di ogni ramo se ne andrebbero anche gli strati intermedi e le cache montate che le costruzioni degli altri progetti hanno appena usato, e la finestra di 24 ore del lunedì non servirebbe. Per questo anche dopo ogni esecuzione `until=24h`, che BuildKit confronta con l'ultimo uso (rilievo della revisione: il compito chiedeva il comando senza filtro, che non è innocuo per gli altri progetti; se Alberto lo preferisce, basta togliere il filtro) |
|
||||
| 2026-10-21 | Resti di act_runner: contenitori fermi (`exited`, `created`, `dead`), volumi e reti il cui nome comincia con `GITEA-ACTIONS-TASK-<numero>` seguito da `_` o `-`, più vecchi di 90 minuti; volumi e reti solo se nessun contenitore, nemmeno fermo, li usa (`docker ps -a --filter volume=…` e `network=…`). Contenitori e volumi senza `-f`; il volume `act-toolcache` resta | act_runner dà a tutto ciò che crea per un lavoro il prefisso `GITEA-ACTIONS-TASK-<id del compito>` (`internal/app/run/runner.go`); act chiama il contenitore `<prefisso>_WORKFLOW-<flusso>_JOB-<lavoro>` (`createSimpleContainerName`; le versioni più vecchie `-WORKFLOW-…-JOB-…-<impronta>`), i volumi `<nome>` e `<nome>-env`, la rete `<nome>-<lavoro>-network`, e monta `act-toolcache`, la cache degli strumenti di tutti i lavori (`pkg/runner/run_context.go`; controllato su gitea.com il 21 ottobre). Un lavoro vivo ha il contenitore acceso e usa volumi e rete; i 90 minuti, come per i resti della CI di Febe, coprono l'istante in cui un lavoro che parte li ha creati e non ancora usati, se un giorno il runner farà più lavori insieme. Il `Created` di una rete si legge con `{{json .Created}}`: senza, il modello lo stampa nel formato di Go e non in RFC 3339 |
|
||||
| 2026-10-21 | Registro: con `REGISTRY_TOKEN` la pulizia del lunedì toglie le etichette `sha-<da 7 a 40 cifre esadecimali>` del pacchetto container `febe` oltre le 10 più recenti per data di creazione, con l'API dei pacchetti di Gitea 28: `GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50` fino alla prima pagina vuota e `DELETE /api/v1/packages/{proprietario}/container/febe/{versione}` (risponde 204). Sceglie `.gitea/scripts/versioni-registro.js` (Node, senza rete, provato con `tests/Febe.Tests/Packaging/versioni-registro.json`); lo script ricontrolla la forma prima di ogni DELETE. Mai `main`, `latest`, `X.Y.Z` (anche `-rc.N`), i digest o altro; un rifiuto dell'API è un avviso, non un lavoro rosso; il token sta solo nell'intestazione di curl e non si stampa | Percorsi controllati sul codice di Gitea `release/v28` (`routers/api/v1/api.go`: `ListPackageVersions` e `DeletePackageVersion` nel gruppo `/packages/{username}`, con token e ambito «package»; `routers/api/v1/packages/package.go`: `page` e `limit`, versioni interne escluse, DELETE con 204) e su docs.gitea.com («List package versions», «Delete a package version»). In Gitea ogni etichetta di un contenitore è una versione del pacchetto con i suoi file: togliere `sha-…` non tocca `main` o una versione che puntano allo stesso manifest, e i blob rimasti senza riferimenti li toglie la pulizia dei pacchetti di Gitea (`[cron.cleanup_packages]`), purché l'immagine sia un manifest semplice e non un indice (riga seguente sulle attestazioni). Le versioni `sha256:…` senza etichetta non si toccano mai: si contano soltanto. Node e non jq: Node c'è in ogni contenitore dei lavori (lo usano le azioni) e nelle prove, jq non c'è in `node:24-trixie` né in Git Bash. Prende il posto della regola di pulizia dei pacchetti suggerita il 20 ottobre |
|
||||
| 2026-10-21 | L'immagine di Febe si costruisce e si pubblica senza attestazioni: `--provenance=false --sbom=false` fra gli argomenti comuni di `.gitea/scripts/costruisci-immagine.sh` (l'archivio provato e la spinta sul registro), così sul registro ogni etichetta è un manifest semplice | Con il builder `docker-container` buildx aggiunge da sé l'attestazione di provenienza (`mode=min`; docs.docker.com, «Build attestations») e l'immagine spinta diventa un indice con due figli spinti per digest, l'immagine e l'attestazione. Gitea tiene ogni figlio come una versione a sé, `sha256:…` senza etichetta, a cui sono legati configurazione e strati (release/v28, `routers/api/packages/container/manifest.go`: `processOciImageManifest` lega i blob alla versione del manifest stesso con `createFileFromBlobReference`, `processOciImageIndex` salva solo l'indice e le proprietà `container.manifest.reference`), e togliere un'etichetta toglie solo i file di quella versione: gli strati sarebbero rimasti per sempre (rilievo della revisione). Con un manifest semplice gli strati stanno nella versione dell'etichetta, e quando nessuna versione li usa più li cancella `[cron.cleanup_packages]` (attiva per impostazione predefinita, `@midnight`, `OLDER_THAN = 24h`: `custom/conf/app.example.ini`). Si perde l'attestazione di provenienza, che nessuno legge: da dove viene l'immagine lo dicono le etichette `febe.ci.*` e quelle OCI. Le versioni `sha256:…` (spinte a mano, o con più piattaforme; la CI non ha ancora pubblicato nulla, perché manca `REGISTRY_TOKEN`) lo script non le tocca, perché l'API dei pacchetti non dice se un indice le rimanda ancora, e ne scrive il numero; se servisse, le toglie una regola di pulizia di Gitea con schema `sha256:.+` e 7 giorni, che salta quelle rimandate e sempre `latest` (`services/packages/container/cleanup.go`, `ShouldBeSkipped`; schema confrontato con tutta la versione, `(?i)\A…\z`) |
|
||||
| 2026-10-21 | Prova della pulizia: `pulizia.yml` ha l'input `prova` (`type: boolean`, `default: false`, «Solo prova») e il passo passa `gitea.event.inputs.prova` allo script, che con `--prova` elenca che cosa toglierebbe (immagini con dimensione ed età, cache di costruzione, resti della CI di Febe e di act_runner, etichette del registro) con soli comandi che leggono e, sul registro, soli GET. Nella pulizia vera le immagini le sceglie Docker; nella prova le stima lo script con la stessa regola, contando come già tolti i contenitori che la pulizia toglierebbe prima | Gitea 28 mostra un input booleano come una casella (`templates/repo/actions/workflow_dispatch_inputs.tmpl`) e nell'evento lo scrive come testo, «true» o «false» (`routers/web/repo/actions/view.go`, `Run`: `strconv.FormatBool(ctx.FormBool(name))`); il lunedì l'evento non ha input, e la stringa vuota vuol dire pulizia vera. Il passo accetta solo «true» (la prova) e «false» o niente (la pulizia vera): un avvio con l'API passa il valore così com'è (`routers/api/v1/repo/action.go`, `ActionsDispatchWorkflow`: `inputs[name] = value`, senza conversione), e qualunque altro valore («True», «1») ferma il lavoro con un errore senza toccare nulla. Allo stesso modo lo script, prima di chiamare Docker, rifiuta con codice 2 ogni opzione diversa da `--prova` e ogni argomento in più: una prova scritta in un altro modo (`--dry-run`, `-n`, `prova`) prima faceva partire la pulizia vera con codice 0 (rilievo della revisione) |
|
||||
| 2026-10-21 | `pulizia-docker.sh` gira con `BUILDX_BUILDER=default`: la cache che pota è quella del builder del demone | Con il plugin buildx `docker builder` diventa `docker buildx` (`cmd/docker/builder.go` del client Docker), che lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione, che `setup-buildx-action` crea con `--use` (`src/context.ts`) e che il modo «esecuzione» ha già tolto. I comandi buildx che toccano i builder di Febe li indicano per nome |
|
||||
| 2026-10-21 | Il lavoro «controlli» legge anche gli script Node della CI (`node --check .gitea/scripts/*.js`) | Come `bash -n` per gli script di shell: un errore di sintassi in `versioni-registro.js` si vede in pochi secondi, non alla pulizia del lunedì |
|
||||
| 2026-10-21 | Nei modi «settimanale» e «completa» la pulizia legge lo store delle immagini del demone (`docker info --format '{{json .DriverStatus}}'`: con `io.containerd.snapshotter.v1` è quello di containerd, altrimenti il classico) e lo scrive all'inizio; con containerd, o se non lo sa, la prova avverte che le età che elenca sono solo indicative | Da quando contano le 24 ore di `image prune --filter until` dipende dallo store (rilievo della revisione). Con quello classico Docker confronta il `Created` della configurazione, cioè la costruzione (moby, `daemon/images/image_prune.go`: `img.Created.After(until)`); con quello di containerd il `CreatedAt` del record dell'immagine sul demone (`daemon/containerd/image_list.go`: `image.CreatedAt.Before(until)`), che containerd conserva quando lo stesso nome viene riscaricato. Nessun comando mostra quel `CreatedAt` (`docker image ls` dà il `Created` della configurazione anche con containerd), quindi la prova resta sull'età dalla costruzione e lo dice. Lo store di containerd è il predefinito nelle installazioni nuove di Docker Engine dalla 29; su Unraid è più probabile quello classico. `docker info` solo legge |
|
||||
| 2026-10-21 | Della pulizia del lunedì si dice anche che cosa `image prune -a` toglie alle immagini che un contenitore usa: i nomi in più. La pulizia vera confronta i nomi prima e dopo e scrive, nome per nome, quelli tolti a un'immagine che resta; la prova li stima secondo lo store (classico: tutti tranne l'ultimo in ordine alfabetico del nome completo, `docker.io/library/…` per Docker Hub; containerd: tutti tranne quelli da cui i contenitori sono stati creati, e l'ultimo se un contenitore la usa per identificativo). Il comando resta quello chiesto | Rilievo della revisione: la prova saltava ogni immagine in uso, e i documenti dicevano che un'immagine usata da un contenitore non si tocca. Docker non toglie l'immagine, ma con lo store classico `ImagesPrune` non guarda i contenitori e chiama `ImageDelete` senza forza su ogni riferimento, in ordine alfabetico (`daemon/images/image_prune.go`, uguale in moby v24.0.9, v27.5.1 e master; `reference/store.go`, `lexicalRefs`); `ImageDelete` rifiuta solo l'ultimo riferimento di un'immagine in uso (`image_delete.go`, `isSingleReference`), quindi può sparire proprio il nome da cui il contenitore è stato creato (un'applicazione di Unraid creata da `app:1.2` che si chiama anche `app:latest`). Con containerd `filterImagesUsedByContainers` protegge solo il nome di `Config.Image` e, se il contenitore usa l'immagine per identificativo o digest, l'ultimo nome (`daemon/containerd/image_prune.go`). Il demone finto delle prove fa lo stesso con l'uno e con l'altro store |
|
||||
| 2026-10-25 | I primi campioni reali di Instagram vengono dal file HAR che Alberto ha esportato dal suo browser il 21 ottobre (DevTools, filtro Fetch/XHR), non dalla sonda: le sole risposte utili sono state convertite nel formato grezzo della sonda in una cartella temporanea fuori dal repository, accorciate dal lato grezzo (raccolte: 2 per 4 contenuti, scelti fra foto, video con audio e video senza; pagina successiva: 1 per 3; profili suggeriti: i primi 3), ripulite con `febe-sonda ripulisci` e controllate con `febe-sonda verifica` («Verifica superata»). Del HAR si è letta solo la forma (percorsi, tipi, chiavi), mai valori, intestazioni o cookie; i grezzi convertiti si cancellano a fine lavoro | Richiesta di Alberto del 25 ottobre («vedi tu quale ti risulta più utile»: HAR o guida). La guida descrive richieste costruite a mano verso l'API, con intestazioni copiate, vietate dalle regole 2–4 di §2, e un formato (`GraphImage`, `edge_sidecar_to_children`) che nel HAR non compare: non si usa. Il HAR invece è ciò che la pagina riceve davvero, cioè il campione reale che chiede la regola 10. Accorciare dal lato grezzo tiene i campioni piccoli senza cambiarne la forma; la ripulitura costruisce l'elenco dei frammenti sensibili da tutto il grezzo, quindi accorciare dopo non servirebbe |
|
||||
| 2026-10-25 | La cattura legge come dati anche le risposte `text/javascript` (e ogni tipo che contiene «javascript») che la pagina chiede da sé (risorsa XHR o Fetch), oltre a quelle dichiarate JSON; i file di script non si leggono mai. Una sola regola, `DataResponses.IsData`, per `ResponseTap` e `CaptureCollector` | Nel HAR tutte le risposte GraphQL (`/graphql/query`, `/api/graphql`: storie, raccolte, ricerca) sono `text/javascript`; solo le REST (`/api/v1/…`) sono `application/json`. Con la regola di prima Febe scartava proprio i dati di storie e raccolte: è il motivo per cui non leggeva nulla. Le risposte con il prefisso `for (;;);` (`/ajax/…`: definizioni delle pagine, registri di navigazione) non sono JSON e non portano contenuti: restano scartate |
|
||||
| 2026-10-25 | Del documento principale di una pagina del sito (`text/html`, cornice principale) si leggono i blocchi `<script type="application/json">`: ogni blocco arriva ai lettori come una risposta a sé, con il descrittore del documento, letto mentre si scorre e uno solo in memoria alla volta (`DataResponses.EmbeddedJsonBlocks`); un documento senza blocchi validi si segnala scartato una volta; `febe-sonda da-har` scrive un campione per blocco. Il corpo del documento si chiede con `Network.getResponseBody`, già nell'elenco ammesso | Una pagina aperta per indirizzo (`Page.navigate`, come fanno tutte le ricette) riceve i dati del primo schermo dentro il documento e chiede con XHR solo le pagine successive: senza, la prima pagina di un profilo arriverebbe «vuota». **Da confermare dal vivo**: il HAR del 21 ottobre non conteneva documenti. Se i dati arrivano invece con XHR, la lettura del documento non trova nulla e non cambia niente. Blocco per blocco e non riuniti in un array (rilievo della revisione): riuniti davano una sola lettura con una sola paginazione, la prima del documento, e il «has_next_page» delle raccolte o il «more_available: false» di un post finiva sugli elementi di un altro blocco. Da confermare dal vivo: le regole di testo di `segnali.json` ora vedono anche i blocchi piccoli uno per uno. L'arrivo del documento non cancella più la sua stessa richiesta in corso (la cornice cambia documento prima che il corpo sia finito: si tiene la richiesta con l'identificativo del caricatore nuovo) |
|
||||
| 2026-10-25 | Nel vocabolario dei lettori, `relevance.keys`: se una risposta non contiene nessuna di quelle chiavi è «non pertinente» (`ReadShape.Unrelated`) e si ignora, invece di contare come forma sconosciuta; `CaptureCollector` non la conserva nemmeno, così una pagina che continua a mandare registri si assesta lo stesso. Per Instagram: `image_versions2`, `video_versions`, `carousel_media`, `taken_at`, `username`; per il sito di prova l'elenco è vuoto e tutto resta come prima | Instagram manda molte risposte JSON che non c'entrano con i contenuti (promozioni, il segno «storia vista», registri). Con le risposte `text/javascript` lette, ognuna di queste avrebbe fermato una ricetta come «formato non riconosciuto» ogni volta che il dato atteso tardava. Una risposta che ha le chiavi dei contenuti ma una forma che il vocabolario non descrive resta «formato non riconosciuto» (§6.4). L'elenco non si ricava dal vocabolario: sul sito di prova la forma sconosciuta di prova non ha nessuna sua chiave e deve restare sconosciuta |
|
||||
| 2026-10-25 | `IResponseObserver.OnBodyDropped`: la cattura avvisa quando il corpo di una risposta annunciata non arriverà (troppo grande, caricamento fallito, non JSON, pagina cambiata, browser riavviato), e `CaptureCollector` smette di aspettarlo | Prima un corpo scartato restava «in arrivo» per 15 secondi e `SettleAsync` non si assestava: con le risposte `/ajax/…` di Instagram, che arrivano a ogni scorrimento e cambio di pagina, ogni raffica avrebbe aspettato fino al limite |
|
||||
| 2026-10-25 | `lettori.instagram.json` è «confermato» e compilato soltanto con chiavi che compaiono nei campioni ripuliti (una prova lo controlla chiave per chiave): contenuto `pk`, `code`, `taken_at`, `caption.text`, `image_versions2.candidates`, `video_versions`, `carousel_media` e `carousel_media_count` (chiavi viste ma sempre vuote: nessuna serie nei campioni), `user`/`owner`, `expiring_at`, `video_duration`; versione `url`, `width`, `height`; profilo `pk`/`id`, `username`, `full_name`, `is_private`, `friendship_status.following`, `hd_profile_pic_url_info`/`hd_profile_pic_versions`/`profile_pic_url`, `latest_reel_media`; raccolta `id`, `title`, `user`, `items`; pagina `has_next_page`/`more_available`, `end_cursor`; account collegato `xdt_viewer.user`. Restano vuoti `pinned`, `postCount` e `version.hasAudio` | Regola 10. `has_audio` sta sul contenuto, non sulla versione: ogni versione di `video_versions` conta come file completo (H5 si conferma scaricando). Le versioni video delle storie non hanno dimensioni: si prende la prima (101), che nei post ha le stesse dimensioni e la stessa banda delle altre due. `xdt_viewer.user` ha solo l'identificativo: il lettore lo tiene (`ReadResult.ViewerId`) per riconoscere l'account collegato quando il suo profilo compare altrove (H10 resta aperta) |
|
||||
| 2026-10-25 | L'identificativo di una raccolta si tiene nella forma dell'indirizzo: dal `highlight:17841…` dei dati il lettore toglie un prefisso fatto di sole lettere e due punti. Un oggetto con `id` e `title` è una raccolta solo se ha anche il proprietario o i contenuti (quando il vocabolario li nomina) | Nel HAR i dati dicono `highlight:<17 cifre>` e l'indirizzo del visualizzatore `/stories/highlights/<17 cifre>/`: senza normalizzare, ricetta e visualizzatore non si sarebbero mai riconosciuti. Senza il secondo vincolo una promozione o una sezione di pagina con `id` e `title` diventava una raccolta finta, e quelle vere sarebbero risultate tolte |
|
||||
| 2026-10-25 | Ripulitura: `latest_reel_media` è una data (si tiene); i valori sotto chiavi che hanno l'aspetto di un segreto (`token`, `key`, `secret`, `session`, `cookie`, `auth`, …) diventano un riempitivo neutro della stessa forma (lettere `x`, cifre `7`) invece di un valore finto vario | `latest_reel_media` è la data dell'ultima storia, della stessa natura di `taken_at`. Un valore finto estratto lettera per lettera da un `organic_tracking_token` di 340 caratteri sembra un segreto vero a gitleaks, che nella CI avrebbe fermato il lavoro «controlli» su dati finti; il riempitivo ha la stessa forma e nessuna entropia |
|
||||
| 2026-10-25 | Senza l'identificativo del contenuto nell'indirizzo del visualizzatore (Instagram: `/stories/highlights/{highlight}/`, uguale per tutti i contenuti della raccolta) i contenuti si contano sull'elenco ricevuto: il primo mostrato è il primo dell'elenco e ogni clic su «avanti» ne sposta uno; il conteggio non va mai avanti senza un clic. Un video si lascia entro l'inizio del clic + la sua durata − 1,5 s × umore·ritmo; se non si fa più in tempo, si chiude senza «avanti» e i contenuti dopo non si salvano (evento «visualizzatore-chiuso-prima»). Con l'identificativo nell'indirizzo (le storie, `/stories/{username}/{id}/`) si segue l'indirizzo come prima. In entrambi i modi il permesso StoryView per il contenuto successivo si chiede appena quello attuale è a video, prima dell'attesa di §7.7 (che si conta da quando è comparso); un contenuto comparso da solo dopo l'ultimo dell'elenco non si salva e il visualizzatore si chiude | Nel HAR quattro richieste fatte guardando contenuti diversi di una raccolta hanno lo stesso Referer: l'indirizzo non dice quale contenuto è a video. Regola 7 e §6.3: nella prima versione il permesso arrivava dopo che il contenuto era già comparso, e con umore o ritmo oltre 1 il clic cadeva dopo la fine del video, saltava un contenuto e portava nella raccolta successiva (rilievi della revisione). Meglio perdere contenuti che salvarne di non mostrati. Restano da misurare dal vivo il clic che la pagina ignora (il conteggio andrebbe avanti) e quanto il sito tiene una foto; con la spaziatura di 4 s del Governatore i video più brevi di 4–6 s si chiudono prima |
|
||||
| 2026-10-25 | Anche dopo un errore imprevisto (non dopo un segnale di arresto) la ricetta chiude il visualizzatore e salva ciò che è stato mostrato fin lì. Un visualizzatore che non si chiude con «viewer-close» ferma la ricetta come «bersaglio non trovato», anche dopo un altro arresto (tetto, errore); dopo un annullamento si salva ciò che è stato mostrato e la pagina resta com'è; ciò che un clic apre a un indirizzo che la mappa non riconosce si chiude prima di fermarsi | Un visualizzatore lasciato aperto passa da solo alle storie degli account successivi (§6.3), e solo «bersaglio non trovato» ferma la sessione e mette la pagina a riposo. Prima un indirizzo senza identificativo del contenuto faceva fallire la ricetta con il visualizzatore aperto, e un annullamento (pausa, segnale), che arriva quasi sempre durante l'attesa su una storia, faceva perdere storie già segnate come viste |
|
||||
| 2026-10-25 | Il bersaglio `profile-not-found` è facoltativo per Controllo del profilo, Storico, Taggati e Reel: si cerca solo se la mappa lo imposta; senza, un profilo che non c'è non dà dati ed è giudicato come una pagina vuota | Per Instagram non c'è ancora un segno verificato (H11) e le ricette del profilo devono poter girare con le sole pagine. Con il segno impostato l'account si segna «Non raggiungibile» come prima |
|
||||
| 2026-10-25 | Dopo aver aperto profilo, home ed elenco dei seguiti (e dopo il clic su una scheda) le ricette aspettano il dato atteso, lasciano assestare la pagina e prendono tutto ciò che è arrivato dal segno in poi; Controllo e Storico aspettano anche la prima pagina della griglia (fino a 20 s). La paginazione di un cammino viene solo dalle risposte che portano i suoi elementi, o da una pagina vuota; l'elenco dei seguiti non salva mai un profilo con `IsFollowed` falso (i profili suggeriti), né l'account collegato; la home «è arrivata» con contenuti, una voce della barra delle storie o una pagina, non con soli profili. «Tu» nasce anche da `ViewerId` più un profilo con lo stesso identificativo in una risposta qualunque del giro | Su Instagram intestazione del profilo, griglia, raccolte e home arrivano in risposte diverse, anche dopo la prima; risposte su altro (un post con `more_available:false`, le raccolte con `has_next_page:false`) dicono «non ce n'è altro» di sé stesse e avrebbero chiuso uno storico; i 30 profili suggeriti hanno `friendship_status.following:false`. Sul sito di prova, dove tutto arriva insieme, il comportamento resta quello di prima |
|
||||
| 2026-10-25 | Una ricetta che la mappa dei bersagli o il vocabolario dei lettori non lasciano girare finisce in `NotConfigured` («Da configurare»), non più in «bersaglio non trovato» o «formato non riconosciuto»: non conta per la sospensione, il motore non la pianifica, lo dice una volta per ricetta e per avvio, e annulla con un evento un comando di Alberto che non può partire. Senza il giro dei seguiti le storie dei seguiti si controllano account per account | I rifiuti dei primi file di Instagram, che erano scheletri, contavano come guasti: dopo tre sessioni il motore sospendeva le ricette come se Instagram fosse cambiato, e le sospensioni restavano anche con file nuovi |
|
||||
| 2026-10-25 | All'avvio Febe calcola un'impronta SHA-256 di `lettori.<sito>.json` e `bersagli.<sito>.json` come caricati (incorporati o copia nella cartella Dati, fine riga ignorati) e la conserva in `motore.configurazione-raccolta`; quando cambia, e al primo avvio che la calcola, azzera una volta sospensioni ed errori consecutivi delle ricette, con una riga in Attività se c'era qualcosa da azzerare. Il registro (fonte «raccolta») dice da dove vengono i due file e com'è il vocabolario, quali ricette non possono girare, e avvisa se una copia nella cartella Dati è ancora «ipotesi» mentre quella incorporata è «confermato» o ferma ricette che quella incorporata lascerebbe girare. Mai il contenuto dei file | Le sospensioni contate con i file vecchi non devono sopravvivere a quelli nuovi, e nel database di Alberto con ogni probabilità ce ne sono. Una copia vecchia nella cartella Dati vince sempre su quella incorporata: senza il registro resterebbe invisibile. La cartella `config/` accanto al programma non si legge mai (la riga del 13 ottobre lo dava per vero) |
|
||||
| 2026-10-25 | Lo stato del collegamento nella barra laterale viene dal cookie di sessione (dal modo del motore, o dal servizio di collegamento quando il motore non gira), non dal fatto che l'account «Tu» sia già noto | Su Instagram «Tu» può arrivare molto dopo il collegamento (H10: i dati danno solo l'identificativo dell'account collegato) e la barra diceva «Da collegare» mentre Febe raccoglieva |
|
||||
| 2026-10-25 | `bersagli.instagram.json`: compilate solo le pagine con una prova reale nel HAR del 21 ottobre (i modelli che Instagram stesso manda in `/ajax/bulk-route-definitions/` e i Referer delle richieste della pagina): home `/`, profilo `/{username}/`, post `/p/{code}/`, storie `/stories/{username}/{id}/`, raccolte `/stories/highlights/{highlight}/` senza identificativo del contenuto. Vuoti l'elenco dei seguiti, le pagine di ripresa e tutti i bersagli (H11). La forma delle storie coincide anche con l'indirizzo delle raccolte (nome utente «highlights»): accettato, perché per le storie è «un altro account» e il visualizzatore si chiude, e la ricetta delle raccolte legge solo la sua pagina | Regola 10: niente di inventato. Il HAR non aveva documenti né attributi degli elementi, quindi nessun ruolo né nome accessibile. Girano le ricette che aprono solo pagine (giro dei seguiti, controllo del profilo, storico, post singolo); storie, raccolte, Taggati e Reel aspettano i bersagli |
|
||||
| 2026-10-25 | `febe-sonda da-har --har <file> --a <cartella>`: un HAR esportato dagli strumenti per sviluppatori diventa una cartella di campioni grezzi nel formato della sonda: solo le risposte di dati del sito (`DataResponses.IsData`) e il JSON incorporato nei documenti, mai intestazioni, cookie, query o corpi delle richieste; il nome del file viene dall'operazione GraphQL solo se ha la forma di un nome del codice (finisce con Query, Mutation o Subscription, senza cifre ripetute), altrimenti «risposta» o «documento». Rifiuta un HAR o una cartella dentro un repository e una cartella non vuota | Alberto raccoglie più volentieri dal suo browser di tutti i giorni che con la sonda: così può ripulire e verificare da sé, sulla sua macchina, e mandare solo la copia ripulita (§14.5) |
|
||||
| 2026-10-25 | `tools/bersagli/raccogli-bersagli.js`: i bersagli si raccolgono con uno script in sola lettura che Alberto incolla nella Console del suo browser: un solo ascoltatore dei clic, nessuna modifica alla pagina, niente rete, cookie o archivi; calcola ruolo e nome accessibile come `TargetResolver`, registra la forma degli indirizzi prima e dopo il clic, sostituisce i nomi con NOME e prepara per ogni clic le voci `role`, `name`, `href` e `index` della mappa | Il HAR non porta gli attributi degli elementi; la sonda li registrerebbe, ma chiede di avviare un Chromium a parte. La forma dell'indirizzo dopo il clic dice anche se l'indirizzo delle storie segue ogni storia |
|
||||
| 2026-10-25 | La paginazione di una pagina (griglia, schede, giro dei seguiti, elenco dei seguiti) viene dalla risposta che porta più elementi non ancora incontrati, l'ultima a pari merito; una risposta che riporta solo elementi già letti non conta come pagina successiva né per la sua paginazione. Una risposta vuota senza profilo è la pagina vuota di un cammino solo quando risponde a un suo gesto (pagina di ripresa, scheda, scorrimento), mai all'apertura del profilo; con il profilo dell'account è la griglia vuota anche accanto alle raccolte, se il profilo dice «0 pubblicazioni» | Rilievi della revisione: su Instagram la pagina di un post del profilo stesso («more_available: false») e le raccolte di un account che non ne ha (connessione vuota con «has_next_page: false», forma identica a una griglia vuota) chiudevano lo storico dopo la prima pagina o senza post; sul sito di prova un profilo con raccolte e senza post aspettava 20 s a ogni controllo. Un account Instagram senza post resta così con lo storico aperto: costa un'attesa e una pagina a sessione, mai post persi |
|
||||
| 2026-10-25 | Mentre «Storie di un account» non può girare con la configurazione del sito, la visita di un profilo non seguito non serve le storie: si pianifica all'intervallo del profilo, non conta come lavoro di storie, e il giro dei seguiti non accoda «Storie segnalate dalla barra» (ogni giro segnala di nuovo l'account finché le storie non si vedono). `SyncQueue` non annulla più i «Post singolo» accodati dalla raccolta: li toglie solo per un account che non si contatta, e mentre la ricetta non può girare aspettano | Con i file di Instagram di oggi un profilo non seguito si sarebbe aperto fino a 24 volte più spesso del dovuto senza raccogliere nulla, e la Coda si sarebbe riempita a ogni sessione di storie che non sarebbero mai partite. Un «Post singolo» annullato non tornava più in coda (nessuno ricontrolla gli indirizzi scaduti), mentre §6.5 punto 5 vuole che il recupero passi da lì: difetto precedente a questo lavoro (commit `aff81df`), trovato dalla revisione. Effetto: su Instagram queste ricette ora girano davvero, dentro il loro tetto (Prudente: 10 l'ora, 60 al giorno) |
|
||||
| 2026-11-12 | Le attività di Febe stanno nelle issue di Gitea, come negli altri repository di Alberto: etichette Area/Kind/Priority/Status, un traguardo per tappa (M0–M8) e per versione, il lavoro finito come issue chiusa con il suo resoconto «Fatto». `docs/stato.md` resta il resoconto fra le sessioni e rimanda alle issue per ciò che è da fare. Motivo: richiesta di Alberto del 12/11; un posto solo per le cose da fare, visibile anche fuori dal repository. |
|
||||
| 2026-11-12 | **Strada B: la pagina chiede i dati** (issue #34). Dalla pagina di Instagram già aperta Febe chiede al sito gli stessi dati che chiede la sua applicazione web, con `Runtime.evaluate` + `fetch`, solo verso gli indirizzi di `richieste.<sito>.json` scritti da campioni reali, in sola lettura, una richiesta per volta col permesso del Governatore; i gettoni restano nella pagina e allo script torna solo il corpo. Cambiano §2 regola 2 (eccezione), §6.1 (nuova riga dei comandi e regole delle richieste), §14.5 e la regola 4 di `CLAUDE.md`; il resto di §2 non cambia | La prova dal vivo di Alberto è fallita: le ricette passive dipendono da una mappa dei bersagli e da indirizzi che si scoprono solo su Instagram, e nessuno dei 9 bersagli era compilato. Scelta di Alberto fra A (indirizzi e tastiera), B e C (misto), sapendo che B lascia una traccia diversa da una visita normale |
|
||||
| 2026-11-12 | `febe-sonda richieste --har <file> --a <file .json>`: descrive la forma delle richieste XHR/Fetch della pagina al sito (metodo, percorso con `{numero}`/`{testo}` al posto delle parti che non sono parole note del sito, nomi di parametri, intestazioni e campi del corpo, struttura delle variabili, nella query come nel corpo); dei valori solo il tipo, tranne elenchi chiusi uguali per tutti (`x-ig-app-id`, `x-asbd-id`, nomi e `doc_id`/`query_hash` delle operazioni, grandezza delle pagine solo per i nomi che la indicano, vero/falso). Un nome si tiene se è in un elenco chiuso, o se ha la forma di un nome del codice (senza punto, senza tre cifre di fila) e non compare da nessuna parte nel HAR come valore (indirizzi, cookie, intestazioni, corpi delle richieste e delle risposte, dati incorporati nelle pagine); altrimenti «(nome tolto)». Un corpo che non è un modulo né JSON si descrive intero, mai spezzato su «&» e «=». Le forme si distinguono per metodo, percorso, operazione (nome, intestazione `x-fb-friendly-name` o `x-root-field-name`) e identificativo dell'interrogazione, e le occorrenze si uniscono chiave per chiave. `OperationName` accetta anche il suffisso della pagina successiva (`…Query_connection`). Rifiuta HAR e file d'uscita dentro un repository, una cartella e un file d'uscita che esiste già | `da-har` butta via di proposito intestazioni, parametri e corpi delle richieste; per scrivere `richieste.instagram.json` serve la loro forma, e deve poter uscire dalla macchina di Alberto senza ripulitura: per costruzione non contiene valori personali |
|
||||
| 2026-11-12 | Ripulitura e verifica sul HAR vero: (1) un numero lungo con esponente o virgola (`1.2e+21`) si falsifica cifra per cifra, lasciando segno, punto ed esponente, così resta un numero JSON valido; (2) la verifica non cerca dentro i valori che l'elenco ammesso tiene di proposito (un tipo di file, una data, una dimensione), mai però nelle chiavi di dati, che la ripulitura falsifica sempre, e indica sotto quale chiave sopravvive un frammento, mai il frammento; (3) le parole degli indirizzi finti (`sito`, `altro`, `esempio`) e le estensioni dei file non contano come frammenti. Campioni del secondo HAR accorciati sulla copia **ripulita** e già verificata, non sui grezzi | Sul HAR del 12/11 `ripulisci` si fermava su un numero con esponente e `verifica` dava 223 falsi allarmi (frammenti come «script» dentro `text/javascript`). Accorciare la copia ripulita evita di aprire i grezzi anche solo per tagliarli: togliere elementi da una copia verificata non può aggiungere valori dei grezzi |
|
||||
| 2026-11-12 | Vocabolario dei lettori di Instagram: `profile.postCount` = `media_count` e una chiave nuova `highlight.cover` (`cover_media.cropped_image_version`), letta come una versione. Le griglie delle schede Reel e Con tag restano anteprime, non contenuti | Dal secondo HAR: `media_count` compare solo nella scheda del profilo; la copertina delle raccolte è nell'elenco delle raccolte del profilo; le anteprime delle schede non hanno `taken_at` né `video_versions` (regola 9: si legge solo ciò che i campioni mostrano) |
|
||||
| 2026-11-13 | `febe-sonda da-har` e `richieste` leggono anche un HAR **troncato**: se il file finisce prima del suo JSON, e solo in quel caso, tengono le voci complete di `log.entries`, scartano quella dentro cui il file finisce e lo dicono a schermo e nel resoconto (`Truncated`, `DroppedEntry`). Per riconoscere il caso il lettore JSON lavora in modalità «dati non finiti»: la fine del file non è un errore, un errore di sintassi sì, e un file rotto in qualunque altro modo resta rifiutato. Per `richieste` la voce scartata conta comunque come dati: si chiude dove si ferma (il testo interrotto tenuto fino al taglio) e passa per le stesse regole di una voce intera (base64, pagine con blocchi incorporati, intestazioni, moduli); in più ogni stringa JSON del testo interrotto conta come valore, così un nome che è un dato solo lì viene tolto lo stesso. Resta fuori solo un valore tagliato a metà, di cui c'è solo l'inizio. Lettura comune in `HarFile` | Il 12/11 sera Chrome ha troncato due esportazioni dello stesso giro: la prima a 200 000 byte esatti, la seconda a 57 MB a metà di un corpo di risposta. Prima la sonda diceva solo «non è un file HAR valido (riga …)», senza distinguere un file tagliato da uno sbagliato, e non dava nulla della parte buona. La revisione avversaria ha trovato che la prima versione non contava i valori del testo interrotto né applicava alla voce scartata le regole di base64 e pagine: corretto prima del commit |
|
||||
| 2026-11-13 | Le foto del profilo hanno un **terzo schema dei nomi**, predefinito `{account}\profilo\{data}_{ora}_{codice}_{n}` (chiave `libreria.schema-profilo`), accanto a quello generale e a quello delle raccolte; Impostazioni ▸ Generali lo mostra come terzo campo, con la cartella `profilo` nel risultato. Niente cartella dell'anno; `{codice}` sono le prime otto cifre dello SHA-256 e `{n}` vale sempre 1, tenuto perché i nomi si leggano come gli altri e l'importazione li riconosca con il riconoscitore di Febe. Senza `{codice}` l'avviso dice che due foto possono avere lo stesso nome; `{raccolta}` è un errore. Una richiesta di salvataggio senza il terzo schema tiene quello salvato | Decisione di Alberto su #38 (12/11): le foto del profilo dentro ogni account, in `<account>\profilo\…`. Con lo schema unico bastava cambiare quello generale perché finissero con i post; uno schema proprio, come per le raccolte, le tiene separate qualunque cosa dica il generale |
|
||||
| 2026-11-13 | Rapporto di diagnostica della raccolta (#39): un registratore unico (`CollectionDiagnostics`) tiene per ogni sessione del motore, e per ogni giorno fuori dalle sessioni, solo conteggi, misure, orari, valori di elenchi chiusi e forme degli indirizzi; le tracce finite vanno in `Dati/diagnostica/sessioni-aaaa-mm-gg.jsonl` (JSON per riga, 14 giorni, una riga rovinata si salta) e «Esporta il rapporto di diagnostica» in Attività (`GET /api/engine/diagnostica`, ammesso anche con un problema di configurazione) le scarica in un file JSON. La struttura delle chiavi delle risposte sconosciute è quella **severa** (`KeyStructure.DescribeStrict`): resta solo una chiave fatta tutta di parole di un **elenco chiuso** (`StructureWords`: le parole delle chiavi dei campioni ripuliti di `tests/Febe.Tests/campioni`, dei vocabolari dei lettori incorporati e degli indirizzi del sito; alcune parole che sono anche nomi, come «max», solo dentro una chiave composta) e non uguale a un valore stringa dello stesso corpo; ogni altra chiave diventa `#`, anche un nome utente senza punto («marta_92») o un codice di post. Le forme degli indirizzi (`PathPatterns`) e la regola delle chiavi-dato (`KeyStructure.IsDataKey`) passano da `tools/Febe.Sonda` a `Febe.Core`, e la sonda le richiama. Gli eventi «formato non riconosciuto» scrivono ancora la struttura di prima: passarli a quella severa è un seguito possibile | Il file deve poter uscire dalla macchina di Alberto senza ripulitura, quindi niente testo libero per costruzione. Non nel database: nessuna migrazione, dimensione limitata dai tetti delle tracce e dai 14 giorni, cartella che si può cancellare a mano senza toccare nulla. Elenco chiuso e non regole su che aspetto ha un nome: un nome utente fatto di lettere e cifre non si distingue da una chiave, e la revisione l'ha trovato nel rapporto. Ammesso con un problema di configurazione perché l'indirizzo non risponda mai con un errore, ma lì il motore non è partito e il rapporto è vuoto |
|
||||
| 2026-11-13 | Rapporto di diagnostica (#39), seconda revisione: nella struttura severa una chiave fatta di sole parole «solo composte» (`max_mark`) non passa più, e le **voci di una mappa** (chiavi sorelle i cui valori hanno la stessa forma) diventano `#` anche se fatte di parole dell'elenco, salvo le chiavi intere dei vocabolari dei lettori (`user`, `owner`). Una sessione scrive nel registro una riga «in corso» quando parte e al più ogni 5 minuti a fine ricetta; leggendo resta la riga finita, altrimenti l'ultima, e la testa del rapporto conta `fileIlleggibili` e `sessioniSenzaFine`. Il registratore ascolta anche i cambi dell'interruttore (da `EngineHost`), contando una volta sola lo stesso segnale detto anche dal rilevatore. La prova sulla riservatezza confronta le chiavi della struttura con i campi veri dei campioni e del corpo, non con `StructureWords` | Un nome fatto di parole comuni («the_artist») passava la sola lista; una mappa di nomi si riconosce dalla forma dei valori, a costo di qualche dettaglio (`first_frame` e `igtv_first_frame` diventano `#`). Senza righe intermedie una chiusura brusca cancellava proprio la sessione andata storta e la testa diceva 0; il cookie di sessione perso arriva all'interruttore senza passare dal rilevatore e il rapporto non lo diceva. Una prova che usa la funzione sotto prova come oracolo non trova i suoi errori. Resta il rischio di un solo nome di parole comuni usato come chiave, senza sorelle della stessa forma e mai ripetuto come valore |
|
||||
| 2026-11-13 | Rapporto di diagnostica (#39), terza revisione: nella struttura severa una chiave con un **valore semplice** (testo, numero, vero o falso, null) resta solo se è un **campo dell'elenco chiuso** (`StructureWords.IsFieldKey`: chiavi intere dei vocabolari dei lettori e delle chiavi dei campioni ripuliti, congelate nel codice perché i campioni non viaggiano con Febe), altrimenti `#`. Le voci di una mappa si riconoscono anche quando i valori non hanno la stessa forma esatta: due valori sorelli entrambi oggetti o entrambi elenchi, di cui uno vuoto, o entrambi elenchi di valori semplici, o con almeno metà delle chiavi in comune, o con un campo d'identità in comune (`pk`, `id`, `username`…); in un elenco di oggetti le chiavi che ha solo il primo diventano `#`; fra le voci restano solo i campi dell'elenco chiuso. Una traccia finita la cui scrittura fallisce si riscrive con la riga successiva e quando si raccoglie il rapporto (al più 16 in attesa); le righe «in corso» non si riscrivono | La regola della stessa forma esatta lasciava passare i nomi in mappe di conteggi o di valori vuoti, in voci con campi facoltativi diversi (il caso normale degli utenti di Instagram) e in elenchi di mappe a una voce. Il prezzo è il dettaglio: un campo nuovo con un valore semplice diventa `#`. Senza la riscrittura, un errore momentaneo proprio sulla riga finale lasciava nel registro solo le righe «in corso» e dopo un riavvio la sessione contava fra quelle senza fine |
|
||||
| 2026-11-13 | Prova di scala della libreria (§4.6, 200 000 elementi): i limiti valgono **per classe** di interrogazione, circa 5-8 volte i tempi misurati a macchina scarica: 250 ms per finestre e ricerche su indice (prima finestra, salto a una data, filtri, «è già noto», SHA-256, coda), 1500 ms per le aggregazioni sull'intera libreria o su un account (ricerche, totali, conteggi, caricamento delle impronte, elenco degli account con i conteggi, scheda dell'account). Ogni interrogazione si misura come il **migliore** di almeno tre giri dopo uno di riscaldamento, e se resta sopra il limite si riprova (al più 15 giri o 20 s, con una pausa di 100 ms) finché scende sotto. La classe gira `[DoNotParallelize]`, dopo le prove parallele; il riempimento resta fuori dalla misura e ha solo un tetto contro un blocco (20 minuti) | #46: la prova cadeva sotto carico senza nessun cambio di codice («scheda account» 1770 ms nella CI, 251,7 ms in locale). Due aggregazioni (140-200 ms a vuoto) stavano nella classe da 250 ms, con un margine di 1,2-1,8 volte; e tre giri consecutivi non superano un picco di carico, mentre le altre 11 prove parallele misuravano nello stesso momento. Il minimo è la stima giusta del costo: il carico aggiunge solo tempo, e un'interrogazione davvero più lenta resta sopra il limite in ogni giro |
|
||||
| 2026-11-13 | Scheda dell'account: byte in libreria e file in coda in **una sola passata** sui file dell'account, partendo dai suoi elementi (`entry CROSS JOIN media`), non più due interrogazioni separate | #46: senza le statistiche di ANALYZE SQLite partiva dall'indice dello stato dei file e leggeva i file di tutta la libreria per la scheda di un account; sotto carico era l'interrogazione che rallentava di più (1770 ms nella CI). Ora il piano è lo stesso con e senza statistiche e proporzionale all'account, come per `LoadPerceptualHashesAsync` |
|
||||
| 2026-11-13 | Avvio di Chromium (`ChromiumLaunchOptions.StartupTimeout`): **120 s** invece di 30 per aprire la porta di debug, e la prima scheda si aspetta entro la **stessa scadenza**, non più 50 tentativi da 100 ms; finisce subito se il processo si chiude, e una risposta lenta o mancata di `/json/list` vale «non ancora» come già per `/json/version`. Il ricollegamento dopo una connessione caduta usa la stessa scadenza ma smette appena il processo si chiude o il supervisore lo sostituisce, così non tiene il blocco del collegamento a un riavvio. Nessun comando CDP nuovo e nessun cambio della riga di comando (§6.1) | #46: la scadenza serve solo contro un Chromium vivo e bloccato, perché uno che si chiude fa già fallire l'avvio all'istante. Su una macchina carica (la CI era 4-6 volte più lenta del solito, un NAS durante un controllo di parità) Febe uccideva un Chromium lento ma sano e ricominciava da capo sotto lo stesso carico, anche per sempre; i 5 s per la prima scheda erano il punto più fragile |
|
||||
| 2026-11-13 | Nelle prove i limiti di tempo sono **protezioni contro un blocco, non misure**: ogni attesa finisce appena la sua condizione è vera e il limite è largo (il browser delle prove dell'interfaccia: 2 minuti per avvio, comandi DevTools e condizioni, e si ferma subito se Chromium si chiude, con le sue ultime righe di stderr; l'avvio del server di prova: 4 minuti, con l'ultimo errore del browser); niente attese fisse né conteggi di tentativi al posto di una scadenza. Ciò che una prova deve far accadere a un certo momento (il rilascio di un blocco, una lettura che non deve finire mai) gira su un thread suo, non sul pool; il pool delle prove parte con almeno 64 thread. Il browser delle prove dell'interfaccia usa la porta di debug 0 e legge quella scelta da Chromium; il browser di Febe resta sulla porta fissa (§6.1). Nelle prove di WebView2 su Windows la seconda «Scollega» e l'arresto non hanno più un limite di 10 s: la prova chiede che il processo del browser esca davvero (atteso per condizione) e che il profilo sparisca, con 90 s solo contro un blocco | #46: le prove cadevano a ogni carico del runner, ogni volta prove diverse, mai sul codice cambiato. Un limite stretto su un'attesa non misura nulla: dice solo quanto era carica la macchina. Con il parallelismo per metodo diverse prove bloccano thread del pool, e un pool di 2-4 thread ne aggiunge altri lentamente: il rilascio di un blocco dopo 300 ms arrivava dopo più di 10 s. Fra la porta libera trovata e il bind di Chromium un altro processo poteva prenderla. Con tutti i core occupati il processo di WebView2 (a priorità bassa) segnala l'uscita dopo i 15 s di attesa dell'host: la prova di «Scollega» cadeva 5 volte su 5 a 15,7-21 s, mentre ciò che deve escludere, una WebView orfana, tiene vivo il processo per sempre e lascia il profilo |
|
||||
| 2026-11-13 | `FebeDatabase.DisposeAsync` chiude davvero i file prima di tornare: ogni comando SQLite si chiude appena usato (gli aiuti `Execute` e `Scalar` sulla connessione dello scrittore, e un ambito che chiude i comandi di ogni lettura), le connessioni di lettura del pool si chiudono **prima** dello scrittore, così è lo scrittore, ultimo, a togliere `febe.sqlite-wal` e `-shm`. All'arresto `FebeApp` aspetta anche i lavori in sottofondo che un avvio ancora in corso aggiunge mentre si ferma | #46: un comando lasciato al garbage collector tiene viva la sua istruzione finché il finalizzatore non passa; la connessione chiusa nel frattempo si chiudeva davvero solo dopo, e il WAL spariva durante lo spostamento della cartella Dati (`Could not find file …febe.sqlite-wal`). Riprodotto tenendo occupato il thread del finalizzatore, ora con una prova apposita. Una connessione di sola lettura chiusa per ultima lascia il WAL: per questo il pool si svuota prima |
|
||||
| 2026-11-15 | Ricerca dei profili (#37), prima parte: si cerca **nel pannello «Cerca» di Instagram**, scrivendo con `Input.dispatchKeyEvent` (già in §6.1) da una mappa chiusa di tasti (`SearchKeyMap`: lettere, cifre, `.`, `_` e spazio, più Backspace ed End), cancellando e riscrivendo con i tasti; si leggono le risposte `PolarisSearchBoxRefetchableQuery` del campione ripulito 000002. Nessun comando CDP nuovo, nessun `doc_id`, nessuna richiesta della pagina; non si preme mai Invio e non si clicca mai un risultato; solo profili | Decisioni 1 e 2 di Alberto del 15/11: la ricerca deve essere quella che il sito fa già quando una persona scrive, senza chiamate inventate; un risultato aperto o una «ricerca recente» scritta sarebbero un'azione in più sul sito |
|
||||
| 2026-11-15 | Categoria del Governatore `ProfileSearch`: tetti propri per ora e per giorno (Prudente 240/1200, Equilibrato 300/1500, Rapido 360/1800, nessuno sopra 2×Rapido), un blocco proprio e una spaziatura propria (`SearchSpacing` 1,2 s × ritmo) più uno **scarto d'incrocio** della stessa durata fra un passo di ricerca e un'azione del motore, in tutte e due le direzioni. Non serve una sessione, non conta fra le azioni della sessione, non consuma i tetti della raccolta e non conta come «ultima azione del motore» (`GetLastActionAtAsync(null)` esclude `ProfileSearch` e `DataDownload`). La fermano come il motore l'interruttore (§7.6), Alberto al browser, la pausa e la fascia oraria; le riduzioni dei tetti valgono anche qui | Decisione 3: niente sezione separata nelle impostazioni, una riga nella tabella di Prudenza. Un passo di ricerca è una frazione di testo scritto, non un profilo aperto: con i tetti della raccolta la ricerca si fermerebbe dopo poche lettere e ruberebbe passi alla raccolta |
|
||||
| 2026-11-15 | `PageTurns`: un blocco FIFO sull'unica pagina del browser, a turni fra motore e ricerca. Il motore prende un turno per ricetta e lo cede ai permessi che aprono una pagina; la ricerca prende il turno per un passo e lo lascia appena il motore aspetta. Fuori sessione la ricerca apre Instagram e la pagina torna a riposo quando la finestra si chiude (5 s) o dopo 3 minuti senza testo nuovo, solo se l'ultima ad aver usato la pagina è la ricerca | Decisione 4: una sola pagina, nessuna seconda scheda (§6.1). Il turno per ricetta evita che una ricerca entri a metà di una lettura e sposti la pagina sotto i piedi della ricetta |
|
||||
| 2026-11-15 | Foto dei risultati: `BrowserFileFetcher` (solo CDN, §6.5) con un permesso `DataDownload` per foto, al più 2 in parallelo e 8 per risposta, ridotte a JPEG di 160 px in una **cache solo in memoria** (400 foto, 8 MB, 3 giorni, chiavi casuali di 32 cifre esadecimali); i byte contano nel budget giornaliero dei dati. L'interfaccia le chiede a Febe (`/api/ricerca/foto/{chiave}`), mai a Instagram. Un errore HTTP passa al rilevatore dei segnali e svuota la coda | Decisione 5: le foto non sono archivio e non devono restare su disco; una chiave casuale non rivela il profilo né l'indirizzo firmato |
|
||||
| 2026-11-15 | Il controllo del fuoco della casella (`TargetResolver.BuildFocusExpression`) è uno script di sola lettura che restituisce lo stato e la **lunghezza** del testo, mai il testo; un tasto non ricevuto vale «Tasti non ricevuti» prima di «Fuoco perso» | Regola 10: il testo cercato non deve tornare indietro dalla pagina né finire nei log. Da confermare con Alberto (domanda N1) che uno script così rientri in §6.1 |
|
||||
| 2026-11-15 | La finestra legge la ricerca **a domande** (POST `/api/ricerca`, GET `/api/ricerca?client=`, POST `/api/ricerca/fine`), non con un flusso SSE; un cliente si riconosce da 16 cifre esadecimali scelte dalla pagina; il testo è al più di 60 caratteri e la richiesta deve venire dall'Origin dell'interfaccia | Una sola persona e una finestra: le domande ogni poche centinaia di millisecondi bastano e non tengono aperta una connessione per ogni scheda; l'Origin impedisce che una pagina di un altro sito faccia scrivere Febe |
|
||||
| 2026-11-15 | Prima di aprire Instagram per una ricerca fuori sessione si guarda il cookie di sessione: se manca vale **Disconnessione** (segnale §7.6), non un errore della ricerca | Senza sessione Instagram mostrerebbe l'accesso: aprirlo per niente è un'azione in più e la regola di §7.6 è la stessa del motore |
|
||||
| 2026-11-15 | Il sito di prova risponde alla ricerca (`/dati/cerca`) **con le chiavi del campione ripulito 000002**, lette dallo stesso vocabolario di Instagram; pannello «Cerca» con i bersagli `search-open` e `search-box` in `bersagli.prova.json`. Per Instagram i due bersagli restano da raccogliere (H11): finché Alberto non li conferma la ricerca dal vivo dice «Febe non sa ancora dove sta «Cerca» su questo sito…» (`SearchState.NotConfigured`) | Regola 9: il formato non si inventa. Le prove e la modalità dimostrativa (risultati e foto disegnati, nessuna rete) mostrano la ricerca funzionante senza toccare Instagram |
|
||||
| 2026-11-15 | Diagnostica della ricerca: nel rapporto solo i conteggi dei passi per esito (`searchSteps`, elenco chiuso `SearchOutcome`) e delle foto per sorte (`searchPhotos`: scaricata, rifiutata, saltata, altrimenti «altro»), fuori sessione; mai testo, nomi o indirizzi. Nella cronologia una riga per finestra di ricerca con il numero di passi, risposte e foto | «Tracciare sempre tutto» (richiesta di Alberto) senza dati di altre persone (§2 regola 10 e #39) |
|
||||
| 2026-11-15 | Ricerca dei profili (#37), seconda parte: la finestra «Aggiungi account» ha **una sola casella** senza linguette. I suggerimenti locali (seguiti e account in Febe, al più 8, prima chi comincia con il testo) si filtrano nella pagina a ogni lettera; il testo va a Febe 150 ms dopo l'ultima lettera; i risultati di Instagram si uniscono per identificativo e poi per nome, senza doppioni | È il comportamento chiesto da Alberto (come 4K Stogram): i profili noti subito, Instagram quando arriva |
|
||||
| 2026-11-15 | Nella stessa casella: più nomi incollati (a capo, virgola, punto e virgola, più indirizzi) vanno a `/api/accounts/parse` e in «Da aggiungere», mai su Instagram; la riga «Aggiungi @nome per nome utente» aggiunge il nome scritto; «Scegli fra tutti i profili che segui» riapre l'elenco a spunte con «Seleziona tutti» (default della domanda Q8) | L'aggiunta per nome e la scelta in blocco restano possibili, anche finché la ricerca su Instagram non è configurata (H11) |
|
||||
| 2026-11-15 | Il dialogo di `core/ui.js` accetta `onEscape` (Esc chiude prima l'elenco dei suggerimenti, il secondo Esc il dialogo) e `onClose` (una volta sola comunque si chiuda: `POST /api/ricerca/fine`, fine delle domande) | La ricerca non deve restare aperta su Instagram quando la finestra non c'è più |
|
||||
| 2026-11-15 | Scena dimostrativa `alvolante` (motore `UserDriving`, ricerca `non-possibile`) | Mostrare e provare il caso in cui Alberto usa il browser senza un browser vero |
|
||||
| 2026-11-15 | Ricerca dei profili, revisione: una risposta della ricerca vale per il testo nella casella **solo se la pagina ne ha avviato la richiesta dopo l'ultimo tasto**. `ResponseTap` ascolta anche l'evento `Network.requestWillBeSent` (un evento del dominio già attivo con `Network.enable`, nessun comando nuovo) e dà a ogni richiesta del sito un numero d'ordine; prima di ogni tasto, Backspace compresi, la ricerca annota dove sono arrivate le richieste. Fra quelle avviate dopo l'ultimo tasto si prende la più recente, subito; senza numero d'ordine (un flusso di eventi che non lo porta) si torna all'ordine d'arrivo con la pagina quieta. Della richiesta si guarda solo il tipo di indirizzo, niente si conserva né si registra | Il campione 000002 non ripete il testo cercato: mentre Febe scrive la pagina chiede anche i prefissi, e le loro risposte possono arrivare dopo quella giusta (modalità «ricerca/disordine» del sito di prova). Prenderle per il testo intero le metteva nella memoria delle risposte per 5 minuti |
|
||||
| 2026-11-15 | Una pagina che mostra un testo già cercato dalla sua memoria non manda richieste: la ricerca tiene le risposte lette **su quella pagina** e, se dopo l'attesa minima la pagina è quieta e non è arrivato nulla, usa quella del testo. Il ricordo vale fino alla prossima pagina aperta o messa a riposo (`PageTurns.Generation`), insieme a ciò che Febe ha scritto nella casella | Modalità «ricerca/memoria» del sito di prova: senza, tornare a un testo già scritto finiva in «Instagram non ha mandato risultati». Con la generazione della pagina, durante una sessione la lettera nuova è l'unico tasto, invece di cancellare e riscrivere tutto a ogni passo |
|
||||
| 2026-11-15 | Riposo della pagina con i turni: la pagina vuota a fine sessione e dopo che Alberto ha usato il browser passa da `PageTurns.TakeForRestAsync`. Se la ricerca tiene o aspetta la pagina, il riposo **tocca alla ricerca** (`RestOwed`), che lo fa a finestra chiusa (5 s) o dopo 3 minuti senza testo nuovo, subito se Instagram ha chiesto di rallentare, anche se non ha mai scritto; la ricerca mette a riposo anche la pagina del motore su cui ha scritto. La pagina di accesso di Alberto aspetta il turno (al più 15 s). Supera la condizione «solo se l'ultima ad aver usato la pagina è la ricerca» della riga dei turni | Durante una sessione è il motore ad aprire le pagine: una sessione finita mentre Alberto cercava lasciava Instagram aperto fuori sessione (§6.1). Un riposo o una navigazione senza turno potevano cadere a metà di un passo della ricerca |
|
||||
| 2026-11-15 | Un tasto premuto si rilascia sempre: se il passo viene annullato fra «giù» e «su», `HumanGestures.PressKeyAsync` manda comunque il rilascio del tasto e di Maiusc, senza attesa | La pagina passa poi al motore o ad Alberto: un tasto rimasto giù cambierebbe ciò che scrivono |
|
||||
| 2026-11-15 | Le foto della ricerca arrivano all'interfaccia con `Cache-Control: no-store` | La cache delle foto è solo in memoria: il browser che mostra Febe non deve tenerne una copia sul suo disco |
|
||||
| 2026-11-15 | La ricerca riprende da sola dopo un arresto passeggero: dopo «Ho finito» e dopo la pausa (ricontrollate ogni 2 s, senza chiedere al Governatore), all'apertura della fascia o allo scadere di un tetto (il `RetryAfter` del rifiuto), dopo «Riprendi» (il cambio dell'interruttore). Dopo un errore o «nessuna risposta» lo stesso testo, scritto di nuovo, si riprova. La finestra continua a chiedere lo stato (ogni 2 s) mentre la ricerca è ferma per uno di questi motivi, e subito quando cambia lo stato del motore | I testi dicevano «riprende quando hai finito», ma la finestra smetteva di chiedere e il servizio non riprovava |
|
||||
| 2026-11-15 | Nella finestra, l'indirizzo di un post, di un reel, di una storia o di un'altra pagina di Instagram non diventa un nome (`p`, `reel`, `stories`…): stesso elenco di `UsernameParser.ReservedPaths` | Incollare `instagram.com/p/…` offriva «Aggiungi @p per nome utente» |
|
||||
| 2026-11-15 | Il mockup 04 è superato da #37: il riferimento è la schermata `docs/schermate/04-aggiungi-account.png` finché Alberto non ne fornisce uno nuovo (domanda Q9) | Non esiste il sorgente del mockup nel repository; la schermata segue gli elementi del foglio di stile (mockup 13) |
|
||||
| 2026-11-15 | Risposte di Alberto sulla ricerca dei profili (#37): il controllo del fuoco con `Runtime.evaluate` in sola lettura è ammesso e scritto in §6.1 (N1); i turni cadono a ogni ricetta e prima di ogni apertura di pagina, non dentro il visualizzatore né fra le raffiche di scorrimento (N2); l'ascolto di `Network.requestWillBeSent`, solo per l'indirizzo, è ammesso e scritto in §6.1; le foto dei profili seguiti non si scaricano per ora | Domande poste ad Alberto il 15 novembre 2026 alla fine del disegno; tutte con la risposta consigliata |
|
||||
| 2026-11-16 | **Richieste dirette con la sessione copiata dal browser** (issue #36): Alberto accede nel browser di Febe; a «Ho finito» Febe copia cookie, user agent, gettoni e `doc_id` nella sessione salvata e chiede i dati con un solo client HTTP, senza browser in sottofondo, come Mimante con Bidoo. Cambiano §1, §2 regole 1, 2, 4, 5, 7, 8 e 11, §3, §6 (nuova §6.0), §7.4, §7.6, §13.2, §14.2 e le regole 3, 4, 7 e 10 di `CLAUDE.md`. Sostituisce la «strada B» del 12 novembre | Decisione di Alberto del 16 novembre 2026, presa dopo che gli erano stati detti i rischi: un client .NET ha un'impronta TLS e HTTP/2 diversa dal browser e Instagram può riconoscerlo. Restano sola lettura, Governatore, arresto al primo segnale, niente CAPTCHA, un account, formati mai inventati |
|
||||
| 2026-11-16 | `doc_id`, gettoni e identificativo dell'account si leggono dai moduli della pagina all'accesso (`<Operazione>_instagramRelayOperation`, `DTSGInitialData`, `LSD`, `CurrentUserInitialData`), con `Runtime.evaluate` in sola lettura; `x-csrftoken` è il valore del cookie `csrftoken` | Risposte di Alberto del 16 novembre. Il HAR del 16/11 (#35) mostra che tutti i 17 `doc_id` usati dalla pagina stanno in quei moduli del codice pubblico, uguali al 12/11 |
|
||||
| 2026-11-16 | Il client del sito non segue i rinvii; un rinvio, un 401 o 403, un HTML al posto del JSON o un JSON senza i campi attesi fermano la sessione come una Verifica, finché le forme vere non sono note (H16). Mai un nuovo accesso automatico | Risposta di Alberto: «avvisando se non trovi i campi previsti; l'utente valuterà se rieseguire l'accesso». Le forme trovate su internet (`login_required`, `checkpoint_required`, `require_login`) vengono da segnalazioni di comunità, non da campioni |
|
||||
| 2026-11-16 | Le storie si leggono con una richiesta per account e non risultano viste: chiusa la domanda 11, cambiato §3 | Risposta di Alberto del 16 novembre (consigliata): segnarle viste sarebbe una scrittura, vietata dalla regola 5 |
|
||||
| 2026-11-16 | Sessione salvata in `Dati/sessione/sessione.json`, fuori da SQLite e dalle copie giornaliere: DPAPI dell'utente su Windows (`ProtectedData` del framework desktop, nessun pacchetto nuovo); AES-256-GCM in Docker con la chiave da `FEBE_CHIAVE_SESSIONE` o da `chiave.bin` con permessi del solo proprietario; scrittura atomica; «Scollega» la cancella | Mimante usa AES-GCM con la chiave accanto al file, che su Windows non è protetta; DPAPI lega la sessione all'utente e alla macchina, cioè la regola 4. Le copie giornaliere del database spargerebbero il segreto |
|
||||
| 2026-11-16 | Il client del sito aggiorna da sé nella sessione salvata i cookie rinnovati dal sito e `x-ig-www-claim`; un nuovo accesso dal browser ricopia tutto e vince; Febe non scrive mai nei cookie del browser; mentre il browser è aperto il motore è fermo | Evita due client sulla stessa sessione e un comando CDP di scrittura (`Network.setCookie`) |
|
||||
| 2026-11-16 | Su Windows il client del sito usa le impostazioni proxy del sistema, come WebView2; in Docker esce dal contenitore come Chromium. HTTP/2 con ripiego su HTTP/1.1, niente HTTP/3 | Stessa strada di rete del browser che ha creato la sessione; HTTP/3 vorrebbe `libmsquic` nell'immagine |
|
||||
| 2026-11-16 | La consegna delle risposte ai lettori sta in `ResponseDelivery` (Febe.Core): JSON con profondità 256 o blocchi incorporati nella pagina, uno alla volta, lettori isolati. La usano `ResponseTap` e, dalla tappa S2 di #36, il client del sito (S1, nessun cambiamento di comportamento) | Le risposte catturate e quelle chieste devono arrivare ai lettori e ai segnali nello stesso modo |
|
||||
| 2026-11-16 | I rifiuti del catalogo delle richieste (`RequestCatalog`) stanno nel codice, non nel JSON: ogni nome che contiene `Mutation`, le famiglie GraphQL di chat, messaggi, presenza, promozioni, pubblicità e telemetria, i percorsi di telemetria e navigazione (`/logging_client_events`, `/ajax/…`, `/ws/`, `/api/v1/web/`, `/api/v1/discover/web/`…), ogni percorso con un host, una query o un valore come primo segmento; GraphQL solo verso `/api/graphql` e `/graphql/query` con POST, gli indirizzi semplici solo con GET; niente intestazione `cookie` nel modello | Una copia di `richieste.<sito>.json` modificata nella cartella dei dati non deve poter togliere un divieto (regole 3, 6) |
|
||||
| 2026-11-16 | `richieste.<sito>.json` ha chiavi in inglese come gli altri file di configurazione; per ogni intestazione e campo dice la fonte del valore (`constant:`, `cookie:csrftoken`, `session:` user_agent, lsd, fb_dtsg, app_id, claim, account_id, doc_id, `operation`, `variables`, `computed`, `pending` se ancora da stabilire nella tappa S4). Un'operazione con un nome o un valore tolto dalla sonda nelle variabili resta «non configurata» e il client la rifiuta; nessun `doc_id` nel repository. Le categorie del Governatore sono quelle che ci sono già, fino ai tetti per richiesta della tappa S3 | Regola 9: le forme non mostrano tutto, e ciò che manca non si indovina |
|
||||
| 2026-11-16 | Il contratto del client del sito (S1 di #36) si chiude nel codice: un'operazione con un'intestazione o un campo `pending` (o col nome tolto dalla sonda) non può essere configurata, quindi oggi nessuna operazione di Instagram lo è; un permesso vale per una sola richiesta, contato per riferimento (`SpentPermits`) e speso anche se la richiesta è poi rifiutata; i valori del caso hanno una forma (cifre per gli identificativi, i caratteri di un nome utente, di un codice o di una raccolta) e quelli che finiscono nel percorso non portano `/ ? # %` né punti soli; i percorsi del catalogo non hanno segmenti vuoti, `.` o `..` né caratteri fuori da lettere, cifre e `/_.-{}`; un indirizzo semplice non può puntare a GraphQL; la categoria «ricerca» è solo di un'operazione che porta `{search_text}` e nessun account o contenuto, e viceversa; `SiteAnswer` prende l'operazione del catalogo, non un percorso | Revisione della tappa S1: altrimenti una copia modificata nella cartella dei dati (`/./ajax/bz`, che `System.Uri` riduce a `/ajax/bz`), un valore come `..` o un permesso riusato aggirerebbero i divieti delle regole 4, 8, 9 e 10; il tetto della ricerca è fuori dalle sessioni (§7.4) |
|
||||
@@ -34,13 +34,17 @@ Sul registro di Gitea, `192.168.30.23:3000/alby96/febe`:
|
||||
| `:latest` | l'ultima versione rilasciata senza trattino: quella del modello di Unraid e di `compose.yml` | a ogni rilascio stabile |
|
||||
| `:X.Y.Z` | una versione rilasciata (anche `X.Y.Z-rc.N` per un'anteprima) | mai: serve per tornare a una versione precisa |
|
||||
| `:main` | l'ultimo commit di `main` che ha passato la verifica | a ogni unione in `main`: per provare, non per l'archivio vero |
|
||||
| `:sha-<7 caratteri>` | un commit di `main` preciso | mai |
|
||||
| `:sha-<7 caratteri>` | un commit di `main` preciso | mai; sul registro restano le 10 più recenti |
|
||||
|
||||
Ogni immagine costruita dalla CI dice da dove viene, nelle etichette Docker `febe.ci.workflow`, `febe.ci.run`,
|
||||
`febe.ci.ref` e `febe.ci.commit` e in `org.opencontainers.image.version` e `.revision`:
|
||||
`docker inspect --format '{{json .Config.Labels}}' <immagine>`. Docker copia queste etichette anche nel contenitore di
|
||||
Febe: la pulizia della CI non le usa per scegliere che cosa togliere, quindi un Febe sullo stesso Docker del runner
|
||||
della CI non viene mai toccato.
|
||||
della CI non viene mai toccato, né la sua immagine, anche a contenitore fermo. Su quel Docker, però, la pulizia del
|
||||
lunedì toglie le immagini che nessun contenitore usa e che sono state create più di 24 ore fa: un'immagine di Febe
|
||||
tenuta senza contenitore (una versione precedente, per tornare indietro) se ne va, e si riscarica dal registro, dove
|
||||
`:X.Y.Z` resta. E se l'immagine del Febe vero ha più nomi (`:latest` e `:0.1.0`, per esempio), resta, ma con uno solo:
|
||||
gli altri la pulizia li toglie (`docs/processo.md`, «Pulizia»).
|
||||
|
||||
## Volumi
|
||||
|
||||
|
||||
@@ -9,14 +9,74 @@ evidenza); un **file** è ogni singola foto o video. I contatori contano element
|
||||
|
||||
## Aggiungere account
|
||||
|
||||
«Aggiungi account» apre una finestra con due linguette:
|
||||
«Aggiungi account» apre una finestra con **una sola casella di ricerca**, come in 4K Stogram. Scrivi un nome utente
|
||||
o un nome completo (anche solo una parte, «mar» trova @marta.rossi e Mario Bianchi): sotto la casella compare un
|
||||
elenco che si aggiorna a ogni lettera.
|
||||
|
||||
- **Dai profili che segui:** l'elenco dei profili che segui, letto da Febe a ritmo umano e dentro i tetti. La prima
|
||||
volta va letto («Leggi l'elenco»): può servire più di una sessione, e la finestra dice a che punto è («Letti 96
|
||||
profili, continuo alla prossima sessione»). L'elenco resta in memoria con la data di lettura e si rilegge solo se lo
|
||||
chiedi. I profili già presenti in Febe sono attenuati.
|
||||
- **Per nome utente:** scrivi o incolla nomi utente o indirizzi di profilo, uno per riga (`nome.utente`,
|
||||
`@nome.utente` oppure `instagram.com/nome.utente`). Serve per i profili pubblici che non segui.
|
||||
- **Profili che segui e account in Febe:** compaiono subito, mentre scrivi, dalla memoria di Febe. Per averli bisogna
|
||||
aver letto almeno una volta l'elenco dei profili che segui («Leggi l'elenco», in basso nella finestra).
|
||||
- **Da Instagram:** i profili che trova Instagram arrivano poco dopo, di solito in un paio di secondi. Un profilo che
|
||||
compare in tutte e due le parti è mostrato una volta sola.
|
||||
|
||||
Ogni riga ha la **foto del profilo**, il nome utente, il nome completo e le etichette «Seguito», «Privato», «Già in
|
||||
Febe». Finché la foto non è arrivata vedi le iniziali. La foto c'è per gli account già in Febe e per i profili che
|
||||
Instagram ha appena trovato; un profilo che segui ma che non è in Febe ha la foto solo quando compare anche fra i
|
||||
risultati di Instagram per lo stesso testo, altrimenti restano le iniziali: Febe non conserva le foto dei profili che
|
||||
segui, e senza la ricerca su Instagram (per esempio con una lettera sola) non ne ha. «Privato» e «Seguito» li sa solo Febe: un profilo che Febe non
|
||||
conosce non ha queste etichette anche se è privato. I profili «Già in Febe» non si aggiungono una seconda volta, anche
|
||||
se nel frattempo hanno cambiato nome.
|
||||
|
||||
- **Aggiungere:** premi «Aggiungi» sulla riga, o un clic sulla riga, o scendi con le frecce e premi Invio. Il profilo
|
||||
passa in **«Da aggiungere»**, sotto la casella; la × lo toglie. Esc chiude l'elenco dei suggerimenti, un secondo Esc
|
||||
chiude la finestra.
|
||||
- **Per nome utente:** l'ultima riga dell'elenco, «Aggiungi @nome per nome utente», aggiunge il nome che hai scritto
|
||||
anche se non compare fra i risultati (Invio fa lo stesso). Febe controlla il profilo alla prossima sessione.
|
||||
- **Più nomi insieme:** incolla nella casella più nomi utente o indirizzi di profilo, uno per riga o separati da
|
||||
virgole (`nome.utente`, `@nome.utente`, `instagram.com/nome.utente`). Vanno tutti in «Da aggiungere»; quelli già in
|
||||
Febe e quelli non validi sono spiegati sotto l'elenco, con il loro posto («2° nome: …»). Gli spazi da soli non
|
||||
separano: «mario rossi» si cerca. L'indirizzo di un post, di un reel o di una storia non è un profilo: la finestra lo
|
||||
dice e non lo aggiunge. Incollati mentre è aperto l'elenco completo dei seguiti, i nomi vanno in «Da aggiungere» lo
|
||||
stesso: le caselle dei profili che segui si spuntano e un avviso dice quanti sono.
|
||||
- **Scegli fra tutti i profili che segui:** apre al posto di «Da aggiungere» l'elenco completo dei profili che segui,
|
||||
con le caselle di spunta e «Seleziona tutti»; la casella in alto lo filtra. L'elenco è letto da Febe a ritmo umano e
|
||||
dentro i tetti: la prima volta può servire più di una sessione, e la finestra dice a che punto è («Letti 96 profili,
|
||||
continuo alla prossima sessione»). Resta in memoria con la data di lettura e si rilegge solo se lo chiedi.
|
||||
|
||||
### Come cerca su Instagram
|
||||
|
||||
Cerca il **browser di Febe**, non la pagina che stai guardando: apre il pannello «Cerca» di Instagram e scrive il testo
|
||||
nella sua casella, a ritmo umano, come faresti tu. Legge i risultati che Instagram manda a quella pagina e ne scarica le
|
||||
foto, che tiene per poco e solo in memoria. Non apre mai i profili trovati e non fa clic sui risultati, quindi le tue
|
||||
«ricerche recenti» su Instagram non cambiano. Cerca solo profili, niente hashtag né luoghi. Le lettere accentate si
|
||||
cercano senza accento («Niccolò» diventa «niccolo»); simboli diversi da punto, trattino basso e spazio restano solo
|
||||
nei suggerimenti locali.
|
||||
|
||||
Ogni passo della ricerca chiede il permesso al Governatore, con un tetto proprio e largo che non consuma i tetti della
|
||||
raccolta («Ricerche di profili» in [Limiti e comportamento](Limiti-e-comportamento)). Durante una sessione la ricerca e
|
||||
la raccolta si danno il turno sull'unica pagina: i risultati di Instagram possono aspettare che finisca un passo della
|
||||
raccolta (la finestra dice «In attesa del turno…»), la sessione non si ferma. Fuori dalle sessioni, quando chiudi la
|
||||
finestra o dopo qualche minuto senza lettere nuove, il browser torna alla pagina vuota. Anche se una sessione finisce
|
||||
mentre stai cercando: la pagina torna vuota appena la ricerca ha finito.
|
||||
|
||||
La riga sotto «Da Instagram» dice quando la ricerca su Instagram non è possibile; i suggerimenti locali funzionano
|
||||
sempre:
|
||||
|
||||
| Messaggio | Perché |
|
||||
|---|---|
|
||||
| «Stai usando il browser di Febe…» | Lo stai usando tu (accesso, verifica, «Apri il browser»): la ricerca riprende da sola quando premi «Ho finito», senza riscrivere |
|
||||
| «Febe è in pausa…» | La pausa ferma anche la ricerca: riprende da sola quando premi «Riprendi» |
|
||||
| «Fuori dalla fascia oraria…» | Fuori fascia Febe non apre Instagram, neanche per cercare: la ricerca riprende da sola quando la fascia si apre, se la finestra è ancora aperta |
|
||||
| «Febe è fermo…» o il motivo dell'arresto | Un segnale di Instagram (verifica, rallentamento, disconnessione) ferma anche la ricerca; riprende da sola dopo «Riprendi» o alla fine del rallentamento. Vedi [Attività e arresti](Attivita-e-arresti) |
|
||||
| Tetto delle ricerche raggiunto | Il tetto orario o giornaliero delle ricerche di profili; riprende da solo |
|
||||
| «… non è riuscita: riprova» e simili | Riscrivi lo stesso testo, anche solo con uno spazio in più: Febe ci riprova |
|
||||
| «Il browser di Febe non è pronto» / «Il motore non è avviato» | Febe si sta avviando o il browser non è collegato |
|
||||
| «Febe non sa ancora dove sta «Cerca» su questo sito: per ora vedi solo i profili che segui.» | Mancano i bersagli del pannello «Cerca» per questo sito (vedi sotto). Se invece dice che Febe «non sa ancora leggere le risposte della ricerca», manca il lettore delle risposte |
|
||||
| «La ricerca su Instagram è in uso da un'altra finestra» | Cerca una finestra di Febe alla volta: l'ultima in cui hai scritto |
|
||||
|
||||
**Ancora da verificare dal vivo.** Su Instagram vero la ricerca ha bisogno dei bersagli `search-open` e `search-box`
|
||||
(il comando «Cerca» e la sua casella), che si raccolgono con una prova dal vivo: finché mancano, sotto «Da Instagram»
|
||||
leggi «Febe non sa ancora dove sta «Cerca» su questo sito: per ora vedi solo i profili che segui.» e funzionano i suggerimenti locali e l'aggiunta per nome. La scrittura nella casella con il browser di
|
||||
Windows (WebView2) non è ancora stata provata.
|
||||
|
||||
A destra scegli il **punto di partenza**, che poi puoi cambiare account per account:
|
||||
|
||||
|
||||
@@ -18,7 +18,52 @@
|
||||
pieni, formati non riconosciuti, e gli avvisi che non sono arrivati (vedi [Avvisi e Telegram](Avvisi-e-Telegram)).
|
||||
|
||||
Comandi: **«Metti in pausa»** (Febe non apre nulla finché non premi «Riprendi»), **«Riprendi»**, **«Apri il
|
||||
browser»**.
|
||||
browser»**, **«Diagnostica»** (vedi sotto).
|
||||
|
||||
## Il rapporto di diagnostica
|
||||
|
||||
Se una prova va storta (Febe si ferma, non trova nulla, scarica meno del previsto) e vuoi farla guardare a qualcuno,
|
||||
manda il **rapporto di diagnostica**: un solo file che racconta che cosa ha fatto il motore, senza i dati di nessuno.
|
||||
|
||||
1. Apri **Attività** e premi **«Diagnostica»** nella riga del titolo (al telefono è l'icona del file con la freccia;
|
||||
il suggerimento dice «Esporta il rapporto di diagnostica»).
|
||||
2. Il file `febe-diagnostica-aaaa-mm-gg.json` finisce nei download del browser (su Windows nella cartella Download,
|
||||
come ogni scaricamento della finestra di Febe).
|
||||
3. Allegalo così com'è al messaggio o alla segnalazione su Gitea, dicendo più o meno a che ora è successo il problema.
|
||||
|
||||
Che cosa contiene, per ogni sessione delle ultime due settimane e per le ore fuori dalle sessioni: le pagine aperte
|
||||
(solo il tipo di pagina e la forma dell'indirizzo, come `/{username}/`), le risposte ricevute per tipo con numero e
|
||||
misure, che cosa ne hanno fatto i lettori (per le risposte dalla forma sconosciuta, solo la struttura delle chiavi),
|
||||
le ricette con l'esito, i segnali di arresto, i file messi in coda e scaricati, e **perché ogni sessione è finita**.
|
||||
|
||||
Che cosa **non** contiene: nomi utente, didascalie, codici dei post, identificativi, indirizzi, cookie, password,
|
||||
corpi delle risposte, testi dei messaggi. Lo puoi aprire con un editor di testo e controllare. È più severo dei
|
||||
registri di Febe, che i nomi utente li scrivono.
|
||||
|
||||
Febe tiene le tracce in `Dati/diagnostica` per **14 giorni** e cancella da sé solo i file più vecchi di quella
|
||||
cartella. Una sessione in corso lascia una riga quando parte e poi al più ogni cinque minuti, alla fine di una
|
||||
ricetta: se Febe si chiude di colpo (un arresto imprevisto, il computer spento a forza, il contenitore fermato), la
|
||||
sessione resta nel rapporto fino all'ultima di quelle righe, «in corso» e senza causa della fine.
|
||||
|
||||
In cima al file quattro numeri dicono che cosa sicuramente manca:
|
||||
|
||||
| Campo | Che cosa conta |
|
||||
|---|---|
|
||||
| `righeRovinate` | righe del registro tagliate a metà da uno spegnimento brusco |
|
||||
| `erroriRegistratore` | errori del registratore da quando Febe è partito, scritture non riuscite comprese |
|
||||
| `fileIlleggibili` | giorni del registro che non si sono potuti leggere (un altro programma teneva aperto il file, un errore del disco): le loro sessioni non ci sono |
|
||||
| `sessioniSenzaFine` | sessioni interrotte da una chiusura brusca: di loro manca quello che è successo dopo l'ultima riga |
|
||||
|
||||
Anche con tutti e quattro a 0 il rapporto può non essere intero. Di una chiusura brusca si perdono gli ultimi minuti
|
||||
della sessione e le ore fuori dalle sessioni del giorno (scritte solo a fine giornata o quando Febe si chiude bene).
|
||||
Gli elenchi di ogni sessione hanno un tetto: quello che lo supera non c'è, e `overflow` della sessione dice quante
|
||||
voci mancano (pagine, navigazioni, gruppi di risposte, forme sconosciute, segnali, ricette), quante risposte sono
|
||||
rimaste senza esito perché arrivate in troppe insieme (`requests`) e quante notizie sono arrivate tardi (`late`),
|
||||
quando la loro sessione era già chiusa.
|
||||
|
||||
Con un problema di configurazione il motore non parte e Febe mostra solo la pagina del problema: il rapporto non
|
||||
serve, perché non c'è nessuna sessione da raccontare. Le tracce delle sessioni precedenti restano in
|
||||
`Dati/diagnostica` e tornano nel rapporto appena il problema è risolto.
|
||||
|
||||
## La striscia rossa
|
||||
|
||||
|
||||
@@ -37,9 +37,10 @@ seguire; passa al tuo account solo quando hai visto come si comporta.
|
||||
Questa guida descrive ciò che c'è nel programma, non ciò che si spera. Alcune cose dipendono da prove che si possono
|
||||
fare solo con Instagram o su Windows:
|
||||
|
||||
- **Raccolta da Instagram: non ancora attiva.** Le ricette, il motore, la libreria e gli scaricamenti funzionano e sono
|
||||
provati contro un sito di prova locale. Su Instagram le ricette si rifiutano di girare («la mappa dei bersagli non è
|
||||
ancora compilata») finché la sonda passiva non ha confermato le ipotesi H1–H11. Vedi
|
||||
- **Raccolta da Instagram: in parte attiva (25 ottobre 2026).** Febe legge le risposte vere di Instagram (lettori
|
||||
scritti su risposte reali, ripulite). Girano giro dei seguiti, controllo del profilo, storico e post singolo: foto e
|
||||
video dei post e dei reel. Storie, raccolte in evidenza e schede Taggati e Reel aspettano i bersagli dei comandi
|
||||
(ipotesi H11) e rispondono «la mappa dei bersagli non è ancora compilata». Non è ancora stato provato dal vivo. Vedi
|
||||
[Ipotesi da verificare](Ipotesi-da-verificare).
|
||||
- **Versione per Windows: pronta, non ancora provata su un Windows vero.** Programma di installazione e versione
|
||||
portabile ci sono; le prove che si fanno solo su Windows (S1–S3) sono aperte. Vedi
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
# Ipotesi da verificare
|
||||
|
||||
Febe è costruito su alcune ipotesi che non si possono provare senza Instagram (voci **H**) o senza i due browser veri
|
||||
(voci **S**). Finché una voce non è provata, non ci si costruisce sopra: per questo la raccolta da Instagram non è
|
||||
ancora attiva. Lo stato aggiornato e i dettagli tecnici sono in `docs/sonda/esito.md` e `docs/sonda/esito-locale.md`
|
||||
nel repository; i passi precisi delle prove in `docs/prove-dal-vivo.md`.
|
||||
(voci **S**). Finché una voce non è provata, non ci si costruisce sopra. Lo stato aggiornato e i dettagli tecnici sono
|
||||
in `docs/sonda/esito.md` e `docs/sonda/esito-locale.md` nel repository; i passi precisi delle prove in
|
||||
`docs/prove-dal-vivo.md`.
|
||||
|
||||
**Dal 25 ottobre 2026** Febe legge le risposte vere di Instagram: i lettori sono scritti sulle risposte che il tuo
|
||||
browser ha ricevuto il 21 ottobre (un file HAR), ripulite. Girano le ricette che aprono solo pagine (giro dei seguiti,
|
||||
controllo del profilo, storico, post singolo). Storie, raccolte in evidenza e schede Taggati e Reel aspettano i
|
||||
**bersagli** (H11): i nomi e i ruoli di pulsanti come l'anello delle storie, «avanti» e la X, che nel HAR non c'erano.
|
||||
|
||||
Le prove dal vivo le fai **tu**, con l'**account di prova**, mai con l'account principale prima di aver visto Febe
|
||||
all'opera. Se in qualunque momento compare una verifica, un CAPTCHA o un avviso dell'account: fermati, risolvi a mano,
|
||||
@@ -14,28 +19,32 @@ locali, mai Instagram; **da provare** = serve una prova tua.
|
||||
|
||||
## Voci H: Instagram
|
||||
|
||||
Si provano tutte con la **sonda passiva** (parte A di `docs/prove-dal-vivo.md`): avvii `febe-sonda registra`, navighi
|
||||
tu in Instagram seguendo l'elenco (pagina iniziale, un profilo pubblico, un privato che segui, delle storie, una
|
||||
raccolta, le schede taggati e reel, l'elenco dei seguiti, un post), la sonda registra ciò che la pagina riceve; poi
|
||||
Si provano con la **sonda passiva** (parte A di `docs/prove-dal-vivo.md`): avvii `febe-sonda registra`, navighi tu in
|
||||
Instagram seguendo l'elenco (pagina iniziale, un profilo pubblico, un privato che segui, delle storie, una raccolta, le
|
||||
schede taggati e reel, l'elenco dei seguiti, un post), la sonda registra ciò che la pagina riceve; poi
|
||||
`febe-sonda ripulisci` e `febe-sonda verifica` sulla tua macchina, e mandi solo la cartella **ripulita**. La sonda non
|
||||
compie gesti e non apre pagine da sola.
|
||||
|
||||
Più semplice, con il **browser di tutti i giorni** (parte A bis): registri un HAR con il filtro «Tutti», incolli nella
|
||||
Console lo script `tools/bersagli/raccogli-bersagli.js` per i bersagli, poi `febe-sonda da-har`, `ripulisci` e
|
||||
`verifica`, e mandi solo la copia ripulita e il testo dei bersagli.
|
||||
|
||||
| | Ipotesi | Stato | Come la provi |
|
||||
|---|---|---|---|
|
||||
| H1 | La pagina iniziale consegna i post recenti dei profili che segui con i dati completi dei file | Da provare | Sonda, pagina iniziale: scorri piano una decina di post |
|
||||
| H1 | La pagina iniziale consegna i post recenti dei profili che segui con i dati completi dei file | Da provare (il HAR non conteneva la pagina iniziale) | Sonda, pagina iniziale: scorri piano una decina di post |
|
||||
| H2 | La barra delle storie dice quali profili seguiti hanno storie attive e a quando risale l'ultima | Da provare | Sonda, pagina iniziale caricata: passa sopra la prima voce della barra |
|
||||
| H3 | La pagina di un profilo consegna identificativo, pubblico o privato, se lo segui, la prima pagina dei post con serie e video, le raccolte; scorrendo arrivano le pagine successive | Da provare | Sonda: un profilo pubblico che non segui e uno privato che segui, scorrendo 3–4 schermate |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | Da provare | Sonda: apri le storie di un seguito dall'anello, guardane 2–3, chiudi con la X prima che passi all'account successivo |
|
||||
| H5 | Per i video arriva almeno un indirizzo con audio e video insieme | Da provare | Sonda: un post video e una storia video |
|
||||
| H3 | La pagina di un profilo consegna identificativo, pubblico o privato, se lo segui, la prima pagina dei post con serie e video, le raccolte; scorrendo arrivano le pagine successive | In parte: forma dell'indirizzo e del profilo viste nel HAR; le risposte della pagina profilo da provare | Sonda: un profilo pubblico che non segui e uno privato che segui, scorrendo 3–4 schermate |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | In parte: il visualizzatore delle raccolte riceve l'elenco completo con gli indirizzi; quello delle storie di un account da provare | Sonda: apri le storie di un seguito dall'anello, guardane 2–3, chiudi con la X prima che passi all'account successivo |
|
||||
| H5 | Per i video arriva almeno un indirizzo con audio e video insieme | In parte: tre versioni `.mp4` per video, «ha l'audio» detto dal contenuto; da confermare scaricando | Sonda: un post video e una storia video |
|
||||
| H6 | Le schede «Taggati» e «Reel» si comportano come la griglia | Da provare | Sonda: apri le due schede di un profilo e scorri |
|
||||
| H7 | I file del CDN si scaricano dal browser (`Network.loadNetworkResource`) | Provato in locale (24 MB integri); da provare con il CDN vero | Prima sessione dal vivo (parte B): i file arrivano in Libreria, stato «scaricato» |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | Da provare (non provocarli di proposito) | Se durante la sonda compare una verifica, annota l'ora e manda la riga ripulita di `navigazioni.jsonl` |
|
||||
| H9 | Un contenuto di una raccolta in evidenza ha lo stesso identificativo che aveva come storia | Da provare | Sonda: apri una raccolta che contiene una storia ancora attiva |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati della pagina, senza leggere i cookie | Da provare | Sonda, pagina iniziale |
|
||||
| H11 | I comandi della pagina si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | Da provare; lo scheletro `bersagli.instagram.json` è pronto | Durante tutta la sonda: passa col puntatore sui comandi elencati prima di usarli; manda le sole righe dei comandi, con i nomi di persona sostituiti |
|
||||
| H9 | Un contenuto di una raccolta in evidenza ha lo stesso identificativo che aveva come storia | Indizio: i contenuti delle raccolte hanno identificativo e scadenza come le storie | Sonda: apri una raccolta che contiene una storia ancora attiva |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati della pagina, senza leggere i cookie | Non basta: i dati danno solo l'identificativo dell'account collegato; Febe lo riconosce quando compare il suo profilo | Sonda, pagina iniziale |
|
||||
| H11 | I comandi della pagina si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | Da provare: il HAR non aveva gli attributi dei comandi. Pagine compilate, bersagli vuoti | Durante tutta la sonda: passa col puntatore sui comandi elencati prima di usarli; manda le sole righe dei comandi, con i nomi di persona sostituiti |
|
||||
|
||||
Finché H1–H11 non sono provate e la mappa dei bersagli e il vocabolario dei lettori non sono compilati sui campioni
|
||||
ripuliti, le ricette su Instagram rispondono «la mappa dei bersagli non è ancora compilata» senza aprire pagine.
|
||||
Finché i bersagli non sono compilati, le ricette che ne hanno bisogno rispondono «la mappa dei bersagli non è ancora
|
||||
compilata» senza aprire pagine; in Attività risultano «Da configurare» e il motore non le pianifica.
|
||||
|
||||
## Voci S: i due browser
|
||||
|
||||
|
||||
@@ -73,18 +73,25 @@ senza dati di Instagram, li riceve dall'elemento appena trovato.
|
||||
- **Libreria:** dove finiscono foto e video, una cartella per account. Può stare su un disco di rete.
|
||||
- **Dati:** database, profilo del browser, miniature, registro, copie. Deve stare su un disco locale.
|
||||
|
||||
Due schemi dei nomi, in Impostazioni ▸ Generali ▸ Nomi dei file, con anteprima del risultato. Predefiniti:
|
||||
Tre schemi dei nomi, in Impostazioni ▸ Generali ▸ Nomi dei file, con anteprima del risultato: uno generale (post,
|
||||
storie, taggati), uno per le raccolte in evidenza e uno per le foto del profilo. Predefiniti:
|
||||
|
||||
```text
|
||||
{account}\{tipo}\{anno}\{data}_{ora}_{codice}_{n}
|
||||
{account}\evidenza\{raccolta}\{data}_{ora}_{codice}_{n}
|
||||
{account}\profilo\{data}_{ora}_{codice}_{n}
|
||||
|
||||
marta.demo\post\2026\2026-10-10_18-22-05_DBx3kQ2_2.jpg
|
||||
marta.demo\evidenza\Estate 2025\2025-08-02_10-11-12_3391207_1.jpg
|
||||
marta.demo\profilo\2026-09-30_21-04-33_a3f9c2e1_1.jpg
|
||||
```
|
||||
|
||||
Le foto del profilo hanno il loro schema perché restino in una cartella a parte anche se cambi quello generale: una
|
||||
copia a ogni cambio di foto, con le prime otto cifre dell'impronta del file al posto del codice.
|
||||
|
||||
- Segnaposto: `account`, `tipo`, `anno`, `mese`, `data`, `ora`, `codice`, `n` (posizione del file nell'elemento),
|
||||
`raccolta`. Un segnaposto sconosciuto è un errore.
|
||||
`raccolta` (solo nello schema delle raccolte). Un segnaposto sconosciuto è un errore, e il campo sbagliato si
|
||||
colora di rosso.
|
||||
- Data e ora nei nomi sono nel tuo fuso; la data di modifica del file è quella di pubblicazione (si può spegnere).
|
||||
- I nomi sono ripuliti per Windows (caratteri vietati, nomi riservati, punti e spazi finali); un percorso oltre 240
|
||||
caratteri si accorcia prima nel nome del file, poi nelle cartelle. Un nome già occupato diventa `nome (2).ext`: mai
|
||||
|
||||
@@ -29,6 +29,7 @@ ritoccati guardando che cosa succede.
|
||||
| Pagine di storico | 20 / 100 | 30 / 180 | 45 / 300 |
|
||||
| Post singoli | 10 / 60 | 15 / 100 | 20 / 160 |
|
||||
| Pagine dell'elenco dei seguiti | 15 / 60 | 20 / 90 | 30 / 150 |
|
||||
| Ricerche di profili | 240 / 1200 | 300 / 1500 | 360 / 1800 |
|
||||
| Dati scaricati al giorno | 4 GB | 8 GB | 16 GB |
|
||||
| Storico per account al giorno | 300 post | 500 post | 800 post |
|
||||
| Avvio graduale | 7 giorni | 5 giorni | 3 giorni |
|
||||
@@ -60,7 +61,8 @@ ritoccati guardando che cosa succede.
|
||||
con pesi (frequenza e ritardo), mai lo stesso. Lo storico avanza su un solo account per sessione.
|
||||
- **Umore della sessione.** Ogni sessione ha un fattore di velocità estratto una volta: alcune sono svelte, altre lente.
|
||||
- **Riposo.** A fine sessione, nelle pause e di notte il browser sta su una pagina vuota: nessuna pagina di Instagram
|
||||
resta aperta fuori da una sessione.
|
||||
resta aperta fuori da una sessione, salvo mentre cerchi un profilo in «Aggiungi account» (fino a quando chiudi la
|
||||
finestra o a qualche minuto dopo l'ultima lettera).
|
||||
- **Lo storico non corre più veloce degli scaricamenti.** Lo storico di un account si sospende finché quell'account ha
|
||||
più di 60 file in attesa o il tetto dei dati è raggiunto: gli indirizzi dei file scadono, accumularli non serve.
|
||||
|
||||
@@ -75,6 +77,10 @@ ritmo «naturale»), limiti dell'account. Risponde con un permesso o con un rifi
|
||||
giorno dopo; le altre proseguono.
|
||||
- Quando valgono insieme più riduzioni (avvio graduale, tetti dimezzati dopo un rallentamento) si applica la più forte,
|
||||
non il loro prodotto.
|
||||
- **Ricerche di profili.** La ricerca della finestra «Aggiungi account» ha tetti propri, larghi apposta: fanno da
|
||||
guardia e non devono fermare l'uso normale, e non consumano i tetti della raccolta. Non serve una sessione, ma valgono
|
||||
l'interruttore, la pausa e la fascia oraria; fra due passi della ricerca, e fra la ricerca e il motore, passa almeno
|
||||
poco più di un secondo. Vedi [Account e impostazioni](Account-e-impostazioni).
|
||||
|
||||
## Avvio graduale
|
||||
|
||||
|
||||
@@ -55,7 +55,9 @@ una sua copia, ha la sessione di Instagram.**
|
||||
- Lo stato del collegamento è sempre in fondo alla barra laterale: collegato, da collegare, verifica richiesta, sessione
|
||||
chiusa.
|
||||
- Il tuo profilo compare tra gli account segnato «Tu», con «Post in cui è taggato» attivo: è così che si scaricano i
|
||||
post in cui sei taggato. (Riconoscere il tuo account dai dati della pagina è l'ipotesi H10, ancora da confermare.)
|
||||
post in cui sei taggato. Su Instagram i dati della pagina danno solo l'identificativo del tuo account: Febe ti
|
||||
riconosce quando compare anche il tuo profilo (per esempio la tua voce nella barra delle storie); fino ad allora la
|
||||
barra laterale dice «Collegato» e «Nome non ancora noto». È l'ipotesi H10, ancora da confermare dal vivo.
|
||||
|
||||
Poi aggiungi gli account da seguire: [Account e impostazioni](Account-e-impostazioni).
|
||||
|
||||
|
||||
@@ -33,9 +33,10 @@ dati.
|
||||
|
||||
Controlla in quest'ordine, guardando [Attività](Attivita-e-arresti):
|
||||
|
||||
1. **Raccolta da Instagram non ancora attiva.** Se in «Appena fatto» vedi «non può girare su instagram: la mappa dei
|
||||
bersagli non è ancora compilata», è lo stato attuale del progetto: le ricette su Instagram aspettano i risultati
|
||||
della sonda (ipotesi H1–H11, vedi [Ipotesi da verificare](Ipotesi-da-verificare)). Non è un guasto.
|
||||
1. **Ricetta «Da configurare».** Se in Attività vedi «non può girare su instagram: la mappa dei bersagli non è ancora
|
||||
compilata», è lo stato attuale del progetto per storie, raccolte e schede Taggati e Reel: aspettano i bersagli dei
|
||||
comandi (ipotesi H11, vedi [Ipotesi da verificare](Ipotesi-da-verificare)). Non è un guasto, e quelle ricette non
|
||||
vengono sospese.
|
||||
2. **Non collegato**, **verifica richiesta** o **sessione chiusa**: la barra laterale lo dice. Vedi
|
||||
[Primo collegamento](Primo-collegamento) e [Attività e arresti](Attivita-e-arresti).
|
||||
3. **Fuori fascia** o **giorno non attivo**: Attività dice «Fuori fascia» e quando riprende.
|
||||
@@ -46,6 +47,21 @@ Controlla in quest'ordine, guardando [Attività](Attivita-e-arresti):
|
||||
stato scaricato una volta.
|
||||
8. **Disco pieno:** vedi sotto.
|
||||
|
||||
## Cercare un profilo da aggiungere
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|---|---|
|
||||
| Sotto «Da Instagram» c'è «Febe non sa ancora dove sta «Cerca» su questo sito: per ora vedi solo i profili che segui.» | Su Instagram mancano ancora i bersagli del pannello «Cerca» (`search-open`, `search-box`, ipotesi H11 di [Ipotesi da verificare](Ipotesi-da-verificare)): si raccolgono con una prova dal vivo. Intanto usa i suggerimenti dei profili che segui, la riga «Aggiungi @nome per nome utente» o incolla più nomi |
|
||||
| «Stai usando il browser di Febe…» | Mentre usi tu il browser (accesso, verifica, pagina Browser) Febe non cerca: premi «Ho finito», e la ricerca riprende da sola con il testo che c'è nella casella |
|
||||
| «Febe è in pausa…» | Premi «Riprendi»: la ricerca riprende da sola |
|
||||
| «… non è riuscita: riprova», «Instagram non ha mandato risultati…» | Riscrivi lo stesso testo (basta uno spazio in più) o aggiungi una lettera: Febe ci riprova |
|
||||
| Un profilo che segui ha solo le iniziali | Febe non conserva le foto dei profili che segui: la foto arriva solo se il profilo compare anche fra i risultati di Instagram per lo stesso testo, o se l'account è già in Febe |
|
||||
| «È l'indirizzo di un post, di un reel…» | Hai incollato l'indirizzo di un post, di un reel o di una storia: serve quello del profilo, `instagram.com/nome.utente` |
|
||||
| «Fuori dalla fascia oraria…» o «Febe è fermo…» | Fuori fascia e durante un arresto Febe non apre Instagram, neanche per cercare. I suggerimenti locali funzionano; la ricerca riprende da sola quando la fascia si apre o l'arresto finisce |
|
||||
| «In attesa del turno…» per qualche secondo | Una sessione sta facendo un passo della raccolta sull'unica pagina del browser: i risultati arrivano appena la pagina è libera |
|
||||
| Nessun suggerimento mentre scrivi | Su Instagram Febe cerca da due lettere in su. I profili che segui compaiono già dalla prima lettera, ma solo se l'elenco dei seguiti è stato letto almeno una volta («Leggi l'elenco») |
|
||||
| Su Windows i risultati di Instagram non arrivano mai | La scrittura nella casella di Instagram con il browser di Windows non è ancora stata provata dal vivo: riferisci il caso, con il rapporto di diagnostica |
|
||||
|
||||
## File e libreria
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|
||||
@@ -52,7 +52,8 @@ si può usare. Dettagli in [Installazione con Docker e Unraid](Installazione-Doc
|
||||
- È un browser normale: nessuna modifica di user agent, impronta, lingua, fuso orario o intestazioni; niente modalità
|
||||
senza finestra; niente proxy; nessuna estensione «stealth».
|
||||
- Salvataggio delle password e compilazione automatica sono spenti: nel profilo resta solo la sessione.
|
||||
- Fra una sessione e l'altra sta su una pagina vuota; non segue mai collegamenti che portano fuori da Instagram.
|
||||
- Fra una sessione e l'altra sta su una pagina vuota, salvo mentre cerchi un profilo in «Aggiungi account»; non segue
|
||||
mai collegamenti che portano fuori da Instagram.
|
||||
- Verso Instagram parla solo il browser di Febe. L'unica altra connessione verso i server di Instagram è lo
|
||||
scaricamento dei file già indicati dalla pagina, dal solo CDN (e oggi passa anch'essa dal browser).
|
||||
|
||||
@@ -60,7 +61,9 @@ si può usare. Dettagli in [Installazione con Docker e Unraid](Installazione-Doc
|
||||
|
||||
Febe non mette «mi piace», non segue, non commenta, non scrive messaggi, non reagisce alle storie, non tocca annunci né
|
||||
suggerimenti. L'unica traccia che lascia è quella di una normale visita, **compresa la visualizzazione delle storie:
|
||||
le storie aperte da Febe risultano viste.** Un profilo privato che non ti ha accettato non si tocca.
|
||||
le storie aperte da Febe risultano viste.** Un profilo privato che non ti ha accettato non si tocca. Quando cerchi un
|
||||
profilo, Febe scrive nella casella «Cerca» di Instagram ma non fa clic sui risultati: le tue ricerche recenti su
|
||||
Instagram non cambiano.
|
||||
|
||||
## Un account, un motore
|
||||
|
||||
@@ -71,15 +74,17 @@ visite e il rischio.
|
||||
|
||||
Il registro contiene azioni ed esiti: nomi utente sì; didascalie, corpi delle risposte, password, cookie, tasti,
|
||||
indirizzi firmati dei file, gettoni (compreso quello di Telegram) no. Il client del browser registra solo i nomi dei
|
||||
comandi, mai i loro parametri. Il registro è nella cartella dei dati (`registro`), un file al giorno, tenuto
|
||||
comandi, mai i loro parametri. Di una ricerca di profili restano solo quanti passi ha fatto e come sono finiti, mai il
|
||||
testo che hai scritto né i nomi trovati; le foto dei profili trovati stanno solo in memoria, per poco, e non finiscono
|
||||
mai su disco. Il registro è nella cartella dei dati (`registro`), un file al giorno, tenuto
|
||||
quattordici giorni.
|
||||
|
||||
## Che cosa esce da Febe
|
||||
|
||||
| Verso | Che cosa | Quando |
|
||||
|---|---|---|
|
||||
| Instagram | Le visite del browser di Febe, con la tua sessione | Nelle sessioni, dentro la fascia |
|
||||
| CDN di Instagram | Lo scaricamento dei file indicati dalla pagina | Quando ci sono file in coda |
|
||||
| Instagram | Le visite del browser di Febe, con la tua sessione | Nelle sessioni, dentro la fascia; e quando cerchi un profilo in «Aggiungi account» |
|
||||
| CDN di Instagram | Lo scaricamento dei file indicati dalla pagina | Quando ci sono file in coda, e per le foto dei profili trovati dalla ricerca |
|
||||
| Telegram (`api.telegram.org`) | Il testo degli avvisi | Solo se hai configurato il bot |
|
||||
|
||||
Nient'altro: niente statistiche, niente aggiornamenti automatici, nessun carattere o icona caricato dalla rete.
|
||||
|
||||
@@ -196,10 +196,14 @@ richieste di unione, protezione di `main`, rilievi di sicurezza, rilasci, correz
|
||||
- `installatore`: `Febe-Setup-<versione>-ci.<numero>.exe` e lo zip portabile, fra gli artefatti per 14 giorni;
|
||||
- `immagine`, dopo l'installatore: l'immagine Docker, provata senza rete (parte, diventa «healthy», si ferma) e
|
||||
scansionata con Trivy; dopo un push su `main` va sul registro come `:main` e `:sha-<commit>`. Alla fine si toglie
|
||||
tutto ciò che l'esecuzione ha creato sul demone Docker, che è condiviso con gli altri progetti;
|
||||
tutto ciò che l'esecuzione ha creato sul demone Docker, che è condiviso con gli altri progetti, e poi, di tutti, le
|
||||
immagini senza nome e la cache di costruzione che nessuno usa da 24 ore;
|
||||
- `rilascio.yml`, a ogni tag `vX.Y.Z`: prove, installatore e zip, immagine provata e scansionata, pubblicata come
|
||||
`:X.Y.Z` e `:latest` (solo per le versioni senza trattino), poi la release;
|
||||
- `pulizia.yml`, ogni lunedì e a mano: i resti delle esecuzioni interrotte e le immagini senza nome vecchie.
|
||||
- `pulizia.yml`, ogni lunedì e a mano: i resti delle esecuzioni interrotte e dei lavori di act_runner, le immagini che
|
||||
nessun contenitore usa e la cache di costruzione più vecchie di 24 ore, di tutti i progetti, e sul registro le
|
||||
`:sha-` oltre le 10 più recenti; mai un contenitore, un volume o una rete che non sia della CI. A mano, con «Solo
|
||||
prova», elenca che cosa toglierebbe e non toglie nulla (`docs/processo.md`, «Pulizia»).
|
||||
|
||||
Nella CI le prove del sito di prova (categoria `SitoDiProva`) girano due volte: con il seme 13 e con un seme diverso
|
||||
a ogni esecuzione, scritto nel registro del lavoro. Per rifare un errore con quel seme:
|
||||
|
||||
@@ -10,5 +10,6 @@ Le immagini sono il riferimento grafico di §10.3 della specifica. Sono in scala
|
||||
| `08-impostazioni-generali.png` | Originale |
|
||||
| `10-collegamento-instagram.png` | Originale |
|
||||
| `miniature/02…14` | **Ritagli ingranditi della panoramica**: gli originali a piena risoluzione non sono stati forniti. Bastano per disposizione e gerarchia, non per misure e testi minuti |
|
||||
| `miniature/04-aggiungi-account.png` | **Superato da #37** (ricerca unica dei profili): linguette ed elenco a spunte non ci sono più. Finché Alberto non fornisce un mockup nuovo, il riferimento della finestra è la schermata `docs/schermate/04-aggiungi-account.png`, con le differenze in `docs/schermate/differenze.md` |
|
||||
|
||||
Quando arrivano gli originali mancanti vanno messi qui con i nomi di §10.3 e i ritagli in `miniature/` si possono cancellare.
|
||||
@@ -94,9 +94,11 @@ Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri proget
|
||||
La verifica gira a ogni push su qualunque ramo e a mano (Actions ▸ verifica ▸ Esegui, con un seme facoltativo). Su un
|
||||
ramo un push nuovo annulla l'esecuzione in corso; su `main` ogni unione arriva fino in fondo. Un'esecuzione a mano non
|
||||
annulla mai quella di un push (l'evento fa parte del gruppo di concorrenza): solo il push scrive gli stati del commit
|
||||
che servono per unire, e un lavoro annullato lascerebbe lo stato «failure».
|
||||
che servono per unire, e un lavoro annullato lascerebbe lo stato «failure». Se Gitea perde l'evento di un push (è successo
|
||||
il 13 novembre 2026, con il server che rispondeva 500), un'esecuzione a mano verde non basta per unire, nemmeno da
|
||||
amministratore, perché la regola vale anche per loro: si spinge un commit nuovo sul ramo e si unisce sulla sua verifica.
|
||||
|
||||
Altri flussi: `rilascio.yml` a ogni tag (vedi «Rilasci») e `pulizia.yml` ogni lunedì (vedi «Pulizia»).
|
||||
Altri flussi: `rilascio.yml` a ogni tag (vedi «Rilasci») e `pulizia.yml` ogni lunedì e a mano (vedi «Pulizia»).
|
||||
|
||||
### Il mondo sintetico e il suo seme
|
||||
|
||||
@@ -129,20 +131,39 @@ Sul registro di Gitea, `192.168.30.23:3000/alby96/febe`:
|
||||
| `:latest` | `rilascio`, solo versioni senza trattino | a ogni rilascio stabile | Unraid e Docker Compose |
|
||||
| `:X.Y.Z` | `rilascio` (anche `X.Y.Z-rc.1` per un'anteprima) | mai | una versione precisa, per tornare indietro |
|
||||
| `:main` | `verifica`, dopo ogni unione in `main` | a ogni unione (mai all'indietro) | provare `main` su un server di prova; non per l'archivio vero |
|
||||
| `:sha-<7 caratteri>` | `verifica`, dopo ogni unione in `main` | mai | un commit preciso di `main` |
|
||||
| `:sha-<7 caratteri>` | `verifica`, dopo ogni unione in `main` | mai; restano le 10 più recenti | un commit preciso di `main` |
|
||||
|
||||
Ogni immagine della CI porta le etichette Docker `febe.ci.workflow`, `febe.ci.run`, `febe.ci.ref` e `febe.ci.commit`,
|
||||
oltre a quelle OCI del Dockerfile: da un'immagine si risale all'esecuzione e al commit. Docker le copia in ogni
|
||||
contenitore creato dall'immagine, anche in un Febe vero: per questo la pulizia non le usa mai per scegliere che cosa
|
||||
togliere (vedi «Pulizia»). Le `:sha-` si accumulano: una
|
||||
regola di pulizia dei pacchetti (Impostazioni ▸ Pacchetti ▸ Regole di pulizia) può tenere sempre `latest`, `main` e
|
||||
le versioni e togliere le `sha-.*` più vecchie di 30 giorni.
|
||||
togliere (vedi «Pulizia»). Le `:sha-` non si accumulano: con il segreto `REGISTRY_TOKEN`, la pulizia del lunedì tiene le
|
||||
10 più recenti e toglie le altre; `:main`, `:latest` e le versioni restano sempre.
|
||||
|
||||
Perché togliere un'etichetta liberi davvero spazio, l'immagine si pubblica come un manifest semplice, senza attestazioni
|
||||
(`--provenance=false --sbom=false` in `.gitea/scripts/costruisci-immagine.sh`): in Gitea ogni etichetta è una versione
|
||||
del pacchetto che tiene la configurazione e gli strati, e i blob che nessuna versione usa più li cancella la pulizia dei
|
||||
pacchetti di Gitea stessa, ogni notte, quando hanno più di 24 ore (`[cron.cleanup_packages]`, attiva per impostazione
|
||||
predefinita). Con le attestazioni, che buildx aggiunge da sé, l'immagine sarebbe un indice: Gitea terrebbe ogni manifest
|
||||
figlio come una versione a sé, `sha256:…` senza etichetta, con gli strati, e togliere l'etichetta toglierebbe solo
|
||||
l'indice. La pulizia del lunedì non tocca mai le versioni `sha256:…` (l'API dei pacchetti non dice se un'etichetta le usa
|
||||
ancora) e scrive quante sono. Se ce ne sono (un'immagine spinta a mano, o con più piattaforme), quelle che nessuna
|
||||
etichetta usa più le toglie una regola di pulizia di Gitea, da impostare una volta sul proprietario del pacchetto
|
||||
(Impostazioni ▸ Pacchetti ▸ regole di pulizia): tipo container, attiva, schema delle versioni da rimuovere `sha256:.+`,
|
||||
più vecchie di 7 giorni (il valore più basso dopo lo zero, che toglierebbe anche un figlio appena spinto e non ancora
|
||||
rimandato dal suo indice), nessun numero da tenere. Gitea confronta lo schema con tutta la versione, salta da sé
|
||||
le versioni `sha256:` che un indice ancora rimanda e sempre `latest`, e applica la regola ogni notte; una regola non deve
|
||||
mai toccare `main` e le versioni.
|
||||
|
||||
## Pulizia
|
||||
|
||||
Il demone Docker è condiviso con gli altri progetti, e ci può girare anche un Febe vero, avviato da un'immagine che la
|
||||
CI ha pubblicato e che quindi porta le sue etichette `febe.ci.*`. La CI di Febe toglie solo ciò che può provare suo
|
||||
(`.gitea/scripts/pulizia-docker.sh`):
|
||||
Il demone Docker è condiviso con gli altri progetti di Alberto e, molto probabilmente, con le applicazioni di Unraid; ci
|
||||
può girare anche un Febe vero, avviato da un'immagine che la CI ha pubblicato e che quindi porta le sue etichette
|
||||
`febe.ci.*`. Dal 21 ottobre 2026, per decisione di Alberto, la pulizia (`.gitea/scripts/pulizia-docker.sh`) toglie due
|
||||
cose: ciò che la CI di Febe può provare suo e ciò che non serve più a nessuno, di qualunque progetto. Mai un
|
||||
contenitore, un volume o una rete che non sia della CI.
|
||||
|
||||
Ciò che è della CI di Febe si riconosce da segni che nessuna immagine porta (le etichette `febe.ci.*` no: Docker le
|
||||
copia in ogni contenitore creato dall'immagine, anche in un Febe vero):
|
||||
|
||||
- contenitori di prova: l'etichetta `febe.ci.prova=<esecuzione>`, che mette solo `prova-immagine.sh` con
|
||||
`docker run --label` e che nessuna immagine porta (lo controlla `PipelineTests`), e insieme il nome esatto
|
||||
@@ -150,18 +171,71 @@ CI ha pubblicato e che quindi porta le sue etichette `febe.ci.*`. La CI di Febe
|
||||
- immagini provate: il nome locale `febe-ci:<esecuzione>`, tolto per nome, mai per identificativo e mai con `-f`. Se la
|
||||
stessa immagine ha anche un nome del registro, quello resta; se un contenitore la usa, resta tutto;
|
||||
- builder buildx: il contenitore `buildx_buildkit_febe-ci-<esecuzione>0` con l'immagine `moby/buildkit` e il suo volume
|
||||
`…_state`;
|
||||
- più le immagini senza nome più vecchie di 72 ore che nessun contenitore usa.
|
||||
`…_state`.
|
||||
|
||||
`PipelineTests` fa girare la pulizia contro un demone finto (`tests/Febe.Tests/Packaging/fake-docker.sh`) con un Febe
|
||||
vero acceso e uno fermo che portano le etichette delle loro immagini: non li deve toccare.
|
||||
Ciò che resta dei lavori di act_runner si riconosce dal nome che act_runner dà a tutto ciò che crea per un lavoro,
|
||||
`GITEA-ACTIONS-TASK-<numero del compito>…`: il contenitore del lavoro, i suoi volumi `<nome>` e `<nome>-env`, la sua
|
||||
rete `<nome>-<lavoro>-network`. Se ne vanno i contenitori fermi e i volumi e le reti che nessun contenitore usa, più
|
||||
vecchi di 90 minuti. Il volume `act-toolcache`, la cache degli strumenti condivisa fra i lavori, resta.
|
||||
|
||||
Ciò che non serve più a nessuno lo toglie Docker stesso (`docker image prune`, `docker builder prune`), che non toglie
|
||||
mai un'immagine usata da un contenitore, acceso o fermo: un'applicazione di Unraid ferma tiene la sua immagine. Se però
|
||||
quell'immagine ha più nomi, `image prune -a` le toglie quelli in più (vedi «Che cosa costa»).
|
||||
|
||||
| Quando | Che cosa si toglie |
|
||||
|---|---|
|
||||
| alla fine di ogni lavoro «immagine», sempre | il contenitore di prova con i suoi volumi anonimi, l'immagine provata, il builder buildx dell'esecuzione con la sua cache, l'archivio dell'immagine, le credenziali del registro |
|
||||
| alla fine di ogni lavoro «immagine» (verifica e rilascio), sempre | il contenitore di prova con i suoi volumi anonimi, l'immagine provata, il builder buildx dell'esecuzione con la sua cache, l'archivio dell'immagine, le credenziali del registro; poi, di tutti i progetti, le immagini senza nome che nessun contenitore usa e la cache di costruzione penzolante del demone, cioè quella che nessuna immagine condivide, non usata da 24 ore (`pulizia-docker.sh penzolanti`). Un errore qui è solo un avviso: il lavoro non diventa rosso |
|
||||
| all'inizio di ogni lavoro «immagine» | i resti di esecuzioni interrotte più vecchi di 90 minuti (un lavoro dura al massimo 60 minuti): contenitori di prova **fermi**, immagini `febe-ci:`, builder; e ciò che ha lasciato un tentativo precedente della stessa esecuzione |
|
||||
| ogni lunedì e a mano (`pulizia.yml`) | gli stessi resti, l'immagine `febe:ci` del vecchio flusso se nessuno la usa, le immagini senza nome più vecchie di 72 ore |
|
||||
| mai | immagini, contenitori e volumi degli altri progetti; un contenitore Febe che non sia di prova, anche se porta le etichette `febe.ci.*`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso settimanale diventa rosso); la cache di costruzione del demone; i volumi con un nome; le immagini col nome del registro |
|
||||
| ogni lunedì alle 4:17 e a mano (`pulizia.yml`, `pulizia-docker.sh completa`) | gli stessi resti e l'immagine `febe:ci` del vecchio flusso; i resti di act_runner; **le immagini che nessun contenitore usa create più di 24 ore fa**, di tutti i progetti, anche col nome del registro; la cache di costruzione del demone non usata da più di 24 ore; con il segreto `REGISTRY_TOKEN`, sul registro le `:sha-` oltre le 10 più recenti. Prima e dopo `docker system df`, alla fine un riepilogo di che cosa è andato via |
|
||||
| mai | `docker system prune`, `container prune`, `volume prune`, `network prune`; un contenitore, un volume o una rete che non sia della CI: un Febe vero, anche se porta le etichette `febe.ci.*`, le applicazioni di Unraid, i volumi con i dati, `act-toolcache`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso del lunedì diventa rosso); un'immagine usata da un contenitore, anche fermo (i suoi nomi in più sì: vedi sotto); `image prune -a` e `builder prune -a` senza il filtro delle 24 ore; sul registro `:main`, `:latest` e le versioni `X.Y.Z` |
|
||||
|
||||
Che cosa costa:
|
||||
|
||||
- le immagini di base che fra un lavoro e l'altro nessun contenitore usa (`node:24-trixie` del lavoro «prove»,
|
||||
`moby/buildkit` dei builder, quelle dei lavori degli altri progetti) si riscaricano alla prima esecuzione che le
|
||||
chiede dopo il lunedì: qualche minuto e qualche centinaio di MB in più, una volta. L'immagine dei lavori
|
||||
(`ubuntu-latest`) resta, perché durante la pulizia la usa il lavoro stesso;
|
||||
- da quando contano le 24 ore delle immagini dipende dallo store delle immagini del demone, che la pulizia scrive
|
||||
all'inizio. Con lo store classico (il più probabile su Unraid) contano dalla costruzione dell'immagine: una
|
||||
scaricata ieri ma costruita un mese fa se ne va, e una costruita con una data fissa (costruzioni riproducibili,
|
||||
`SOURCE_DATE_EPOCH`) non è mai protetta dalla finestra. Con lo store di containerd (predefinito nelle installazioni
|
||||
nuove di Docker Engine dalla 29) contano da quando il nome è arrivato sul demone, e un nome riscaricato tiene la data di
|
||||
prima: un'immagine appena riscaricata con un nome che c'era già, e non ancora usata da un contenitore, se ne va. Con
|
||||
tutti e due, un'immagine scaricata e non ancora usata non è al sicuro. La prova dà sempre l'età dalla costruzione, e
|
||||
con containerd lo dice: lì il suo elenco è solo indicativo;
|
||||
- un'immagine costruita a mano e tenuta senza contenitore (per esempio quella di `docker build -t febe .`) se ne va e va
|
||||
ricostruita; una versione di Febe tenuta per tornare indietro si riscarica dal registro, dove `:X.Y.Z` resta;
|
||||
- un'immagine che un contenitore usa resta, ma se ha più nomi `image prune -a` le toglie quelli in più. Con lo store
|
||||
classico resta solo l'ultimo in ordine alfabetico del nome completo, anche quando il contenitore è stato creato da un
|
||||
altro: un'applicazione di Unraid creata da `app:1.2`, se la stessa immagine si chiama anche `app:latest`, continua a
|
||||
girare, ma in locale `app:1.2` non c'è più, e Unraid la mostra da aggiornare o la riscarica. Con lo store di
|
||||
containerd restano i nomi da cui i contenitori sono stati creati. Un Febe vero avviato da `:latest`, se la stessa
|
||||
immagine si chiama anche `:0.1.0`, perde `:0.1.0` e resta `:latest`. La prova elenca questi nomi e la pulizia vera li
|
||||
scrive uno per uno;
|
||||
- la cache di costruzione del builder del demone, con cui costruiscono gli altri progetti: resta quella usata nelle
|
||||
ultime 24 ore. Dopo ogni esecuzione di Febe se ne va quella che nessuna immagine condivide (strati intermedi, cache
|
||||
montate con `RUN --mount=type=cache`) e che nessuno usa da un giorno; il lunedì anche quella condivisa e quella
|
||||
interna di BuildKit, con lo stesso limite. Una costruzione che si ripete almeno una volta al giorno ritrova la sua
|
||||
cache; una più rara la rifà.
|
||||
|
||||
**Prova senza togliere nulla.** Actions ▸ pulizia ▸ Esegui, con «Solo prova» spuntato: il registro del lavoro elenca
|
||||
che cosa toglierebbe (le immagini con dimensione ed età, i nomi in più delle immagini in uso, la cache di costruzione, i
|
||||
resti della CI di Febe e di act_runner, le `:sha-` del registro) e non toglie nulla: solo comandi che leggono, e sul
|
||||
registro solo GET. Si lancia prima della prima pulizia vera e dopo ogni cambio dello script. Dal server, nella cartella
|
||||
del repository:
|
||||
`bash .gitea/scripts/pulizia-docker.sh completa --prova` (il registro solo con `REGISTRY_TOKEN`, `GITEA_API` e
|
||||
`PROPRIETARIO` nell'ambiente). Una prova scritta in un altro modo non diventa la pulizia vera: un'opzione diversa da
|
||||
`--prova` (`--dry-run`, `-n`, `--Prova`) o una parola in più (`prova` senza trattini) fermano lo script con codice 2
|
||||
prima che tocchi Docker, e il flusso accetta per «prova» solo `true` e `false` (un avvio con l'API che passa un altro
|
||||
valore, «True» o «1», si ferma con un errore). Le immagini, nella pulizia vera, le sceglie Docker; nella prova le stima
|
||||
lo script con la stessa regola.
|
||||
|
||||
`PipelineTests` fa girare la pulizia contro un demone finto (`tests/Febe.Tests/Packaging/fake-docker.sh`), con lo store
|
||||
classico e con quello di containerd, con un Febe vero acceso e uno fermo, applicazioni di Unraid accese e ferme (una con
|
||||
due nomi), il lavoro della pulizia stessa, resti veri e finti di act_runner, e contro un'API dei pacchetti finta
|
||||
(`fake-curl.sh`): controlla che cosa resta, che nessun comando vietato parta, che la prova non tocchi nulla e dica ciò
|
||||
che la pulizia vera poi toglie, che una prova scritta male si fermi, e che il token non finisca mai nel registro del
|
||||
lavoro.
|
||||
|
||||
## Rilievi di sicurezza
|
||||
|
||||
@@ -211,4 +285,13 @@ di ogni blocco `run`), gli script con un client Docker finto. Restano da vedere
|
||||
`node:24-trixie` con le azioni dentro; le prove con il browser nel contenitore (nessuna saltata); `upload-artifact@v3`
|
||||
con `retention-days`; la concorrenza; il builder buildx con il nome dell'esecuzione; la prova del contenitore senza
|
||||
rete fino a «healthy»; il download e la scansione di Trivy (e se trova CRITICAL da correggere); gitleaks sulla storia;
|
||||
la pubblicazione su `main` con il segreto; la pulizia settimanale sul demone vero.
|
||||
la pubblicazione su `main` con il segreto.
|
||||
|
||||
Della pulizia del 21 ottobre 2026 (script e API provati con un client Docker e un curl finti) restano da vedere: la
|
||||
casella «Solo prova» di Gitea che arriva al lavoro come «true»; i nomi che questo act_runner dà ai suoi contenitori,
|
||||
volumi e reti; che cosa la prova dice di togliere sul demone vero, da leggere prima della prima pulizia vera; poi la
|
||||
pulizia vera: `docker builder prune` passato a buildx con `BUILDX_BUILDER=default`, il tempo e lo spazio recuperato,
|
||||
le immagini riscaricate dopo; con il segreto, l'API dei pacchetti con `REGISTRY_TOKEN` (elenco a pagine e DELETE delle
|
||||
`:sha-`), e che dopo la prima pubblicazione con `--provenance=false --sbom=false` il pacchetto non abbia versioni
|
||||
`sha256:…` (la riga del registro nel lavoro della pulizia, o la pagina del pacchetto su Gitea); la pulizia di ogni
|
||||
esecuzione alla fine del lavoro «immagine».
|
||||
@@ -86,6 +86,240 @@ Quando i lettori e la mappa sono stati scritti sui campioni ripuliti, **cancella
|
||||
|
||||
---
|
||||
|
||||
## A bis. Bersagli e campioni dal browser di tutti i giorni (25 ottobre 2026)
|
||||
|
||||
Scopo: completare ciò che il file HAR del 21 ottobre non poteva dare. Quel file aveva solo le risposte **Fetch/XHR**
|
||||
(il filtro del pannello Rete era su «Fetch/XHR»): nessun documento, quindi nessun dato incorporato nelle pagine, e
|
||||
nessun attributo degli elementi (ruoli, nomi accessibili, collegamenti). Da lì sono venuti i lettori
|
||||
(`lettori.instagram.json`) e le pagine della mappa (`bersagli.instagram.json`), ma i **bersagli** sono ancora vuoti:
|
||||
«Storie di un account», «Raccolta in evidenza», «Taggati» e «Reel» si rifiutano di girare finché non ci sono (H11).
|
||||
Mancano anche le risposte della home, del profilo e della sua griglia, delle storie, delle schede, dell'elenco dei
|
||||
seguiti e di un post con più foto.
|
||||
|
||||
Si raccolgono le due cose nello stesso giro, dal browser che usi tutti i giorni, senza la sonda: un file HAR completo
|
||||
e i bersagli dei comandi che clicchi. **Navighi solo tu**: nessun programma clicca o apre pagine.
|
||||
|
||||
### A bis 1. Prima di cominciare
|
||||
|
||||
- Chrome su Windows, con Instagram aperto e l'accesso già fatto, come il 21 ottobre.
|
||||
- Una cartella **fuori da qualunque repository git**, per esempio `C:\febe-har\2026-10-25` (qui sotto
|
||||
`<cartella>`): lì vanno il file HAR, i campioni grezzi e il testo dei bersagli. Il file HAR contiene i cookie della
|
||||
sessione e i dati di altre persone: **non si invia mai** e non va nel repository (`febe-sonda da-har` rifiuta un
|
||||
file o una cartella dentro un repository).
|
||||
- Il file `tools/bersagli/raccogli-bersagli.js` del repository, aperto in un editor per copiarlo
|
||||
(`tools/bersagli/LEGGIMI.md` dice che cosa registra).
|
||||
- Come in tutta questa guida: se compare una verifica, un CAPTCHA o un avviso dell'account, **fermati**, risolvi a
|
||||
mano, annota l'ora e riferisci.
|
||||
|
||||
### A bis 2. Strumenti per sviluppatori
|
||||
|
||||
1. Con Instagram aperto premi **F12** (oppure Ctrl+Maiusc+I).
|
||||
2. Scheda **Rete**: spunta **Conserva log** e nel filtro dei tipi scegli **Tutti**, **non** «Fetch/XHR»: servono
|
||||
anche i documenti.
|
||||
3. Ricarica la pagina (**F5**) con il pannello aperto: così anche il primo documento della home finisce nel registro.
|
||||
4. Scheda **Console**: incolla tutto il contenuto di `raccogli-bersagli.js` e premi Invio. La prima volta Chrome può
|
||||
chiedere di scrivere una frase di conferma prima di accettare un incolla: scrivila come indica e incolla di nuovo.
|
||||
Deve comparire «Febe: raccolta dei bersagli attiva (sola lettura)».
|
||||
|
||||
Lo script legge soltanto: non clicca, non cambia la pagina, non manda nulla a nessuno, non legge cookie né le memorie
|
||||
del browser. A ogni clic la Console scrive «Febe: clic N registrato». Se la pagina si ricarica del tutto (F5, un
|
||||
indirizzo scritto a mano) la raccolta si perde: **incolla di nuovo lo script**.
|
||||
|
||||
### A bis 3. Che cosa fare, nell'ordine
|
||||
|
||||
Muoviti con calma, come al solito, e annota l'ora d'inizio di ogni passo. I comandi in **grassetto** sono quelli da
|
||||
cliccare: è il clic che registra ruolo e nome accessibile.
|
||||
|
||||
1. **Home.** Attendi il caricamento e scorri piano per una decina di post.
|
||||
2. **Un profilo.** Scrivi nella barra l'indirizzo di un profilo pubblico (è un caricamento completo, come quando Febe
|
||||
apre un profilo), poi **incolla di nuovo lo script** nella Console. Scorri la griglia per 3–4 schermate.
|
||||
3. **Le storie di un seguito.** Dal suo profilo clicca la **foto con l'anello**. Vai avanti di **due** storie
|
||||
cliccando la **zona a destra**. Prima che finiscano, chiudi con la **X**: non lasciare che il visualizzatore passi da
|
||||
solo all'account successivo.
|
||||
4. **Una raccolta in evidenza.** Da un profilo clicca una **raccolta**, vai avanti **una volta** con la zona a destra,
|
||||
chiudi con la **X**.
|
||||
5. **Le schede «Reel» e «Taggati»** di un profilo: clicca la **scheda** e scorri un poco, per ognuna.
|
||||
6. **I tuoi seguiti.** Dal tuo profilo clicca **«Seguiti»** e scorri l'elenco per 3–4 schermate.
|
||||
7. **Un post con più foto** (una serie): aprilo dalla griglia e passa alla foto successiva con la **freccia**.
|
||||
8. **La ricerca** (bersagli `search-open` e `search-box`, issue #37). Clicca **«Cerca»** nella colonna laterale,
|
||||
poi **clicca nella casella** e scrivi a mano le prime lettere di un nome. **Non cliccare nessun risultato** (finirebbe
|
||||
fra le tue ricerche recenti, ed è proprio ciò che Febe non fa mai): chiudi il pannello cliccando di nuovo **«Cerca»**.
|
||||
|
||||
Ci si aspetta: nessuna verifica, nessun avviso.
|
||||
|
||||
### A bis 4. Il testo dei bersagli
|
||||
|
||||
1. Nella Console scrivi `febeBersagli()` e premi Invio: i clic registrati vanno negli appunti e la Console dice
|
||||
quanti sono (se la copia non riesce, li scrive nella Console: copiali da lì).
|
||||
2. Incollali in un file di testo nuovo, per esempio `<cartella>\bersagli.txt`. Nei testi i nomi visti negli
|
||||
indirizzi e le `@parole` sono già diventati `NOME`, e negli indirizzi resta solo la forma (`/stories/<x>/<x>/`).
|
||||
**Leggi il file e sostituisci con `NOME` ogni nome di persona rimasto** (nomi scritti per esteso, frasi delle
|
||||
didascalie).
|
||||
|
||||
### A bis 5. Il file HAR
|
||||
|
||||
1. Scheda **Rete**: pulsante per **esportare il HAR** (la freccia verso il basso nella barra del pannello) e salva in
|
||||
`<cartella>\instagram.har`. Se Chrome offre due voci, scegli quella senza dati sensibili; se poi la conversione
|
||||
dice che le risposte sono «senza corpo», esporta di nuovo con l'altra voce.
|
||||
2. Chiudi gli strumenti per sviluppatori.
|
||||
|
||||
### A bis 6. Conversione, ripulitura e verifica (sulla tua macchina)
|
||||
|
||||
```sh
|
||||
febe-sonda da-har --har <cartella>\instagram.har --a <cartella>\grezzi
|
||||
febe-sonda ripulisci --da <cartella>\grezzi --a <cartella>\ripuliti
|
||||
febe-sonda verifica --grezzi <cartella>\grezzi --ripuliti <cartella>\ripuliti
|
||||
```
|
||||
|
||||
Dal repository: `dotnet run --project tools/Febe.Sonda -- da-har …`, e così per gli altri due.
|
||||
|
||||
- `da-har` scrive i campioni grezzi nello stesso formato della sonda, in una cartella **nuova** (rifiuta una cartella
|
||||
già usata). Tiene solo le risposte di dati del sito e i dati incorporati nei documenti; lascia fuori file, immagini,
|
||||
script e ogni altro sito; **non copia mai** intestazioni, cookie, parametri degli indirizzi o corpi delle richieste.
|
||||
Ogni file prende il nome dell'operazione GraphQL quando c'è (per esempio `000012-PolarisStoriesV3HighlightsPageQuery.json`),
|
||||
altrimenti `risposta` o `documento`: mai un pezzo di indirizzo, che può contenere un nome. Stampa solo conteggi.
|
||||
- `ripulisci` va lanciato **una volta sola su tutta la cartella**: i valori finti cambiano a ogni esecuzione.
|
||||
- La verifica deve dire **«Verifica superata»**. Se no, dice in quale file sopravvive un frammento (mai il frammento
|
||||
stesso): **cancella la cartella `ripuliti`**, non inviare nulla e riferisci il messaggio.
|
||||
|
||||
### A bis 7. Che cosa mandare
|
||||
|
||||
1. La cartella **ripulita** (compressa) e il testo della verifica.
|
||||
2. Il file `bersagli.txt`, con i nomi sostituiti.
|
||||
3. Le note: a che ora hai fatto ogni passo, che cosa è andato diversamente da come descritto.
|
||||
|
||||
Mai: il file HAR, la cartella `grezzi`, schermate con nomi di altre persone. Quando lettori e mappa sono stati scritti
|
||||
sui campioni ripuliti, **cancella il file HAR e la cartella `grezzi`** (§14.5).
|
||||
|
||||
---
|
||||
|
||||
## A ter. Richieste e risposte per «la pagina chiede i dati» (12 novembre 2026, issue #35)
|
||||
|
||||
Scopo: con la decisione del 12 novembre (issue #34, specifica §2 regola 2 e §6.1) Febe chiede i dati al sito dalla
|
||||
pagina, con le stesse richieste che fa l'applicazione web di Instagram. Per scriverle (`richieste.instagram.json`) e
|
||||
leggerne le risposte servono, da un solo giro nel tuo browser:
|
||||
|
||||
- la **forma delle richieste** che la pagina fa: indirizzi, nomi dei parametri e delle intestazioni, operazioni
|
||||
GraphQL. La dà il nuovo `febe-sonda richieste`, che non scrive nessun valore personale;
|
||||
- le **risposte**, ripulite come sempre con `da-har`, `ripulisci` e `verifica`.
|
||||
|
||||
Niente script dei bersagli, questa volta: con la strada B Febe non cerca più i comandi nella pagina. **Navighi solo
|
||||
tu**: nessun programma clicca o apre pagine.
|
||||
|
||||
### A ter 1. Prima di cominciare
|
||||
|
||||
- Chrome su Windows, con Instagram aperto e l'accesso già fatto.
|
||||
- Una cartella **nuova, fuori da qualunque repository git**, per esempio `C:\febe-har\2026-11-12` (qui sotto
|
||||
`<cartella>`). Il file HAR contiene i cookie della sessione e i dati di altre persone: **non si invia mai**.
|
||||
- Febe compilato dal repository aggiornato (serve il comando `richieste`).
|
||||
- Se compare una verifica, un CAPTCHA o un avviso dell'account, **fermati**, risolvi a mano, annota l'ora e riferisci.
|
||||
|
||||
### A ter 2. Strumenti per sviluppatori
|
||||
|
||||
1. Con Instagram aperto premi **F12**.
|
||||
2. Scheda **Rete**: spunta **Conserva log** e nel filtro dei tipi scegli **Tutti**, non «Fetch/XHR».
|
||||
3. Ricarica la pagina (**F5**) con il pannello aperto.
|
||||
|
||||
### A ter 3. Che cosa fare, nell'ordine
|
||||
|
||||
Muoviti con calma, come al solito, e annota l'ora d'inizio di ogni passo. Ogni passo corrisponde a una richiesta che
|
||||
Febe dovrà saper fare.
|
||||
|
||||
Da qui in poi i profili si aprono **cliccando**, mai scrivendo l'indirizzo nella barra: un indirizzo scritto a mano
|
||||
ricarica tutta la pagina e i dati arrivano dentro il documento, non come richiesta della pagina, e il file non li
|
||||
descriverebbe.
|
||||
|
||||
1. **Ricerca, lettera per lettera, di un profilo che segui.** Clicca **Cerca** nella barra a sinistra e scrivi
|
||||
**piano**, una lettera ogni secondo circa, il suo nome (almeno 5 lettere), finché compare nei risultati. Poi
|
||||
**clicca il risultato**: si apre il suo profilo.
|
||||
2. **Il profilo.** Attendi, poi scorri la griglia finché si caricano **almeno due** pagine di post in più (3–4
|
||||
schermate).
|
||||
3. **Le sue schede.** Clicca **Reel** e scorri un poco; poi **Taggati** e scorri un poco.
|
||||
4. **Le sue storie**, se ne ha: clicca la foto con l'anello, vai avanti di **due** storie, chiudi con la **X** prima
|
||||
che finiscano.
|
||||
5. **Una raccolta in evidenza** dello stesso profilo: aprila, vai avanti **una volta**, chiudi con la **X**.
|
||||
6. **Un post con più foto o un video**: aprilo dalla griglia e passa alla foto successiva con la freccia.
|
||||
7. **Ricerca di un profilo pubblico che non segui**, come al passo 1, lettera per lettera, e **clicca il
|
||||
risultato**: attendi il caricamento e scorri una schermata.
|
||||
8. **I tuoi seguiti.** Clicca la tua foto nella barra a sinistra, poi **«Seguiti»**, e scorri l'elenco finché si
|
||||
caricano **almeno due** pagine in più. Poi, nella casella **Cerca** dentro l'elenco, scrivi piano tre lettere e
|
||||
chiudi.
|
||||
9. **La home.** Clicca il logo, attendi e scorri piano per una decina di post; apri la barra delle storie solo se lo
|
||||
fai di solito.
|
||||
|
||||
Ci si aspetta: nessuna verifica, nessun avviso.
|
||||
|
||||
### A ter 4. Il file HAR
|
||||
|
||||
Scheda **Rete**: **esporta il HAR** in `<cartella>\instagram.har`. Se Chrome offre due voci, scegli quella **senza**
|
||||
dati sensibili (toglie cookie e autorizzazioni, che non servono); se poi `da-har` dice che le risposte sono «senza
|
||||
corpo», esporta di nuovo con l'altra voce. Chiudi gli strumenti per sviluppatori.
|
||||
|
||||
### A ter 5. Forma delle richieste, conversione, ripulitura e verifica (sulla tua macchina)
|
||||
|
||||
```sh
|
||||
febe-sonda richieste --har <cartella>\instagram.har --a <cartella>\richieste.json
|
||||
febe-sonda da-har --har <cartella>\instagram.har --a <cartella>\grezzi
|
||||
febe-sonda ripulisci --da <cartella>\grezzi --a <cartella>\ripuliti
|
||||
febe-sonda verifica --grezzi <cartella>\grezzi --ripuliti <cartella>\ripuliti
|
||||
```
|
||||
|
||||
Dal repository: `dotnet run --project tools/Febe.Sonda -- richieste …`, e così per gli altri.
|
||||
|
||||
- `richieste` scrive un file **nuovo** (rifiuta un file che esiste già, una cartella e un file dentro un
|
||||
repository). Per ogni richiesta distinta della pagina al sito: metodo, percorso (le parti che non sono parole fisse
|
||||
del sito diventano `{numero}` o `{testo}`), nomi dei parametri e dei campi del corpo con il **tipo** del valore
|
||||
(«numero», «testo», «vuoto»), nomi delle intestazioni, struttura delle variabili GraphQL; quante volte la pagina
|
||||
l'ha fatta, gli stati e i tipi delle risposte. Dei valori restano solo quelli uguali per tutti: l'identificativo
|
||||
dell'applicazione, i nomi e gli identificativi (`doc_id`) delle operazioni, la grandezza delle pagine, vero/falso.
|
||||
I valori delle altre intestazioni sono `(valore tolto)`. Un nome che nel file HAR compare anche come valore (un
|
||||
nome utente usato come chiave, per esempio) diventa `(nome tolto)`. Stampa solo conteggi.
|
||||
- I valori fissi delle variabili (per esempio da quale «superficie» parte una ricerca) restano «testo», perché lo
|
||||
strumento non sa distinguerli da ciò che scrivi tu: se servono, te li chiedo per nome e li guardi tu nel HAR.
|
||||
- **Leggi `richieste.json` prima di inviarlo**: non deve esserci un nome, un cognome, un indirizzo di posta, un
|
||||
testo che hai scritto. Se ne trovi uno, non inviarlo e dimmi dove (il campo, non il valore).
|
||||
- Per `da-har`, `ripulisci` e `verifica` vale quanto scritto in A bis 6.
|
||||
|
||||
### A ter 6. Che cosa mandare
|
||||
|
||||
1. `richieste.json`, dopo averlo letto.
|
||||
2. La cartella **ripulita** (compressa) e il testo della verifica.
|
||||
3. Le note: a che ora hai fatto ogni passo, che cosa è andato diversamente, se la ricerca e l'elenco dei seguiti si
|
||||
sono comportati come descritto.
|
||||
|
||||
Mai: il file HAR, la cartella `grezzi`. Quando richieste e lettori sono stati scritti, **cancella il file HAR e la
|
||||
cartella `grezzi`** (§14.5).
|
||||
|
||||
## A quater. I pezzi che mancano al HAR del 12 novembre
|
||||
|
||||
Il HAR del 12 novembre (un giro veloce) ha dato quasi tutto: profilo, schede, raccolte, storie, ricerca, pagina
|
||||
iniziale (esito in `docs/sonda/richieste-instagram.md`). Mancano due cose, e per quelle basta un giro corto, con la
|
||||
stessa preparazione (A ter 1 e A ter 2) e la stessa procedura alla fine (A ter 4, 5 e 6), in una cartella nuova:
|
||||
|
||||
1. **I tuoi seguiti** (A ter passo 8): clicca la tua foto nella barra a sinistra, poi **«Seguiti»**, e scorri
|
||||
l'elenco finché si caricano **almeno due** pagine in più. Senza questo il giro dei seguiti non si può scrivere.
|
||||
2. **Le pagine successive dei post** (A ter passo 2): apri cliccando un profilo che segui e che abbia molti post,
|
||||
e scorri la griglia finché si caricano **almeno due** pagine in più (3–4 schermate).
|
||||
|
||||
Niente storie questa volta: guardarle le segna come viste.
|
||||
|
||||
**Perché il HAR non si tronchi.** Il primo tentativo (12 novembre, sera) è arrivato troncato due volte: la prima
|
||||
esportazione a 200 000 byte esatti, la seconda a 57 MB, quando Chrome ha smesso di scrivere a metà di una risposta,
|
||||
dopo 141 voci. La parte completa arrivava solo alla pagina iniziale. Quasi tutto il peso sono i corpi di immagini e video che il pannello Rete tiene
|
||||
insieme alle risposte di dati. Per restare leggeri:
|
||||
|
||||
- apri Instagram e aspetta che la pagina iniziale sia caricata, poi **svuota il pannello Rete** (il cerchio barrato
|
||||
in alto a sinistra) e solo allora comincia il giro: così nel file c'è solo il giro;
|
||||
- non aprire post, reel o video e non lasciare che la pagina iniziale li faccia partire: per i seguiti e per la
|
||||
griglia di un profilo bastano le miniature;
|
||||
- esporta appena hai finito, e aspetta che il file sia scritto del tutto prima di rinominarlo.
|
||||
|
||||
Se il file è troncato lo stesso, `febe-sonda` lo dice («Il file HAR è troncato») e legge comunque le voci complete,
|
||||
scartando quella dentro cui il file finisce. Conta che cosa è arrivato con `febe-sonda richieste`: se mancano i seguiti o la seconda
|
||||
pagina dei post, rifai il giro più corto (per esempio i seguiti in un file e lo scorrimento in un altro).
|
||||
|
||||
---
|
||||
|
||||
## B. Prima sessione dal vivo, dopo M3
|
||||
|
||||
Scopo: vedere Febe fare una sessione vera, piccola, con il profilo **Prudente**, e i file arrivare in libreria.
|
||||
@@ -163,15 +397,20 @@ cosa aspettarsi; riferisci per ogni voce «sì/no» e, dove chiesto, la schermat
|
||||
anche `--cdn-di-prova http://127.0.0.1:8482`.
|
||||
2. Avvia Febe **con cartelle di prova** (i dati veri non si toccano):
|
||||
`"%LOCALAPPDATA%\Programs\Febe\Febe.exe" --dati C:\FebeProva\dati --libreria C:\FebeProva\libreria --sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30`
|
||||
3. In Account ▸ Aggiungi account ▸ «Per nome utente»: `marta.prova` e `luca.prova`, «Scarica tutto e tieni aggiornato».
|
||||
3. In Account ▸ Aggiungi account scrivi `marta.prova` nella casella e scegli la riga «Aggiungi @marta.prova per nome
|
||||
utente»; lo stesso con `luca.prova`; «Scarica tutto e tieni aggiornato».
|
||||
4. Su `marta.prova`: «Controlla ora».
|
||||
5. Atteso entro qualche minuto, in **Attività**: una sessione con righe «ricetta.…» senza errori; l'anteprima del
|
||||
browser mostra le pagine del sito di prova (fotogrammi con `Page.captureScreenshot`); in **Libreria** le foto e i video
|
||||
di Marta con le miniature (corpo delle risposte con `Network.getResponseBody`, scorrimento con
|
||||
`Input.dispatchMouseEvent`, scaricamenti con `Network.loadNetworkResource` e `IO.read`).
|
||||
6. Riferisci: numero di file arrivati; eventuali righe gialle o rosse di Attività; nel registro, le righe
|
||||
6. **Scrittura nella casella (ricerca dei profili, #37).** Con la finestra del browser fuori schermo, apri di nuovo
|
||||
Aggiungi account e scrivi `mar` nella casella. Atteso entro qualche secondo, sotto «Da Instagram», i profili del sito
|
||||
di prova con la foto (tasti con `Input.dispatchKeyEvent`). Se la finestra dice che il browser «non riceve i tasti»,
|
||||
WebView2 non accetta i tasti fuori schermo: riferiscilo così com'è.
|
||||
7. Riferisci: numero di file arrivati; l'esito del passo 6; eventuali righe gialle o rosse di Attività; nel registro, le righe
|
||||
`[browser]` con «WebView2» e qualunque «Comando CDP … è fallito».
|
||||
7. Prima prova di S3 senza Instagram: Esci, riapri Febe con lo stesso comando **senza** `--accesso-di-prova`. Atteso:
|
||||
8. Prima prova di S3 senza Instagram: Esci, riapri Febe con lo stesso comando **senza** `--accesso-di-prova`. Atteso:
|
||||
Collegamento dice «Collegato» (il cookie del sito di prova è rimasto nel profilo `C:\FebeProva\dati\browser`).
|
||||
|
||||
### C4. S2 — la pagina lavora fuori vista
|
||||
|
||||
|
Before Width: | Height: | Size: 239 KiB After Width: | Height: | Size: 262 KiB |
|
Before Width: | Height: | Size: 202 KiB After Width: | Height: | Size: 203 KiB |
|
Before Width: | Height: | Size: 189 KiB After Width: | Height: | Size: 170 KiB |
|
Before Width: | Height: | Size: 236 KiB After Width: | Height: | Size: 212 KiB |
|
Before Width: | Height: | Size: 170 KiB After Width: | Height: | Size: 159 KiB |
|
Before Width: | Height: | Size: 160 KiB After Width: | Height: | Size: 147 KiB |
|
Before Width: | Height: | Size: 126 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 147 KiB After Width: | Height: | Size: 136 KiB |
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 64 KiB |
|
Before Width: | Height: | Size: 72 KiB After Width: | Height: | Size: 69 KiB |
@@ -10,7 +10,7 @@ solo per l'interfaccia di Febe (§10.7).
|
||||
| `02-visualizzatore.png` | `/libreria`, clic su un post con più file, seconda foto | `miniature/02-visualizzatore.png` |
|
||||
| `03-account.png` | `/account?tema=chiaro` | `docs/mockup/03-account.png` |
|
||||
| `03-account-telefono.png` | `/account`, 390 × 844 | (nessuno: tabella come elenco) |
|
||||
| `04-aggiungi-account.png` | `/account?dialogo=aggiungi`, tre profili scelti | `miniature/04-aggiungi-account.png` |
|
||||
| `04-aggiungi-account.png` | `/account?dialogo=aggiungi`, «gaia» scritto nella casella, due profili aggiunti, puntatore su una riga (passo `aggiungi.js`; rifatta il 15/11 da Windows) | `miniature/04-aggiungi-account.png` (superato da #37, vedi sotto) |
|
||||
| `05-account-impostazioni.png` | `/account/3/impostazioni` (@studio.lumen.demo) | `miniature/05-account-impostazioni.png` |
|
||||
| `11-libreria-fermo-tema-scuro.png` | `/libreria?scena=fermo&tema=scuro` | striscia rossa di `miniature/11-attivita-fermo-tema-scuro.png` |
|
||||
| `12-account-storie-tema-scuro.png` | `/account/2?tema=scuro&tipo=storie` (@marta.demo) | `miniature/12-account-storie-tema-scuro.png` |
|
||||
@@ -18,8 +18,8 @@ solo per l'interfaccia di Febe (§10.7).
|
||||
| `14-telefono.png` | `/libreria`, 390 × 844 | (il mockup mostra Attività al telefono) |
|
||||
| `account-cronologia.png` | `/account/2/cronologia` | (nessuno) |
|
||||
| `06-attivita.png` | `/attivita?scena=sessione&tema=chiaro` | `miniature/06-attivita.png` |
|
||||
| `06-attivita-tutti-i-tetti.png` | come sopra, «Tutti i tetti» aperto | (nessuno: §7.4) |
|
||||
| `07-limiti-e-comportamento.png` | `/impostazioni/limiti`, 1440 × 1470 | `miniature/07-limiti-e-comportamento.png` |
|
||||
| `06-attivita-tutti-i-tetti.png` | come sopra, «Tutti i tetti» aperto (rifatta il 15/11 da Windows: c'è la riga «Ricerche di profili») | (nessuno: §7.4) |
|
||||
| `07-limiti-e-comportamento.png` | `/impostazioni/limiti`, 1440 × 1470 (rifatta il 15/11 da Windows: riga «Ricerche di profili», 240 all'ora e 1.200 al giorno con «Prudente») | `miniature/07-limiti-e-comportamento.png` |
|
||||
| `07-limiti-su-misura.png` | come sopra, un tetto cambiato: «Su misura» e barra di salvataggio attiva | (nessuno: §7.5) |
|
||||
| `08-impostazioni-generali.png` | `/impostazioni/generali` | `docs/mockup/08-impostazioni-generali.png` |
|
||||
| `09-importa-sorgente.png` | `/importa?passo=1&veste=docker` | (nessuno: passo 1 di §9.1) |
|
||||
@@ -68,6 +68,36 @@ dovute ai dati dimostrativi:
|
||||
- **Telefono, libreria.** `14-telefono.png` mostra la libreria; la pagina Attività del mockup al telefono è in
|
||||
`14-attivita-telefono.png`. I filtri a pastiglia vanno a capo su due righe.
|
||||
|
||||
### Aggiungi account dopo la ricerca unica (#37)
|
||||
|
||||
Il mockup 04 mostra due linguette («Dai profili che segui», «Per nome utente») e l'elenco a spunte dei seguiti. La
|
||||
richiesta di #37 (una sola casella, suggerimenti mentre si scrive, con foto, come 4K Stogram) lo supera: finché non c'è
|
||||
un mockup nuovo (domanda Q9 per Alberto), il riferimento è questa schermata. Confronto fatto il 15/11 a 1440 × 900:
|
||||
|
||||
- **Uguale al mockup.** Misure e posizione del dialogo, titolo con la X, colonna destra («Per i 2 account scelti», i
|
||||
tre punti di partenza, «Quanto indietro nel tempo», la nota azzurra), piede con «Elenco letto il…», «Rileggi
|
||||
l'elenco», «Annulla» e il pulsante che dice quanti account aggiunge. Avatar, etichette ed elenchi usano gli stessi
|
||||
elementi del foglio di stile (mockup 13).
|
||||
- **Voluto da #37.** Niente linguette: sotto il titolo c'è una riga di separazione e poi la casella, più alta (40 px)
|
||||
e larga quanto la colonna. Al posto dell'elenco a spunte c'è «Da aggiungere», coperto nella schermata dall'elenco dei
|
||||
suggerimenti: un riquadro sospeso con l'ombra dei menu, diviso in «Profili che segui e account in Febe» e «Da
|
||||
Instagram per «gaia»», righe da 52 px con foto rotonda da 40 px, nome utente in grassetto, nome completo sotto,
|
||||
etichette «Seguito» (con l'icona della persona con la spunta), «Privato», «Già in Febe» e il pulsante «Aggiungi» /
|
||||
«Aggiunto» (azzurro chiaro con la spunta). La riga scelta con la tastiera ha il fondo azzurro chiaro dei filtri,
|
||||
quella sotto il puntatore il grigio dei menu. L'ultima riga, «Aggiungi @gaia per nome utente», resta in parte sotto
|
||||
il bordo: l'elenco scorre.
|
||||
- **«Seleziona tutti»** non è più accanto alla casella: sta nell'elenco completo dei seguiti, che si apre con
|
||||
«Scegli fra tutti i profili che segui (98)» sopra «Da aggiungere».
|
||||
- **Contenuti dimostrativi.** Le foto sono disegni generati; i risultati «Da Instagram» sono nomi inventati dalla
|
||||
dimostrazione (`gaia_foto`, `gaia.viaggi`, `gaia_official` con il segno di profilo verificato).
|
||||
- **Foto nei suggerimenti locali.** Nella dimostrazione ogni riga di «Profili che segui e account in Febe» ha la foto
|
||||
perché la ricerca dimostrativa restituisce anche quei profili. Con Instagram vero una riga locale ha la foto solo se
|
||||
il profilo è già in Febe con la sua foto o se è comparso fra i risultati di una ricerca recente; altrimenti mostra le
|
||||
iniziali (vedi la guida, «Aggiungi account»). Dopo la revisione del 15/11 cambiano solo attributi ARIA: nessuna
|
||||
differenza visibile, la schermata resta quella.
|
||||
- **Telefono** (390 × 844, non nella tabella di §10.7): una colonna; nelle righe le etichette vanno sotto il nome, i nomi
|
||||
lunghi finiscono con i puntini e il pulsante resta a destra; il piede va su due righe.
|
||||
|
||||
### Seconda parte (Attività, Impostazioni, Collegamento, Importa)
|
||||
|
||||
Rifatte con `bash tools/schermate/tutte.sh 8490` (le righe dopo «Part 2»), su una dimostrazione appena avviata: la
|
||||
@@ -83,11 +113,16 @@ schermata del motore fermo si prende per prima, perché «Riprendi» resta spent
|
||||
collegamento a «Doppioni da decidere», sotto gli elenchi: il mockup non lo prevede (§9.5).
|
||||
- **Attività, fermo.** La striscia rossa ha «Riprendi» solo nell'intestazione della pagina (non doppio). Nel giorno
|
||||
la parte dopo l'arresto è tratteggiata in rosso, come nel mockup; lo storico degli incidenti sta in fondo.
|
||||
- **Attività, «Diagnostica».** Nella riga del titolo c'è un terzo pulsante, «Diagnostica» con l'icona del file con la
|
||||
freccia, che i mockup 06 e 11 non hanno: scarica il rapporto di diagnostica (#39, §7.9). Nella finestra stretta i
|
||||
tre pulsanti stanno sulla riga con le scritte; al telefono restano tre icone accanto al titolo, senza andare a capo.
|
||||
Schermate di Attività (06, 11, 14) rifatte il 13/11 da Windows.
|
||||
- **Limiti e comportamento.** Gli orari sono campi di testo a 24 ore («07:30») invece del selettore d'ora del
|
||||
browser, che in alcune lingue mostra AM/PM. I giorni sono cerchi con l'iniziale. La barra di salvataggio resta
|
||||
sempre visibile: spenta con «Nessuna modifica», si accende alla prima modifica.
|
||||
- **Impostazioni generali.** In più rispetto al mockup: lo spazio libero accanto alle cartelle, la nota «Per ora
|
||||
c'è solo l'italiano» sotto la lingua e la riga «Solo versione Windows» accanto ad «Avvio». In Docker le cartelle
|
||||
- **Impostazioni generali.** In più rispetto al mockup: lo spazio libero accanto alle cartelle, il terzo schema «Schema
|
||||
per le foto del profilo» con la cartella `profilo` nel risultato (#38, schermata rifatta il 13/11 da Windows), la
|
||||
nota «Per ora c'è solo l'italiano» sotto la lingua e la riga «Solo versione Windows» accanto ad «Avvio». In Docker le cartelle
|
||||
non si cambiano dall'interfaccia (si cambiano i volumi del contenitore) e la sezione Avvio non c'è.
|
||||
- **Importa, revisione.** Percorso della cartella temporanea della dimostrazione; le immagini dei doppioni sono
|
||||
disegni generati. Il riquadro dei doppioni passa al caso seguente dopo ogni scelta: la schermata torna al primo
|
||||
|
||||
@@ -1,24 +1,52 @@
|
||||
# Esito delle ipotesi di M0 (specifica §6.6)
|
||||
|
||||
Stato al 13 ottobre 2026. Finché una voce non ha un esito con le prove, **non ci si costruisce sopra**: per questo i
|
||||
file di Instagram sono ancora scheletri e le ricette si rifiutano di girare su Instagram (vedi in fondo).
|
||||
Stato al 25 ottobre 2026. Finché una voce non ha un esito con le prove, **non ci si costruisce sopra**.
|
||||
|
||||
**25 ottobre 2026: i primi campioni reali.** Alberto ha mandato un file HAR esportato dal suo browser il 21 ottobre
|
||||
(DevTools, filtro Fetch/XHR: niente documenti, immagini né script). Le risposte utili sono state convertite nel formato
|
||||
della sonda fuori dal repository, ripulite e verificate («Verifica superata»): sono in `tests/Febe.Tests/campioni/instagram`
|
||||
(vedi il suo `LEGGIMI.md`). Con quelle `lettori.instagram.json` è compilato e «confermato», e di
|
||||
`bersagli.instagram.json` sono compilate le pagine con una prova reale (vedi in fondo). Le colonne «Stato» qui sotto
|
||||
dicono che cosa il HAR ha provato e che cosa no.
|
||||
|
||||
**12 novembre 2026: il secondo HAR** (senza filtro, documenti compresi; #35). Risultati in
|
||||
`docs/sonda/richieste-instagram.md`, otto campioni nuovi in `tests/Febe.Tests/campioni/instagram` (da `000009` a
|
||||
`000016`). Che cosa cambia per le ipotesi, senza riscrivere la tabella qui sotto, che resta quella della raccolta coi
|
||||
bersagli:
|
||||
|
||||
- **H1**: la prima pagina del feed è incorporata nel documento della pagina iniziale
|
||||
(`xdt_api__v1__feed__timeline__connection`), le successive con `PolarisFeedRootPaginationCachedQuery_subscribe`.
|
||||
- **H2: provata.** Il vassoio delle storie è incorporato nella pagina iniziale (`xdt_api__v1__feed__reels_tray`): per
|
||||
ogni profilo `latest_reel_media`, `expiring_at` e se è già stato visto.
|
||||
- **H3: provata, salvo le pagine successive.** Scheda (`PolarisProfilePageContentQuery`, con `media_count`), post
|
||||
(`PolarisProfilePostsQuery`, reel e serie compresi, con `end_cursor`), elenco delle raccolte con la copertina. La
|
||||
richiesta della seconda pagina non è nel HAR.
|
||||
- **H4**: le storie attive di un profilo arrivano con `PolarisStoriesV3ReelPageStandaloneQuery`, con scadenza e durata
|
||||
e senza dimensioni dei video; guardarle nel visualizzatore manda `PolarisStoriesV3SeenMutation`.
|
||||
- **H6: risposta diversa dall'ipotesi.** Le schede Reel e Con tag danno anteprime senza data né video, non contenuti
|
||||
completi; i reel del profilo sono comunque fra i post.
|
||||
- **H10: un passo avanti.** Nel blocco incorporato della pagina iniziale `xdt_viewer.user` ha identificativo, nome
|
||||
utente e foto dell'account collegato (`000015-vassoio-storie`), e il lettore lo legge come `Viewer`; nelle
|
||||
risposte alle richieste della pagina ha il solo identificativo. Resta da provare con la raccolta vera (#36).
|
||||
- **La JSON incorporata nel documento** è confermata: 69 blocchi nella pagina iniziale.
|
||||
- **Manca l'elenco dei seguiti**: nessuna richiesta nel HAR (`docs/prove-dal-vivo.md`, parte A quater).
|
||||
|
||||
Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvfb e pagine locali, mai Instagram;
|
||||
**da provare dal vivo** = serve Alberto, con l'account di prova e la sonda (`docs/prove-dal-vivo.md`, parte A).
|
||||
|
||||
| | Ipotesi | Stato | Come si prova (procedura esatta) | Che cosa ne dipende |
|
||||
|---|---|---|---|---|
|
||||
| H1 | La home consegna i post recenti dei seguiti con i dati completi dei file | **Da provare dal vivo** | Sonda, passo A3.1: aprire la home, attendere il caricamento, scorrere piano per una decina di post. Nei campioni ripuliti cercare risposte con elenchi di contenuti (identificativo, data, versioni delle immagini con dimensioni, figli delle serie) | Giro dei seguiti; `pages.home` di `bersagli.instagram.json`; concetti `content.*` e `version.*` di `lettori.instagram.json` |
|
||||
| H2 | La barra delle storie dice quali seguiti hanno storie attive e a quando risale l'ultima | **Da provare dal vivo** | Passo A3.1: con la home caricata, la sonda registra le risposte della barra; nei ripuliti cercare elenchi di profili con un campo data dell'ultima storia | `profile.latestStoryAt`; bersaglio `home-story` |
|
||||
| H3 | Il profilo consegna identificativo, pubblico/privato, se è seguito, prima pagina dei post con serie e video, elenco delle raccolte; lo scorrimento carica le pagine successive | **Da provare dal vivo** | Passi A3.2 e A3.3: profilo pubblico non seguito e profilo privato seguito, scorrendo 3–4 schermate. Nei ripuliti: un nodo profilo con i campi di stato, pagine di contenuti successive con un punto di ripresa | Controllo del profilo, Storico; `profile.*`, `highlight.*`, `page.*`; `pages.profile`, `pages.profileFrom` (facoltativa: se il sito non riparte da un cursore, lo storico riprende scorrendo) |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | **Da provare dal vivo** | Passo A3.4: aprire le storie di un seguito dall'anello del profilo, guardarne 2–3, chiudere con la X **prima** che passi all'account successivo. Nei ripuliti: un elenco di contenuti con data di scadenza; in `navigazioni.jsonl` la forma dell'indirizzo del visualizzatore | Storie di un account; `content.expiresAt`; `pages.storyViewer`; bersagli `profile-story-ring`, `viewer-next`, `viewer-close` |
|
||||
| H5 | Per i video arriva almeno un indirizzo unico con audio e video insieme | **Da provare dal vivo** | Passi A3.2 e A3.4 su un post video e su una storia video. Nei ripuliti: le versioni del video e un campo che dica se hanno l'audio | `version.hasAudio`; scelta della versione di §6.5 punto 1 (se nessuna versione ha audio e video insieme, va riletta §4.9: l'unione delle tracce è fuori dalla versione 1) |
|
||||
| H6 | Le schede «taggati» e «reel» si comportano come la griglia | **Da provare dal vivo** | Passo A3.6: aprire le due schede di un profilo e scorrere | Taggati, Reel; bersagli `profile-tab-tagged`, `profile-tab-reels`; `pages.taggedFrom`, `pages.reelsFrom` |
|
||||
| H1 | La home consegna i post recenti dei seguiti con i dati completi dei file | **Da provare dal vivo**. Il HAR non contiene la home: nessuna risposta del feed | Sonda, passo A3.1: aprire la home, attendere il caricamento, scorrere piano per una decina di post. Nei campioni ripuliti cercare risposte con elenchi di contenuti (identificativo, data, versioni delle immagini con dimensioni, figli delle serie) | Giro dei seguiti; `pages.home` di `bersagli.instagram.json`; concetti `content.*` e `version.*` di `lettori.instagram.json` |
|
||||
| H2 | La barra delle storie dice quali seguiti hanno storie attive e a quando risale l'ultima | **Da provare dal vivo**. Il HAR non contiene la barra delle storie. La data dell'ultima storia di un profilo esiste come `latest_reel_media` (vista nell'autore di un post e nel proprietario di una raccolta) | Passo A3.1: con la home caricata, la sonda registra le risposte della barra; nei ripuliti cercare elenchi di profili con un campo data dell'ultima storia | `profile.latestStoryAt`; bersaglio `home-story` |
|
||||
| H3 | Il profilo consegna identificativo, pubblico/privato, se è seguito, prima pagina dei post con serie e video, elenco delle raccolte; lo scorrimento carica le pagine successive | **In parte**. Forma dell'indirizzo confermata (`/{username}/{?tab}/…`, dalle definizioni delle pagine che Instagram stesso manda); forma del nodo profilo confermata (`pk`, `username`, `is_private`, `friendship_status.following`, `hd_profile_pic_url_info`, `latest_reel_media`). Le risposte della pagina profilo (intestazione, griglia, raccolte, pagine successive) **non** sono nel HAR: da provare dal vivo | Passi A3.2 e A3.3: profilo pubblico non seguito e profilo privato seguito, scorrendo 3–4 schermate. Nei ripuliti: un nodo profilo con i campi di stato, pagine di contenuti successive con un punto di ripresa | Controllo del profilo, Storico; `profile.*`, `highlight.*`, `page.*`; `pages.profile`, `pages.profileFrom` (facoltativa: se il sito non riparte da un cursore, lo storico riprende scorrendo) |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | **In parte**. Il visualizzatore delle raccolte riceve l'elenco completo dei contenuti con indirizzi, `taken_at` ed `expiring_at` (`xdt_api__v1__feed__reels_media__connection`, `text/javascript`); la forma dell'indirizzo delle storie è `/stories/{username}/{?initial_media_id}/`. La risposta delle storie di un account (non di una raccolta) e se l'indirizzo segue ogni storia: da provare dal vivo | Passo A3.4: aprire le storie di un seguito dall'anello del profilo, guardarne 2–3, chiudere con la X **prima** che passi all'account successivo. Nei ripuliti: un elenco di contenuti con data di scadenza; in `navigazioni.jsonl` la forma dell'indirizzo del visualizzatore | Storie di un account; `content.expiresAt`; `pages.storyViewer`; bersagli `profile-story-ring`, `viewer-next`, `viewer-close` |
|
||||
| H5 | Per i video arriva almeno un indirizzo unico con audio e video insieme | **In parte**. `video_versions` dà tre versioni `.mp4` (tipi 101, 102, 103: nei post stesse dimensioni e banda); se c'è l'audio lo dice il contenuto (`has_audio`), non la versione. Che il file abbia davvero audio e video insieme si conferma scaricando (prima sessione dal vivo) | Passi A3.2 e A3.4 su un post video e su una storia video. Nei ripuliti: le versioni del video e un campo che dica se hanno l'audio | `version.hasAudio`; scelta della versione di §6.5 punto 1 (se nessuna versione ha audio e video insieme, va riletta §4.9: l'unione delle tracce è fuori dalla versione 1) |
|
||||
| H6 | Le schede «taggati» e «reel» si comportano come la griglia | **Da provare dal vivo**. Nessuna risposta delle schede nel HAR | Passo A3.6: aprire le due schede di un profilo e scorrere | Taggati, Reel; bersagli `profile-tab-tagged`, `profile-tab-reels`; `pages.taggedFrom`, `pages.reelsFrom` |
|
||||
| H7 | I file del CDN si scaricano con `Network.loadNetworkResource`; se no, con la via di riserva di §6.5 | **Da provare dal vivo**. In locale: scaricati integri (24 MB in 2,2 s; foto e video del sito di prova byte per byte) | Dopo la sonda, con la prima sessione dal vivo (parte B): file arrivati in Libreria, stato «scaricato». **Osservazione locale**: dalla pagina di riposo `about:blank` Chromium rifiuta gli indirizzi locali del CDN di prova (`net::ERR_BLOCKED_BY_PRIVATE_NETWORK_ACCESS_CHECKS`); dalle pagine del sito funziona. Con il CDN pubblico va misurato se lo scaricamento regge anche dalla pagina di riposo | `BrowserFileFetcher`; la via `HttpClient` di §6.5 punto 3 **non è scritta**: resta dietro `IFileFetcher` finché H7 non dice che serve. Codici HTTP di «indirizzo scaduto» (in locale 403 e 410) |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | **Da provare dal vivo** (non provocare segnali di proposito) | Se durante la sonda compare una verifica o un avviso, annotare l'ora e mandare la riga corrispondente di `navigazioni.jsonl` ripulita. Sul sito di prova i casi 429, `/verifica`, sessione terminata e pagine vuote fermano le ricette (prove `StopAndDownloadIntegrationTests`) | `segnali.json` (le regole su Instagram restano ipotesi segnate H8) |
|
||||
| H9 | Un contenuto di una raccolta ha lo stesso identificativo che aveva come storia | **Da provare dal vivo** | Passo A3.5: aprire una raccolta che contenga una storia ancora attiva (o pubblicata e poi messa in evidenza dall'account di prova). Confrontare gli identificativi nei ripuliti: la ripulitura dà a valori uguali lo stesso valore finto | Raccolta in evidenza (collegamento senza riscaricare); sul sito di prova funziona così per costruzione |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati, senza leggere i cookie | **Da provare dal vivo** | Passo A3.1: nei ripuliti della home cercare un nodo che descriva l'account collegato | `viewer` di `lettori.instagram.json`; il profilo «Tu» |
|
||||
| H11 | I bersagli si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | **Da provare dal vivo**. Scheletro pronto: `bersagli.instagram.json` | Durante tutta la sonda: passare col puntatore e cliccare i comandi elencati al passo A3; la sonda registra ruolo, nome accessibile e forma del collegamento in `interazioni.jsonl`. Alberto manda le righe dei soli comandi dell'interfaccia (passo A6) | Tutte le ricette |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | **Da provare dal vivo** (non provocare segnali di proposito). Nessun segnale nel HAR | Se durante la sonda compare una verifica o un avviso, annotare l'ora e mandare la riga corrispondente di `navigazioni.jsonl` ripulita. Sul sito di prova i casi 429, `/verifica`, sessione terminata e pagine vuote fermano le ricette (prove `StopAndDownloadIntegrationTests`) | `segnali.json` (le regole su Instagram restano ipotesi segnate H8) |
|
||||
| H9 | Un contenuto di una raccolta ha lo stesso identificativo che aveva come storia | **Indizio**. I contenuti di una raccolta hanno `pk` ed `expiring_at` come le storie; che il `pk` sia lo stesso della storia originale va visto con una storia ancora attiva | Passo A3.5: aprire una raccolta che contenga una storia ancora attiva (o pubblicata e poi messa in evidenza dall'account di prova). Confrontare gli identificativi nei ripuliti: la ripulitura dà a valori uguali lo stesso valore finto | Raccolta in evidenza (collegamento senza riscaricare); sul sito di prova funziona così per costruzione |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati, senza leggere i cookie | **Non basta**. `xdt_viewer.user` descrive l'account collegato con il solo identificativo, senza nome: Febe lo tiene (`ReadResult.ViewerId`) e riconosce «Tu» quando il suo profilo compare in un'altra risposta. Da provare dal vivo | Passo A3.1: nei ripuliti della home cercare un nodo che descriva l'account collegato | `viewer` di `lettori.instagram.json`; il profilo «Tu» |
|
||||
| H11 | I bersagli si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | **Da provare dal vivo**. Il HAR non ha documenti né attributi degli elementi: i bersagli restano vuoti. Procedura semplificata in `docs/prove-dal-vivo.md`, parte A bis | Durante tutta la sonda: passare col puntatore e cliccare i comandi elencati al passo A3; la sonda registra ruolo, nome accessibile e forma del collegamento in `interazioni.jsonl`. Alberto manda le righe dei soli comandi dell'interfaccia (passo A6) | Tutte le ricette |
|
||||
| S1 | In WebView2 funzionano corpo delle risposte, gesti e fotogrammi | **Da provare** su Windows. Pronto: `WebView2Browser` (Febe.Desktop) con l'adattatore `WebView2CdpSession` (stesso elenco ammesso del client Chromium, provato su Linux con un finto WebView2) | `docs/prove-dal-vivo.md`, parte C3: Febe per Windows con `--sito-di-prova`, una sessione intera (`Network.getResponseBody`, `Input.dispatchMouseEvent`, `Network.loadNetworkResource`/`IO.read`) e l'anteprima di Attività (`Page.captureScreenshot`). `Page.startScreencast` su Windows non serve (la vista remota è solo di Docker) | `WebView2Browser`, `WebView2CdpSession` |
|
||||
| S2 | Su Windows la pagina carica e scorre con la finestra fuori vista | **Da provare** su Windows. Pronti i tre modi di §6.6, scelti con `Febe.exe --browser finestra\|composizione\|edge` (predefinito `finestra`: fuori dallo schermo, `IsVisible` sempre vero, `--disable-features=CalculateNativeWinOcclusion --disable-backgrounding-occluded-windows`) | `docs/prove-dal-vivo.md`, parte C4: sessione sul sito di prova con il browser fuori vista, con la finestra di Febe ridotta a icona e con lo schermo bloccato; se non regge, `composizione` e poi `edge` | `WebView2Browser`, `CompositionHost`, `EdgeBrowser` |
|
||||
| S3 | L'accesso a mano sopravvive al riavvio | **Provato in locale per Docker/Chromium** (cookie scritto con arresto SIGINT, 3 esecuzioni su 3; vedi `esito-locale.md`); **da provare** su Windows (all'arresto Febe chiude WebView2 e ne aspetta l'uscita prima di finire) e nel contenitore vero | Docker: accedere, riavviare il contenitore, controllare il collegamento. Windows: `docs/prove-dal-vivo.md`, parti C3.7 (sito di prova) e C5 (Instagram, account di prova: Esci e riapri, riavvio di Windows, avvio con il computer) | Profilo del browser nella cartella dei dati |
|
||||
@@ -28,14 +56,19 @@ Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvf
|
||||
|
||||
## Che cosa è pronto per ricevere gli esiti
|
||||
|
||||
- `src/Febe.Core/Config/bersagli.instagram.json` (copiato in `config/`): **scheletro**. Elenca le pagine e i bersagli
|
||||
di cui le ricette hanno bisogno, tutti vuoti e segnati con l'ipotesi da cui dipendono. Finché una voce necessaria è
|
||||
vuota, la ricetta risponde «non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano …)»
|
||||
senza aprire pagine e senza chiedere permessi.
|
||||
- `src/Febe.Core/Config/lettori.instagram.json`: **ipotesi**. Contiene solo gli indizi di §6.4 (`pk`, `code`,
|
||||
`taken_at`, `image_versions2.candidates`, `video_versions`, `carousel_media`); ogni altro concetto è vuoto. Con lo
|
||||
stato «ipotesi» le ricette non girano. Va riempito sui campioni ripuliti e portato a «confermato».
|
||||
- `src/Febe.Core/Config/lettori.instagram.json`: **confermato** il 25 ottobre sui campioni reali ripuliti; ogni sua
|
||||
chiave compare in quei campioni (lo controlla `InstagramReaderTests`). Le risposte che non parlano di contenuti
|
||||
(promozioni, «storia vista») si ignorano (`relevance`). Senza riscontro restano vuoti `pinned` e
|
||||
`version.hasAudio`. Il 12 novembre, con il secondo HAR: `postCount` = `media_count`, le serie con i loro figli
|
||||
(`carousel_media`, anche video) e la copertina delle raccolte (`highlight.cover`).
|
||||
- `src/Febe.Core/Config/bersagli.instagram.json`: compilate le **pagine** con una prova reale (home, profilo, post,
|
||||
visualizzatore delle storie e delle raccolte, dalle definizioni delle pagine e dai Referer del HAR); i **bersagli**
|
||||
sono vuoti (H11). Le ricette che non ne hanno bisogno girano; quelle che li usano (storie, raccolte, schede Taggati e
|
||||
Reel) rispondono «la mappa dei bersagli non è ancora compilata (mancano …)» senza aprire pagine e senza chiedere
|
||||
permessi. Questi file si possono sostituire con una copia nella cartella Dati, che vince su quella incorporata.
|
||||
- La cattura legge anche le risposte `text/javascript` chieste dalla pagina (così Instagram manda i dati GraphQL) e il
|
||||
JSON incorporato nel documento della pagina (da confermare dal vivo: il HAR non aveva documenti).
|
||||
- `segnali.json`: regole di partenza, ancora ipotesi H8.
|
||||
- Sonda: `febe-sonda registra`, `ripulisci`, `verifica` (procedura in `docs/prove-dal-vivo.md`).
|
||||
- Sonda: `febe-sonda registra`, `da-har` (da un HAR del browser), `ripulisci`, `verifica` (procedura in `docs/prove-dal-vivo.md`).
|
||||
- Il sito di prova fa girare tutte le ricette con un browser vero (`tests/Febe.Tests/Collection/`): è la prova che la
|
||||
raccolta funziona **quando** mappa e vocabolario saranno compilati, non che Instagram si comporti allo stesso modo.
|
||||
@@ -0,0 +1,118 @@
|
||||
# Le richieste della pagina di Instagram (HAR del 12 novembre 2026)
|
||||
|
||||
Che cosa chiede l'applicazione web di Instagram al sito, ricavato dal secondo HAR di Alberto (#35) per scrivere
|
||||
`richieste.instagram.json` e la raccolta della strada B (#36, decisione #34). Qui ci sono solo **forme**: nomi di
|
||||
operazioni, percorsi, nomi delle variabili e delle chiavi delle risposte. Nessun valore del HAR, nessun `doc_id`.
|
||||
|
||||
## Da dove viene
|
||||
|
||||
- HAR esportato da Alberto il 12 novembre 2026, **senza filtro**, seguendo `docs/prove-dal-vivo.md` parte A ter:
|
||||
pagina iniziale, ricerca di un profilo, il profilo aperto cliccando, le schede Reel, Con tag e Ripubblicati, le
|
||||
raccolte in evidenza, una storia, un post.
|
||||
- Fuori dal repository (`C:\Users\alber\febe-har\2026-11-12`), sulla macchina di Alberto:
|
||||
- `febe-sonda richieste` → `richieste.json`: 45 forme di richieste della pagina al sito;
|
||||
- `febe-sonda da-har` → 142 campioni grezzi (69 blocchi incorporati nell'unico documento, la pagina iniziale, più 73
|
||||
risposte di dati);
|
||||
- `febe-sonda ripulisci` e `febe-sonda verifica` → «Verifica superata» su 142 file (44 102 frammenti controllati).
|
||||
- Nel repository: otto di quelle risposte, accorciate sulla copia ripulita, in `tests/Febe.Tests/campioni/instagram`
|
||||
(file da `000009` a `000016`, vedi il suo `LEGGIMI.md`).
|
||||
|
||||
## Che cosa serve a Febe e da dove arriva
|
||||
|
||||
Le operazioni GraphQL sono `POST` con corpo `application/x-www-form-urlencoded`, su due indirizzi:
|
||||
|
||||
- `/api/graphql`: scheda, post, Reel, Con tag ed elenco delle raccolte del profilo, ricerca, storie di un profilo;
|
||||
- `/graphql/query`: pagina iniziale e contenuti delle raccolte in evidenza (con le intestazioni `x-root-field-name`
|
||||
e `x-bloks-version-id`), e la scheda Ripubblicati (senza quelle intestazioni).
|
||||
|
||||
La pagina manda anche `PolarisStoriesV3AdsPoolQuery` (le pubblicità fra le storie) a un terzo indirizzo: a Febe non
|
||||
serve. Le risposte arrivano come `text/javascript`, tranne le pagine successive della pagina iniziale
|
||||
(`PolarisFeedRootPaginationCachedQuery_subscribe`), che arrivano come `application/json`; la cattura le legge tutte e
|
||||
due (`DataResponses`).
|
||||
|
||||
| Che cosa serve | Operazione | Variabili (`variables`) | Radice della risposta | Pagina successiva | Campione |
|
||||
|---|---|---|---|---|---|
|
||||
| Intestazione del profilo: nome, foto grande, privato, seguito, numero dei post | `PolarisProfilePageContentQuery` | `id` (numero), `enable_integrity_filters` | `data.user` | — | `000009-scheda-profilo` |
|
||||
| Post del profilo, reel e serie compresi | `PolarisProfilePostsQuery` | `username` (testo), `data.count` = 12 e quattro `include_*`/`latest_*` | `data.xdt_api__v1__feed__user_timeline_graphql_connection` | `page_info.end_cursor` e `has_next_page`; la richiesta della pagina 2 **non è nel HAR** | `000010-post-del-profilo`, `000016-serie-con-video` |
|
||||
| Scheda Reel | `PolarisProfileReelsTabContentQuery` | `user_id`, `data.target_user_id`, `data.page_size` = 12, `data.include_feed_video` | `data.fetch__XDTUserDict.clips_connection` | `page_info` | `000011-reel-del-profilo` (anteprime) |
|
||||
| Scheda Con tag | `PolarisProfileTaggedTabContentQuery` | `user_id`, `count` = 12 | `data.xdt_api__v1__usertags__user_id__feed_connection` | `page_info` (il cursore è un numero) | `000012-con-tag` (anteprime) |
|
||||
| Scheda Ripubblicati | `PolarisProfileRepostsTabContentQuery` (su `/graphql/query`) | `user_id` | `data.fetch__XDTUserDict.user_reposts_timeline` | `repost_more_available`, `repost_next_max_id` | non copiato |
|
||||
| Elenco delle raccolte in evidenza | `PolarisProfileStoryHighlightsTrayContentQuery` | `user_id` | `data.highlights` (`edges[].node`: `id`, `title`, `cover_media`, `user`) | `page_info` | `000013-raccolte-del-profilo` |
|
||||
| Contenuti delle raccolte | `PolarisStoriesV3HighlightsPageQuery`, poi `…PaginationQuery` | `reel_ids` (elenco di `highlight:<numero>`), `initial_reel_id`, `first`, `last`; la seconda anche `after`, `before`, `is_highlight` | `xdt_api__v1__feed__reels_media__connection` | `after` | `000006`, `000007` (primo HAR) |
|
||||
| Storie attive di un profilo | `PolarisStoriesV3ReelPageStandaloneQuery` | `reel_ids_arr` (elenco di identificativi di profilo) | `data.xdt_api__v1__feed__reels_media.reels_media[]` | — | `000014-storie-di-un-profilo` |
|
||||
| Chi ha storie attive | nessuna richiesta: blocco incorporato nella pagina iniziale | — | `xdt_api__v1__feed__reels_tray.tray[]` (`user`, `latest_reel_media`, `expiring_at`, `seen`) | — | `000015-vassoio-storie` |
|
||||
| Ricerca dei profili (#37) | `PolarisSearchBoxRefetchableQuery` | `data.query`, `data.context`, `data.search_surface`, `data.search_session_id`, `data.rank_token` (vuoto alla prima), `data.include_reel`, `hasQuery` | `data.xdt_api__v1__fbsearch__topsearch_connection.users[]` (`position`, `user` con `pk`, `username`, `full_name`, `profile_pic_url`, `hd_profile_pic_url_info.url`) | — | `000002-ricerca-profili` (primo HAR) |
|
||||
| Un post intero | `GET /api/v1/media/{numero}/info/` | nessun parametro | `items[]` | — | `000005-post-video` (primo HAR) |
|
||||
| Pagina iniziale | `PolarisFeedRootPaginationCachedQuery_subscribe`; la prima pagina è incorporata nel documento | `after`, `first` = 12, `data.device_id`, `variant` e altro | `xdt_api__v1__feed__timeline__connection` | `after` | non copiato |
|
||||
|
||||
Che cosa dicono i campioni (le prove sono in `InstagramReaderTests`):
|
||||
|
||||
- **I post del profilo bastano per il profilo**: la griglia comprende i reel (`product_type` `clips`) con
|
||||
`video_versions` e le serie (`media_type` 8) con i figli in `carousel_media`, anche video (`serie-con-video`: 20
|
||||
figli, il tredicesimo un video con la sua copertina). Le schede Reel e Con tag invece
|
||||
danno **anteprime** senza `taken_at` né `video_versions`: per un contenuto di quelle schede serve
|
||||
`/api/v1/media/{numero}/info/`.
|
||||
- **`media_count`** (numero dei post) c'è solo nella scheda del profilo; ora è `profile.postCount` del vocabolario.
|
||||
- **Copertina delle raccolte**: `cover_media.cropped_image_version.url` (jpg o webp); ora è `highlight.cover`.
|
||||
- **Le storie di un profilo si chiedono senza aprire il visualizzatore**: `PolarisStoriesV3ReelPageStandaloneQuery`
|
||||
risponde con le storie, la scadenza e la durata. Le versioni video delle storie non hanno dimensioni. Questo
|
||||
riguarda la domanda 11 di §16 (le storie con la strada B), che resta di Alberto.
|
||||
- **Chi ha storie** si legge dal vassoio incorporato nella pagina iniziale, senza richieste: 120 voci nel HAR.
|
||||
- **L'account collegato** (H10): nello stesso blocco della pagina iniziale `xdt_viewer.user` ha identificativo, nome
|
||||
utente e foto; nelle risposte alle richieste della pagina ha il solo identificativo. Il lettore lo legge già come
|
||||
`Viewer`.
|
||||
- **`ProfilePostsQuery` vuole il nome utente, le altre operazioni del profilo l'identificativo numerico**: Febe deve
|
||||
tenere tutti e due (la ricerca e la scheda del profilo li danno insieme).
|
||||
|
||||
## Richieste di scrittura che Febe non deve mai mandare
|
||||
|
||||
Nel HAR la pagina le ha mandate da sola, durante l'uso normale. Con la strada B Febe chiede solo operazioni di lettura
|
||||
dell'elenco chiuso, quindi queste non partono mai da Febe; ma vanno escluse per nome anche dalla configurazione
|
||||
(`richieste.instagram.json` deve rifiutare ogni nome che finisce per `Mutation`):
|
||||
|
||||
| Operazione | Quando la manda la pagina | Che cosa fa |
|
||||
|---|---|---|
|
||||
| `PolarisStoriesV3SeenMutation` | a ogni storia guardata nel visualizzatore (6 volte nel HAR) | segna la storia come vista: chi l'ha pubblicata vede Alberto fra gli spettatori |
|
||||
| `usePolarisRegisterInRecentSearchesMutation` | cliccando un risultato della ricerca | aggiunge il profilo alle ricerche recenti di Alberto |
|
||||
| `usePolarisLikeMediaXIGLikeMutation` | un «mi piace» dato durante la sessione | mette «mi piace» a un post |
|
||||
|
||||
Corollario: la raccolta di oggi, che guarda le storie **nel visualizzatore**, le segna come viste. Chiederle con
|
||||
`ReelPageStandaloneQuery` no, perché il segno «vista» è una richiesta a parte.
|
||||
|
||||
## Che cosa porta ogni richiesta, oltre alle variabili
|
||||
|
||||
Uguali per tutte le operazioni GraphQL del HAR, da prendere **dalla pagina al momento della richiesta** (mai salvati,
|
||||
mai nei registri, regola 10):
|
||||
|
||||
- campi del corpo: `doc_id` (17 cifre, uno per operazione; cambia quando Instagram pubblica una versione nuova
|
||||
dell'applicazione web), `fb_api_req_friendly_name` (il nome dell'operazione), `fb_api_caller_class` =
|
||||
`RelayModern`, `server_timestamps`, `variables`, e i campi di sessione `fb_dtsg`, `av`, `__user`, `__a`,
|
||||
`__comet_req`, `__req`, `__rev`, `__s`, `__hs`, `__hsi`, `__hsdp`, `__hblp`, `__sjsp`, `__csr`, `__dyn`,
|
||||
`__spin_r`, `__spin_b`, `__spin_t`, `__ccg`, `__crn`, `__d`, `dpr`, più un campo il cui nome `febe-sonda richieste`
|
||||
ha tolto perché nel HAR compare anche come valore;
|
||||
- intestazioni: `x-csrftoken`, `x-fb-lsd`, `x-ig-app-id`, `x-asbd-id`, `x-fb-friendly-name`, `x-fb-entry-nonce`,
|
||||
`x-ig-max-touch-points` e, su `/graphql/query`, `x-root-field-name` e `x-bloks-version-id`. Le altre
|
||||
(`user-agent`, `sec-ch-ua*`, `referer`, i cookie) le mette il browser da solo e restano come sono (regola 4).
|
||||
|
||||
Il punto aperto per #36 è **da dove prendere `doc_id` e i campi di sessione**. Inventarli è vietato (regola 9), e
|
||||
copiarli dal HAR non funziona perché cambiano. §6.1 vuole che i gettoni restino nella pagina e che allo script torni
|
||||
solo il corpo della risposta. Le vie da valutare:
|
||||
|
||||
1. **solo dentro la pagina**: lo script di `Runtime.evaluate` (la riga di §6.1 della strada B) prende `doc_id` e i
|
||||
campi di sessione dal codice della pagina e manda la richiesta; dipende dai nomi interni dell'applicazione web;
|
||||
2. **`doc_id` dalle richieste della pagina, il resto dentro la pagina**: `doc_id` e il nome dell'operazione sono
|
||||
uguali per tutti e non segreti, e si possono ricavare dall'ultima richiesta della stessa operazione che la pagina
|
||||
ha mandato da sé; i campi di sessione restano allo script nella pagina. Serve però che il client CDP legga i corpi
|
||||
delle richieste, cosa che oggi non fa (`ResponseTap` ascolta solo le risposte): `Network.requestWillBeSent` con
|
||||
`postData`, ed eventualmente `Network.getRequestPostData`, che non è nell'elenco di §6.1. Va deciso con Alberto;
|
||||
3. leggere dalle richieste della pagina anche i campi di sessione e le intestazioni (`fb_dtsg`, `x-csrftoken`,
|
||||
`x-fb-lsd`) è escluso: i gettoni uscirebbero dalla pagina, contro §6.1.
|
||||
|
||||
## Che cosa manca e serve un altro HAR
|
||||
|
||||
- **L'elenco dei seguiti**: nel HAR non c'è nessuna richiesta dell'elenco (né `friendships` né un'operazione
|
||||
GraphQL). Senza, il giro dei seguiti non si può scrivere.
|
||||
- **La seconda pagina dei post di un profilo** (`PolarisProfilePostsQuery` con `after`, o un'altra operazione): nel
|
||||
HAR c'è solo la prima.
|
||||
|
||||
La procedura per raccoglierli è in `docs/prove-dal-vivo.md`, parte A quater.
|
||||
@@ -1,10 +1,275 @@
|
||||
# Stato
|
||||
|
||||
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
|
||||
Aggiornato il 20 ottobre 2026, versione 0.1.1 (anteprima).
|
||||
Aggiornato il 16 novembre 2026, versione 0.1.2 in `main` (il tag `v0.1.2` non è stato creato). **Le attività stanno
|
||||
su Gitea**: issue, etichette e traguardi di https://gitea.encke-hake.ts.net/Alby96/Febe. Questo file resta il resoconto
|
||||
fra le sessioni; ciò che è da fare si legge nelle issue aperte.
|
||||
|
||||
## In breve
|
||||
|
||||
**16 novembre 2026: richieste dirette con la sessione copiata dal browser** (#36, tappe S0 e S1; #52).
|
||||
|
||||
- Il HAR nuovo di Alberto (home, due ricerche, due profili) è stato letto solo in forma aggregata, senza stampare
|
||||
valori: 487 voci complete, troncato a 55,5 MB, **nessun corpo delle risposte del sito** (va rifatto più corto, #35).
|
||||
Utile lo stesso: i `doc_id` sono uguali a quelli del 12 novembre per 17 operazioni (H14), e stanno tutti nei moduli
|
||||
JavaScript pubblici della pagina (`<Operazione>_instagramRelayOperation`, 229 moduli, 67 di scrittura); i gettoni
|
||||
(`DTSGInitialData`, `LSD`, `CurrentUserInitialData`) si leggono dai moduli; l'elenco dei seguiti ha le sue
|
||||
operazioni (`usePolarisGetFollowListQuery`). Confronto dei `doc_id` nel commento su #36.
|
||||
- **Decisioni di Alberto** (7 righe in `docs/decisioni.md`, specifica §1, §2, §3, §6.0 nuova, §6.1, §6.3, §6.5, §6.6
|
||||
H12–H17, §7.4, §7.6, §13.2, §16 domanda 11, regole 3, 4, 7 e 10 di `CLAUDE.md`): accesso a mano nel browser di
|
||||
Febe, poi Febe copia cookie, user agent, gettoni e `doc_id` nella sessione salvata cifrata e lavora con richieste
|
||||
HTTP dirette, senza browser in sottofondo, come Mimante con Bidoo; i rinvii non si seguono e una risposta senza i
|
||||
campi attesi ferma e avvisa, senza riaccesso automatico; le storie si leggono con una richiesta e non risultano
|
||||
viste. Le tappe S0–S7 stanno in #36.
|
||||
- **Il browser che a volte restava vuoto** (#52): nove cause trovate e ordinate (la pagina di riposo `about:blank`
|
||||
mostrata all'apertura, «Apri il browser» dopo una disconnessione, la finestra nascosta su Windows quando si lascia
|
||||
la pagina, lo schermo remoto senza controllo dei fotogrammi in Docker, e altre); correzione su un ramo a parte.
|
||||
- **Tappa S1, il giunto senza cambiare comportamento**: `ResponseDelivery` (in Core) consegna ai lettori le risposte
|
||||
catturate e, da S2, quelle chieste, nello stesso modo; `ResponseTap` la usa con gli stessi conteggi e messaggi.
|
||||
Contratti `SiteRequest`, `SiteAnswer` (che non stampa mai corpi, cookie o percorsi concreti) e `ISiteRequester`,
|
||||
con `SiteRequestGuard`: niente richiesta senza un permesso concesso, della categoria giusta e mai usato prima
|
||||
(`SpentPermits`); valori del caso con la loro forma (cifre per gli identificativi, nessun «/», «?», «%» nei
|
||||
segmenti). `RequestCatalog` legge `richieste.instagram.json` e `richieste.prova.json` e rifiuta, nel codice e
|
||||
quindi anche in una copia modificata nella cartella dei dati: ogni nome con `Mutation`, le famiglie di chat,
|
||||
posta, presenza, promozioni e telemetria, i percorsi `/ajax/`, `/ws/`, `/logging_client_events`, `/api/v1/web/`,
|
||||
host, parametri, segmenti «.» o vuoti, GraphQL fuori da `POST /api/graphql` e `/graphql/query`. Nessun `doc_id` nel
|
||||
repository (si leggono all'accesso, S4). Il catalogo di Instagram ha 10 operazioni, **nessuna ancora configurata**:
|
||||
le forme della sonda tolgono un nome di campo presente in ogni richiesta GraphQL e non dicono da dove vengano
|
||||
`__dyn`, `__csr`, `__rev`, `__spin_*`, `__req`, `sec-ch-ua*` e altri (fonti «pending», da chiudere in S4); il
|
||||
catalogo di prova ne ha 8 configurate su 11. Prove nuove: 87 (`RequestCatalogTests`, `SiteRequesterTests`,
|
||||
`ResponseDeliveryTests`, con `ScriptedRequester` sui campioni ripuliti). Il campione 000016 viene da
|
||||
`PolarisProfilePostsQuery`, non da `media/{numero}/info`.
|
||||
- **Domande per Alberto** (anche su #36): la sonda può tenere i nomi di campo che oggi toglie («(nome tolto)»: sono
|
||||
nomi di codice, non valori) e il tipo JSON dei valori (numero o testo)? Le corrispondenze `__user`/`av` →
|
||||
identificativo dell'account e `reel_ids_arr` → account sono dedotte, non confermate.
|
||||
- **Non verificato**: nessuna richiesta diretta è mai partita verso Instagram (le prove usano solo il sito di prova);
|
||||
H12, H13, H15, H16 e H17 aspettano le prove dal vivo di Alberto.
|
||||
|
||||
**15 novembre 2026: una sola casella per cercare i profili, con suggerimenti e foto** (#37).
|
||||
|
||||
- «Aggiungi account» ha una sola casella. Mentre Alberto scrive compaiono subito i suggerimenti locali (profili
|
||||
seguiti e account già in Febe), poi i risultati di Instagram con la foto, uniti senza doppioni. Frecce e Invio
|
||||
aggiungono, Esc chiude l'elenco; più nomi incollati vanno in «Da aggiungere», mai su Instagram; «Scegli fra tutti i
|
||||
profili che segui» apre il vecchio elenco con le caselle.
|
||||
- Come cerca: il browser di Febe apre «Cerca» su Instagram e scrive nella casella con `Input.dispatchKeyEvent`, solo
|
||||
lettere, cifre, «.», «_» e spazi (`SearchKeyMap`, mai Invio, Tab o Esc), dopo aver controllato che il fuoco sia nella
|
||||
casella. Legge la risposta `PolarisSearchBoxRefetchableQuery` (campione ripulito 000002) e **non fa mai clic su un
|
||||
risultato**, che finirebbe fra le ricerche recenti. Solo profili.
|
||||
- Governatore: categoria nuova «Ricerche di profili» con tetti propri (Prudente 240/ora e 1200/giorno, Equilibrato
|
||||
300/1500, Rapido 360/1800) che non consumano quelli della raccolta; si ferma con l'interruttore, la pausa, fuori
|
||||
fascia e quando Alberto usa il browser. In sessione ricerca e motore si danno il turno sull'unica pagina
|
||||
(`PageTurns`); a fine sessione la pagina torna comunque al riposo.
|
||||
- Foto: dal CDN con `BrowserFileFetcher` e un permesso per foto, ridotte a 160 px, solo in memoria (nessun file su
|
||||
disco dice chi si è cercato), servite con `no-store`.
|
||||
- Risposte di Alberto del 15 novembre (righe in `docs/decisioni.md`, §6.1 aggiornato): il controllo del fuoco con
|
||||
`Runtime.evaluate` in sola lettura è ammesso; i turni restano a ogni ricetta e prima di ogni apertura di pagina;
|
||||
l'ascolto di `Network.requestWillBeSent`, solo per l'indirizzo, è ammesso; le foto dei profili seguiti non si
|
||||
scaricano per ora.
|
||||
- Schermate rifatte: 04 (che sostituisce il mockup 04, Q9), 06 e 07 con la riga nuova dei tetti.
|
||||
- Prove con Chromium in un contenitore Linux locale (stesso ambiente della CI): suite intera 1058 su 1058, le prove
|
||||
della ricerca, dell'interfaccia e del riavvio di Chromium 5 volte su 5. Nella prima CI erano cadute due prove per
|
||||
gare dei tempi nelle prove stesse, non nel prodotto: «al volante» rilasciava la risposta prima che la pagina la
|
||||
chiedesse, e `AfterACrashChromiumRestarts…` leggeva lo stato fra il conteggio del riavvio e «Running».
|
||||
- **Su Instagram vero la ricerca non parte ancora**: i bersagli `search-open` e `search-box` di
|
||||
`bersagli.instagram.json` sono vuoti (H11) finché Alberto non li raccoglie dal vivo; fino ad allora funzionano i
|
||||
suggerimenti locali e la dimostrazione. Mai provato: la scrittura in WebView2 con la finestra fuori schermo (passo
|
||||
C3 delle prove dal vivo).
|
||||
|
||||
**13 novembre 2026, sera: le prove che cadevano con il runner carico** (#46).
|
||||
|
||||
- Cause trovate, non solo tempi allungati. Tre erano difetti del prodotto:
|
||||
- `FebeDatabase.DisposeAsync` lasciava i file aperti: i comandi SQLite non chiusi tenevano viva la connessione
|
||||
fino al finalizzatore, e il WAL spariva durante lo spostamento della cartella Dati (`FoldersAutostart…`). Ora
|
||||
ogni comando si chiude (`Sql.Execute`/`Scalar`, `CommandScope` per le letture) e il pool di lettura si svuota prima
|
||||
dello scrittore; prova nuova `DatabaseCloseTests`, che cade senza la correzione.
|
||||
- La scheda dell'account, senza le statistiche di ANALYZE, leggeva i file di tutta la libreria: ora una passata sola
|
||||
sui file dell'account (`AccountStore.GetStatsAsync`).
|
||||
- All'arresto `FebeApp` non aspettava i lavori in sottofondo aggiunti da un avvio ancora in corso.
|
||||
- Avvio di Chromium: 120 s invece di 30 per un browser vivo ma lento, e la prima scheda si aspetta entro la stessa
|
||||
scadenza (prima 5 s); un Chromium che si chiude fa fallire subito come prima. Il ricollegamento dopo una connessione
|
||||
caduta smette appena il processo cambia.
|
||||
- Prove: i limiti di tempo sono protezioni contro un blocco, non misure (aiuto comune `TestWait`); la prova di scala
|
||||
ha limiti per classe di interrogazione, prende il tempo migliore e gira da sola dopo le prove parallele; il browser
|
||||
delle prove dell'interfaccia usa la porta 0 e mostra lo stderr di Chromium quando fallisce; la prova di «Scollega»
|
||||
di WebView2 chiede che il processo esca davvero, non 10 s. Cinque righe in `docs/decisioni.md`.
|
||||
- Verificato su Windows con tutti i core occupati: le classi corrette 10 volte su 10, la prova di scala 5 su 5, le
|
||||
prove di WebView2 3 su 3. **Non verificato qui**: le prove con Chromium e Xvfb girano solo nella CI Linux; il
|
||||
contenitore Linux con 2 CPU non è partito perché C: era pieno (0,2 GB liberi) e Docker Desktop si è fermato.
|
||||
- **Per Alberto**: liberare spazio su C: (il disco di Docker, `docker_data.vhdx`, è di circa 45 GB) e riavviare
|
||||
Docker Desktop; poi si possono togliere le immagini `febe-ui46:base`, `febe-ui46:locale` e `febe-ci46-locale`.
|
||||
|
||||
**13 novembre 2026, pomeriggio: il rapporto di diagnostica della raccolta** (#39).
|
||||
|
||||
- Attività ha un terzo pulsante, «Diagnostica», che scarica `febe-diagnostica-AAAA-MM-GG.json`
|
||||
(`GET /api/engine/diagnostica`, ammesso anche con un problema di configurazione, ma allora vuoto). Per ogni sessione
|
||||
degli ultimi 14 giorni, più un gruppo per giorno «fuori sessione»: pagine aperte (nome della pagina e forma
|
||||
dell'indirizzo, mai i nomi), navigazioni, risposte per tipo, forma, stato e dimensione con ciò che i lettori ne
|
||||
hanno fatto, struttura delle chiavi delle forme sconosciute (stretta: solo parole di un elenco chiuso, il resto `#`),
|
||||
obiettivi cliccati, giudizi, ricette con esito e segnale, segnali, permessi negati, file in coda e scaricati con la
|
||||
causa, e il motivo d'arresto (`SessionStopCause`, nuovo). Le intestazioni dicono se il rapporto può essere
|
||||
incompleto (righe rovinate, file illeggibili, errori del registratore, sessioni senza fine).
|
||||
- Il registratore (`Febe.Core.Collection.Diagnostics`) scrive in `Dati/diagnostica/sessioni-AAAA-MM-GG.jsonl`, una
|
||||
riga all'inizio della sessione, ogni 5 minuti e alla fine; non lancia mai eccezioni verso la raccolta. Le forme degli
|
||||
indirizzi (`PathPatterns`) e la regola delle chiavi-dato sono passate dalla sonda a Core, e la sonda le richiama.
|
||||
Specifica §7.9 e §13.2, guida (Attività e arresti), righe in `docs/decisioni.md`, `LEGGIMI.md`; schermate di
|
||||
Attività (06, 11, 14) rifatte e confrontate con i mockup 06 e 11 (`differenze.md`).
|
||||
- Prove nuove: unità del registratore, del registro e del rapporto, motivi d'arresto sul banco del motore, endpoint e
|
||||
dimostrazione per scena, e la prova chiesta da #39 che il rapporto non contiene valori (nomi con punto, nomi usati
|
||||
come chiavi, codici, cursori, indirizzi firmati, cookie), con controlli di mutazione. Tre giri di revisione
|
||||
avversaria: 17 + 6 + 2 difetti confermati, tutti corretti.
|
||||
- **Non verificato qui**: le prove con Chromium (fra cui `DiagnosticPrivacyIntegrationTests`, la ricetta vera sul sito
|
||||
di prova) girano solo nella CI Linux. Il rapporto non è ancora stato provato dal vivo: va guardato alla prova #40.
|
||||
|
||||
**13 novembre 2026, giorno: le foto del profilo hanno il loro schema** (#38).
|
||||
|
||||
- PR #45 è **unita in `main`** (305791f) con la verifica verde (esecuzione 272). Forzare l'unione non era possibile:
|
||||
la protezione di `main` vale anche per gli amministratori.
|
||||
- Le foto del profilo hanno un terzo schema dei nomi, predefinito `{account}\profilo\{data}_{ora}_{codice}_{n}`,
|
||||
accanto a quello generale e a quello delle raccolte: restano in `<account>\profilo` anche se Alberto cambia lo schema
|
||||
generale (sua decisione su #38). In Impostazioni ▸ Generali è il terzo campo, con la cartella `profilo` nel risultato
|
||||
e il campo rosso se è sbagliato; confrontata con il mockup 08 e rifatta `docs/schermate/08-impostazioni-generali.png`.
|
||||
Specifica §4.7, guida (Libreria) e una riga in `docs/decisioni.md`.
|
||||
- Prove nuove: nomi e regole del terzo schema, anteprima, impostazioni (un salvataggio senza il terzo schema lo tiene),
|
||||
salvataggio dei file con uno schema generale piatto, riconoscimento all'importazione, ricostruzione del database.
|
||||
- **Resta di #38**: che le foto arrivino davvero, con la raccolta riscritta (#36), anche per gli account aggiunti dalla
|
||||
ricerca (#37).
|
||||
|
||||
**13 novembre 2026, notte: il HAR dello scorrimento è troncato** (#35).
|
||||
|
||||
- Alberto ha esportato il giro corto della parte A quater (seguiti e seconda pagina dei post). Il file è arrivato
|
||||
troncato due volte: la prima a 200 000 byte esatti, la seconda a 57 MB, a metà del corpo di una risposta.
|
||||
- `febe-sonda` ora legge un HAR troncato: tiene le voci complete, scarta quella dentro cui il file finisce e lo dice;
|
||||
un file rotto altrove resta rifiutato. Per `richieste` i valori della voce scartata contano lo stesso, testo
|
||||
interrotto compreso, così nessun nome che è un dato passa per via del taglio (`HarFile`, 16 casi in
|
||||
`HarFileTests`, riga in `docs/decisioni.md`). Revisione avversaria (21 agenti): 6 rilievi confermati, tutti
|
||||
corretti. Il principale: la prima versione non contava i valori del testo interrotto, né applicava alla voce
|
||||
scartata le regole di base64 e delle pagine.
|
||||
- Del giro sono arrivate 141 voci, e la parte completa si ferma alla pagina iniziale. Dopo la ripulitura restano 6
|
||||
campioni: pagina successiva del feed, griglia di Esplora, promozioni e configurazione della pagina. «Verifica
|
||||
superata». Nessuno è fra i pezzi che servono: **seguiti e seconda pagina dei post mancano ancora.** In
|
||||
`docs/prove-dal-vivo.md` (A quater) ora c'è come esportare senza che il file si tronchi: svuotare il pannello Rete
|
||||
dopo il caricamento della pagina iniziale, niente video, esportare subito.
|
||||
- PR #45 (secondo HAR, lettori, sonda per i HAR troncati): Gitea, che quella notte rispondeva 500, ha perso
|
||||
l'evento del push di 78aa32b, e la verifica non è partita. Lanciata a mano (esecuzione 262) è verde in tutti e
|
||||
quattro i lavori, ma un'esecuzione a mano non scrive gli stati del commit, e la protezione di `main` non lascia
|
||||
unire neanche un amministratore. Per questo c'è un commit in più, che riporta questo caso anche in
|
||||
`docs/processo.md`: il suo push fa girare la verifica che serve. L'unione restava rifiutata (405) anche dopo,
|
||||
perché il ramo era indietro rispetto a `main`, che aveva il commit di unione di #44: `main` è stato unito nel
|
||||
ramo, senza cambiare il contenuto, e la verifica è girata di nuovo.
|
||||
- PR #44 è unita; anche la verifica di `main` del 12/11 (esecuzione 250) è caduta solo sul caricamento del rapporto
|
||||
di Trivy, per le risposte 500 di Gitea.
|
||||
|
||||
**12 novembre 2026, sera: il secondo HAR** (#35).
|
||||
|
||||
- Alberto ha mandato un HAR senza filtro, un giro veloce su Instagram. Sulla sua macchina, fuori dal repository:
|
||||
`febe-sonda richieste` (45 forme di richieste), `da-har` (142 campioni grezzi), `ripulisci` e `verifica` →
|
||||
«Verifica superata». Per arrivarci sono serviti tre correttivi alla sonda (numeri con esponente, falsi allarmi
|
||||
della verifica, parole degli indirizzi finti; `docs/decisioni.md`), con tre prove nuove.
|
||||
- **Esito** in `docs/sonda/richieste-instagram.md`: quale operazione dà che cosa (scheda e post del profilo, raccolte,
|
||||
storie di un profilo, ricerca, pagina iniziale), i campi che ogni richiesta porta e che vanno presi dalla pagina, e
|
||||
le tre scritture che la pagina manda da sola e Febe mai (storia vista, ricerca recente, «mi piace»). Riassunto per
|
||||
ipotesi in `docs/sonda/esito.md`.
|
||||
- **Otto campioni nuovi** (`000009`–`000016`), accorciati sulla copia ripulita; il lettore li legge già, con due
|
||||
aggiunte al vocabolario (`postCount` = `media_count`, `highlight.cover`) e sette prove nuove in
|
||||
`InstagramReaderTests`. Il blocco della pagina iniziale dà anche nome e foto dell'account collegato (H10).
|
||||
- **Manca ancora**: l'elenco dei seguiti e la seconda pagina dei post. Giro corto per Alberto in
|
||||
`docs/prove-dal-vivo.md`, parte **A quater**. Punto aperto per #36: da dove prendere `doc_id` e i campi di sessione,
|
||||
che per §6.1 restano nella pagina (tre vie in `docs/sonda/richieste-instagram.md`).
|
||||
- **Revisione avversaria** prima del commit (18 agenti): 8 rilievi confermati, tutti corretti. Fra questi due difetti
|
||||
della verifica (una chiave di dati grezza poteva passare sotto la regola della chiave che la contiene; un carattere
|
||||
come il segno Kelvin poteva fermarla invece di segnalare la fuga), una serie con un video che era già nel HAR e che
|
||||
i documenti davano per mancante, e la via «riusa l'ultima richiesta della pagina», che come era scritta faceva
|
||||
uscire i gettoni dalla pagina.
|
||||
- PR #44 (strada B nei documenti e `febe-sonda richieste`): **unita in `main`** (0153280) con la verifica verde al
|
||||
quinto tentativo. I primi tre sono caduti su prove di tempi del runner sovraccarico, ogni volta prove diverse e mai
|
||||
su codice cambiato:
|
||||
- riempimento della libreria in 291 s;
|
||||
- Chromium che non risponde sulla porta di debug;
|
||||
- spostamento della cartella con la shell nativa.
|
||||
|
||||
Il quarto si è interrotto per il riavvio del PC. Queste prove instabili meritano una issue a parte.
|
||||
|
||||
**12 novembre 2026: la prova dal vivo non è andata, la raccolta va ripensata.**
|
||||
|
||||
- Alberto: con i dati veri Febe non trova gli account e non scarica nulla (#33).
|
||||
- **Che cosa dicono i dati di Febe sul PC di Alberto** (`%LOCALAPPDATA%\Febe`): l'ultima esecuzione è del 26/10 con la
|
||||
0.1.1; nel database 0 elementi, 0 file, 0 seguiti, 33 sessioni da 0 azioni; «Elenco dei seguiti» e «Controllo del
|
||||
profilo» fermi su «Bersaglio non trovato» e «mappa-incompleta».
|
||||
- **Perché**: le ricette dipendono dalla mappa dei bersagli, che si può raccogliere solo su Instagram (parte «A bis»,
|
||||
mai fatta). Anche con la 0.1.2 l'elenco dei seguiti non ha indirizzo e storie, raccolte, Taggati e Reel non hanno
|
||||
bersagli. È un difetto di disegno, non un errore da correggere.
|
||||
- **Decisione di Alberto** (#34, chiusa): **strada B, la pagina chiede i dati.** Dalla pagina di Instagram già
|
||||
aperta Febe chiede al sito gli stessi dati che chiede la sua applicazione web, solo verso gli indirizzi di
|
||||
`richieste.instagram.json`, in sola lettura, una richiesta per volta col permesso del Governatore. Scritta in
|
||||
`docs/decisioni.md`, nella specifica (§2 regola 2 con la sua unica eccezione, §6.1 riga e regole delle richieste,
|
||||
§14.5) e nella regola 4 di `CLAUDE.md`. Foto dei profili: dentro ogni account (`<account>\profilo\…`, #38).
|
||||
- **Pronto per i campioni nuovi** (#35): `febe-sonda richieste --har <file> --a <file .json>` descrive la forma delle
|
||||
richieste della pagina (metodo, percorso con `{numero}`/`{testo}`, nomi di parametri, intestazioni e campi,
|
||||
struttura delle variabili GraphQL) senza alcun valore personale, con 27 prove nuove su un HAR sintetico. Una revisione avversaria (23 agenti) ha trovato 17 difetti confermati, tutti corretti prima del commit: tre fughe possibili (un nome utente usato come chiave, un corpo di testo spezzato in nomi, un identificativo piccolo copiato), interrogazioni GET unite fra loro, pagine successive perse nell'unione, un arresto su uno stato non numerico, e parti della specifica (§1, regola 5, §6.3, §7.4) ancora in contrasto con l'eccezione. Nuova domanda aperta 11 (§16): le storie con la strada B. Procedura
|
||||
per Alberto in `docs/prove-dal-vivo.md`, parte **A ter**. Finché il HAR nuovo non arriva, `richieste.instagram.json`
|
||||
e i lettori nuovi non si possono scrivere (regola 10): la raccolta riscritta (#36) e la ricerca unica (#37) hanno
|
||||
bisogno di quei campioni.
|
||||
- Richieste nuove: ricerca unica dei profili con le foto, aggiornata mentre si scrive (#37); foto dei profili in una
|
||||
cartella separata (#38). In più la diagnostica della raccolta (#39), i campioni nuovi (#35), la prova dal vivo (#40)
|
||||
e la chiusura della 0.2.0 (#41), tutte nel traguardo «0.2.0 — Raccolta che funziona su Instagram».
|
||||
- **Lavoro passato su Gitea**, come negli altri repository: etichette Area/Kind/Priority/Status, un traguardo chiuso
|
||||
per tappa (M0–M8) e per versione (0.1.1, 0.1.2), 23 attività chiuse con il loro resoconto «Fatto» (#13–#32, più #3,
|
||||
#5 e #8 assegnate alle versioni). I punti 6 e 8 di «Da fare» qui sotto sono ora #42 e #43.
|
||||
|
||||
**26 ottobre 2026.**
|
||||
|
||||
- La lettura di Instagram è in `main` (PR #11, commit di unione `fbc40fb`), con la verifica verde anche su `main`:
|
||||
controlli e gitleaks, 859 prove senza nessuna saltata, installatore, immagine.
|
||||
- **`REGISTRY_TOKEN` c'è** (segreto di Alberto, la CI lo vede): rilanciato il lavoro «immagine» della verifica di
|
||||
`main`, Febe è sul registro di Gitea per la prima volta, come `:main` e `:sha-fbc40fb`. `:latest` arriva con
|
||||
`v0.1.2`; fino ad allora su Unraid serve `:main`.
|
||||
- **Prima pulizia settimanale vera** (26/10 alle 5:17, esecuzione 56): tolte 3 immagini che nessun contenitore usava
|
||||
(`node:24-trixie`, `postgres:17`, `moby/buildkit`), 1,85 GB, più 218 MB di cache di costruzione; il registro non
|
||||
l'ha toccato perché il token non c'era ancora.
|
||||
- **Rilascio 0.1.2** (ramo `rilascio/0.1.2`): versione, CHANGELOG e stato. Dopo l'unione Alberto crea `v0.1.2` sul
|
||||
commit di unione; `rilascio.yml` pubblica `:0.1.2` e `:latest` e la release con installatore, zip, modello di Unraid
|
||||
e archivio per Compose.
|
||||
|
||||
**25 ottobre 2026: Febe legge le risposte vere di Instagram** (PR #11, in `main` dal 26/10).
|
||||
|
||||
- **Il guasto**: Instagram manda i dati di storie e raccolte (GraphQL) come `text/javascript`, e la cattura leggeva
|
||||
solo le risposte dichiarate JSON: le scartava tutte. In più `lettori.instagram.json` e `bersagli.instagram.json` erano
|
||||
scheletri e le ricette si rifiutavano di girare.
|
||||
- **I campioni**: Alberto ha mandato un HAR del suo browser (21/10, filtro Fetch/XHR) e una guida. La guida descrive
|
||||
richieste costruite a mano, vietate dalle regole 2–4, e un formato che nel HAR non compare: non si è usata. Del HAR si
|
||||
è letta solo la forma; le 8 risposte utili, accorciate dal lato grezzo, ripulite e verificate («Verifica superata»),
|
||||
sono in `tests/Febe.Tests/campioni/instagram` (vedi il suo `LEGGIMI.md`). I grezzi convertiti sono stati cancellati.
|
||||
- **Che cosa cambia**: la cattura legge le risposte `text/javascript` chieste dalla pagina e il JSON incorporato nel
|
||||
documento (questo da confermare: il HAR non aveva documenti); le risposte che non parlano di contenuti si ignorano;
|
||||
il vocabolario di Instagram è «confermato» e ogni sua chiave compare nei campioni; la mappa ha le pagine viste nel
|
||||
traffico vero, i bersagli no. Le ricette del profilo reggono dati che arrivano in risposte diverse; il visualizzatore
|
||||
delle raccolte conta i contenuti (l'indirizzo non cambia); le ricette che la configurazione non lascia girare sono
|
||||
«Da configurare», non guasti, e le sospensioni dovute ai file vecchi si azzerano da sole al primo avvio.
|
||||
- **Che cosa gira su Instagram**: giro dei seguiti, controllo del profilo, storico, post singolo. **Non ancora**:
|
||||
storie, raccolte, Taggati, Reel (mancano i bersagli, H11) ed elenco dei seguiti (manca l'indirizzo). Nulla è stato
|
||||
provato dal vivo.
|
||||
- **Strumenti per Alberto**: `febe-sonda da-har` (HAR → campioni grezzi, poi `ripulisci` e `verifica`) e
|
||||
`tools/bersagli/raccogli-bersagli.js` (bersagli in sola lettura dalla Console); procedura in
|
||||
`docs/prove-dal-vivo.md`, parte A bis.
|
||||
- **Cancellazione automatica delle immagini delle Actions**: era già attiva dal 21/10 (ogni lavoro «immagine» toglie la
|
||||
sua immagine e le penzolanti; ogni lunedì la pulizia completa, la prima vera lunedì 26/10 alle 4:17). Nulla da
|
||||
cambiare. L'immagine si pubblica sul registro solo con `REGISTRY_TOKEN` (c'è dal 26/10, vedi sopra).
|
||||
- Lavoro fatto da più agenti in parallelo, ciascuno su un ramo di lavoro, poi revisione avversaria: 21 rilievi, 17
|
||||
confermati e corretti (uno solo in parte, vedi sotto), e un solo commit. Prove: 783 superate su Windows (76 saltate:
|
||||
Chromium e Xvfb); nella CI 859 superate, nessuna saltata.
|
||||
|
||||
**21 ottobre 2026.**
|
||||
|
||||
- **0.1.1 rilasciata**: tag `v0.1.1`, release con installatore, zip portabile, modello Unraid e archivio per Compose.
|
||||
L'immagine Docker non è pubblicata, perché `REGISTRY_TOKEN` manca ancora.
|
||||
- **La pulizia della CI toglie tutto ciò che non serve più** (decisione di Alberto). Dopo ogni lavoro «immagine» se ne
|
||||
vanno le immagini senza nome e la cache di costruzione che nessuno usa da 24 ore: la prima volta 26,31 GB. Ogni
|
||||
lunedì se ne vanno le immagini che nessun contenitore usa, la cache vecchia, i resti di act_runner e le `:sha-` oltre
|
||||
le 10 più recenti. Mai contenitori, volumi o reti che non siano della CI. A mano c'è «Solo prova» (`docs/processo.md`,
|
||||
«Pulizia»).
|
||||
- Le tre prove d'interfaccia trovate instabili dalla CI con Chromium vero sono stabili (#3 e #5 il 20/10, #8 il 21/10).
|
||||
Le prove d'interfaccia non usano più pause a tempo fisso.
|
||||
|
||||
**20 ottobre 2026.** Febe per Windows non riusciva a collegarsi: il browser di Febe non diventava mai pronto (registro di
|
||||
Alberto del 14 e del 19/10). Era un errore di thread, corretto. Febe per Windows ha girato per la prima volta su un
|
||||
Windows vero: collegamento, account e sessioni contro il sito di prova, dall'interfaccia. Lo stesso giorno sono arrivati:
|
||||
@@ -16,8 +281,8 @@ Windows vero: collegamento, account e sessioni contro il sito di prova, dall'int
|
||||
- altre tre correzioni trovate provando: lo storico completato doppio o bloccato, la vista remota durante un cambio di
|
||||
pagina, il pannello «Collegato come @».
|
||||
|
||||
Il lavoro è su sei rami, ciascuno con la sua revisione avversaria, unito in `main` con la PR #2 (CI) e la PR
|
||||
d'integrazione della 0.1.1.
|
||||
Il lavoro è su sei rami, ciascuno con la sua revisione avversaria, unito in `main` con la PR #2 (CI), la PR
|
||||
d'integrazione #4, la #6 e la #7 (rilascio 0.1.1). Il 21/10 sono seguite la #9 (pulizia) e la #10 (prove d'interfaccia).
|
||||
|
||||
Tutte le tappe M0–M8 sono state realizzate in una volta, su richiesta di Alberto del 13 ottobre 2026, sul ramo
|
||||
`febe-v1`. Il programma è completo e provato **contro il sito di prova locale** (§14.2) con un Chromium vero su Xvfb.
|
||||
@@ -54,20 +319,34 @@ protezione di `main` sono in `docs/processo.md`.
|
||||
|
||||
## Da fare (di Alberto)
|
||||
|
||||
1. **Sonda di M0** con l'account di prova (domanda 2 di §16): `docs/prove-dal-vivo.md`, parte A. Poi mandare i
|
||||
campioni **ripuliti** e le righe di `interazioni.jsonl` dei comandi dell'interfaccia: con quelli si compilano
|
||||
`bersagli.instagram.json` e `lettori.instagram.json` e si portano le ipotesi H1–H11 a un esito.
|
||||
2. **Prima sessione dal vivo** dopo la sonda, con il profilo Prudente su un profilo pubblico (parte B).
|
||||
1. **Bersagli e campioni dal browser di tutti i giorni** (`docs/prove-dal-vivo.md`, parte A bis, una decina di
|
||||
minuti): HAR con il filtro «Tutti» e «Conserva log», lo script `tools/bersagli/raccogli-bersagli.js` nella Console,
|
||||
poi `febe-sonda da-har`, `ripulisci`, `verifica`. Mandare solo la cartella ripulita e il testo dei bersagli: con
|
||||
quelli si compilano i bersagli di storie, raccolte, Taggati e Reel e si confermano la home, il profilo e le storie
|
||||
di un account (H1–H4, H6, H11). In alternativa la sonda (parte A).
|
||||
2. **Prima sessione dal vivo** con il profilo Prudente su un profilo pubblico (parte B): già possibile per giro dei
|
||||
seguiti, controllo del profilo, storico e post singolo. Da guardare: i file in Libreria (H5, H7), «Tu» riconosciuto
|
||||
(H10), nessun «formato non riconosciuto» in Attività.
|
||||
3. **Windows**: C5.2–C5.5 (C5.1, l'accesso con l'account di prova, è riuscito il 20/10), S2 con la finestra ridotta a
|
||||
icona e con lo schermo bloccato, C2 (installatore della 0.1.1 su un Windows pulito). **Docker su Unraid**: S3–S6 nel contenitore
|
||||
icona e con lo schermo bloccato, C2 (installatore della 0.1.2 su un Windows pulito). **Docker su Unraid**: S3–S6 nel contenitore
|
||||
vero.
|
||||
4. Le domande aperte di §16 (sono state adottate le proposte della terza colonna, vedi `docs/decisioni.md`).
|
||||
5. Il segreto `REGISTRY_TOKEN` nel repository: senza, la CI e il rilascio costruiscono, provano e scansionano
|
||||
l'immagine, ma non la pubblicano (lo dicono con un avviso). Il 20/10 mancava ancora.
|
||||
5. **Tag `v0.1.2`** sul commit di unione di `rilascio/0.1.2` in `main`: `git tag -a v0.1.2 -m "Febe 0.1.2"` e
|
||||
`git push origin v0.1.2` (`docs/processo.md`, «Rilasci»). Poi su Unraid basta `:latest`. `REGISTRY_TOKEN` c'è dal
|
||||
26/10; il flusso del tag `v0.1.1` non serve più rilanciarlo: pubblicherebbe la 0.1.1, senza la lettura di Instagram.
|
||||
6. Sicurezza dell'istanza Gitea: la registrazione è aperta, senza CAPTCHA, con quattro account creati da programmi fra
|
||||
agosto e settembre. Il runner `fa94b0298b8d` è registrato per tutta l'istanza e i suoi lavori parlano con il Docker
|
||||
dell'host, quindi un utente registrato potrebbe farci girare un suo flusso. Si consiglia di chiudere la registrazione
|
||||
(`[service] DISABLE_REGISTRATION = true`) o di registrare il runner per il solo utente o repository.
|
||||
7. **Pulizia**: la prima vera è girata il 26/10 (esecuzione 56, store classico) e ha tolto solo immagini che nessun
|
||||
contenitore usava; da guardare, se serve, il suo registro. Dal lunedì 2/11 toglie anche le `:sha-` del registro oltre
|
||||
le 10 più recenti.
|
||||
8. Da decidere:
|
||||
- dopo ogni esecuzione la cache di costruzione si toglie solo se nessuno la usa da 24 ore (`--filter until=24h`).
|
||||
Senza filtro, a ogni push se ne andrebbe anche quella appena usata dagli altri progetti; per cambiare basta togliere
|
||||
il filtro in `pulizia-docker.sh penzolanti`;
|
||||
- gli script di shell di `.gitea/` e `installer/` hanno i commenti in italiano, contro «codice e commenti in
|
||||
inglese»: o un'eccezione in `docs/decisioni.md`, o una traduzione in un ramo a parte.
|
||||
|
||||
## Rilievi aperti (20 ottobre)
|
||||
|
||||
@@ -82,6 +361,31 @@ protezione di `main` sono in `docs/processo.md`.
|
||||
(vuota) e quella vera arriva dopo la pausa minima, circa 20 minuti. È il comportamento della specifica, ma chi ha
|
||||
appena collegato Febe aspetta.
|
||||
|
||||
## Rilievi aperti (25 ottobre)
|
||||
|
||||
- Nessuna di queste modifiche è stata provata con Instagram: la prima sessione dal vivo (parte B) dirà se i dati del
|
||||
primo schermo arrivano nel documento o con XHR, se i file video hanno l'audio (H5) e se si scaricano (H7).
|
||||
- I blocchi JSON dei documenti di Instagram non si sono mai visti (il HAR non aveva documenti): forma e ordine ignoti.
|
||||
Le regole di testo di `segnali.json` ora li guardano uno per uno; un falso segnale si vedrebbe in Attività.
|
||||
- Visualizzatore senza identificativo nell'indirizzo (le raccolte): un clic «avanti» che la pagina ignora non si vede,
|
||||
e il conteggio salverebbe un contenuto non mostrato; una foto che il sito lascia da sola fa restare indietro il
|
||||
conteggio. Da misurare quando i bersagli ci saranno. Con le storie l'indirizzo dice quale storia è a video, se
|
||||
Instagram lo aggiorna (da confermare con lo script dei bersagli).
|
||||
- Un account Instagram senza post resta con lo storico aperto: a ogni sessione costa un'attesa di 20 s e una pagina.
|
||||
- Il pannello «Con queste impostazioni» di un profilo non seguito conta le visite all'intervallo delle storie anche
|
||||
mentre le storie non possono girare (sovrastima).
|
||||
- «Post singolo» accodati per gli indirizzi scaduti ora girano davvero (prima la coda li annullava): dentro il loro
|
||||
tetto, ma sono azioni in più su Instagram.
|
||||
|
||||
## Rilievi aperti (21 ottobre)
|
||||
|
||||
- Le note della release scritte da `rilascio.yml` senza immagine dicono «`:latest` resta sulla versione precedente», ma
|
||||
sul registro un'immagine precedente non c'è mai stata. Da riformulare per il caso della prima pubblicazione.
|
||||
- Un solo timeout di `OpenAsync` all'apertura di `/browser` (`AfterHoFinitoLeavingTheBrowserPageChangesNothingMore`) in
|
||||
migliaia di esecuzioni delle prove d'interfaccia, senza causa trovata. Se ricompare nella CI, va fatto dire a
|
||||
`OpenAsync` quale condizione mancava.
|
||||
- Su questo PC Febe ha avvisato «Disco quasi pieno»: libreria e dati stanno su C:, dove restano circa 12 GB.
|
||||
|
||||
## Rimandato, e perché
|
||||
|
||||
- Via `HttpClient` verso il CDN (§6.5 punto 3): dipende da H7.
|
||||
|
||||
@@ -152,8 +152,10 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
_tracker.MarkUsed(_clock.Now);
|
||||
if (openLogin)
|
||||
{
|
||||
// The engine ends its session when the lease starts; wait for it before taking the page.
|
||||
// The engine ends its session when the lease starts; wait for it before taking the page. A search step
|
||||
// in progress (issue #37) stops at its next check of the lease: the login page waits for its turn.
|
||||
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
|
||||
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
|
||||
var result = await _browser.Cdp.NavigateAsync(_loginUrl, ct).ConfigureAwait(false);
|
||||
_log.Info("collegamento", result.Succeeded
|
||||
? "Alberto usa il browser: pagina di accesso aperta."
|
||||
@@ -540,6 +542,29 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page turn for Alberto's login page, so that no step of the profile search runs under it; after 15 seconds
|
||||
/// the page is taken anyway (Alberto asked for it), and null comes back.
|
||||
/// </summary>
|
||||
private async Task<PageTurn?> TakePageAsync(CancellationToken ct)
|
||||
{
|
||||
if (_engine is not { } engine)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
limit.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
try
|
||||
{
|
||||
return await engine.Services.PageTurns.TakeAsync(PageUser.Engine, limit.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string?> CurrentUrlAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -24,4 +24,7 @@ public sealed class DeferredRecipeRunner : IRecipeRunner
|
||||
: Task.FromResult(new RecipeOutcome(RecipeStatus.Cancelled, 0, 0, "Il browser non è ancora pronto."));
|
||||
|
||||
public Task RestAsync(CancellationToken ct) => _target?.RestAsync(ct) ?? Task.CompletedTask;
|
||||
|
||||
/// <summary>The real runner's answer; before the browser is up nothing is known, and nothing is held back.</summary>
|
||||
public string? NotConfiguredReason(RecipeKind kind) => _target?.NotConfiguredReason(kind);
|
||||
}
|
||||
@@ -2,7 +2,10 @@ using System.Globalization;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Import;
|
||||
@@ -35,6 +38,8 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
private readonly FebeAppOptions _options;
|
||||
private readonly IFebePlatform _platform;
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
// The start adds to these lists from its background tasks while a stop may already be running (#46): one lock.
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<Task> _background = [];
|
||||
private readonly List<IDisposable> _disposables = [];
|
||||
private readonly List<Action> _unsubscribe = [];
|
||||
@@ -82,10 +87,19 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
|
||||
public CollectionPipeline? Pipeline { get; private set; }
|
||||
|
||||
/// <summary>The profile search (issue #37): local suggestions at once, the site's own search box between engine actions.</summary>
|
||||
public ProfileSearchService? Search { get; private set; }
|
||||
|
||||
public ImportService? Import { get; private set; }
|
||||
|
||||
public PerceptualHashIndex? HashIndex { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The recorder of the diagnostic report (issue #39), with its log in <c>Dati/diagnostica</c> (null with a
|
||||
/// configuration problem). Flushed when Febe stops.
|
||||
/// </summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; private set; }
|
||||
|
||||
/// <summary>When Alberto last used the browser («Riprendi» after a verification).</summary>
|
||||
public BrowserUseTracker Tracker { get; } = new();
|
||||
|
||||
@@ -246,13 +260,24 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
userIsDriving: () => browser.UserIsDriving,
|
||||
isConnected: () => connection.IsConnected == true,
|
||||
ct: ct).ConfigureAwait(false);
|
||||
// The diagnostic report (issue #39): one recorder for the engine, the pipeline and the interface. What the
|
||||
// capture sees goes to the session in progress, if any.
|
||||
var diagnostics = new CollectionDiagnostics(Clock, () => services.Runtime.CurrentSession?.SessionId, new DiagnosticLog(data.Diagnostics, Clock));
|
||||
Diagnostics = diagnostics;
|
||||
services.Diagnostics = diagnostics;
|
||||
EventHandler<Permit> permitDenied = (_, permit) => diagnostics.PermitDenied(null, permit.Kind, permit.Reason);
|
||||
services.Governor.Denied += permitDenied;
|
||||
OnStop(() => services.Governor.Denied -= permitDenied);
|
||||
var runner = new DeferredRecipeRunner();
|
||||
var engine = new EngineHost(services, runner);
|
||||
Engine = engine;
|
||||
var search = new ProfileSearchService(services);
|
||||
Search = search;
|
||||
search.Start();
|
||||
connection.AttachEngine(engine);
|
||||
EventHandler<bool> drivingChanged = (_, _) => engine.NotifyUserDrivingChanged();
|
||||
browser.UserDriving.Changed += drivingChanged;
|
||||
_unsubscribe.Add(() => browser.UserDriving.Changed -= drivingChanged);
|
||||
OnStop(() => browser.UserDriving.Changed -= drivingChanged);
|
||||
_telegram = new TelegramClient(hooks.TelegramHandler);
|
||||
var telegramChannel = new TelegramAlertChannel(_telegram);
|
||||
|
||||
@@ -264,10 +289,12 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
s.AddSingleton(Tracker);
|
||||
s.AddSingleton(engine.Monitor);
|
||||
s.AddSingleton<IEngineControl>(new EngineHostControl(engine));
|
||||
s.AddSingleton<IProfileSearch>(search);
|
||||
s.AddSingleton<IConnectionService>(connection);
|
||||
s.AddSingleton<IEngineSettingsControl>(new EngineHostSettingsControl(engine));
|
||||
s.AddSingleton(ingest);
|
||||
s.AddSingleton<IBrowserPreview>(new LiveBrowserPreview(browser, Clock));
|
||||
s.AddSingleton<IDiagnosticSource>(new RecordedDiagnosticSource(diagnostics));
|
||||
s.AddSingleton<IConfigurationProblems>(new StartupProblems([]));
|
||||
if (Import is not null)
|
||||
{
|
||||
@@ -303,10 +330,43 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
|
||||
// Housekeeping in the background: temporary files of an interrupted run, the daily copy of the database.
|
||||
var lifetime = _lifetime.Token;
|
||||
_background.Add(Task.Run(() => CleanTemporaryFilesAsync(staging, layout, lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => Alerts.WatchDiskSpaceAsync(lifetime), CancellationToken.None));
|
||||
InBackground(() => CleanTemporaryFilesAsync(staging, layout, lifetime));
|
||||
InBackground(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime));
|
||||
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, search, lifetime));
|
||||
InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime));
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="work"/> in the background; the stop waits for it.</summary>
|
||||
private void InBackground(Func<Task> work)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_background.Add(Task.Run(work, CancellationToken.None));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Keeps <paramref name="disposable"/> for the stop; disposes it at once when the stop already took its list.</summary>
|
||||
private void DisposeOnStop(IDisposable disposable)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) == 0)
|
||||
{
|
||||
_disposables.Add(disposable);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
disposable.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Keeps <paramref name="unsubscribe"/> for the stop.</summary>
|
||||
private void OnStop(Action unsubscribe)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_unsubscribe.Add(unsubscribe);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StartWebAsync(FebeAppHooks hooks, Action<IServiceCollection> register)
|
||||
@@ -336,7 +396,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
|
||||
/// <summary>The browser, then the pipeline, the downloads, the connection check and the engine.</summary>
|
||||
private async Task BringUpBrowserAsync(LibraryIngest ingest, string staging, EngineServices services, EngineHost engine, DeferredRecipeRunner runner, CancellationToken ct)
|
||||
private async Task BringUpBrowserAsync(LibraryIngest ingest, string staging, EngineServices services, EngineHost engine, DeferredRecipeRunner runner, ProfileSearchService search, CancellationToken ct)
|
||||
{
|
||||
var browser = Browser!;
|
||||
await browser.RunAsync(ct).ConfigureAwait(false);
|
||||
@@ -369,12 +429,21 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
// Rule 7: the pages Alberto opens (login, verification) are his, not the engine's, while no session runs.
|
||||
UserOwnsPage = () => browser.UserIsDriving && services.Runtime.CurrentSession is null,
|
||||
Log = Log.ForBrowser(),
|
||||
Diagnostics = Diagnostics,
|
||||
PageTurns = services.PageTurns,
|
||||
SearchOptions = search.Options,
|
||||
SearchPhotos = search.Photos,
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
runner.Target = Pipeline.Runner;
|
||||
if (Pipeline.Search is { } searchRunner)
|
||||
{
|
||||
search.Attach(searchRunner, Pipeline.SearchPhotos);
|
||||
}
|
||||
await CheckCollectionConfigurationAsync(Pipeline, engine, ct).ConfigureAwait(false);
|
||||
var changes = Web.Services.GetRequiredService<LibraryChanges>();
|
||||
_disposables.Add(changes.Attach(Pipeline.Downloads, Clock));
|
||||
_background.Add(Task.Run(() => DownloadLoopAsync(Pipeline.Downloads, ct), CancellationToken.None));
|
||||
DisposeOnStop(changes.Attach(Pipeline.Downloads, Clock));
|
||||
InBackground(() => DownloadLoopAsync(Pipeline.Downloads, ct));
|
||||
|
||||
// Every finished recipe may have queued files: the queue looks at once instead of at its next idle poll.
|
||||
var downloads = Pipeline.Downloads;
|
||||
@@ -387,7 +456,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
|
||||
services.Events.Notified += WakeDownloads;
|
||||
_unsubscribe.Add(() => services.Events.Notified -= WakeDownloads);
|
||||
OnStop(() => services.Events.Notified -= WakeDownloads);
|
||||
|
||||
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
|
||||
if (o.TestSiteAutoLogin && Connection.IsConnected != true)
|
||||
@@ -395,7 +464,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
await TestSiteLoginAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_background.Add(Task.Run(() => Connection.RunAsync(ct), CancellationToken.None));
|
||||
InBackground(() => Connection.RunAsync(ct));
|
||||
await engine.StartAsync(ct).ConfigureAwait(false);
|
||||
Log.Info("motore", Connection.IsConnected == true
|
||||
? "Motore avviato: il browser è collegato."
|
||||
@@ -412,6 +481,39 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which reader vocabulary and target map the collection uses, in the log: where each came from (embedded in Febe or
|
||||
/// the copy in the Data folder) and in what state, never what is in them; a warning when a copy in the Data folder
|
||||
/// hides a better embedded file. Then the engine clears, once, the suspensions and failures of the recipes counted
|
||||
/// against other files (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>). Before the engine loop starts.
|
||||
/// </summary>
|
||||
private async Task CheckCollectionConfigurationAsync(CollectionPipeline pipeline, EngineHost engine, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var configuration = CollectionConfiguration.Describe(_options.Site.Name, pipeline.Vocabulary, pipeline.SiteMap);
|
||||
foreach (var line in configuration.Lines)
|
||||
{
|
||||
Log.Info("raccolta", line);
|
||||
}
|
||||
|
||||
foreach (var warning in configuration.Warnings)
|
||||
{
|
||||
Log.Warn("raccolta", warning);
|
||||
}
|
||||
|
||||
if (await engine.ApplyCollectionConfigurationAsync(configuration.Fingerprint, ct).ConfigureAwait(false))
|
||||
{
|
||||
Log.Info("raccolta", $"Configurazione della raccolta diversa dall'ultimo avvio (impronta {configuration.Fingerprint[..12]}): sospensioni ed errori contati delle ricette azzerati.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Never a reason not to collect: the suspensions stay as they are, «Riattiva» still clears them.
|
||||
Log.Warn("raccolta", "Non riesco a confrontare la configurazione della raccolta con quella dell'ultimo avvio: le ricette sospese restano come sono.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Development with the test site only (<c>--accesso-di-prova</c>): what Alberto does by hand on Instagram — open
|
||||
/// the site once, so that its session cookie exists — then back to the rest page.
|
||||
@@ -582,17 +684,46 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
foreach (var task in _background.ToArray())
|
||||
|
||||
// A start still in progress adds tasks while the first ones are awaited: look again until nothing new appears,
|
||||
// so nothing still reads the database once it is closed (#46).
|
||||
var awaited = 0;
|
||||
while (true)
|
||||
{
|
||||
await Quietly(() => task).ConfigureAwait(false);
|
||||
Task[] pending;
|
||||
lock (_gate)
|
||||
{
|
||||
pending = _background.Skip(awaited).ToArray();
|
||||
}
|
||||
|
||||
if (pending.Length == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
foreach (var task in pending)
|
||||
{
|
||||
await Quietly(() => task).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
awaited += pending.Length;
|
||||
}
|
||||
|
||||
foreach (var disposable in _disposables)
|
||||
IDisposable[] disposables;
|
||||
Action[] unsubscribes;
|
||||
lock (_gate)
|
||||
{
|
||||
disposables = [.. _disposables];
|
||||
unsubscribes = [.. _unsubscribe];
|
||||
_disposables.Clear();
|
||||
}
|
||||
|
||||
foreach (var disposable in disposables)
|
||||
{
|
||||
disposable.Dispose();
|
||||
}
|
||||
|
||||
foreach (var unsubscribe in _unsubscribe)
|
||||
foreach (var unsubscribe in unsubscribes)
|
||||
{
|
||||
unsubscribe();
|
||||
}
|
||||
@@ -606,11 +737,20 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
await Quietly(() => import.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Search is { } profileSearch)
|
||||
{
|
||||
profileSearch.Detach();
|
||||
await Quietly(() => profileSearch.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Pipeline is { } pipeline)
|
||||
{
|
||||
await Quietly(() => pipeline.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// What is still open of the diagnostic report: sessions as in progress, the day outside sessions as it is.
|
||||
Diagnostics?.Dispose();
|
||||
|
||||
if (Connection is { } connection)
|
||||
{
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
|
||||
@@ -19,8 +19,17 @@ public sealed record ResponseTapOptions
|
||||
/// <summary>How long to wait for one body before giving up on it (one stuck request must not block the others).</summary>
|
||||
public TimeSpan BodyTimeout { get; init; } = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>Decides from the declared MIME type whether a body is worth parsing as JSON.</summary>
|
||||
public Func<string, bool> IsJsonMimeType { get; init; } = static mime => mime.Contains("json", StringComparison.OrdinalIgnoreCase);
|
||||
/// <summary>
|
||||
/// Decides from the declared MIME type and the resource type whether a body is worth parsing as JSON
|
||||
/// (<see cref="DataResponses.IsData"/>: JSON, and JavaScript the page fetched itself).
|
||||
/// </summary>
|
||||
public Func<string, string?, bool> IsDataResponse { get; init; } = DataResponses.IsData;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the main document of a site page is read too, for the JSON blocks it embeds
|
||||
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>).
|
||||
/// </summary>
|
||||
public bool ReadPageDocuments { get; init; } = true;
|
||||
|
||||
/// <summary>Per-resource buffer of the browser (<c>Network.enable</c> maxResourceBufferSize).</summary>
|
||||
public int BrowserResourceBufferBytes { get; init; } = 32 * 1024 * 1024;
|
||||
@@ -37,30 +46,36 @@ public sealed record ResponseTapStats(long Responses, long JsonBodies, long Body
|
||||
/// and the metadata of every response and main-frame navigation to <see cref="IResponseObserver"/>s.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It does not filter by address: readers recognise data by its shape (spec §6.4). Bodies stay in memory for the
|
||||
/// time of the reading, are never written to disk and never logged. Event handlers only queue work; bodies are
|
||||
/// fetched and parsed on a background worker, one at a time.
|
||||
/// It does not filter by address: readers recognise data by its shape (spec §6.4). A body is read when the browser
|
||||
/// declares it as JSON, or as JavaScript fetched by the page (Instagram's GraphQL answers), and the main document of a
|
||||
/// site page is read for the JSON blocks it embeds, each handed to consumers as an answer of its own with the
|
||||
/// document's descriptor. Bodies stay in memory for the time of the reading, are never written to disk and never
|
||||
/// logged. Event handlers only queue work; bodies are fetched and parsed on a background worker, one at a time.
|
||||
/// </remarks>
|
||||
public sealed class ResponseTap : IAsyncDisposable
|
||||
{
|
||||
private const int MaxRequestOrders = 4096;
|
||||
|
||||
private readonly ICdpSession _cdp;
|
||||
private readonly HostClassifier _hosts;
|
||||
private readonly IClock _clock;
|
||||
private readonly IBrowserLog _log;
|
||||
private readonly ResponseTapOptions _options;
|
||||
private readonly ConcurrentDictionary<string, ResponseDescriptor> _inFlight = new(StringComparer.Ordinal);
|
||||
private readonly ResponseDelivery _delivery;
|
||||
private readonly ConcurrentDictionary<string, PendingBody> _inFlight = new(StringComparer.Ordinal);
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<IResponseConsumer> _consumers = [];
|
||||
private readonly List<IResponseObserver> _observers = [];
|
||||
private readonly Channel<ResponseDescriptor> _queue = Channel.CreateUnbounded<ResponseDescriptor>(new UnboundedChannelOptions { SingleReader = true });
|
||||
private readonly Channel<PendingBody> _queue = Channel.CreateUnbounded<PendingBody>(new UnboundedChannelOptions { SingleReader = true });
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly List<IDisposable> _subscriptions = [];
|
||||
private readonly Dictionary<string, long> _requestOrders = new(StringComparer.Ordinal);
|
||||
private long _requestCounter;
|
||||
private Task? _worker;
|
||||
private volatile string? _mainFrameId;
|
||||
private long _responses;
|
||||
private long _jsonBodies;
|
||||
private long _bodyErrors;
|
||||
private long _parseErrors;
|
||||
private long _decodeErrors;
|
||||
private long _skipped;
|
||||
|
||||
public ResponseTap(ICdpSession cdp, HostClassifier hosts, IClock clock, IBrowserLog? log = null, ResponseTapOptions? options = null)
|
||||
@@ -70,6 +85,7 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_log = log ?? NullBrowserLog.Instance;
|
||||
_options = options ?? new ResponseTapOptions();
|
||||
_delivery = new ResponseDelivery("Cattura", (message, exception) => _log.Warn(message, exception));
|
||||
}
|
||||
|
||||
/// <summary>Raised for every main-frame navigation (sanitized address).</summary>
|
||||
@@ -77,9 +93,9 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
|
||||
public ResponseTapStats Stats => new(
|
||||
Interlocked.Read(ref _responses),
|
||||
Interlocked.Read(ref _jsonBodies),
|
||||
_delivery.JsonBodies,
|
||||
Interlocked.Read(ref _bodyErrors),
|
||||
Interlocked.Read(ref _parseErrors),
|
||||
Interlocked.Read(ref _decodeErrors) + _delivery.ParseErrors,
|
||||
Interlocked.Read(ref _skipped));
|
||||
|
||||
public IDisposable AddConsumer(IResponseConsumer consumer)
|
||||
@@ -124,6 +140,7 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
throw new InvalidOperationException("La cattura è già avviata.");
|
||||
}
|
||||
|
||||
_subscriptions.Add(_cdp.On("Network.requestWillBeSent", OnRequestWillBeSent));
|
||||
_subscriptions.Add(_cdp.On("Network.responseReceived", OnResponseReceived));
|
||||
_subscriptions.Add(_cdp.On("Network.loadingFinished", OnLoadingFinished));
|
||||
_subscriptions.Add(_cdp.On("Network.loadingFailed", OnLoadingFailed));
|
||||
@@ -181,7 +198,14 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
|
||||
private void OnReconnected(object? sender, EventArgs e)
|
||||
{
|
||||
_inFlight.Clear();
|
||||
foreach (var key in _inFlight.Keys)
|
||||
{
|
||||
if (_inFlight.TryRemove(key, out _))
|
||||
{
|
||||
NotifyDropped(key, BodyDropReason.Reconnected);
|
||||
}
|
||||
}
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
@@ -196,6 +220,51 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page starts a request: a site request gets its order (issue #37), kept until its response. Only the host
|
||||
/// kind of the address is looked at; nothing of the request is kept or logged.
|
||||
/// </summary>
|
||||
private void OnRequestWillBeSent(JsonElement p)
|
||||
{
|
||||
if (p.ValueKind != JsonValueKind.Object
|
||||
|| !p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId
|
||||
|| !p.TryGetProperty("request", out var request) || request.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var url = request.TryGetProperty("url", out var u) ? u.GetString() : null;
|
||||
if (_hosts.Classify(url) != HostKind.Site)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var order = Interlocked.Increment(ref _requestCounter);
|
||||
lock (_requestOrders)
|
||||
{
|
||||
if (_requestOrders.Count >= MaxRequestOrders)
|
||||
{
|
||||
// Requests whose response never came: their order is forgotten, and their answers count by arrival.
|
||||
_requestOrders.Clear();
|
||||
}
|
||||
|
||||
// A redirect starts the same request again: the later order holds.
|
||||
_requestOrders[requestId] = order;
|
||||
}
|
||||
|
||||
foreach (var observer in SnapshotObservers())
|
||||
{
|
||||
try
|
||||
{
|
||||
observer.OnRequestStarted(order);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Cattura: errore in un osservatore delle richieste.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnResponseReceived(JsonElement p)
|
||||
{
|
||||
if (p.ValueKind != JsonValueKind.Object || !p.TryGetProperty("requestId", out var idElement) || !p.TryGetProperty("response", out var response))
|
||||
@@ -225,7 +294,8 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
mime,
|
||||
type,
|
||||
isMainDocument,
|
||||
_clock.Now);
|
||||
_clock.Now,
|
||||
TakeRequestOrder(requestId));
|
||||
|
||||
Interlocked.Increment(ref _responses);
|
||||
foreach (var observer in SnapshotObservers())
|
||||
@@ -240,35 +310,60 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
if (_options.IsJsonMimeType(mime) && status is >= 200 and < 600 && status != 204)
|
||||
if (_options.IsDataResponse(mime, type) && status is >= 200 and < 600 && status != 204)
|
||||
{
|
||||
_inFlight[requestId] = descriptor;
|
||||
_inFlight[requestId] = new PendingBody(descriptor, IsPageDocument: false);
|
||||
}
|
||||
else if (_options.ReadPageDocuments && descriptor.HostKind == HostKind.Site && status is >= 200 and < 300
|
||||
&& DataResponses.IsPageDocument(mime, isMainDocument))
|
||||
{
|
||||
_inFlight[requestId] = new PendingBody(descriptor, IsPageDocument: true);
|
||||
}
|
||||
}
|
||||
|
||||
private long TakeRequestOrder(string requestId)
|
||||
{
|
||||
lock (_requestOrders)
|
||||
{
|
||||
return _requestOrders.Remove(requestId, out var order) ? order : 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnLoadingFinished(JsonElement p)
|
||||
{
|
||||
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId
|
||||
|| !_inFlight.TryRemove(requestId, out var descriptor))
|
||||
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var length = p.TryGetProperty("encodedDataLength", out var len) && len.TryGetDouble(out var d) ? d : 0;
|
||||
if (length > _options.MaxBodyBytes)
|
||||
NotifyLoadingFinished(requestId, length);
|
||||
if (!_inFlight.TryRemove(requestId, out var pending))
|
||||
{
|
||||
Interlocked.Increment(ref _skipped);
|
||||
return;
|
||||
}
|
||||
|
||||
_queue.Writer.TryWrite(descriptor);
|
||||
if (length > _options.MaxBodyBytes)
|
||||
{
|
||||
Interlocked.Increment(ref _skipped);
|
||||
NotifyDropped(requestId, BodyDropReason.TooLarge);
|
||||
return;
|
||||
}
|
||||
|
||||
_queue.Writer.TryWrite(pending);
|
||||
}
|
||||
|
||||
private void OnLoadingFailed(JsonElement p)
|
||||
{
|
||||
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId)
|
||||
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId)
|
||||
{
|
||||
_inFlight.TryRemove(requestId, out _);
|
||||
return;
|
||||
}
|
||||
|
||||
TakeRequestOrder(requestId);
|
||||
if (_inFlight.TryRemove(requestId, out _))
|
||||
{
|
||||
NotifyDropped(requestId, BodyDropReason.LoadingFailed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,8 +379,16 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
_mainFrameId = frame.TryGetProperty("id", out var id) ? id.GetString() : _mainFrameId;
|
||||
|
||||
// Requests of the previous document that never finished (e.g. a body the page did not read: Chromium then
|
||||
// sends no loadingFinished) will not finish any more: forget them.
|
||||
_inFlight.Clear();
|
||||
// sends no loadingFinished) will not finish any more: forget them. The new document itself is kept: the frame
|
||||
// commits it before its body has finished loading (its request id is the frame's loader id).
|
||||
var loader = frame.TryGetProperty("loaderId", out var l) ? l.GetString() : null;
|
||||
foreach (var key in _inFlight.Keys)
|
||||
{
|
||||
if (key != loader && _inFlight.TryRemove(key, out _))
|
||||
{
|
||||
NotifyDropped(key, BodyDropReason.FrameNavigated);
|
||||
}
|
||||
}
|
||||
Publish(frame.TryGetProperty("url", out var u) ? u.GetString() : null, sameDocument: false);
|
||||
}
|
||||
|
||||
@@ -325,64 +428,77 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
|
||||
private async Task WorkAsync(CancellationToken ct)
|
||||
{
|
||||
await foreach (var descriptor in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
|
||||
try
|
||||
{
|
||||
IResponseConsumer[] consumers;
|
||||
lock (_gate)
|
||||
await foreach (var pending in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
consumers = [.. _consumers];
|
||||
}
|
||||
|
||||
if (consumers.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
JsonDocument? document;
|
||||
try
|
||||
{
|
||||
document = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpCommandException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
|
||||
{
|
||||
// The body may already be evicted from the browser's buffer, or the page navigated away.
|
||||
Interlocked.Increment(ref _bodyErrors);
|
||||
_log.Debug($"Cattura: corpo non disponibile ({ex.GetType().Name}).");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (document is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
Interlocked.Increment(ref _jsonBodies);
|
||||
foreach (var consumer in consumers)
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
await consumer.ConsumeAsync(descriptor, document, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn($"Cattura: errore in un lettore ({consumer.GetType().Name}).", ex);
|
||||
}
|
||||
await HandleAsync(pending, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
|
||||
{
|
||||
// One unexpected body must not stop the capture of the following ones. Only the type: the message
|
||||
// of a parsing error may quote the body.
|
||||
_log.Warn($"Cattura: errore imprevisto nella lettura di una risposta ({ex.GetType().Name}).");
|
||||
NotifyDropped(pending.Descriptor.RequestId, BodyDropReason.Unexpected);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<JsonDocument?> FetchBodyAsync(string requestId, CancellationToken ct)
|
||||
/// <summary>Fetches one body and hands it to the consumers; tells the observers once when nothing reached them.</summary>
|
||||
private async Task HandleAsync(PendingBody pending, CancellationToken ct)
|
||||
{
|
||||
var descriptor = pending.Descriptor;
|
||||
IResponseConsumer[] consumers;
|
||||
lock (_gate)
|
||||
{
|
||||
consumers = [.. _consumers];
|
||||
}
|
||||
|
||||
if (consumers.Length == 0)
|
||||
{
|
||||
NotifyDropped(descriptor.RequestId, BodyDropReason.NoConsumers);
|
||||
return;
|
||||
}
|
||||
|
||||
byte[]? bytes;
|
||||
try
|
||||
{
|
||||
bytes = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpCommandException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
|
||||
{
|
||||
// The body may already be evicted from the browser's buffer, or the page navigated away.
|
||||
Interlocked.Increment(ref _bodyErrors);
|
||||
_log.Debug($"Cattura: corpo non disponibile ({ex.GetType().Name}).");
|
||||
NotifyDropped(descriptor.RequestId, ex is TimeoutException ? BodyDropReason.Timeout : BodyDropReason.Unavailable);
|
||||
return;
|
||||
}
|
||||
|
||||
if (bytes is null)
|
||||
{
|
||||
NotifyDropped(descriptor.RequestId, BodyDropReason.Unavailable);
|
||||
return;
|
||||
}
|
||||
|
||||
// The same delivery as the answers the site client asks for (issue #36): captured and requested answers reach
|
||||
// the readers identically.
|
||||
var delivered = pending.IsPageDocument
|
||||
? await _delivery.DeliverDocumentAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false)
|
||||
: await _delivery.DeliverBodyAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false);
|
||||
if (delivered == 0)
|
||||
{
|
||||
NotifyDropped(descriptor.RequestId, pending.IsPageDocument ? BodyDropReason.NoJsonBlock : BodyDropReason.NotJson);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The decoded bytes of a body, or null when the browser gives none or it cannot be decoded.</summary>
|
||||
private async Task<byte[]?> FetchBodyAsync(string requestId, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(_options.BodyTimeout);
|
||||
@@ -402,34 +518,56 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
}
|
||||
|
||||
var encoded = result.TryGetProperty("base64Encoded", out var b) && b.ValueKind == JsonValueKind.True;
|
||||
byte[] bytes;
|
||||
if (encoded)
|
||||
if (!encoded)
|
||||
{
|
||||
if (!body.TryGetBytesFromBase64(out var decoded))
|
||||
{
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
return null;
|
||||
}
|
||||
|
||||
bytes = decoded;
|
||||
}
|
||||
else
|
||||
{
|
||||
bytes = Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
|
||||
return Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
|
||||
}
|
||||
|
||||
try
|
||||
if (!body.TryGetBytesFromBase64(out var decoded))
|
||||
{
|
||||
return JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 256 });
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Declared as JSON but it is not (or has a prefix): readers will be told by the probe in M0.
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
Interlocked.Increment(ref _decodeErrors);
|
||||
return null;
|
||||
}
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
/// <summary>Tells the observers that a body they may be waiting for will not come, and why.</summary>
|
||||
private void NotifyDropped(string requestId, BodyDropReason reason)
|
||||
{
|
||||
foreach (var observer in SnapshotObservers())
|
||||
{
|
||||
try
|
||||
{
|
||||
observer.OnBodyDropped(requestId, reason);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Cattura: errore in un osservatore delle risposte.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tells the observers how many bytes a response took on the network (every response, read or not).</summary>
|
||||
private void NotifyLoadingFinished(string requestId, double encodedBytes)
|
||||
{
|
||||
var bytes = encodedBytes is > 0 and < long.MaxValue ? (long)encodedBytes : 0;
|
||||
foreach (var observer in SnapshotObservers())
|
||||
{
|
||||
try
|
||||
{
|
||||
observer.OnLoadingFinished(requestId, bytes);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Cattura: errore in un osservatore delle risposte.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A body to fetch once its loading has finished.</summary>
|
||||
private sealed record PendingBody(ResponseDescriptor Descriptor, bool IsPageDocument);
|
||||
|
||||
private IResponseObserver[] SnapshotObservers()
|
||||
{
|
||||
lock (_gate)
|
||||
|
||||
@@ -79,4 +79,16 @@ public sealed record GestureSettings
|
||||
|
||||
/// <summary>Length of a distraction.</summary>
|
||||
public Interval DistractionMs { get; init; } = new(15000, 90000);
|
||||
|
||||
/// <summary>Gap between two keys while typing (issue #37), before mood and pace.</summary>
|
||||
public Interval KeyGapMs { get; init; } = new(60, 250, 110);
|
||||
|
||||
/// <summary>How long a key is held down.</summary>
|
||||
public Interval KeyHoldMs { get; init; } = new(40, 120);
|
||||
|
||||
/// <summary>Probability of a short hesitation before a key, as a person who thinks of the next letter.</summary>
|
||||
public double TypingHesitationProbability { get; init; } = 0.03;
|
||||
|
||||
/// <summary>Length of such a hesitation, before mood and pace.</summary>
|
||||
public Interval TypingHesitationMs { get; init; } = new(300, 900);
|
||||
}
|
||||
@@ -239,6 +239,84 @@ public sealed class HumanGestures
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Presses one key with a human hold time, through <c>Input.dispatchKeyEvent</c>; with a real Shift key down and
|
||||
/// up around it when the stroke needs Shift. Throws <see cref="GestureInterruptedException"/> while Alberto drives.
|
||||
/// </summary>
|
||||
public async Task PressKeyAsync(KeyStroke key, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
EnsureUserNotDriving();
|
||||
var shift = (key.Modifiers & KeyModifiers.Shift) != 0;
|
||||
var shiftKey = new KeyStroke("Shift", "ShiftLeft", 16, KeyModifiers.Shift, null);
|
||||
var shiftDown = false;
|
||||
var keyDown = false;
|
||||
try
|
||||
{
|
||||
if (shift)
|
||||
{
|
||||
shiftDown = true;
|
||||
await Keyboard.KeyDownAsync(_cdp, shiftKey, ct).ConfigureAwait(false);
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(Draw(new Interval(30, 90))), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
keyDown = true;
|
||||
await Keyboard.KeyDownAsync(_cdp, key, ct).ConfigureAwait(false);
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(Draw(Settings.KeyHoldMs)), ct).ConfigureAwait(false);
|
||||
await Keyboard.KeyUpAsync(_cdp, key, ct).ConfigureAwait(false);
|
||||
keyDown = false;
|
||||
if (shift)
|
||||
{
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(Draw(new Interval(20, 70))), ct).ConfigureAwait(false);
|
||||
await Keyboard.KeyUpAsync(_cdp, shiftKey with { Modifiers = KeyModifiers.None }, ct).ConfigureAwait(false);
|
||||
shiftDown = false;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
// A cancelled step never leaves a key or Shift down in the page, which goes to the engine or to Alberto next.
|
||||
if (keyDown || shiftDown)
|
||||
{
|
||||
await ReleaseQuietlyAsync(keyDown ? key : null, shiftDown ? shiftKey with { Modifiers = KeyModifiers.None } : null).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReleaseQuietlyAsync(KeyStroke? key, KeyStroke? shiftKey)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (key is not null)
|
||||
{
|
||||
await Keyboard.KeyUpAsync(_cdp, key, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (shiftKey is not null)
|
||||
{
|
||||
await Keyboard.KeyUpAsync(_cdp, shiftKey, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// The browser is gone or restarting: no key stays down in a page that no longer exists.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The gap before the next key while typing: 60–250 ms (median 110) times mood and pace, now and then a short
|
||||
/// hesitation.
|
||||
/// </summary>
|
||||
public async Task TypingGapAsync(CancellationToken ct = default)
|
||||
{
|
||||
var gap = Draw(Settings.KeyGapMs);
|
||||
if (_random.Chance(Settings.TypingHesitationProbability))
|
||||
{
|
||||
gap += Draw(Settings.TypingHesitationMs);
|
||||
}
|
||||
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(gap * Multiplier), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Waits a drawn time from <paramref name="interval"/> (milliseconds), multiplied by mood and pace.</summary>
|
||||
public async Task<TimeSpan> WaitAsync(Interval interval, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Febe.Browser.Gestures;
|
||||
|
||||
/// <summary>
|
||||
/// The closed key map of the profile search (issue #37): the only characters Febe may type into the site's search
|
||||
/// box, each with its full key stroke. Letters a–z, digits, «.», «_» (Shift and Minus, with a real Shift key) and the
|
||||
/// space. There is no path to Enter, Tab or Escape: <see cref="Keyboard.ForText"/>, which maps a line break to Enter,
|
||||
/// is never used by the search.
|
||||
/// </summary>
|
||||
public static class SearchKeyMap
|
||||
{
|
||||
/// <summary>The stroke for <paramref name="c"/>, or null when the search may not type it.</summary>
|
||||
public static KeyStroke? For(char c)
|
||||
{
|
||||
var text = c.ToString(CultureInfo.InvariantCulture);
|
||||
return c switch
|
||||
{
|
||||
>= 'a' and <= 'z' => new KeyStroke(text, "Key" + char.ToUpperInvariant(c).ToString(CultureInfo.InvariantCulture), char.ToUpperInvariant(c), KeyModifiers.None, text),
|
||||
>= '0' and <= '9' => new KeyStroke(text, "Digit" + text, c, KeyModifiers.None, text),
|
||||
'.' => new KeyStroke(".", "Period", 190, KeyModifiers.None, "."),
|
||||
'_' => new KeyStroke("_", "Minus", 189, KeyModifiers.Shift, "_"),
|
||||
' ' => new KeyStroke(" ", "Space", 32, KeyModifiers.None, " "),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>True when every character of <paramref name="text"/> is in the map.</summary>
|
||||
public static bool CanType(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
foreach (var c in text)
|
||||
{
|
||||
if (For(c) is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Backspace: the only key the search uses to erase.</summary>
|
||||
public static KeyStroke Backspace { get; } = Keyboard.Special(SpecialKey.Backspace);
|
||||
|
||||
/// <summary>End: the only key the search uses to move the caret.</summary>
|
||||
public static KeyStroke End { get; } = Keyboard.Special(SpecialKey.End);
|
||||
}
|
||||
@@ -29,7 +29,12 @@ public sealed record ChromiumLaunchOptions
|
||||
/// <summary>Start page: always the rest page.</summary>
|
||||
public string StartUrl { get; init; } = "about:blank";
|
||||
|
||||
public TimeSpan StartupTimeout { get; init; } = TimeSpan.FromSeconds(30);
|
||||
/// <summary>
|
||||
/// How long a Chromium that is alive may take to open its debugging port and its first tab. A crash fails the start
|
||||
/// at once; this only bounds a browser that hangs, so it is generous for a loaded machine (docs/decisioni.md, #46).
|
||||
/// </summary>
|
||||
public TimeSpan StartupTimeout { get; init; } = TimeSpan.FromSeconds(120);
|
||||
|
||||
|
||||
public RestartPolicy Restart { get; init; } = RestartPolicy.Default;
|
||||
|
||||
|
||||
@@ -255,27 +255,37 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
$"La porta di debug {port} non è limitata a 127.0.0.1 ({listeners.Count} punti di ascolto): avvio annullato (specifica §6.1).");
|
||||
}
|
||||
|
||||
await ConnectAsync(port, ct).ConfigureAwait(false);
|
||||
await ConnectAsync(
|
||||
port,
|
||||
deadline,
|
||||
() => process.HasExited ? $"Chromium si è chiuso all'avvio (codice {process.ExitCode}). {_supervisor?.StderrTail()}".TrimEnd() : null,
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ConnectAsync(int port, CancellationToken ct)
|
||||
/// <summary>
|
||||
/// Connects to the first page target. The first tab may appear a while after the port opens on a loaded machine:
|
||||
/// the wait shares the start deadline, and ends at once when <paramref name="gone"/> says the process is no longer the
|
||||
/// one to connect to (it exited, or the supervisor replaced it): nobody waits on the connect lock for a dead browser.
|
||||
/// </summary>
|
||||
private async Task ConnectAsync(int port, DateTimeOffset deadline, Func<string?> gone, CancellationToken ct)
|
||||
{
|
||||
await _connectLock.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
CdpTarget? page = null;
|
||||
for (var attempt = 0; attempt < 50 && page is null; attempt++)
|
||||
CdpTarget? page;
|
||||
while ((page = await TryFindPageAsync(port, ct).ConfigureAwait(false)) is null)
|
||||
{
|
||||
page = await CdpTargetDiscovery.FindPageAsync(port, ct).ConfigureAwait(false);
|
||||
if (page is null)
|
||||
if (gone() is { } reason)
|
||||
{
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
|
||||
throw new InvalidOperationException(reason);
|
||||
}
|
||||
}
|
||||
|
||||
if (page is null)
|
||||
{
|
||||
throw new InvalidOperationException("Chromium non ha nessuna scheda aperta.");
|
||||
if (_clock.Now >= deadline)
|
||||
{
|
||||
throw new InvalidOperationException("Chromium non ha nessuna scheda aperta.");
|
||||
}
|
||||
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var client = await CdpClient.ConnectAsync(page.WebSocketDebuggerUrl, _log, null, ct).ConfigureAwait(false);
|
||||
@@ -304,6 +314,23 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The page target, or null when there is none yet or the endpoint did not answer this time.</summary>
|
||||
private static async Task<CdpTarget?> TryFindPageAsync(int port, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await CdpTargetDiscovery.FindPageAsync(port, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
catch (TaskCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
return null; // a slow answer of /json/list, not a missing one
|
||||
}
|
||||
}
|
||||
|
||||
private void OnClientDisconnected(object? sender, Exception? reason)
|
||||
{
|
||||
if (Volatile.Read(ref _stopping) == 1 || Volatile.Read(ref _restarting) == 1 || !ReferenceEquals(sender, Volatile.Read(ref _client)))
|
||||
@@ -330,11 +357,19 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
return;
|
||||
}
|
||||
|
||||
for (var attempt = 0; attempt < 3; attempt++)
|
||||
// The process that dropped the connection: if it exits or the supervisor restarts it, stop at once and leave
|
||||
// the connect lock to the restart, which connects by itself.
|
||||
var processId = supervisor.ProcessId;
|
||||
string? Gone() => supervisor.State != SupervisedState.Running || supervisor.ProcessId != processId
|
||||
? "Chromium è stato riavviato o si è chiuso durante il ricollegamento."
|
||||
: null;
|
||||
|
||||
var deadline = _clock.Now + _launch.StartupTimeout;
|
||||
for (var attempt = 0; attempt < 3 && Gone() is null; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ConnectAsync(_options.DebugPort, ct).ConfigureAwait(false);
|
||||
await ConnectAsync(_options.DebugPort, deadline, Gone, ct).ConfigureAwait(false);
|
||||
_log.Info("Collegamento con Chromium ripristinato.");
|
||||
return;
|
||||
}
|
||||
@@ -344,6 +379,11 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
}
|
||||
}
|
||||
|
||||
if (Gone() is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_log.Warn("Collegamento con Chromium perso: riavvio del browser.");
|
||||
supervisor.KillCurrent();
|
||||
}
|
||||
|
||||
@@ -38,7 +38,12 @@ public sealed record BrowserDriverOptions
|
||||
/// read-only state with <c>Runtime.evaluate</c>, targets found with the target map and clicked with human gestures
|
||||
/// through <c>Input</c>, wheel bursts, and the rest page. It never opens an address outside the site.
|
||||
/// </summary>
|
||||
public sealed class BrowserPageDriver : IPageDriver
|
||||
/// <remarks>
|
||||
/// As <see cref="ISearchInput"/> it types into the site's search box for the profile search (issue #37): the focus
|
||||
/// check is one read-only <c>Runtime.evaluate</c> that never returns the text, and keys come only from the closed
|
||||
/// <see cref="SearchKeyMap"/>.
|
||||
/// </remarks>
|
||||
public sealed class BrowserPageDriver : IPageDriver, ISearchInput
|
||||
{
|
||||
/// <summary>Read-only: the page has loaded and painted (input before the first paint is ignored by Chromium).</summary>
|
||||
private const string ReadyExpression =
|
||||
@@ -190,6 +195,52 @@ public sealed class BrowserPageDriver : IPageDriver
|
||||
|
||||
public Task RestAsync(CancellationToken ct) => _cdp.RestAsync(ct);
|
||||
|
||||
public async Task<SearchFocus> FocusAsync(CancellationToken ct)
|
||||
{
|
||||
var (found, focused, length, atEnd) = await _resolver.FocusAsync(SiteTargets.SearchBox, ct).ConfigureAwait(false);
|
||||
return found ? new SearchFocus(true, focused, length, atEnd) : SearchFocus.None;
|
||||
}
|
||||
|
||||
public Task EndKeyAsync(CancellationToken ct) => _gestures.PressKeyAsync(SearchKeyMap.End, ct);
|
||||
|
||||
public async Task EraseAsync(int count, Action? beforeKey, CancellationToken ct)
|
||||
{
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
await _gestures.TypingGapAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
beforeKey?.Invoke();
|
||||
await _gestures.PressKeyAsync(SearchKeyMap.Backspace, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<int> TypeAsync(Func<int, CancellationToken, ValueTask<char?>> next, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(next);
|
||||
var typed = 0;
|
||||
while (true)
|
||||
{
|
||||
if (typed > 0)
|
||||
{
|
||||
await _gestures.TypingGapAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The checks of the caller run right before the key they allow.
|
||||
if (await next(typed, ct).ConfigureAwait(false) is not { } c)
|
||||
{
|
||||
return typed;
|
||||
}
|
||||
|
||||
// A second line behind the text rules of Core: a character outside the map is never sent.
|
||||
var stroke = SearchKeyMap.For(c) ?? throw new ArgumentException("Carattere che la ricerca non scrive.", nameof(next));
|
||||
await _gestures.PressKeyAsync(stroke, ct).ConfigureAwait(false);
|
||||
typed++;
|
||||
}
|
||||
}
|
||||
|
||||
private (HumanGestures, TargetActions) CreateGestures(double mood)
|
||||
{
|
||||
var gestures = new HumanGestures(_cdp, _clock, _random, mood, _options.Pace, _options.UserIsDriving, _options.Gestures);
|
||||
|
||||
@@ -5,9 +5,11 @@ using Febe.Browser.Hosting;
|
||||
using Febe.Browser.Targets;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Library;
|
||||
@@ -23,8 +25,8 @@ namespace Febe.Browser.Recipes;
|
||||
public sealed record CollectionSite(string Name, string BaseUrl, HostClassifier Hosts, SessionCookieOptions SessionCookie)
|
||||
{
|
||||
/// <summary>
|
||||
/// Instagram. Its target map and reader vocabulary are still skeletons until M0: every recipe refuses to run and
|
||||
/// says why, without touching the site.
|
||||
/// Instagram. Its reader vocabulary is confirmed on real cleaned samples and its map has the pages seen in real
|
||||
/// traffic, not yet the targets: a recipe that needs a target refuses to run and says why, without touching the site.
|
||||
/// </summary>
|
||||
public static CollectionSite Instagram { get; } = new("instagram", "https://www.instagram.com", HostClassifier.Instagram, SessionCookieOptions.Instagram);
|
||||
|
||||
@@ -84,6 +86,24 @@ public sealed record CollectionPipelineOptions
|
||||
public Func<bool>? UserOwnsPage { get; init; }
|
||||
|
||||
public IBrowserLog? Log { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The recorder of the diagnostic report (issue #39): it observes the responses of the page, the readers, the
|
||||
/// recipes, the stop signals and the download queue. Null: nothing is recorded.
|
||||
/// </summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The turns of the one page shared by the recipes and the profile search (issue #37). Null: no profile search
|
||||
/// (the pipeline builds no search runner).
|
||||
/// </summary>
|
||||
public PageTurns? PageTurns { get; init; }
|
||||
|
||||
/// <summary>Times and bounds of the profile search.</summary>
|
||||
public ProfileSearchOptions SearchOptions { get; init; } = ProfileSearchOptions.Default;
|
||||
|
||||
/// <summary>Where the photos of the search results are kept (memory). Null: the search fetches no photo.</summary>
|
||||
public SearchPhotoCache? SearchPhotos { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -94,8 +114,10 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
{
|
||||
private readonly List<IDisposable> _subscriptions = [];
|
||||
|
||||
private CollectionPipeline(ResponseTap tap, SignalDetector signals, CaptureCollector capture, BrowserPageDriver driver, RecipeRunner runner, DownloadQueue downloads, SiteMap siteMap, TargetMap targets)
|
||||
private CollectionPipeline(ResponseTap tap, SignalDetector signals, CaptureCollector capture, BrowserPageDriver driver, RecipeRunner runner, DownloadQueue downloads, SiteMap siteMap, TargetMap targets, ProfileSearchRunner? search, SearchPhotoQueue? searchPhotos)
|
||||
{
|
||||
Search = search;
|
||||
SearchPhotos = searchPhotos;
|
||||
Tap = tap;
|
||||
Signals = signals;
|
||||
Capture = capture;
|
||||
@@ -119,6 +141,12 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
|
||||
public DownloadQueue Downloads { get; }
|
||||
|
||||
/// <summary>The browser half of the profile search (issue #37); null without <see cref="CollectionPipelineOptions.PageTurns"/>.</summary>
|
||||
public ProfileSearchRunner? Search { get; }
|
||||
|
||||
/// <summary>The photo queue of the profile search; null without a photo cache.</summary>
|
||||
public SearchPhotoQueue? SearchPhotos { get; }
|
||||
|
||||
public SiteMap SiteMap { get; }
|
||||
|
||||
public TargetMap Targets { get; }
|
||||
@@ -138,7 +166,8 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
|
||||
var tap = new ResponseTap(options.Cdp, site.Hosts, options.Clock, options.Log);
|
||||
var signals = new SignalDetector(rules, options.Breaker, options.Clock) { UserOwnsPage = options.UserOwnsPage };
|
||||
var capture = new CaptureCollector(new ShapeReader(vocabulary), options.Clock);
|
||||
var diagnostics = options.Diagnostics;
|
||||
var capture = new CaptureCollector(new ShapeReader(vocabulary), options.Clock) { Diagnostics = diagnostics };
|
||||
var driver = new BrowserPageDriver(options.Cdp, targets, site.Hosts, options.Clock, options.Random, new BrowserDriverOptions
|
||||
{
|
||||
SiteBaseUrl = site.BaseUrl,
|
||||
@@ -160,22 +189,75 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
DataBudget = options.DataBudget,
|
||||
Breaker = options.Breaker,
|
||||
Options = options.Recipes,
|
||||
Diagnostics = diagnostics,
|
||||
PageTurns = options.PageTurns,
|
||||
});
|
||||
var fetcher = new BrowserFileFetcher(options.Cdp, site.Hosts, options.Log);
|
||||
var downloads = new DownloadQueue(
|
||||
options.Storage,
|
||||
options.Ingest,
|
||||
new BrowserFileFetcher(options.Cdp, site.Hosts, options.Log),
|
||||
fetcher,
|
||||
options.DataBudget,
|
||||
options.Clock,
|
||||
options.Random,
|
||||
new DownloadOptions { StagingFolder = options.StagingFolder },
|
||||
signals);
|
||||
|
||||
var pipeline = new CollectionPipeline(tap, signals, capture, driver, runner, downloads, siteMap, targets);
|
||||
ProfileSearchRunner? search = null;
|
||||
SearchPhotoQueue? searchPhotos = null;
|
||||
if (options.PageTurns is { } turns)
|
||||
{
|
||||
search = new ProfileSearchRunner(
|
||||
driver,
|
||||
driver,
|
||||
capture,
|
||||
siteMap,
|
||||
options.Governor,
|
||||
signals,
|
||||
options.Breaker,
|
||||
options.Clock,
|
||||
options.Random,
|
||||
turns,
|
||||
options.SearchOptions,
|
||||
options.UserIsDriving,
|
||||
diagnostics);
|
||||
if (options.SearchPhotos is { } photos)
|
||||
{
|
||||
// Photos only while the page is on the site: from the rest page the browser may block the CDN (H7).
|
||||
searchPhotos = new SearchPhotoQueue(
|
||||
photos,
|
||||
fetcher,
|
||||
options.Governor,
|
||||
options.DataBudget,
|
||||
options.Breaker,
|
||||
options.Clock,
|
||||
options.Random,
|
||||
options.SearchOptions,
|
||||
signals,
|
||||
() => turns.LastUser is not null)
|
||||
{
|
||||
Diagnostics = diagnostics,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
var pipeline = new CollectionPipeline(tap, signals, capture, driver, runner, downloads, siteMap, targets, search, searchPhotos);
|
||||
pipeline._subscriptions.Add(tap.AddObserver(signals));
|
||||
pipeline._subscriptions.Add(tap.AddConsumer(signals));
|
||||
pipeline._subscriptions.Add(tap.AddObserver(capture));
|
||||
pipeline._subscriptions.Add(tap.AddConsumer(capture));
|
||||
if (diagnostics is not null)
|
||||
{
|
||||
diagnostics.SiteMap = siteMap;
|
||||
pipeline._subscriptions.Add(tap.AddObserver(diagnostics));
|
||||
EventHandler<Signal> signalRaised = (_, signal) => diagnostics.SignalRaised(signal);
|
||||
signals.SignalRaised += signalRaised;
|
||||
pipeline._subscriptions.Add(new Unsubscribe(() => signals.SignalRaised -= signalRaised));
|
||||
EventHandler<DownloadProgress> progress = (_, step) => diagnostics.DownloadSettled(step);
|
||||
downloads.Progress += progress;
|
||||
pipeline._subscriptions.Add(new Unsubscribe(() => downloads.Progress -= progress));
|
||||
}
|
||||
|
||||
await tap.StartAsync(ct).ConfigureAwait(false);
|
||||
return pipeline;
|
||||
}
|
||||
@@ -187,6 +269,16 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
subscription.Dispose();
|
||||
}
|
||||
|
||||
if (SearchPhotos is not null)
|
||||
{
|
||||
await SearchPhotos.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Tap.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private sealed class Unsubscribe(Action action) : IDisposable
|
||||
{
|
||||
public void Dispose() => action();
|
||||
}
|
||||
}
|
||||
@@ -139,6 +139,39 @@ public sealed class TargetResolver
|
||||
};
|
||||
const nameRe = spec.name ? new RegExp(spec.name, 'i') : null;
|
||||
const hrefRe = spec.href ? new RegExp(spec.href, 'i') : null;
|
||||
if (spec.focus) {
|
||||
// The focus check of the search box (issue #37): whether the focus is in the box, how many characters it
|
||||
// holds and whether the caret is at the end. Never its text, and nothing about any other field.
|
||||
const boxes = [];
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
const role = roleOf(el);
|
||||
if (spec.roles.length > 0 && !spec.roles.includes(role)) continue;
|
||||
if (nameRe && !nameRe.test(nameOf(el, role))) continue;
|
||||
const r = el.getBoundingClientRect();
|
||||
let shown = r.width > 0 && r.height > 0;
|
||||
if (shown && typeof el.checkVisibility === 'function') {
|
||||
shown = el.checkVisibility({ opacityProperty: true, visibilityProperty: true });
|
||||
}
|
||||
if (shown) boxes.push(el);
|
||||
if (boxes.length >= 50) break;
|
||||
}
|
||||
const at = spec.index < 0 ? boxes.length + spec.index : spec.index;
|
||||
const box = at >= 0 && at < boxes.length ? boxes[at] : null;
|
||||
if (!box) return { found: false, focused: false, length: null, atEnd: false };
|
||||
const active = document.activeElement;
|
||||
const inBox = !!active && (active === box || box.contains(active));
|
||||
let length = null;
|
||||
let atEnd = false;
|
||||
if (inBox) {
|
||||
const tag = active.tagName.toLowerCase();
|
||||
const type = (active.getAttribute('type') || '').toLowerCase();
|
||||
if ((tag === 'input' && type !== 'password') || tag === 'textarea') {
|
||||
length = active.value.length;
|
||||
atEnd = active.selectionStart === length && active.selectionEnd === length;
|
||||
}
|
||||
}
|
||||
return { found: true, focused: inBox, length, atEnd };
|
||||
}
|
||||
const candidates = document.querySelectorAll(hrefRe ? 'a[href], area[href]' : '*');
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
@@ -241,6 +274,45 @@ public sealed class TargetResolver
|
||||
return Script.Replace("__SPEC__", json.ToJsonString(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The read-only focus check of a text box target (issue #37): the same role and name query as
|
||||
/// <see cref="BuildExpression"/>, answering only «found, focused, length, caret at the end», never the text.
|
||||
/// </summary>
|
||||
public static string BuildFocusExpression(TargetSpec spec)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
var json = new JsonObject
|
||||
{
|
||||
["roles"] = new JsonArray([.. spec.Roles.Select(r => (JsonNode?)JsonValue.Create(r))]),
|
||||
["name"] = spec.NamePattern is null ? null : TargetMap.ExpandNamePattern(spec.NamePattern, null),
|
||||
["href"] = null,
|
||||
["index"] = spec.Index,
|
||||
["focus"] = true,
|
||||
};
|
||||
return Script.Replace("__SPEC__", json.ToJsonString(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Runs the focus check of <paramref name="id"/>; a target not configured is never looked up.</summary>
|
||||
public async Task<(bool Found, bool Focused, int? Length, bool AtEnd)> FocusAsync(string id, CancellationToken ct = default)
|
||||
{
|
||||
if (!_map.Contains(id) || _map.Get(id) is not { IsConfigured: true } spec)
|
||||
{
|
||||
return (false, false, null, false);
|
||||
}
|
||||
|
||||
var value = await _cdp.EvaluateAsync(BuildFocusExpression(spec), ct).ConfigureAwait(false);
|
||||
if (value.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return (false, false, null, false);
|
||||
}
|
||||
|
||||
var found = value.TryGetProperty("found", out var f) && f.ValueKind == JsonValueKind.True;
|
||||
var focused = found && value.TryGetProperty("focused", out var g) && g.ValueKind == JsonValueKind.True;
|
||||
int? length = focused && value.TryGetProperty("length", out var l) && l.ValueKind == JsonValueKind.Number && l.TryGetInt32(out var n) ? n : null;
|
||||
var atEnd = focused && value.TryGetProperty("atEnd", out var e) && e.ValueKind == JsonValueKind.True;
|
||||
return (found, focused, length, atEnd);
|
||||
}
|
||||
|
||||
private async Task<(List<TargetElement> All, double Width, double Height)> MeasureAsync(TargetSpec spec, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
|
||||
{
|
||||
var value = await _cdp.EvaluateAsync(BuildExpression(spec, parameters), ct).ConfigureAwait(false);
|
||||
|
||||
@@ -24,6 +24,13 @@ public enum ActionKind
|
||||
/// <summary>One page of the list of profiles Alberto follows.</summary>
|
||||
FollowingListPage,
|
||||
|
||||
/// <summary>
|
||||
/// One step of the profile search toward the site: opening Instagram for the search, opening its «Cerca» panel or
|
||||
/// focusing its box, or one burst of typing (issue #37). Outside sessions, with its own wide budget that does not
|
||||
/// consume the collection budgets.
|
||||
/// </summary>
|
||||
ProfileSearch,
|
||||
|
||||
/// <summary>Bytes downloaded from the CDN (daily byte budget).</summary>
|
||||
DataDownload,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>One configuration file of the collection as it was loaded.</summary>
|
||||
/// <param name="Name">File name: <c>lettori.instagram.json</c>, <c>bersagli.instagram.json</c>.</param>
|
||||
/// <param name="OverridePath">The editable copy in the Data folder that was loaded; null for the copy embedded in Febe.</param>
|
||||
/// <param name="Text">Its content (for the fingerprint only: never logged).</param>
|
||||
public sealed record CollectionConfigurationFile(string Name, string? OverridePath, string Text)
|
||||
{
|
||||
public bool IsOverride => OverridePath is not null;
|
||||
|
||||
/// <summary>Where it came from, in Italian, for the log: never what is in it.</summary>
|
||||
public string Origin => OverridePath is { } path
|
||||
? $"la copia nella cartella dei dati ({path})"
|
||||
: $"il file incorporato in Febe ({Name})";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The reader vocabulary and target map one site runs on, as the collection pipeline loaded them: where each came from
|
||||
/// (the copy embedded in Febe, or an editable copy in the Data folder, which always wins), its state, the recipes they
|
||||
/// leave unable to run, and a fingerprint of their content. The engine clears the suspensions of the recipes when the
|
||||
/// fingerprint changes (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>). Nothing here comes from the site.
|
||||
/// </summary>
|
||||
public sealed class CollectionConfiguration
|
||||
{
|
||||
private CollectionConfiguration(
|
||||
string site,
|
||||
ReaderVocabulary vocabulary,
|
||||
SiteMap map,
|
||||
CollectionConfigurationFile vocabularyFile,
|
||||
CollectionConfigurationFile mapFile,
|
||||
ReaderVocabulary? embeddedVocabulary,
|
||||
SiteMap? embeddedMap)
|
||||
{
|
||||
Site = site;
|
||||
Vocabulary = vocabulary;
|
||||
Map = map;
|
||||
VocabularyFile = vocabularyFile;
|
||||
MapFile = mapFile;
|
||||
EmbeddedVocabulary = embeddedVocabulary;
|
||||
EmbeddedMap = embeddedMap;
|
||||
Blocked = BlockedBy(map, vocabulary);
|
||||
Fingerprint = FingerprintOf(site, vocabularyFile, mapFile);
|
||||
}
|
||||
|
||||
/// <summary>The site name of the files (<c>instagram</c>, <c>prova</c>).</summary>
|
||||
public string Site { get; }
|
||||
|
||||
public ReaderVocabulary Vocabulary { get; }
|
||||
|
||||
public SiteMap Map { get; }
|
||||
|
||||
public CollectionConfigurationFile VocabularyFile { get; }
|
||||
|
||||
public CollectionConfigurationFile MapFile { get; }
|
||||
|
||||
/// <summary>The vocabulary embedded in Febe, when there is one (the same as <see cref="Vocabulary"/> without a copy).</summary>
|
||||
public ReaderVocabulary? EmbeddedVocabulary { get; }
|
||||
|
||||
/// <summary>The map embedded in Febe, when there is one (the same as <see cref="Map"/> without a copy).</summary>
|
||||
public SiteMap? EmbeddedMap { get; }
|
||||
|
||||
/// <summary>Recipes these files do not let run (<see cref="RecipeStatus.NotConfigured"/>), in the order of <see cref="RecipeKind"/>.</summary>
|
||||
public IReadOnlyList<RecipeKind> Blocked { get; }
|
||||
|
||||
/// <summary>SHA-256 of the two files as loaded (lower-case hexadecimal), line endings aside.</summary>
|
||||
public string Fingerprint { get; }
|
||||
|
||||
/// <summary>What the log says at start-up: where each file came from and in what state, and what cannot run.</summary>
|
||||
public IReadOnlyList<string> Lines
|
||||
{
|
||||
get
|
||||
{
|
||||
var all = Enum.GetValues<RecipeKind>().Length;
|
||||
var vocabularyState = Vocabulary.Status == VocabularyStatus.Confirmed ? "confermato" : "ipotesi";
|
||||
if (Vocabulary.MissingConcepts.Count > 0)
|
||||
{
|
||||
vocabularyState += $", {Vocabulary.MissingConcepts.Count.ToString(CultureInfo.InvariantCulture)} concetti ancora senza chiavi";
|
||||
}
|
||||
|
||||
var missing = Map.Missing(SitePages.All, SiteTargets.All).Count;
|
||||
var mapState = missing == 0 ? "tutte le voci compilate" : $"{missing.ToString(CultureInfo.InvariantCulture)} voci vuote o assenti";
|
||||
return
|
||||
[
|
||||
$"Vocabolario dei lettori per «{Site}»: {VocabularyFile.Origin}, {vocabularyState}.",
|
||||
$"Mappa dei bersagli per «{Site}»: {MapFile.Origin}, {mapState}.",
|
||||
Blocked.Count == 0
|
||||
? "Con questa configurazione tutte le ricette possono girare."
|
||||
: $"Con questa configurazione non possono girare {Blocked.Count.ToString(CultureInfo.InvariantCulture)} ricette su {all.ToString(CultureInfo.InvariantCulture)}: {Names(Blocked)}.",
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A copy in the Data folder that hides a better embedded file: a vocabulary still «ipotesi» while the embedded one
|
||||
/// is «confermato», or a map that leaves recipes unable to run that the embedded one lets run. A stale copy would
|
||||
/// otherwise keep the new files of an update from ever being used.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Warnings
|
||||
{
|
||||
get
|
||||
{
|
||||
var warnings = new List<string>();
|
||||
if (VocabularyFile.IsOverride && EmbeddedVocabulary is { } embedded
|
||||
&& Vocabulary.Status == VocabularyStatus.Hypothesis && embedded.Status == VocabularyStatus.Confirmed)
|
||||
{
|
||||
warnings.Add($"Il vocabolario dei lettori in {VocabularyFile.OverridePath} è ancora un'ipotesi, mentre quello incorporato in Febe è confermato: la copia nella cartella dei dati nasconde quello nuovo. Toglila (o aggiornala) e riavvia Febe.");
|
||||
}
|
||||
|
||||
if (MapFile.IsOverride && EmbeddedMap is { } embeddedMap)
|
||||
{
|
||||
var hidden = MissingFrom(Map).Except(MissingFrom(embeddedMap)).ToList();
|
||||
if (hidden.Count > 0)
|
||||
{
|
||||
warnings.Add($"La mappa dei bersagli in {MapFile.OverridePath} lascia ferme ricette che con quella incorporata in Febe potrebbero girare ({Names(hidden)}): la copia nella cartella dei dati nasconde quella nuova. Toglila (o aggiornala) e riavvia Febe.");
|
||||
}
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes what was loaded for <paramref name="site"/>: <paramref name="vocabulary"/> and <paramref name="map"/>
|
||||
/// as the pipeline loaded them (their <c>Source</c> tells a Data-folder copy from the embedded file). The text of a
|
||||
/// copy is read again from its path for the fingerprint.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">A copy in the Data folder cannot be read any more.</exception>
|
||||
public static CollectionConfiguration Describe(string site, ReaderVocabulary vocabulary, SiteMap map)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(site);
|
||||
ArgumentNullException.ThrowIfNull(vocabulary);
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
var vocabularyFile = LoadedFile($"lettori.{site}.json", vocabulary.Source);
|
||||
var mapFile = LoadedFile($"bersagli.{site}.json", map.Source);
|
||||
var embeddedVocabulary = vocabularyFile.IsOverride ? Try(() => ReaderVocabulary.LoadEmbedded(vocabularyFile.Name)) : vocabulary;
|
||||
var embeddedMap = mapFile.IsOverride ? Try(() => SiteMap.LoadEmbedded(mapFile.Name)) : map;
|
||||
return new CollectionConfiguration(site, vocabulary, map, vocabularyFile, mapFile, embeddedVocabulary, embeddedMap);
|
||||
}
|
||||
|
||||
/// <summary>The recipes a map and a vocabulary do not let run, by the same rule as the runner's.</summary>
|
||||
public static IReadOnlyList<RecipeKind> BlockedBy(SiteMap map, ReaderVocabulary vocabulary)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
ArgumentNullException.ThrowIfNull(vocabulary);
|
||||
return vocabulary.IsUsable ? MissingFrom(map) : Enum.GetValues<RecipeKind>();
|
||||
}
|
||||
|
||||
/// <summary>The recipes whose pages or targets the map lacks, whatever the vocabulary.</summary>
|
||||
private static RecipeKind[] MissingFrom(SiteMap map) =>
|
||||
[.. Enum.GetValues<RecipeKind>().Where(kind =>
|
||||
{
|
||||
var (pages, targets) = RecipeRunner.Requirements(kind);
|
||||
return map.Missing(pages, targets).Count > 0;
|
||||
})];
|
||||
|
||||
private static CollectionConfigurationFile LoadedFile(string name, string? source)
|
||||
{
|
||||
if (source is { Length: > 0 } path && !string.Equals(path, name, StringComparison.Ordinal))
|
||||
{
|
||||
return new CollectionConfigurationFile(name, path, File.ReadAllText(path));
|
||||
}
|
||||
|
||||
return new CollectionConfigurationFile(name, null, SiteMap.ReadEmbeddedText(name));
|
||||
}
|
||||
|
||||
private static T? Try<T>(Func<T> load)
|
||||
where T : class
|
||||
{
|
||||
try
|
||||
{
|
||||
return load();
|
||||
}
|
||||
catch (Exception ex) when (ex is FileNotFoundException or InvalidDataException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string FingerprintOf(string site, CollectionConfigurationFile vocabulary, CollectionConfigurationFile map)
|
||||
{
|
||||
static string Normalized(string text) => text.Replace("\r\n", "\n", StringComparison.Ordinal);
|
||||
var text = string.Join('\n', site, vocabulary.Name, Normalized(vocabulary.Text), map.Name, Normalized(map.Text));
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
|
||||
}
|
||||
|
||||
private static string Names(IEnumerable<RecipeKind> kinds) => string.Join(", ", kinds.Select(RecipeRunner.Name));
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// Which responses of the page carry data worth reading (spec §6.2), decided from what the browser declares about
|
||||
/// them, never from the address.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Instagram serves its GraphQL data (<c>/graphql/query</c>, <c>/api/graphql</c>) as <c>text/javascript</c>, and only
|
||||
/// the REST answers (<c>/api/v1/...</c>) as <c>application/json</c> (HAR of Alberto's browser, 21 October 2026). A
|
||||
/// JavaScript type counts only when the page itself fetched it (XHR, Fetch): script files are never parsed.
|
||||
/// </remarks>
|
||||
public static partial class DataResponses
|
||||
{
|
||||
/// <summary>Largest page document whose embedded data is read.</summary>
|
||||
public const int MaxDocumentChars = 16 * 1024 * 1024;
|
||||
|
||||
private static readonly JsonDocumentOptions BlockOptions = new() { MaxDepth = 256 };
|
||||
|
||||
/// <summary>True for a body worth parsing as JSON data.</summary>
|
||||
/// <param name="mimeType">Declared MIME type, without parameters.</param>
|
||||
/// <param name="resourceType">Browser resource type (Document, XHR, Fetch, Script...), when known.</param>
|
||||
public static bool IsData(string mimeType, string? resourceType)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mimeType);
|
||||
if (mimeType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return mimeType.Contains("javascript", StringComparison.OrdinalIgnoreCase)
|
||||
&& resourceType is not null
|
||||
&& (resourceType.Equals("XHR", StringComparison.OrdinalIgnoreCase) || resourceType.Equals("Fetch", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>True for an HTML document of the main frame: the data it embeds is read too (<see cref="EmbeddedJsonBlocks"/>).</summary>
|
||||
public static bool IsPageDocument(string mimeType, bool isMainFrameDocument) =>
|
||||
isMainFrameDocument && mimeType.Equals("text/html", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// The JSON blocks a page embeds in <c><script type="application/json"></c> elements, one parsed document per
|
||||
/// block, in document order; none when there is none. Blocks that are not valid JSON are left out.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Single-page sites put the data of the first screen in the document itself and fetch only the following pages:
|
||||
/// without this, the first page of a profile opened by address would arrive «empty». The reader recognizes the data by
|
||||
/// shape wherever it sits inside a block (spec §6.4).
|
||||
/// <para>
|
||||
/// Every block is an answer of its own and is read on its own, like a response: joined to the others, the
|
||||
/// pagination of one block (collections that say «has_next_page» of themselves, a post that says
|
||||
/// «more_available: false» of itself) would end up on the items of another and end a walk early. The blocks are
|
||||
/// parsed lazily, one per step of the enumeration: the caller disposes each before taking the next, so a large
|
||||
/// document never has all its blocks in memory at once.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static IEnumerable<JsonDocument> EmbeddedJsonBlocks(string html)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(html);
|
||||
return html.Length > MaxDocumentChars ? [] : Blocks(html);
|
||||
}
|
||||
|
||||
private static IEnumerable<JsonDocument> Blocks(string html)
|
||||
{
|
||||
for (var match = NextBlock(html, previous: null); match is not null; match = NextBlock(html, match))
|
||||
{
|
||||
var body = match.Groups["body"];
|
||||
if (TryParse(html.AsMemory(body.Index, body.Length)) is { } block)
|
||||
{
|
||||
yield return block;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The block element after <paramref name="previous"/> (the first one when null), or null at the end.</summary>
|
||||
private static Match? NextBlock(string html, Match? previous)
|
||||
{
|
||||
try
|
||||
{
|
||||
var match = previous is null ? JsonScript().Match(html) : previous.NextMatch();
|
||||
return match.Success ? match : null;
|
||||
}
|
||||
catch (RegexMatchTimeoutException)
|
||||
{
|
||||
// A pathological document: the blocks found so far have been given, the rest is left out.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonDocument? TryParse(ReadOnlyMemory<char> text)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonDocument.Parse(text, BlockOptions);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException)
|
||||
{
|
||||
// Not JSON, or too deep; ArgumentException: text that is not valid UTF-16 (a lone surrogate). Left out.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex("""<script\b[^>]*?\btype\s*=\s*["']?application/json["']?[^>]*>(?<body>.*?)</script\s*>""", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 5000)]
|
||||
private static partial Regex JsonScript();
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Collection.Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// What <see cref="DiagnosticLog.ReadAll"/> found: the traces, oldest first, how many lines were damaged, and how many
|
||||
/// day files could not be opened or read at all (held by another program, a read error of the disk, no permission).
|
||||
/// </summary>
|
||||
public sealed record DiagnosticLogContents(IReadOnlyList<SessionTrace> Traces, int DamagedLines, int UnreadableFiles = 0);
|
||||
|
||||
/// <summary>
|
||||
/// The finished traces of the diagnostic report (issue #39), one JSON line each, in
|
||||
/// <c>Dati/diagnostica/sessioni-AAAA-MM-GG.jsonl</c> by local day of the start of the trace. Kept
|
||||
/// <see cref="DefaultDays"/> days: older files of its own folder (and only those, by their name) are deleted when a
|
||||
/// line is written or the log is read. Each line is written whole and flushed; a damaged line (a stop in the middle
|
||||
/// of a write) is skipped and counted when reading, and so is a file that cannot be read. A session in progress also
|
||||
/// has lines of its own (its start, then checkpoints): when reading, a trace found more than once (same session and
|
||||
/// start) is kept once, the finished line over the ones in progress, else the last one. Thread-safe.
|
||||
/// </summary>
|
||||
public sealed class DiagnosticLog
|
||||
{
|
||||
/// <summary>Days kept, today included.</summary>
|
||||
public const int DefaultDays = 14;
|
||||
|
||||
private const string Prefix = "sessioni-";
|
||||
private const string Extension = ".jsonl";
|
||||
private const string DayFormat = "yyyy-MM-dd";
|
||||
|
||||
private readonly IClock _clock;
|
||||
private readonly Lock _gate = new();
|
||||
private DateOnly? _retentionDay;
|
||||
|
||||
public DiagnosticLog(string folder, IClock clock, int days = DefaultDays)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(days, 1);
|
||||
Folder = Path.GetFullPath(folder);
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
Days = days;
|
||||
}
|
||||
|
||||
public string Folder { get; }
|
||||
|
||||
public int Days { get; }
|
||||
|
||||
/// <summary>Name of the file of a local day.</summary>
|
||||
public static string FileNameFor(DateOnly day) => Prefix + day.ToString(DayFormat, CultureInfo.InvariantCulture) + Extension;
|
||||
|
||||
/// <summary>Appends one finished trace to the file of the local day of its start.</summary>
|
||||
public void Append(SessionTrace trace)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(trace);
|
||||
var line = JsonSerializer.Serialize(trace, DiagnosticsJsonContext.Default.SessionTrace);
|
||||
var bytes = Encoding.UTF8.GetBytes(line + "\n");
|
||||
var day = LocalCalendar.Today(trace.Start, _clock.LocalZone);
|
||||
lock (_gate)
|
||||
{
|
||||
Directory.CreateDirectory(Folder);
|
||||
ApplyRetention(force: false);
|
||||
using var stream = new FileStream(Path.Combine(Folder, FileNameFor(day)), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
|
||||
if (stream.Length > 0)
|
||||
{
|
||||
// A stop in the middle of a write leaves a line without its end: start on a new line, so that only
|
||||
// the damaged line is lost and not this one too.
|
||||
stream.Seek(-1, SeekOrigin.End);
|
||||
if (stream.ReadByte() != '\n')
|
||||
{
|
||||
stream.WriteByte((byte)'\n');
|
||||
}
|
||||
}
|
||||
|
||||
stream.Seek(0, SeekOrigin.End);
|
||||
stream.Write(bytes);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when a trace that started at <paramref name="start"/> is among the days kept.</summary>
|
||||
public bool Keeps(DateTimeOffset start) => LocalCalendar.Today(start, _clock.LocalZone) >= FirstDayKept();
|
||||
|
||||
/// <summary>
|
||||
/// Every trace of the days kept, oldest first, once each (see the class); damaged lines and unreadable files are
|
||||
/// skipped and counted.
|
||||
/// </summary>
|
||||
public DiagnosticLogContents ReadAll()
|
||||
{
|
||||
var traces = new List<SessionTrace>();
|
||||
var damaged = 0;
|
||||
var unreadable = 0;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!Directory.Exists(Folder))
|
||||
{
|
||||
return new DiagnosticLogContents([], 0);
|
||||
}
|
||||
|
||||
ApplyRetention(force: true);
|
||||
var first = FirstDayKept();
|
||||
foreach (var (day, path) in Files().Where(f => f.Day >= first).OrderBy(f => f.Day))
|
||||
{
|
||||
string[] lines;
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
lines = reader.ReadToEnd().Split('\n');
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// One file only: the others are still read, and the report says that one is missing.
|
||||
unreadable++;
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var raw in lines)
|
||||
{
|
||||
var line = raw.Trim();
|
||||
if (line.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (JsonSerializer.Deserialize(line, DiagnosticsJsonContext.Default.SessionTrace) is { } trace)
|
||||
{
|
||||
traces.Add(trace);
|
||||
}
|
||||
else
|
||||
{
|
||||
damaged++;
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
damaged++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new DiagnosticLogContents([.. Latest(traces).OrderBy(t => t.Start)], damaged, unreadable);
|
||||
}
|
||||
|
||||
/// <summary>One trace per session and start: the finished one if there is one, else the last line written.</summary>
|
||||
internal static IEnumerable<SessionTrace> Latest(IEnumerable<SessionTrace> inWriteOrder)
|
||||
{
|
||||
var kept = new Dictionary<(long?, DateTimeOffset), SessionTrace>();
|
||||
foreach (var trace in inWriteOrder)
|
||||
{
|
||||
var key = (trace.Session, trace.Start);
|
||||
if (!kept.TryGetValue(key, out var earlier) || !(trace.InProgress && !earlier.InProgress))
|
||||
{
|
||||
kept[key] = trace;
|
||||
}
|
||||
}
|
||||
|
||||
return kept.Values;
|
||||
}
|
||||
|
||||
private DateOnly FirstDayKept() => LocalCalendar.Today(_clock.Now, _clock.LocalZone).AddDays(-(Days - 1));
|
||||
|
||||
/// <summary>Deletes the files of days before the ones kept (once per day unless forced).</summary>
|
||||
private void ApplyRetention(bool force)
|
||||
{
|
||||
var today = LocalCalendar.Today(_clock.Now, _clock.LocalZone);
|
||||
if (!force && _retentionDay == today)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_retentionDay = today;
|
||||
var first = FirstDayKept();
|
||||
foreach (var (day, path) in Files())
|
||||
{
|
||||
if (day < first)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Tried again at the next write or reading.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The files of this log in the folder, by the day in their name (other files are never touched).</summary>
|
||||
private IEnumerable<(DateOnly Day, string Path)> Files()
|
||||
{
|
||||
if (!Directory.Exists(Folder))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
foreach (var path in Directory.EnumerateFiles(Folder, Prefix + "*" + Extension))
|
||||
{
|
||||
var name = Path.GetFileName(path);
|
||||
var text = name[Prefix.Length..^Extension.Length];
|
||||
if (DateOnly.TryParseExact(text, DayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day))
|
||||
{
|
||||
yield return (day, path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Collection.Diagnostics;
|
||||
|
||||
/// <summary>The head of an exported report.</summary>
|
||||
/// <param name="Version">Febe's version (three numbers).</param>
|
||||
/// <param name="Edition">«docker» or «windows».</param>
|
||||
/// <param name="Created">When the report is written.</param>
|
||||
/// <param name="Zone">Alberto's time zone: the times of the report are written in it.</param>
|
||||
/// <param name="Days">Days the log keeps.</param>
|
||||
/// <param name="DamagedLines">Lines of the log that could not be read («righeRovinate»).</param>
|
||||
/// <param name="RecorderFaults">Errors the recorder swallowed, failed writes among them («erroriRegistratore»).</param>
|
||||
/// <param name="UnreadableFiles">Day files of the log that could not be read («fileIlleggibili»).</param>
|
||||
/// <param name="UnfinishedSessions">Sessions Febe stopped without closing, a crash or a kill («sessioniSenzaFine»).</param>
|
||||
public sealed record DiagnosticReportHeader(
|
||||
string Version,
|
||||
string Edition,
|
||||
DateTimeOffset Created,
|
||||
TimeZoneInfo Zone,
|
||||
int Days = DiagnosticLog.DefaultDays,
|
||||
int DamagedLines = 0,
|
||||
int RecorderFaults = 0,
|
||||
int UnreadableFiles = 0,
|
||||
int UnfinishedSessions = 0);
|
||||
|
||||
/// <summary>
|
||||
/// The file Alberto sends after a live test that went wrong (issue #39, «Esporta il rapporto di diagnostica»):
|
||||
/// UTF-8 JSON without BOM, indented, with the traces of the engine sessions and of the days outside sessions. Like
|
||||
/// the traces, it holds no data value: no address, user name, cookie, body or free text.
|
||||
/// </summary>
|
||||
public static partial class DiagnosticReport
|
||||
{
|
||||
/// <summary>The value of «rapporto».</summary>
|
||||
public const string Title = "diagnostica della raccolta";
|
||||
|
||||
/// <summary>Name of the exported file for the local day of <paramref name="now"/>.</summary>
|
||||
public static string FileName(DateTimeOffset now, TimeZoneInfo zone) =>
|
||||
$"febe-diagnostica-{LocalCalendar.Today(now, zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json";
|
||||
|
||||
/// <summary>Writes the report to <paramref name="stream"/> (left open).</summary>
|
||||
/// <exception cref="InvalidOperationException">Debug builds only: the text holds «://» or «@», which no reduction lets through.</exception>
|
||||
public static void Write(Stream stream, IReadOnlyList<SessionTrace> traces, DiagnosticReportHeader header)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
ArgumentNullException.ThrowIfNull(traces);
|
||||
ArgumentNullException.ThrowIfNull(header);
|
||||
var zone = header.Zone;
|
||||
using var buffer = new MemoryStream();
|
||||
using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Indented = true }))
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
writer.WriteString("rapporto", Title);
|
||||
writer.WriteString("versione", Safe(header.Version));
|
||||
writer.WriteString("edizione", Safe(header.Edition));
|
||||
writer.WriteString("creato", Local(header.Created, zone));
|
||||
writer.WriteString("fuso", Safe(ZoneName(zone)));
|
||||
writer.WriteNumber("giorni", header.Days);
|
||||
|
||||
// Not zero: the report is not the whole story (lines of the log lost, writes or readings that failed, day
|
||||
// files that could not be read, sessions cut short by a crash).
|
||||
writer.WriteNumber("righeRovinate", Math.Max(0, header.DamagedLines));
|
||||
writer.WriteNumber("erroriRegistratore", Math.Max(0, header.RecorderFaults));
|
||||
writer.WriteNumber("fileIlleggibili", Math.Max(0, header.UnreadableFiles));
|
||||
writer.WriteNumber("sessioniSenzaFine", Math.Max(0, header.UnfinishedSessions));
|
||||
WriteTraces(writer, "sessioni", traces.Where(t => t.Session is not null), zone);
|
||||
WriteTraces(writer, "fuoriSessione", traces.Where(t => t.Session is null), zone);
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
var text = Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length);
|
||||
if (text.Contains("://", StringComparison.Ordinal) || text.Contains('@', StringComparison.Ordinal))
|
||||
{
|
||||
throw new InvalidOperationException("Il rapporto di diagnostica contiene un indirizzo o un nome: una riduzione non ha funzionato.");
|
||||
}
|
||||
#endif
|
||||
|
||||
buffer.Position = 0;
|
||||
buffer.CopyTo(stream);
|
||||
stream.WriteByte((byte)'\n');
|
||||
}
|
||||
|
||||
private static void WriteTraces(Utf8JsonWriter writer, string name, IEnumerable<SessionTrace> traces, TimeZoneInfo zone)
|
||||
{
|
||||
writer.WriteStartArray(name);
|
||||
foreach (var trace in traces.OrderBy(t => t.Start))
|
||||
{
|
||||
JsonSerializer.Serialize(writer, InZone(trace, zone), DiagnosticsJsonContext.Default.SessionTrace);
|
||||
}
|
||||
|
||||
writer.WriteEndArray();
|
||||
}
|
||||
|
||||
/// <summary>The same trace with its times written in Alberto's zone (same instants, local offset).</summary>
|
||||
private static SessionTrace InZone(SessionTrace trace, TimeZoneInfo zone) => trace with
|
||||
{
|
||||
Start = Local(trace.Start, zone),
|
||||
End = trace.End is { } end ? Local(end, zone) : null,
|
||||
Pages = [.. trace.Pages.Select(p => p with { At = Local(p.At, zone) })],
|
||||
Recipes = [.. trace.Recipes.Select(r => r with { At = Local(r.At, zone) })],
|
||||
Signals = [.. trace.Signals.Select(s => s with { At = Local(s.At, zone) })],
|
||||
};
|
||||
|
||||
private static DateTimeOffset Local(DateTimeOffset instant, TimeZoneInfo zone) => TimeZoneInfo.ConvertTime(instant, zone);
|
||||
|
||||
/// <summary>
|
||||
/// The IANA name of the zone («Europe/Rome»), also on Windows, whose own names have spaces («W. Europe Standard
|
||||
/// Time»), the one of the computer's region when the Windows name covers several («Europe/Rome» rather than
|
||||
/// «Europe/Berlin» in Italy); the Windows name with its spaces as underscores when there is no IANA one.
|
||||
/// </summary>
|
||||
internal static string ZoneName(TimeZoneInfo zone)
|
||||
{
|
||||
string? region = null;
|
||||
try
|
||||
{
|
||||
region = RegionInfo.CurrentRegion.TwoLetterISORegionName;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// No region (invariant culture): the zone's main IANA name.
|
||||
}
|
||||
|
||||
if (region is { Length: 2 } && TimeZoneInfo.TryConvertWindowsIdToIanaId(zone.Id, region, out var regional))
|
||||
{
|
||||
return regional;
|
||||
}
|
||||
|
||||
return TimeZoneInfo.TryConvertWindowsIdToIanaId(zone.Id, out var iana) ? iana : zone.Id.Replace(' ', '_');
|
||||
}
|
||||
|
||||
private static string Safe(string? text) => text is not null && SafeText().IsMatch(text) ? text : CollectionDiagnostics.Other;
|
||||
|
||||
[GeneratedRegex("^[A-Za-z0-9_./+-]{1,64}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex SafeText();
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection.Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// What one engine session did with the site, for the diagnostic report (issue #39), or what happened outside any
|
||||
/// session on one local day (<see cref="Session"/> null: Alberto at the browser, downloads between sessions).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It holds no data value by construction: only enums, codes from closed lists (signal codes, page and target names
|
||||
/// of the site map), counts, sizes, times and address patterns where every segment that is not a word of the site
|
||||
/// is <c>{numero}</c> or <c>{testo}</c>. Never addresses, user names, bodies, cookies or free text.
|
||||
/// </remarks>
|
||||
public sealed record SessionTrace
|
||||
{
|
||||
/// <summary>The engine session; null for the bucket outside sessions.</summary>
|
||||
public long? Session { get; init; }
|
||||
|
||||
public DateTimeOffset Start { get; init; }
|
||||
|
||||
public DateTimeOffset? End { get; init; }
|
||||
|
||||
public SessionOutcome? Outcome { get; init; }
|
||||
|
||||
public SessionStopCause? StopCause { get; init; }
|
||||
|
||||
/// <summary>The recipe status that stopped the session early, when one did.</summary>
|
||||
public RecipeStatus? StoppedBy { get; init; }
|
||||
|
||||
/// <summary>The speed factor of the session (spec §7.7), two decimals.</summary>
|
||||
public double? Mood { get; init; }
|
||||
|
||||
/// <summary>True for a session still running when the trace was taken (or when Febe stopped).</summary>
|
||||
public bool InProgress { get; init; }
|
||||
|
||||
/// <summary>Pages the recipes opened, in order.</summary>
|
||||
public IReadOnlyList<PageVisit> Pages { get; init; } = [];
|
||||
|
||||
/// <summary>Main-frame navigations (also the ones the engine did not ask for), counted by pattern.</summary>
|
||||
public IReadOnlyList<NavigationGroup> Navigations { get; init; } = [];
|
||||
|
||||
/// <summary>Responses the page received, counted by kind, with sizes and what the readers did with them.</summary>
|
||||
public IReadOnlyList<ResponseGroup> Responses { get; init; } = [];
|
||||
|
||||
/// <summary>Distinct key structures of responses the readers did not recognize (strict: no key that could be data).</summary>
|
||||
public IReadOnlyList<UnknownShape> UnknownShapes { get; init; } = [];
|
||||
|
||||
/// <summary>Verdicts of the recipe steps: «riconosciuto», «vuoto», «sconosciuto».</summary>
|
||||
public IReadOnlyList<VerdictCount> Steps { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<TargetCount> Targets { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<RecipeLine> Recipes { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<SignalLine> Signals { get; init; } = [];
|
||||
|
||||
/// <summary>Refusals of the Governor.</summary>
|
||||
public IReadOnlyList<DenialCount> Denials { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<QueuedFiles> FilesQueued { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<DownloadGroup> Downloads { get; init; } = [];
|
||||
|
||||
/// <summary>Bytes of the files downloaded (what crossed the network), when the queue said.</summary>
|
||||
public long DownloadedBytes { get; init; }
|
||||
|
||||
/// <summary>Steps of the profile search on the site (issue #37), by how they ended: never a typed text or a name.</summary>
|
||||
public IReadOnlyList<SearchStepCount> SearchSteps { get; init; } = [];
|
||||
|
||||
/// <summary>Photos of search results, by what happened to them («scaricata», «rifiutata», «saltata»).</summary>
|
||||
public IReadOnlyList<SearchPhotoCount> SearchPhotos { get; init; } = [];
|
||||
|
||||
/// <summary>Items not kept because a list was full: counted, never dropped silently.</summary>
|
||||
public TraceOverflow Overflow { get; init; } = new();
|
||||
}
|
||||
|
||||
/// <summary>A page a recipe opened: the name in the site map and its shape, never the address.</summary>
|
||||
public sealed record PageVisit(DateTimeOffset At, string Page, string? Pattern, bool Ok);
|
||||
|
||||
/// <summary>Main-frame navigations with the same pattern.</summary>
|
||||
public sealed record NavigationGroup(HostKind HostKind, string? Page, string Pattern, bool SameDocument, int Count);
|
||||
|
||||
/// <summary>Responses with the same host kind, pattern, resource type, MIME type and status class.</summary>
|
||||
/// <param name="Count">Responses seen.</param>
|
||||
/// <param name="Bytes">Sum of what crossed the network.</param>
|
||||
/// <param name="MaxBytes">Largest single response.</param>
|
||||
/// <param name="Recognized">Bodies (or blocks of a page) the readers recognized.</param>
|
||||
/// <param name="Empty">Bodies with no contents (an empty page or list).</param>
|
||||
/// <param name="Unrelated">Bodies that are not about contents (ignored).</param>
|
||||
/// <param name="Unrecognized">Bodies with a shape the readers do not know.</param>
|
||||
/// <param name="NotSite">Bodies of a host that is not the site (not read).</param>
|
||||
/// <param name="NotRead">Responses whose body is not data and is not read at all (images, scripts...).</param>
|
||||
/// <param name="Contents">Contents the readers found.</param>
|
||||
/// <param name="Profiles">Profiles the readers found.</param>
|
||||
/// <param name="Dropped">Bodies that never reached the readers, by reason.</param>
|
||||
public sealed record ResponseGroup(
|
||||
HostKind HostKind,
|
||||
string? Page,
|
||||
string Pattern,
|
||||
string? ResourceType,
|
||||
string Mime,
|
||||
string Status,
|
||||
int Count,
|
||||
long Bytes,
|
||||
long MaxBytes,
|
||||
int Recognized,
|
||||
int Empty,
|
||||
int Unrelated,
|
||||
int Unrecognized,
|
||||
int NotSite,
|
||||
int NotRead,
|
||||
int Contents,
|
||||
int Profiles,
|
||||
IReadOnlyList<DropCount> Dropped);
|
||||
|
||||
public sealed record DropCount(BodyDropReason Reason, int Count);
|
||||
|
||||
public sealed record UnknownShape(string Structure, string Pattern, int Count);
|
||||
|
||||
public sealed record VerdictCount(string Verdict, int Count);
|
||||
|
||||
public sealed record TargetCount(string Target, TargetCheckStatus Status, int Count);
|
||||
|
||||
public sealed record RecipeLine(DateTimeOffset At, RecipeKind Kind, RecipeStatus Status, string? Signal, int Actions, int NewEntries)
|
||||
{
|
||||
/// <summary>For a recipe that failed on an unexpected error: the type name of the exception, never its message.</summary>
|
||||
public string? Error { get; init; }
|
||||
}
|
||||
|
||||
public sealed record SignalLine(DateTimeOffset At, SignalLevel Level, string Code);
|
||||
|
||||
public sealed record DenialCount(ActionKind Action, DenialReason Reason, int Count);
|
||||
|
||||
/// <summary>Search steps that ended the same way (a name of the closed list <see cref="SearchOutcome"/>).</summary>
|
||||
public sealed record SearchStepCount(SearchOutcome Outcome, int Count);
|
||||
|
||||
/// <summary>Photos of search results with the same fate.</summary>
|
||||
public sealed record SearchPhotoCount(string Outcome, int Count);
|
||||
|
||||
/// <summary>Saves of contents read by the recipes: how many, and how many files they put in the download queue.</summary>
|
||||
/// <param name="Outcome">A <see cref="SaveOutcome"/> name, or «Completed» for a «Post singolo» completion.</param>
|
||||
public sealed record QueuedFiles(EntryKind Kind, string Outcome, int Saves, int Files, int Skipped);
|
||||
|
||||
public sealed record DownloadGroup(EntryKind Kind, DownloadStep Step, int Count, long Bytes)
|
||||
{
|
||||
/// <summary>Why a file failed or waits for another attempt (<see cref="DownloadCauses"/>), when the queue said.</summary>
|
||||
public string? Cause { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Items left out because their list reached its cap (<see cref="CollectionDiagnostics"/>).</summary>
|
||||
public sealed record TraceOverflow
|
||||
{
|
||||
public int Pages { get; init; }
|
||||
|
||||
public int Navigations { get; init; }
|
||||
|
||||
public int Responses { get; init; }
|
||||
|
||||
public int UnknownShapes { get; init; }
|
||||
|
||||
public int Signals { get; init; }
|
||||
|
||||
public int Recipes { get; init; }
|
||||
|
||||
/// <summary>Bodies forgotten while still waiting for their reading (too many responses at once).</summary>
|
||||
public int Requests { get; init; }
|
||||
|
||||
/// <summary>Sizes, readings or drops that arrived after their own trace was closed (counted in the trace open then).</summary>
|
||||
public int Late { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What there is to report, with what the report must say about itself.</summary>
|
||||
/// <param name="Traces">The traces, oldest first.</param>
|
||||
/// <param name="DamagedLines">Lines of the log that could not be read (a stop in the middle of a write).</param>
|
||||
/// <param name="RecorderFaults">Errors the recorder swallowed since Febe started (a failed write among them).</param>
|
||||
public sealed record DiagnosticCollection(IReadOnlyList<SessionTrace> Traces, int DamagedLines = 0, int RecorderFaults = 0)
|
||||
{
|
||||
/// <summary>Day files of the log that could not be opened or read: their sessions are missing.</summary>
|
||||
public int UnreadableFiles { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Sessions whose last line in the log is in progress, not running now and not closed by a shutdown: Febe stopped
|
||||
/// without closing them (a crash, a kill), and what they did after their last line is missing.
|
||||
/// </summary>
|
||||
public int UnfinishedSessions { get; init; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
UseStringEnumConverter = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[JsonSerializable(typeof(SessionTrace))]
|
||||
internal sealed partial class DiagnosticsJsonContext : JsonSerializerContext;
|
||||
@@ -353,6 +353,7 @@ public sealed class DownloadQueue
|
||||
{
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, "Indirizzo del file non valido.", _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Failed);
|
||||
Report(media, entry, DownloadStep.Failed, cause: DownloadCauses.BadAddress);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -382,33 +383,35 @@ public sealed class DownloadQueue
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case FetchOutcome.Completed:
|
||||
await IngestAsync(account, entry, media, temp, maxBytes, tally, ct).ConfigureAwait(false);
|
||||
await IngestAsync(account, entry, media, temp, maxBytes, result.BudgetBytes, tally, ct).ConfigureAwait(false);
|
||||
return;
|
||||
case FetchOutcome.TooLarge:
|
||||
var limit = maxBytes is { } m ? ItalianText.Number(Math.Max(1, m / (1024 * 1024))) : "?";
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, $"Video oltre il limite di {limit} MB impostato per l'account.", _clock.Now, ct).ConfigureAwait(false);
|
||||
_retryAt.TryRemove(media.Id, out _);
|
||||
tally.Add(ref tally.Skipped);
|
||||
Report(media, entry, DownloadStep.Skipped);
|
||||
Report(media, entry, DownloadStep.Skipped, result.BudgetBytes);
|
||||
return;
|
||||
case FetchOutcome.HttpError when result.HttpStatus is { } status && _options.ExpiredStatuses.Contains(status):
|
||||
await ExpiredAsync(entry, media, tally, singlePostQueued, ct).ConfigureAwait(false);
|
||||
await ExpiredAsync(entry, media, tally, singlePostQueued, result.BudgetBytes, ct).ConfigureAwait(false);
|
||||
return;
|
||||
case FetchOutcome.HostNotAllowed:
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, "L'indirizzo non è del CDN: non si scarica (specifica §6.5).", _clock.Now, ct).ConfigureAwait(false);
|
||||
_retryAt.TryRemove(media.Id, out _);
|
||||
tally.Add(ref tally.Failed);
|
||||
Report(media, entry, DownloadStep.Failed);
|
||||
Report(media, entry, DownloadStep.Failed, result.BudgetBytes, DownloadCauses.HostNotAllowed);
|
||||
return;
|
||||
case FetchOutcome.NetworkError when IsConnectionError(result.Error):
|
||||
// No connection at all (router restarting, cable out): every file would fail the same way.
|
||||
// No connection at all (router restarting, cable out): every file would fail the same way. Not the
|
||||
// file's fault (no attempt counted), but the report says why it is still waiting.
|
||||
PauseUntil(_clock.Now + _options.ConnectionPause, tally);
|
||||
Report(media, entry, DownloadStep.Retried, result.BudgetBytes, DownloadCauses.Connection);
|
||||
return;
|
||||
default:
|
||||
var error = result.HttpStatus is { } code
|
||||
? $"Il CDN ha risposto {code.ToString(CultureInfo.InvariantCulture)}."
|
||||
: $"Errore di rete durante lo scaricamento ({result.Error ?? "senza dettagli"}).";
|
||||
await RetryLaterAsync(entry, media, error, tally, ct).ConfigureAwait(false);
|
||||
await RetryLaterAsync(entry, media, error, tally, result.BudgetBytes, ct, DownloadCauses.Of(result.HttpStatus)).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -421,11 +424,12 @@ public sealed class DownloadQueue
|
||||
{
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, "Video oltre il limite impostato per l'account.", _clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Skipped);
|
||||
Report(media, entry, DownloadStep.Skipped);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
// Disk full or similar: the file waits for a later pass (nothing was written under the final name).
|
||||
await RetryLaterAsync(entry, media, $"Scrittura non riuscita: {ex.GetType().Name}.", tally, CancellationToken.None).ConfigureAwait(false);
|
||||
await RetryLaterAsync(entry, media, $"Scrittura non riuscita: {ex.GetType().Name}.", tally, null, CancellationToken.None, DownloadCauses.Write).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -455,14 +459,14 @@ public sealed class DownloadQueue
|
||||
/// A failure that may pass: the file waits for a later attempt, a little longer each time; after
|
||||
/// <see cref="DownloadOptions.MaxAttempts"/> failures it is «fallito».
|
||||
/// </summary>
|
||||
private async Task RetryLaterAsync(Entry entry, Media media, string error, Tally tally, CancellationToken ct)
|
||||
private async Task RetryLaterAsync(Entry entry, Media media, string error, Tally tally, long? bytes, CancellationToken ct, string? cause = null)
|
||||
{
|
||||
if (media.Attempts + 1 >= _options.MaxAttempts)
|
||||
{
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, error, _clock.Now, ct).ConfigureAwait(false);
|
||||
_retryAt.TryRemove(media.Id, out _);
|
||||
tally.Add(ref tally.Failed);
|
||||
Report(media, entry, DownloadStep.Failed);
|
||||
Report(media, entry, DownloadStep.Failed, bytes, cause);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -474,10 +478,12 @@ public sealed class DownloadQueue
|
||||
}
|
||||
|
||||
tally.Add(ref tally.Retried);
|
||||
Report(media, entry, DownloadStep.Retried, bytes, cause);
|
||||
}
|
||||
|
||||
private async Task IngestAsync(Account account, Entry entry, Media media, string temp, long? maxBytes, Tally tally, CancellationToken ct)
|
||||
private async Task IngestAsync(Account account, Entry entry, Media media, string temp, long? maxBytes, long fileBytes, Tally tally, CancellationToken ct)
|
||||
{
|
||||
var bytes = fileBytes;
|
||||
MemoryStream? cover = null;
|
||||
try
|
||||
{
|
||||
@@ -489,6 +495,7 @@ public sealed class DownloadQueue
|
||||
{
|
||||
await _budget.RecordAsync(fetched.BudgetBytes, account.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
tally.AddBytes(fetched.BudgetBytes);
|
||||
bytes += fetched.BudgetBytes;
|
||||
}
|
||||
|
||||
if (fetched.Outcome == FetchOutcome.HttpError && fetched.HttpStatus is { } status)
|
||||
@@ -526,13 +533,13 @@ public sealed class DownloadQueue
|
||||
if (saved.Outcome == MediaSaveOutcome.Stored)
|
||||
{
|
||||
tally.Add(ref tally.Stored);
|
||||
Report(media, entry, DownloadStep.Stored);
|
||||
Report(media, entry, DownloadStep.Stored, bytes);
|
||||
}
|
||||
else
|
||||
{
|
||||
await IdenticalAsync(entry, media, saved.Identical!, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Duplicates);
|
||||
Report(media, entry, DownloadStep.Duplicate);
|
||||
Report(media, entry, DownloadStep.Duplicate, bytes);
|
||||
}
|
||||
}
|
||||
finally
|
||||
@@ -582,7 +589,7 @@ public sealed class DownloadQueue
|
||||
/// A file whose renewed address is refused again and again ends «fallito» after
|
||||
/// <see cref="DownloadOptions.MaxAttempts"/> failures, instead of sending «Post singolo» to the site for ever.
|
||||
/// </summary>
|
||||
private async Task ExpiredAsync(Entry entry, Media media, Tally tally, ConcurrentDictionary<long, bool> singlePostQueued, CancellationToken ct)
|
||||
private async Task ExpiredAsync(Entry entry, Media media, Tally tally, ConcurrentDictionary<long, bool> singlePostQueued, long? bytes, CancellationToken ct)
|
||||
{
|
||||
_retryAt.TryRemove(media.Id, out _);
|
||||
if (entry.Kind != EntryKind.Story && media.Attempts + 1 >= _options.MaxAttempts)
|
||||
@@ -590,7 +597,7 @@ public sealed class DownloadQueue
|
||||
var attempts = ItalianText.Number(media.Attempts + 1);
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, $"Indirizzo rifiutato anche dopo il rinnovo ({attempts} tentativi): il file resta «fallito».", _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Failed);
|
||||
Report(media, entry, DownloadStep.Failed);
|
||||
Report(media, entry, DownloadStep.Failed, bytes, DownloadCauses.RefusedAfterRenewal);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -604,7 +611,7 @@ public sealed class DownloadQueue
|
||||
};
|
||||
await _storage.Media.MarkFailedAsync(media.Id, entry.Kind == EntryKind.Story ? MediaState.Failed : MediaState.Expired, why, _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Expired);
|
||||
Report(media, entry, DownloadStep.Expired);
|
||||
Report(media, entry, DownloadStep.Expired, bytes);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -615,7 +622,7 @@ public sealed class DownloadQueue
|
||||
}
|
||||
|
||||
tally.Add(ref tally.Expired);
|
||||
Report(media, entry, DownloadStep.Expired);
|
||||
Report(media, entry, DownloadStep.Expired, bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -632,8 +639,8 @@ public sealed class DownloadQueue
|
||||
}
|
||||
}
|
||||
|
||||
private void Report(Media media, Entry entry, DownloadStep step) =>
|
||||
Progress?.Invoke(this, new DownloadProgress(media.Id, entry.Id, entry.AccountId, entry.Kind, step));
|
||||
private void Report(Media media, Entry entry, DownloadStep step, long? bytes = null, string? cause = null) =>
|
||||
Progress?.Invoke(this, new DownloadProgress(media.Id, entry.Id, entry.AccountId, entry.Kind, step, bytes) { Cause = cause });
|
||||
|
||||
/// <summary>The extension from the content (magic numbers), else from the kind of file.</summary>
|
||||
private static string Extension(string path, Media media)
|
||||
@@ -737,7 +744,44 @@ public enum DownloadStep
|
||||
Skipped,
|
||||
Expired,
|
||||
Failed,
|
||||
|
||||
/// <summary>Not settled: the file waits for a later attempt (a failure that may pass).</summary>
|
||||
Retried,
|
||||
}
|
||||
|
||||
/// <summary>Progress of the queue for the interface: identifiers only, never addresses.</summary>
|
||||
public sealed record DownloadProgress(long MediaId, long EntryId, long AccountId, EntryKind Kind, DownloadStep Step);
|
||||
/// <param name="Bytes">What crossed the network for this file (its cover included), when known.</param>
|
||||
public sealed record DownloadProgress(long MediaId, long EntryId, long AccountId, EntryKind Kind, DownloadStep Step, long? Bytes = null)
|
||||
{
|
||||
/// <summary>Why the file failed or waits for another attempt (<see cref="DownloadCauses"/>); null when it did not.</summary>
|
||||
public string? Cause { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why a file failed or waits for another attempt, for the diagnostic report (issue #39): a closed list of codes,
|
||||
/// never an address or the text of an error.
|
||||
/// </summary>
|
||||
public static class DownloadCauses
|
||||
{
|
||||
/// <summary>A network error that is not a missing connection (the connection pauses the queue instead).</summary>
|
||||
public const string Network = "rete";
|
||||
|
||||
/// <summary>No connection at all: the queue pauses, the file waits without an attempt counted.</summary>
|
||||
public const string Connection = "connessione";
|
||||
|
||||
/// <summary>The file could not be written (disk full or similar).</summary>
|
||||
public const string Write = "scrittura";
|
||||
|
||||
/// <summary>The address of the file is not valid.</summary>
|
||||
public const string BadAddress = "indirizzo-non-valido";
|
||||
|
||||
/// <summary>The address is not of the CDN (spec §6.5).</summary>
|
||||
public const string HostNotAllowed = "host-non-ammesso";
|
||||
|
||||
/// <summary>The renewed address was refused again, too many times.</summary>
|
||||
public const string RefusedAfterRenewal = "rifiutato-dopo-rinnovo";
|
||||
|
||||
/// <summary>«http-404», «http-503»...: the status the CDN answered; <see cref="Network"/> without one.</summary>
|
||||
public static string Of(int? httpStatus) =>
|
||||
httpStatus is >= 100 and < 600 ? "http-" + httpStatus.Value.ToString(CultureInfo.InvariantCulture) : Network;
|
||||
}
|
||||
@@ -73,8 +73,9 @@ public sealed class HostClassifier
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Instagram's public host names: the site and the two CDN families its pages load files from.
|
||||
/// Public knowledge, not response formats; still to be confirmed by the M0 probe.
|
||||
/// Instagram's public host names: the site and the two CDN families its pages load files from. In the HAR of
|
||||
/// 21 October 2026 the data came from www.instagram.com (logging from graph.instagram.com), the video files from
|
||||
/// scontent-*.cdninstagram.com and the scripts from static.cdninstagram.com; fbcdn.net is public knowledge.
|
||||
/// </summary>
|
||||
public static HostClassifier Instagram { get; } = new(
|
||||
["instagram.com"],
|
||||
|
||||
@@ -29,6 +29,11 @@ public enum HostKind
|
||||
/// <param name="ResourceType">Browser resource type (Document, XHR, Fetch, Image, ...), when known.</param>
|
||||
/// <param name="IsMainFrameDocument">True for the document of the main frame (a page load).</param>
|
||||
/// <param name="At">When the response was seen.</param>
|
||||
/// <param name="RequestOrder">
|
||||
/// Order in which the page started the request among the site's requests (from 1, <c>Network.requestWillBeSent</c>);
|
||||
/// 0 when unknown. The profile search (issue #37) tells answers to texts typed before the last key from the answer to
|
||||
/// the text in the box with it.
|
||||
/// </param>
|
||||
public sealed record ResponseDescriptor(
|
||||
string RequestId,
|
||||
HostKind HostKind,
|
||||
@@ -39,7 +44,8 @@ public sealed record ResponseDescriptor(
|
||||
string MimeType,
|
||||
string? ResourceType,
|
||||
bool IsMainFrameDocument,
|
||||
DateTimeOffset At);
|
||||
DateTimeOffset At,
|
||||
long RequestOrder = 0);
|
||||
|
||||
/// <summary>A main-frame navigation: a new document, or a route change inside a single-page site.</summary>
|
||||
/// <param name="HostKind">Site, CDN or other.</param>
|
||||
@@ -69,4 +75,69 @@ public interface IResponseObserver
|
||||
void OnResponse(ResponseDescriptor response);
|
||||
|
||||
void OnNavigation(NavigationDescriptor navigation);
|
||||
|
||||
/// <summary>
|
||||
/// The body of a data response announced by <see cref="OnResponse"/> will not reach the consumers: it failed to
|
||||
/// load, was too large, was not JSON after all (Instagram's «for (;;);» answers), or the page moved on. Observers
|
||||
/// that wait for bodies stop waiting for this one.
|
||||
/// </summary>
|
||||
void OnBodyDropped(string requestId)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The same as <see cref="OnBodyDropped(string)"/>, with the reason (for the diagnostic report, issue #39). The tap
|
||||
/// calls this one; by default it forwards to the overload without a reason.
|
||||
/// </summary>
|
||||
void OnBodyDropped(string requestId, BodyDropReason reason) => OnBodyDropped(requestId);
|
||||
|
||||
/// <summary>
|
||||
/// A response announced by <see cref="OnResponse"/> finished loading: <paramref name="encodedBytes"/> is what
|
||||
/// crossed the network (the browser's encodedDataLength). Called for every response, whether its body is read or not.
|
||||
/// </summary>
|
||||
void OnLoadingFinished(string requestId, long encodedBytes)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page started a request to the site: <paramref name="order"/> is its <see cref="ResponseDescriptor.RequestOrder"/>.
|
||||
/// Nothing else of the request is passed (no address, no body).
|
||||
/// </summary>
|
||||
void OnRequestStarted(long order)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Why the body of a response did not reach the consumers (closed list: a report may show it).</summary>
|
||||
public enum BodyDropReason
|
||||
{
|
||||
/// <summary>Over the size the tap reads (memory guard).</summary>
|
||||
TooLarge,
|
||||
|
||||
/// <summary>The browser says the request failed.</summary>
|
||||
LoadingFailed,
|
||||
|
||||
/// <summary>The page moved to another document before the body finished.</summary>
|
||||
FrameNavigated,
|
||||
|
||||
/// <summary>The browser was restarted or reconnected.</summary>
|
||||
Reconnected,
|
||||
|
||||
/// <summary>Nobody was listening for bodies.</summary>
|
||||
NoConsumers,
|
||||
|
||||
/// <summary>The browser no longer had the body (evicted from its buffer) or gave none.</summary>
|
||||
Unavailable,
|
||||
|
||||
/// <summary>The body did not arrive in time.</summary>
|
||||
Timeout,
|
||||
|
||||
/// <summary>Declared as data, but not JSON after all.</summary>
|
||||
NotJson,
|
||||
|
||||
/// <summary>A page document without any embedded JSON block.</summary>
|
||||
NoJsonBlock,
|
||||
|
||||
/// <summary>An unexpected error while reading it.</summary>
|
||||
Unexpected,
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
namespace Febe.Core.Collection.Privacy;
|
||||
|
||||
/// <summary>
|
||||
/// Turns an address path into a pattern that names nobody (issue #34, issue #39): every segment that is not a known word
|
||||
/// of the site's addresses becomes <c>{numero}</c> or <c>{testo}</c>. Used by the request shapes of the probe and by the
|
||||
/// diagnostic report. A missing word only costs detail, never privacy.
|
||||
/// </summary>
|
||||
public static class PathPatterns
|
||||
{
|
||||
/// <summary>Written in place of a segment made only of digits.</summary>
|
||||
public const string Number = "{numero}";
|
||||
|
||||
/// <summary>Written in place of any other segment that is not a known word.</summary>
|
||||
public const string Text = "{testo}";
|
||||
|
||||
/// <summary>
|
||||
/// Path segments kept as they are: words of the site's addresses, the same for everyone. Anything else (user names,
|
||||
/// identifiers, codes) becomes <see cref="Number"/> or <see cref="Text"/>.
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> Known = new(StringComparer.Ordinal)
|
||||
{
|
||||
"api", "v1", "graphql", "graphql_www", "query", "ajax", "bulk-route-definitions", "navigation", "web", "users",
|
||||
"user", "web_profile_info", "usernameinfo", "info", "feed", "timeline", "reels_media", "reels_tray", "highlights",
|
||||
"highlights_tray", "friendships", "following", "followers", "show", "show_many", "search", "topsearch", "fbsearch",
|
||||
"web_search", "typeahead", "accounts_typeahead", "top_serp", "media", "comments", "usertags", "clips", "stories",
|
||||
"story", "tags", "sections", "discover", "explore", "chaining", "profile", "posts", "reels", "tagged", "saved",
|
||||
"qp", "batch_fetch_web", "logging_client_events", "direct_v2", "inbox", "has_new", "get_presence", "wwwgraphql",
|
||||
"ig", "bz", "web_info", "current_user", "user_info", "locations", "seen", "media_seen", "reel", "p", "accounts",
|
||||
"edit", "activity", "news", "inbox_v2", "notifications", "badge", "home", "graphql_query",
|
||||
|
||||
// Fixed roots of the site's own pages (verification, login, messages...): a stop that lands there must say so,
|
||||
// not «/{testo}/», and the site map must not take them for a profile (SiteMap.Classify).
|
||||
"challenge", "checkpoint", "direct", "login", "logout", "emails", "password", "reset", "two_factor", "onetap",
|
||||
"suspended", "consent", "settings", "help", "legal", "privacy", "terms", "about",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// File extensions a CDN or other address may show in a report: a closed list, so that the last part of a name
|
||||
/// with a dot («nome.cognome») never passes as an extension.
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> Extensions = new(StringComparer.Ordinal)
|
||||
{
|
||||
"jpg", "jpeg", "png", "webp", "heic", "gif", "avif", "mp4", "m4a", "m4v", "webm", "mov", "js", "css", "json",
|
||||
"woff", "woff2", "ttf", "ico", "svg", "html", "txt",
|
||||
};
|
||||
|
||||
/// <summary>The known words, the same for everyone.</summary>
|
||||
public static IReadOnlySet<string> KnownSegments => Known;
|
||||
|
||||
/// <summary>The extensions <see cref="ExtensionOf"/> may answer.</summary>
|
||||
public static IReadOnlySet<string> KnownExtensions => Extensions;
|
||||
|
||||
/// <summary>The path with each segment that is not a known word replaced by <c>{numero}</c> or <c>{testo}</c>.</summary>
|
||||
/// <remarks>Anything after «?» or «#» is dropped first: only a path is a path.</remarks>
|
||||
public static string Of(string path)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(path);
|
||||
var cut = path.IndexOfAny(['?', '#']);
|
||||
if (cut >= 0)
|
||||
{
|
||||
path = path[..cut];
|
||||
}
|
||||
|
||||
var segments = path.Split('/');
|
||||
for (var i = 0; i < segments.Length; i++)
|
||||
{
|
||||
var segment = segments[i];
|
||||
if (segment.Length == 0 || Known.Contains(segment))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
segments[i] = IsDigits(segment) ? Number : Text;
|
||||
}
|
||||
|
||||
return string.Join('/', segments);
|
||||
}
|
||||
|
||||
/// <summary>True for a word of the site kept by <see cref="Of"/>.</summary>
|
||||
public static bool IsKnownSegment(string segment) => Known.Contains(segment);
|
||||
|
||||
/// <summary>The extension of the last segment of <paramref name="path"/> (lower case, no dot) when it is on the closed list; otherwise null.</summary>
|
||||
public static string? ExtensionOf(string? path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var cut = path.IndexOfAny(['?', '#']);
|
||||
if (cut >= 0)
|
||||
{
|
||||
path = path[..cut];
|
||||
}
|
||||
|
||||
var last = path[(path.LastIndexOf('/') + 1)..];
|
||||
var dot = last.LastIndexOf('.');
|
||||
if (dot < 0 || dot == last.Length - 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var extension = last[(dot + 1)..].ToLowerInvariant();
|
||||
return Extensions.Contains(extension) ? extension : null;
|
||||
}
|
||||
|
||||
private static bool IsDigits(string segment)
|
||||
{
|
||||
foreach (var c in segment)
|
||||
{
|
||||
if (!char.IsAsciiDigit(c))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return segment.Length > 0;
|
||||
}
|
||||
}
|
||||
@@ -13,18 +13,69 @@ public static class KeyStructure
|
||||
public const int DefaultMaxLength = 600;
|
||||
private const int MaxDepth = 6;
|
||||
private const int MaxKeysPerObject = 24;
|
||||
private const int MaxCollectDepth = 256;
|
||||
private const int MaxCollectedValues = 100_000;
|
||||
private const int MaxMapCandidates = 64;
|
||||
private const int MaxElementsCompared = 32;
|
||||
|
||||
public static string Describe(JsonElement root, int maxLength = DefaultMaxLength)
|
||||
/// <summary>Fields that identify an account or an item: two siblings that both have one are entries of a map.</summary>
|
||||
private static readonly HashSet<string> IdentityFields = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
Append(sb, root, 0);
|
||||
if (sb.Length > maxLength)
|
||||
"pk", "pk_id", "id", "fbid", "fbid_v2", "strong_id__", "instagram_pk", "user_id", "userID", "username", "full_name",
|
||||
"profile_pic_url", "code",
|
||||
};
|
||||
|
||||
public static string Describe(JsonElement root, int maxLength = DefaultMaxLength) =>
|
||||
Write(root, LooksLikeIdentifier, mapEntries: false, maxLength);
|
||||
|
||||
/// <summary>
|
||||
/// The stricter description of the diagnostic report (issue #39), where not even a name may pass: a key is shown
|
||||
/// only when it is made of words of a closed list (<see cref="StructureWords.IsStructural"/>), and never when it
|
||||
/// equals, ignoring case, a string value found anywhere in the same body. Every other key becomes «#»: a user name
|
||||
/// («marta_92», «jerry»), a post code, a short token, an identifier, a key with a dot or a space.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Keys made of words of the list can still be names («the_artist», «street_style»), so two more rules apply, and
|
||||
/// under both only a field of the closed list (<see cref="StructureWords.IsFieldKey"/>: the keys of the reader
|
||||
/// vocabularies and of the cleaned samples, such as <c>user</c> and <c>owner</c> of a post) stays:
|
||||
/// <list type="bullet">
|
||||
/// <item>a key with a plain value (text, number, true or false, null) is a field or «#»: a map of counts or flags keyed
|
||||
/// by name never shows;</item>
|
||||
/// <item>the keys of a map are «#»: two or more keys of one object whose values are alike (both objects or both
|
||||
/// lists, and one of them empty, or both lists of plain values, or with at least half of their keys in common or a
|
||||
/// shared identity field such as <c>pk</c>), and in a list of two or more objects the keys of the first one that no
|
||||
/// other has (a list of maps with one entry each).</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public static string DescribeStrict(JsonElement root, int maxLength = DefaultMaxLength)
|
||||
{
|
||||
var values = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
CollectStrings(root, values, 0);
|
||||
return Write(root, key => !StructureWords.IsStructural(key) || values.Contains(key), mapEntries: true, maxLength);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when a key is data rather than structure: it looks like an identifier, or it has any character other than
|
||||
/// ASCII letters, digits, «_» and «-» (a user name with a dot, an address, a phrase). Shared with the sample sanitizer
|
||||
/// (spec §14.5) and the diagnostic report.
|
||||
/// </summary>
|
||||
public static bool IsDataKey(string key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
if (LooksLikeIdentifier(key))
|
||||
{
|
||||
sb.Length = Math.Max(0, maxLength - 1);
|
||||
sb.Append('…');
|
||||
return true;
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
foreach (var c in key)
|
||||
{
|
||||
if (!(char.IsAsciiLetterOrDigit(c) || c is '_' or '-'))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -70,7 +121,237 @@ public static class KeyStructure
|
||||
return others > 0 && digits >= 5; // e.g. «id:123456»
|
||||
}
|
||||
|
||||
private static void Append(StringBuilder sb, JsonElement element, int depth)
|
||||
private static string Write(JsonElement root, Func<string, bool> hidden, bool mapEntries, int maxLength)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
Append(sb, root, hidden, mapEntries, 0);
|
||||
if (sb.Length > maxLength)
|
||||
{
|
||||
sb.Length = Math.Max(0, maxLength - 1);
|
||||
sb.Append('…');
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>The string values of the body (keys excluded), for <see cref="DescribeStrict"/>.</summary>
|
||||
private static void CollectStrings(JsonElement element, HashSet<string> values, int depth)
|
||||
{
|
||||
if (depth > MaxCollectDepth || values.Count >= MaxCollectedValues)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
CollectStrings(property.Value, values, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
CollectStrings(item, values, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.String:
|
||||
if (element.GetString() is { Length: > 0 and <= 256 } text)
|
||||
{
|
||||
values.Add(text);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The keys of <paramref name="element"/> that the strict structure hides besides the ones its predicate already
|
||||
/// rejects (see <see cref="DescribeStrict"/>): keys with a plain value, entries of a map, and
|
||||
/// <paramref name="extra"/> (keys that only the first element of a list has), except the fields of the closed list.
|
||||
/// Null when there is none.
|
||||
/// </summary>
|
||||
private static HashSet<string>? MapEntries(JsonElement element, HashSet<string>? extra)
|
||||
{
|
||||
HashSet<string>? entries = null;
|
||||
void Hide(string key)
|
||||
{
|
||||
if (!StructureWords.IsFieldKey(key))
|
||||
{
|
||||
(entries ??= new HashSet<string>(StringComparer.Ordinal)).Add(key);
|
||||
}
|
||||
}
|
||||
|
||||
List<(string Key, Shape Shape)>? candidates = null;
|
||||
var many = false;
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
var shape = ShapeOf(property.Value);
|
||||
if (shape is null)
|
||||
{
|
||||
Hide(property.Name);
|
||||
}
|
||||
else if (many || (candidates?.Count ?? 0) >= MaxMapCandidates)
|
||||
{
|
||||
// So many objects or lists side by side are a map: no need to compare them.
|
||||
many = true;
|
||||
Hide(property.Name);
|
||||
}
|
||||
else
|
||||
{
|
||||
(candidates ??= []).Add((property.Name, shape));
|
||||
}
|
||||
}
|
||||
|
||||
if (candidates is { Count: >= 2 })
|
||||
{
|
||||
var alike = new bool[candidates.Count];
|
||||
for (var i = 0; i < candidates.Count; i++)
|
||||
{
|
||||
for (var j = i + 1; j < candidates.Count; j++)
|
||||
{
|
||||
if (many || Alike(candidates[i].Shape, candidates[j].Shape))
|
||||
{
|
||||
alike[i] = alike[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < candidates.Count; i++)
|
||||
{
|
||||
if (alike[i])
|
||||
{
|
||||
Hide(candidates[i].Key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (extra is not null)
|
||||
{
|
||||
foreach (var key in extra)
|
||||
{
|
||||
Hide(key);
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Two values of one object are alike (entries of a map): both objects or both lists, and one of them empty, or both
|
||||
/// lists of plain values, or both with keys (of the object, of the first element of the list) half in common or an
|
||||
/// identity field in common.
|
||||
/// </summary>
|
||||
private static bool Alike(Shape a, Shape b)
|
||||
{
|
||||
if (a.List != b.List)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a.Keys is null || b.Keys is null)
|
||||
{
|
||||
// A list of plain values is like an empty list or another list of plain values, never like a list of objects.
|
||||
return a.Keys is not { Count: > 0 } && b.Keys is not { Count: > 0 };
|
||||
}
|
||||
|
||||
if (a.Keys.Count == 0 || b.Keys.Count == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var common = 0;
|
||||
foreach (var key in a.Keys)
|
||||
{
|
||||
if (b.Keys.Contains(key))
|
||||
{
|
||||
if (IdentityFields.Contains(key))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
common++;
|
||||
}
|
||||
}
|
||||
|
||||
var union = a.Keys.Count + b.Keys.Count - common;
|
||||
return common * 2 >= union;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The keys of the first element of a list of two or more objects that no other element has (among the first
|
||||
/// <see cref="MaxElementsCompared"/>): in a list of maps with one entry each, the entries. Null when there is none.
|
||||
/// </summary>
|
||||
private static HashSet<string>? OnlyInFirst(JsonElement array)
|
||||
{
|
||||
HashSet<string>? first = null;
|
||||
var others = 0;
|
||||
var seen = 0;
|
||||
foreach (var item in array.EnumerateArray())
|
||||
{
|
||||
if (++seen > MaxElementsCompared)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (item.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (first is null)
|
||||
{
|
||||
first = KeysOf(item);
|
||||
continue;
|
||||
}
|
||||
|
||||
others++;
|
||||
foreach (var property in item.EnumerateObject())
|
||||
{
|
||||
first.Remove(property.Name);
|
||||
}
|
||||
}
|
||||
|
||||
return others > 0 && first is { Count: > 0 } ? first : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a value is, for the map rule: an object or a list (<paramref name="List"/>), with the keys of the object or of
|
||||
/// the first element of the list (empty: an empty object or list, or a list whose first element is an empty object;
|
||||
/// null: a list of plain values or of lists).
|
||||
/// </summary>
|
||||
private sealed record Shape(bool List, HashSet<string>? Keys);
|
||||
|
||||
/// <summary>The shape of a value; null for a plain value (text, number, true or false, null).</summary>
|
||||
private static Shape? ShapeOf(JsonElement value)
|
||||
{
|
||||
switch (value.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
return new Shape(false, KeysOf(value));
|
||||
case JsonValueKind.Array:
|
||||
using (var items = value.EnumerateArray())
|
||||
{
|
||||
if (!items.MoveNext())
|
||||
{
|
||||
return new Shape(true, []);
|
||||
}
|
||||
|
||||
return new Shape(true, items.Current.ValueKind == JsonValueKind.Object ? KeysOf(items.Current) : null);
|
||||
}
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static HashSet<string> KeysOf(JsonElement value) =>
|
||||
value.EnumerateObject().Select(p => p.Name).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
private static void Append(StringBuilder sb, JsonElement element, Func<string, bool> hidden, bool mapEntries, int depth, HashSet<string>? onlyInFirst = null)
|
||||
{
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
@@ -85,9 +366,10 @@ public static class KeyStructure
|
||||
var count = 0;
|
||||
var identifierKeys = 0;
|
||||
JsonElement? identifierSample = null;
|
||||
var entries = mapEntries ? MapEntries(element, onlyInFirst) : null;
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (LooksLikeIdentifier(property.Name))
|
||||
if (hidden(property.Name) || entries?.Contains(property.Name) == true)
|
||||
{
|
||||
identifierKeys++;
|
||||
identifierSample ??= property.Value;
|
||||
@@ -115,7 +397,7 @@ public static class KeyStructure
|
||||
if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
|
||||
{
|
||||
sb.Append(':');
|
||||
Append(sb, property.Value, depth + 1);
|
||||
Append(sb, property.Value, hidden, mapEntries, depth + 1);
|
||||
}
|
||||
|
||||
count++;
|
||||
@@ -132,7 +414,7 @@ public static class KeyStructure
|
||||
if (identifierSample is { ValueKind: JsonValueKind.Object or JsonValueKind.Array } sample)
|
||||
{
|
||||
sb.Append(':');
|
||||
Append(sb, sample, depth + 1);
|
||||
Append(sb, sample, hidden, mapEntries, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +432,8 @@ public static class KeyStructure
|
||||
{
|
||||
if (item.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
|
||||
{
|
||||
Append(sb, item, depth + 1);
|
||||
var extra = mapEntries && item.ValueKind == JsonValueKind.Object ? OnlyInFirst(element) : null;
|
||||
Append(sb, item, hidden, mapEntries, depth + 1, extra);
|
||||
}
|
||||
|
||||
break; // the first element stands for the others
|
||||
|
||||
@@ -127,6 +127,12 @@ public enum ReadShape
|
||||
|
||||
/// <summary>A shape the vocabulary does not describe: event «formato non riconosciuto» (spec §6.4).</summary>
|
||||
Unrecognized,
|
||||
|
||||
/// <summary>
|
||||
/// Nothing the vocabulary speaks about: none of its relevance keys appears anywhere (promotions, logging, a search
|
||||
/// box). Ignored: neither data, nor an empty page, nor an unknown shape (<see cref="ReaderVocabulary.Relevance"/>).
|
||||
/// </summary>
|
||||
Unrelated,
|
||||
}
|
||||
|
||||
/// <summary>Everything one response gave, detached from the JSON document (which is disposed right after).</summary>
|
||||
@@ -146,6 +152,38 @@ public sealed record ReadResult
|
||||
|
||||
public ProfileInfo? Viewer { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Identifier of the connected account, also when the answer describes it with nothing else (Instagram's
|
||||
/// <c>xdt_viewer.user</c>): a profile with this identifier in another answer is the connected account (H10).
|
||||
/// </summary>
|
||||
public string? ViewerId { get; init; }
|
||||
|
||||
/// <summary>For unrecognized responses: the key structure, without any value (spec §6.4).</summary>
|
||||
public string? KeyStructure { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The answer of the site's search box (issue #37), when this response is one. Its profiles are not in
|
||||
/// <see cref="Profiles"/>, so a search answer never looks like a page of the followed list or a profile check.
|
||||
/// </summary>
|
||||
public SearchAnswer? Search { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The profiles a search box answer gave, in their order (issue #37). Never printed with names.</summary>
|
||||
public sealed record SearchAnswer(IReadOnlyList<SearchProfile> Hits)
|
||||
{
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Hits = {Hits.Count}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One profile of a search answer. Private and followed are never in the answer: they stay null.</summary>
|
||||
public sealed record SearchProfile(int Position, ProfileInfo Profile, bool? IsVerified)
|
||||
{
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Position = {Position}, HasPicture = {Profile.Picture is not null}, IsVerified = {IsVerified}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,9 @@ public sealed record HighlightKeys
|
||||
|
||||
/// <summary>The contents of the collection, when the response carries them.</summary>
|
||||
public VocabularyKeys Items { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The cover image of the collection, read as a version.</summary>
|
||||
public VocabularyKeys Cover { get; init; } = VocabularyKeys.None;
|
||||
}
|
||||
|
||||
/// <summary>Keys of the pagination information that comes with a page of data.</summary>
|
||||
@@ -147,6 +150,40 @@ public sealed record PageKeys
|
||||
public VocabularyKeys Cursor { get; init; } = VocabularyKeys.None;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keys of the answer of the site's own search box (issue #37). The search carries its own profile keys, so a site
|
||||
/// whose other concepts use other keys can still serve the search in its own shape. Only profiles are read: hashtags
|
||||
/// and places are ignored.
|
||||
/// </summary>
|
||||
public sealed record SearchKeys
|
||||
{
|
||||
/// <summary>The key of the search answer: found anywhere in the tree, its value holds <see cref="Items"/>.</summary>
|
||||
public VocabularyKeys Root { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The list of profile results under the root.</summary>
|
||||
public VocabularyKeys Items { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>Order of an item in the list (array order when missing).</summary>
|
||||
public VocabularyKeys Position { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The profile node of an item.</summary>
|
||||
public VocabularyKeys Profile { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Id { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Username { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys DisplayName { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The profile picture: the first key present wins (the small one is enough for a suggestion).</summary>
|
||||
public VocabularyKeys Picture { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Verified { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>True when the reader can recognize a search answer.</summary>
|
||||
public bool IsSet => Root.IsSet && Items.IsSet && Id.IsSet && Username.IsSet;
|
||||
}
|
||||
|
||||
/// <summary>Whether the vocabulary is confirmed on real samples or still a hypothesis (spec §6.4, rule 10).</summary>
|
||||
public enum VocabularyStatus
|
||||
{
|
||||
@@ -182,9 +219,24 @@ public sealed record ReaderVocabulary
|
||||
|
||||
public PageKeys Page { get; init; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// The answer of the site's search box (issue #37). Not among <see cref="MissingConcepts"/>: the collection does not
|
||||
/// depend on it, and without it the search on the site is «da configurare».
|
||||
/// </summary>
|
||||
public SearchKeys Search { get; init; } = new();
|
||||
|
||||
/// <summary>The key under which the response describes the connected account (H10).</summary>
|
||||
public VocabularyKeys Viewer { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>
|
||||
/// Keys at least one of which, anywhere in a response, makes it «about contents or profiles». A response that has
|
||||
/// none of them is <see cref="ReadShape.Unrelated"/> and ignored, instead of counting as an unknown shape: a real site
|
||||
/// sends many JSON answers that have nothing to do with contents (Instagram: promotions, logging, «seen» marks).
|
||||
/// Plain key names, not paths. Empty: every response counts (the test site, where any unknown answer is a format
|
||||
/// change).
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Relevance { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Concepts the collection pipeline cannot work without, still unset. While this is not empty, or the status is
|
||||
/// a hypothesis, recipes refuse to run on the site.
|
||||
@@ -283,6 +335,7 @@ public sealed record ReaderVocabulary
|
||||
var p = file.Profile ?? new ProfileDto();
|
||||
var h = file.Highlight ?? new HighlightDto();
|
||||
var g = file.Page ?? new PageDto();
|
||||
var s = file.Search ?? new SearchDto();
|
||||
return new ReaderVocabulary
|
||||
{
|
||||
Site = file.Site.Trim(),
|
||||
@@ -316,9 +369,22 @@ public sealed record ReaderVocabulary
|
||||
Picture = K(p.Picture),
|
||||
LatestStoryAt = K(p.LatestStoryAt),
|
||||
},
|
||||
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items) },
|
||||
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items), Cover = K(h.Cover) },
|
||||
Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) },
|
||||
Search = new SearchKeys
|
||||
{
|
||||
Root = K(s.Root),
|
||||
Items = K(s.Items),
|
||||
Position = K(s.Position),
|
||||
Profile = K(s.Profile),
|
||||
Id = K(s.Id),
|
||||
Username = K(s.Username),
|
||||
DisplayName = K(s.DisplayName),
|
||||
Picture = K(s.Picture),
|
||||
Verified = K(s.Verified),
|
||||
},
|
||||
Viewer = K(file.Viewer),
|
||||
Relevance = [.. (file.Relevance?.Keys ?? []).Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k.Trim()).Distinct(StringComparer.Ordinal)],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -341,7 +407,18 @@ internal sealed class VocabularyFile
|
||||
|
||||
public PageDto? Page { get; set; }
|
||||
|
||||
public SearchDto? Search { get; set; }
|
||||
|
||||
public List<string>? Viewer { get; set; }
|
||||
|
||||
public RelevanceDto? Relevance { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class RelevanceDto
|
||||
{
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<string>? Keys { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class ContentDto
|
||||
@@ -418,6 +495,8 @@ internal sealed class HighlightDto
|
||||
public List<string>? Owner { get; set; }
|
||||
|
||||
public List<string>? Items { get; set; }
|
||||
|
||||
public List<string>? Cover { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class PageDto
|
||||
@@ -429,6 +508,29 @@ internal sealed class PageDto
|
||||
public List<string>? Cursor { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class SearchDto
|
||||
{
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<string>? Root { get; set; }
|
||||
|
||||
public List<string>? Items { get; set; }
|
||||
|
||||
public List<string>? Position { get; set; }
|
||||
|
||||
public List<string>? Profile { get; set; }
|
||||
|
||||
public List<string>? Id { get; set; }
|
||||
|
||||
public List<string>? Username { get; set; }
|
||||
|
||||
public List<string>? DisplayName { get; set; }
|
||||
|
||||
public List<string>? Picture { get; set; }
|
||||
|
||||
public List<string>? Verified { get; set; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
|
||||
@@ -20,10 +20,12 @@ public sealed class ShapeReader
|
||||
private const int MaxDepth = 64;
|
||||
|
||||
private readonly ReaderVocabulary _v;
|
||||
private readonly HashSet<string> _relevance;
|
||||
|
||||
public ShapeReader(ReaderVocabulary vocabulary)
|
||||
{
|
||||
_v = vocabulary ?? throw new ArgumentNullException(nameof(vocabulary));
|
||||
_relevance = new HashSet<string>(vocabulary.Relevance, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
public ReaderVocabulary Vocabulary => _v;
|
||||
@@ -34,8 +36,30 @@ public sealed class ShapeReader
|
||||
var walk = new Walk();
|
||||
Visit(root, walk, owner: null, highlightId: null, depth: 0);
|
||||
|
||||
if (walk.ViewerId is { } viewerId && walk.Profiles.TryGetValue(viewerId, out var own))
|
||||
{
|
||||
// The connected account described by its identifier only, and its profile elsewhere in the same answer.
|
||||
walk.Profiles[viewerId] = own with { IsViewer = true };
|
||||
}
|
||||
|
||||
var profiles = walk.Profiles.Values.ToList();
|
||||
var viewer = profiles.FirstOrDefault(p => p.IsViewer);
|
||||
if (walk.Search is not null)
|
||||
{
|
||||
// A search answer, even with no profile in it: never an empty page and never an unknown shape (issue #37).
|
||||
return new ReadResult
|
||||
{
|
||||
Shape = ReadShape.Recognized,
|
||||
Search = walk.Search,
|
||||
Contents = walk.Contents,
|
||||
Profiles = profiles,
|
||||
Highlights = walk.Highlights,
|
||||
Page = walk.Page,
|
||||
Viewer = viewer,
|
||||
ViewerId = viewer?.Id ?? walk.ViewerId,
|
||||
};
|
||||
}
|
||||
|
||||
if (walk.Contents.Count > 0 || walk.Highlights.Count > 0 || profiles.Count > 0)
|
||||
{
|
||||
return new ReadResult
|
||||
@@ -46,12 +70,18 @@ public sealed class ShapeReader
|
||||
Highlights = walk.Highlights,
|
||||
Page = walk.Page,
|
||||
Viewer = viewer,
|
||||
ViewerId = viewer?.Id ?? walk.ViewerId,
|
||||
};
|
||||
}
|
||||
|
||||
if (IsEmptyShape(root, walk.Page is not null))
|
||||
{
|
||||
return new ReadResult { Shape = ReadShape.Empty, Page = walk.Page };
|
||||
return new ReadResult { Shape = ReadShape.Empty, Page = walk.Page, ViewerId = walk.ViewerId };
|
||||
}
|
||||
|
||||
if (_relevance.Count > 0 && !HasAnyKey(root, 0))
|
||||
{
|
||||
return new ReadResult { Shape = ReadShape.Unrelated, ViewerId = walk.ViewerId };
|
||||
}
|
||||
|
||||
return new ReadResult { Shape = ReadShape.Unrecognized, Page = walk.Page, KeyStructure = KeyStructure.Describe(root) };
|
||||
@@ -93,9 +123,18 @@ public sealed class ShapeReader
|
||||
_v.Page.Cursor.TryGet(node, out var cursor) ? AsText(cursor) : null);
|
||||
}
|
||||
|
||||
if (_v.Viewer.TryGet(node, out var viewerNode) && ReadProfile(viewerNode) is { } viewer)
|
||||
if (_v.Viewer.TryGet(node, out var viewerNode))
|
||||
{
|
||||
walk.AddProfile(viewer with { IsViewer = true });
|
||||
if (ReadProfile(viewerNode) is { } viewer)
|
||||
{
|
||||
walk.AddProfile(viewer with { IsViewer = true });
|
||||
}
|
||||
else if (viewerNode.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
// Instagram describes the connected account with its identifier only (xdt_viewer.user): kept, so a
|
||||
// profile with the same identifier can be recognized as the connected account (H10).
|
||||
walk.ViewerId ??= AsText(Get(_v.Profile.Id, viewerNode));
|
||||
}
|
||||
}
|
||||
|
||||
if (IsContent(node))
|
||||
@@ -116,7 +155,7 @@ public sealed class ShapeReader
|
||||
walk.AddProfile(highlightOwner);
|
||||
}
|
||||
|
||||
var id = AsText(Get(_v.Highlight.Id, node))!;
|
||||
var id = HighlightId(AsText(Get(_v.Highlight.Id, node))!);
|
||||
var before = walk.Contents.Count;
|
||||
if (_v.Highlight.Items.TryGet(node, out var items))
|
||||
{
|
||||
@@ -128,6 +167,7 @@ public sealed class ShapeReader
|
||||
Id = id,
|
||||
Title = AsText(Get(_v.Highlight.Title, node)) ?? string.Empty,
|
||||
Owner = highlightOwner,
|
||||
Cover = _v.Highlight.Cover.TryGet(node, out var cover) ? ReadVersion(cover) : null,
|
||||
Items = walk.Contents.Skip(before).ToList(),
|
||||
Order = walk.Highlights.Count,
|
||||
});
|
||||
@@ -149,6 +189,13 @@ public sealed class ShapeReader
|
||||
|
||||
foreach (var property in node.EnumerateObject())
|
||||
{
|
||||
if (IsSearchRoot(property, out var items))
|
||||
{
|
||||
// The search answer: read with its own keys, and its subtree is not walked for generic profiles.
|
||||
walk.Search ??= ReadSearch(items);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
|
||||
{
|
||||
Visit(property.Value, walk, inherited, highlightId, depth + 1);
|
||||
@@ -156,12 +203,84 @@ public sealed class ShapeReader
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A member named like the search root, whose value holds the list of results (issue #37).</summary>
|
||||
private bool IsSearchRoot(JsonProperty property, out JsonElement items)
|
||||
{
|
||||
items = default;
|
||||
var search = _v.Search;
|
||||
return search.IsSet
|
||||
&& property.Value.ValueKind == JsonValueKind.Object
|
||||
&& search.Root.Paths.Contains(property.Name, StringComparer.Ordinal)
|
||||
&& search.Items.TryGet(property.Value, out items)
|
||||
&& items.ValueKind == JsonValueKind.Array;
|
||||
}
|
||||
|
||||
/// <summary>The profiles of a search answer in their order; hashtags and places are never read.</summary>
|
||||
private SearchAnswer ReadSearch(JsonElement items)
|
||||
{
|
||||
var search = _v.Search;
|
||||
var hits = new List<SearchProfile>();
|
||||
var index = 0;
|
||||
foreach (var item in items.EnumerateArray())
|
||||
{
|
||||
var order = index++;
|
||||
if (item.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var node = search.Profile.TryGet(item, out var inner) && inner.ValueKind == JsonValueKind.Object ? inner : item;
|
||||
var id = AsText(Get(search.Id, node));
|
||||
var username = AsText(Get(search.Username, node));
|
||||
if (id is null || string.IsNullOrWhiteSpace(username))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
FileVersion? picture = null;
|
||||
if (search.Picture.TryGet(node, out var pictureNode))
|
||||
{
|
||||
picture = ReadVersions(pictureNode).MaxBy(x => x.Version.Area)?.Version;
|
||||
}
|
||||
|
||||
var profile = new ProfileInfo
|
||||
{
|
||||
Id = id,
|
||||
Username = username.Trim(),
|
||||
DisplayName = AsText(Get(search.DisplayName, node)),
|
||||
Picture = picture,
|
||||
};
|
||||
var position = AsInt(Get(search.Position, item)) ?? order;
|
||||
hits.Add(new SearchProfile(position, profile, search.Verified.TryGet(node, out var verified) ? AsBool(verified) : null));
|
||||
}
|
||||
|
||||
return new SearchAnswer([.. hits.OrderBy(h => h.Position)]);
|
||||
}
|
||||
|
||||
private bool IsContent(JsonElement node) =>
|
||||
_v.Content.Id.Has(node) && _v.Content.TakenAt.Has(node)
|
||||
&& (_v.Content.Images.Has(node) || _v.Content.Videos.Has(node) || _v.Content.Children.Has(node));
|
||||
|
||||
/// <summary>
|
||||
/// A highlight collection: identifier and title, and — when the vocabulary names them — an owner or its items, so
|
||||
/// that any other object with an «id» and a «title» (a promotion, a section of a page) is not taken for one.
|
||||
/// </summary>
|
||||
private bool IsHighlight(JsonElement node) =>
|
||||
_v.Highlight.Id.Has(node) && _v.Highlight.Title.Has(node) && AsText(Get(_v.Highlight.Id, node)) is not null;
|
||||
_v.Highlight.Id.Has(node) && _v.Highlight.Title.Has(node) && AsText(Get(_v.Highlight.Id, node)) is not null
|
||||
&& ((!_v.Highlight.Owner.IsSet && !_v.Highlight.Items.IsSet) || _v.Highlight.Owner.Has(node) || _v.Highlight.Items.Has(node));
|
||||
|
||||
/// <summary>
|
||||
/// The identifier of a collection as its address carries it: Instagram writes «highlight:17841…» in the data and
|
||||
/// «/stories/highlights/17841…/» in the address (HAR of 21/10/2026), so a «kind:» prefix made of letters is dropped.
|
||||
/// </summary>
|
||||
internal static string HighlightId(string id)
|
||||
{
|
||||
var colon = id.IndexOf(':', StringComparison.Ordinal);
|
||||
return colon > 0 && colon < id.Length - 1 && id.AsSpan(0, colon).IndexOfAnyExcept(Letters) < 0 ? id[(colon + 1)..] : id;
|
||||
}
|
||||
|
||||
private static readonly System.Buffers.SearchValues<char> Letters =
|
||||
System.Buffers.SearchValues.Create("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_");
|
||||
|
||||
private ContentItem? ReadContent(JsonElement node, Walk walk, ProfileInfo? inheritedOwner, string? highlightId)
|
||||
{
|
||||
@@ -322,6 +441,41 @@ public sealed class ShapeReader
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>True when one of the relevance keys of the vocabulary is a property name anywhere under <paramref name="element"/>.</summary>
|
||||
private bool HasAnyKey(JsonElement element, int depth)
|
||||
{
|
||||
if (depth > MaxDepth)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (_relevance.Contains(property.Name) || HasAnyKey(property.Value, depth + 1))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
if (HasAnyKey(item, depth + 1))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Empty»: no list with elements anywhere, and either a recognized pagination or only plain values at the top
|
||||
/// (a bare status or error). Anything richer that nothing recognized is an unknown shape.
|
||||
@@ -464,6 +618,12 @@ public sealed class ShapeReader
|
||||
|
||||
public PageInfo? Page { get; set; }
|
||||
|
||||
/// <summary>Identifier of the connected account when the answer gives no more than that.</summary>
|
||||
public string? ViewerId { get; set; }
|
||||
|
||||
/// <summary>The search box answer, when the response holds one (issue #37).</summary>
|
||||
public SearchAnswer? Search { get; set; }
|
||||
|
||||
/// <summary>Merges what different parts of a response say about the same profile.</summary>
|
||||
public void AddProfile(ProfileInfo profile)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Collection.Privacy;
|
||||
|
||||
namespace Febe.Core.Collection.Readers;
|
||||
|
||||
/// <summary>
|
||||
/// The closed list of words a key may be made of to appear in the strict key structure of the diagnostic report
|
||||
/// (issue #39, <see cref="KeyStructure.DescribeStrict"/>). Every other key is written «#»: a user name, a post code or a
|
||||
/// short token used as a key never leaves the machine, even when the body does not repeat it as a value.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A key passes when it has only ASCII letters, digits, «_» and «-», does not look like an identifier, and every part
|
||||
/// between «_» and «-» is a word of the list (case ignored): <c>image_versions2</c>, <c>__typename</c>,
|
||||
/// <c>has_more_headload_comments</c>. The words come from the keys of the cleaned samples in <c>tests/Febe.Tests/campioni</c>
|
||||
/// (structure only: the sanitizer already replaced every key that is data), from the shipped reader vocabularies
|
||||
/// (<c>lettori.instagram.json</c>, <c>lettori.prova.json</c>) and from the words of the site's addresses
|
||||
/// (<see cref="PathPatterns.KnownSegments"/>). A missing word only costs detail («#»), never privacy.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A few words that are also first names, places or opaque codes (<see cref="CompoundOnly"/>) pass only inside a key
|
||||
/// that also has a word of the list (<c>next_max_id</c>), never alone (a user called «max») nor with one another
|
||||
/// (<c>max_mark</c>, two first names).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A name made only of words of the list («the_artist», «street_style») still passes this check, so the strict structure
|
||||
/// (<see cref="KeyStructure.DescribeStrict"/>) asks more of two kinds of keys. A key with a plain value (text, number,
|
||||
/// true or false, null) stays only when it is a field of the closed list (<see cref="IsFieldKey"/>): the entries of a
|
||||
/// map of counts or flags keyed by name never show. The entries of a map of objects or lists are found by their
|
||||
/// siblings (similar keys, a shared identity field such as <c>pk</c>, an empty value, lists of plain values, or a key
|
||||
/// that only the first element of a list has), and among them too only the fields of the closed list stay. A
|
||||
/// single such name used as the key of an object or a list, with no sibling alike and never repeated as a value in the
|
||||
/// body, is the residual risk of a closed list of words.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class StructureWords
|
||||
{
|
||||
private const string SampleWords = """
|
||||
a accessibility account achievements action activation active ad add additional address ads affiliate agent
|
||||
aggregated ai aigm all allow allowed alpha altezza altro and anonymous api app appearance appreciation archive
|
||||
are artist as asset associated at attachment attribute attributed attribution attributions audience audio author
|
||||
authors auto autodub automatically autore autosave available awaiting award background badge badges bandwidth
|
||||
barra base batch bbox be been behavior benefits best bestie besties bio biography bit blocked blocking bloks
|
||||
bookmarked boost boosted bottomsheet brand branded breaking broadcast broadcasts business button by cache camera
|
||||
can candidates canonical caption capture carousel category chaining challenge chat check city client clip clips
|
||||
club cluster coauthor code codecs collab collaborator collection color comment commenter commenting comments
|
||||
commerce commission community complete composer composition config configs connected connection consideration
|
||||
consumption container content contenuti contenuto context contextual control copertina count countdowns counts
|
||||
cover covered created creation creative creator cropped cropping crosspost crosspostable cta cursor custom cut
|
||||
cutout dash data debug decision default delayed deleted demotion deny derived details detected detection dettagli
|
||||
device did disable disabled discover display distribution dopo download downloads downstream durata duration
|
||||
eager earned edges edit edited editing educational effect effects elements eligibility eligible eligiblity
|
||||
embeds embodiment emojis enable enabled encoding end enforced enough entities entry entrypoint entrypoints
|
||||
errors estimated event exclusive expansion expiration expiring explicit explore extensions external face
|
||||
facepile failure fallback fan favorite fb fbid fbsearch featured feed feedback fetch fetching file filmati
|
||||
filter filtered filters final first fissato fitting flags floating flush follow followed follower followers
|
||||
following for formatted foto foundation frame free friction friendship from full gating gen genai geoblocked
|
||||
gif gifting graphql grid group guardian has hashtag hashtags have hd header headline headload height hidden
|
||||
hide high highlight highlights host hypercard id identifier ids ig igbio igids igtv image improvements in
|
||||
incoming indirizzo info inform infos initial initiate inline insert insights instagram integrity interaction
|
||||
interactive internal interop inventory invited invocation io is item items kb key label labels langs language
|
||||
largest larghezza lat latest length light like liked likers likes link linked links list live lng load locales
|
||||
location locations logging long longform main manifest manually marketplace mashed mashup mashups may media
|
||||
medias member memorialized mention merchandising message messaging meta metadata method mids mime module more
|
||||
ms music mute muted muting mutual name new news next node nome non nonmimicable note notes notice notices num
|
||||
number numero nux of on only open options organic original originality outgoing overlap overlay owner page
|
||||
pagina paid param parent parti partnership parts party path payload per photo pic picture pill pinned pivot
|
||||
pivots pk places play playback player playlist playlists point pos position post prefetch premium presets preview
|
||||
previous privacy private privately producer producers product production products professional profile profilo
|
||||
progressive project promo promotion promotions prompts pronouns pubblicato pubblicazioni public qualities
|
||||
quando questions quick quiet raccolta raccolte rank ranked ranking reaction reactions reason reattribution
|
||||
recommendation recs reel reels referral refresh regulated related remix remixes remixing remove rename render
|
||||
rendered reply report repost reposter representation representations request requesting require reshare reshared
|
||||
resolution response rest restore restricted restyle result results reusable reuse revamp review ring riservato
|
||||
risk risorsa risultati ritratto roll root rotation routing row save saved scade scans scroll scrubber search
|
||||
secondary seconds see seen segments seguiti seguito selector sequence server settings severity share shared
|
||||
sharing shop shopping short should show sigla size sizes sliders smart snippet social sort sound source spam
|
||||
spatial speed sponsor sprite spritesheet start starting stato status sticker stickers storia storie story street
|
||||
string strong style submission submitted submitters subscribe subscriber subscribers subtype successiva successivo
|
||||
suggested supervision surface tab tag tagged tagging tags taken tappable tappables teen template testo text the
|
||||
third threading thumbnail thumbnails time timeline timeout timer timestamp tipo tips title titolo to toggle
|
||||
token tool top topic topics topsearch total totali tracking translated translation translations transparency
|
||||
tray treatment trend trending trial type typename ufi ui ultima unavailable unicode unified unpublished unseen
|
||||
unviewable up upcoming upsell uri url urls us use user userid username users usertags utc v1 v2 variant verified
|
||||
version versione versions versions2 video view viewer viewers views visibile visibility visible visual voci
|
||||
wearable wearables weight welcome width with x xdt xdtuserdict xpost y you zip
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// Every key of the cleaned samples of <c>tests/Febe.Tests/campioni</c> (their data keys were already replaced by the
|
||||
/// sanitizer), frozen here because the samples do not ship with Febe: with the keys of the reader vocabularies, the
|
||||
/// closed list of fields (<see cref="IsFieldKey"/>).
|
||||
/// </summary>
|
||||
private const string SampleKeys = """
|
||||
__bbox __typename accessibility_caption account_badges account_type achievements_info action_type
|
||||
active_meta_verified_benefits additional_audio_info additional_audio_username additional_candidates
|
||||
address_street ai_agent_owner_username ai_agent_type ai_interactive_embodiment_attachment_style_info
|
||||
ai_label_info ai_topic_filters aigm_account_label_info all_previous_submitters
|
||||
all_video_dash_prefetch_representations allow_creator_to_rename altezza altro appearance_effect
|
||||
are_remixes_crosspostable asset_recommendation_info associated_clip_medias
|
||||
attributed_custom_audio_asset_id attribution_label_text attribution_user audience audio audio_asset_id
|
||||
audio_asset_start_time_in_ms audio_filter_infos audio_parts audio_parts_by_filter audio_ranking_info
|
||||
audio_reattribution_info audio_type auto_load_more_enabled autore autosave_to_exclusive_highlight
|
||||
bandwidth barra base_url basel_encoding_timeout best_audio_cluster_id bio_links biography
|
||||
biography_with_entities bit_flags blocking bloks_app_url bloks_sticker boost_unavailable_identifier
|
||||
boost_unavailable_reason boost_unavailable_reason_v2 boosted_status branded_content_tag_info
|
||||
breaking_content_info breaking_creator_info broadcasts camera_tool can_add_tag can_remix_be_shared_to_fb
|
||||
can_remix_be_shared_to_fb_expansion can_reply can_reshare can_see_insights_as_brand
|
||||
can_see_organic_insights can_see_quiet_post_attribution can_toggle_mashups_allowed
|
||||
can_view_more_preview_comments can_viewer_reshare can_viewer_save candidates caption caption_is_edited
|
||||
capture_type carousel_media carousel_media_count carousel_parent_id category challenge_info chiave
|
||||
city_name client_cache_key clips_attribution_info clips_connection clips_creation_entry_point
|
||||
clips_metadata clips_tab_pinned_user_ids coauthor_producer_can_see_organic_insights coauthor_producers
|
||||
code codecs collab_follow_button_info collaborator_edit_eligibility color_filters comment comment_count
|
||||
comment_cover_pos comment_filter_param comment_inform_treatment comment_likes_enabled
|
||||
commenting_disabled_for_viewer comments comments_disabled commerce_integrity_review_decision
|
||||
community_notes_info complete connected_member_count consumption_info content_appreciation_info
|
||||
content_type contenuti contenuto contextual_highlight_info copertina corpo cover_media created_at
|
||||
created_at_for_fb_app created_at_utc creation_tool_info creative_config
|
||||
creator_is_in_premium_reactions_alpha cropped_image_version crosspost_metadata cursor custom_list_info
|
||||
cutout_sticker_info dash_manifest data debug_link default deleted_reason
|
||||
derived_content_start_time_in_composition_in_ms descrittore detection_method dettagli device_timestamp
|
||||
did_report_as_spam disable_caption_and_comment disable_use_in_clips_client_cache display_artist
|
||||
display_labels display_labels_with_translations display_media_id display_uri dopo
|
||||
downstream_use_xpost_deny_reason durata duration_in_ms duration_selector_seconds edges effect_configs
|
||||
effect_filter_name effect_preview eligible_for_text_app_activation_badge eligible_insights_entrypoints
|
||||
eligible_promotions enable_media_notes_production enable_submission_friction enabled end end_cursor
|
||||
entities entry_point_container errors estimated_scans_sizes expiring_at explore extensions
|
||||
external_lynx_url external_media_info external_url face_effect_id facepile_top_likers failure_reason
|
||||
fallback fan_club_id fan_club_info fan_club_name fan_consideration_page_revamp_eligiblity
|
||||
fb_comment_count fb_comments fb_downstream_use_xpost_metadata fb_like_count fb_play_count fb_user_tags
|
||||
fbid fbid_v2 featured_label featured_products feed_demotion_control feed_post_reshare_disabled
|
||||
feed_recs_demotion_control fetch__XDTUserDict file_size_kb filmati filter_options filter_type
|
||||
first_frame fissato floating_context_item_type floating_context_items follow_hashtag_info followed_by
|
||||
follower_count following following_count formatted_clips_media_count formatted_mashups_count foto
|
||||
foundation_improvements_enabled friendship_status full_image_version full_name gating
|
||||
gen_ai_detection_method gen_ai_tool_info geoblocked_comment_notices group guardian_hypercard_content
|
||||
has_anonymous_profile_picture has_audio has_been_mashed_up has_besties_media has_chaining
|
||||
has_created_ssc has_delayed_metadata has_enough_subscribers_for_ssc
|
||||
has_high_risk_gen_ai_inform_treatment has_liked has_longform_media has_more_comments
|
||||
has_more_headload_comments has_more_headload_fb_comments has_next_page has_nonmimicable_additional_audio
|
||||
has_previous_page has_privately_liked has_profile_pic has_restyle_presets has_shared_to_fb
|
||||
has_story_archive has_tagged_users has_translation has_viewer_saved has_viewer_submitted_note
|
||||
has_views_fetching has_visible_media_notes hashtags hd_profile_pic_url_info hd_profile_pic_versions
|
||||
headline height hidden_likes_string_variant hide_creator_marketplace_badge hide_remixing
|
||||
hide_stickers_for_original_language hide_view_all_comment_entrypoint highlights horizon_attribution_info
|
||||
host id ig_artist ig_media_sharing_disabled ig_mention ig_play_count ig_quick_promotion_batch_fetch_root
|
||||
igbio_product igtv_first_frame image_versions2 in incoming_request indirizzo inform_module
|
||||
initial_representation_ids initiate_at_top inline_audio_label insert_new_comment_to_top instagram_pk
|
||||
integrity_review_decision interop_messaging_user_fbid inventory_source invited_coauthor_producers io
|
||||
is_active_on_text_post_app is_active_trial is_affiliate_commission_eligible is_ai_user
|
||||
is_audio_automatically_attributed is_auto_detected is_awaiting_distribution is_bestie is_bookmarked
|
||||
is_business is_cannes is_comments_gif_composer_enabled is_coppa_enforced is_covered
|
||||
is_created_by_media_owner is_creator_requesting_mashup is_cutout_sticker_allowed is_dash_eligible
|
||||
is_educational is_eligible_content_for_post_roll_ad is_eligible_for_audio_effects
|
||||
is_eligible_for_autodub is_eligible_for_autodub_upsell is_eligible_for_organic_eager_refresh
|
||||
is_eligible_for_poe is_eligible_for_poe_premium is_eligible_for_request_a_note is_eligible_for_rta
|
||||
is_eligible_for_vinyl_sticker is_embeds_disabled is_enabled is_explicit is_fan_club_gifting_eligible
|
||||
is_fan_club_promo_video is_fan_club_referral_eligible is_favorite is_fb_only is_feed_favorite
|
||||
is_feed_feedback_aggregated is_feedback_aggregated is_feta_guardian_user is_final is_free_trial_eligible
|
||||
is_guardian_user is_in_profile_grid is_internal_only is_light_weight_check
|
||||
is_light_weight_reuse_allowed_check is_longform_player_eligible is_manually_enabled is_memorialized
|
||||
is_meta_ai_invocation_blocked_by_author is_muting_reel is_open_to_public_submission
|
||||
is_organic_product_tagging_eligible is_original_audio_download_eligible is_paid_partnership
|
||||
is_photo_comments_composer_enabled_for_author is_pivot_page_available is_post_live_clips_media
|
||||
is_private is_professional_account is_public_chat_welcome_video is_quiet_post is_ranked_comment
|
||||
is_regulated_c18 is_reshare_of_text_post_app_media_in_ig is_restricted is_reuse_allowed
|
||||
is_reuse_disabled is_ring_creator is_seen is_shared_from_basel is_shared_to_fb is_short_drama
|
||||
is_social_ufi_disabled is_spatial_image is_story_edited is_third_party_downloads_eligible
|
||||
is_trending_in_clips is_unpublished is_verified is_visual_reply_commenter_notice_enabled
|
||||
is_xpost_from_fb items largest_public_bc_id larghezza lat latest_besties_reel_media latest_reel_media
|
||||
latest_wearables_reel_media_long like_and_view_counts_disabled like_count
|
||||
liked_by_media_owner_badge_enabled link link_text linked_fb_info linked_media_playlist_data
|
||||
live_broadcast_id live_broadcast_visibility lng location locations logging_info_token
|
||||
longform_clip_metadata longform_title magic_cut_end_time magic_cut_start_time
|
||||
main_feed_carousel_starting_media_id mashup_info mashup_type mashups_allowed
|
||||
mashups_allowed_for_carousel max_thumbnails_per_sprite may_have_template_info media
|
||||
media_attributions_data media_count media_cropping_info media_header_display media_id media_note
|
||||
media_notes media_overlay_info media_repost_count media_reposter_bottomsheet_enabled media_type
|
||||
media_ui_attributions_data media_ui_attributions_data_v2 merchandising_pill_info message
|
||||
meta_ai_suggested_prompts meta_verified_benefits_info mezql_token mids mime_type more_available
|
||||
music_asset_info music_canonical_id music_info music_metadata muted muting mutual_followers_count name
|
||||
node nome nome_visibile non_privacy_filtered_mashups_media_count note_submission_disabled
|
||||
num_earned_achievements num_results number_of_qualities numero nux_info oa_owner_is_music_artist
|
||||
organic_tracking_token original_audio_subtype original_audio_title original_height original_media
|
||||
original_media_id original_sound_info original_width originality_info outgoing_request
|
||||
overlap_duration_in_ms owner owner_id page_info pagina parti parti_totali path photo_of_you pk pk_id
|
||||
places play_count playback_resolution_csvqm playback_resolution_mos position premium_reaction_count
|
||||
preview preview_comments previous_trend_rank privacy_filtered_mashups_media_count private_reply_status
|
||||
product_type professional_clips_upsell_type profile_background_color profile_background_secondary_color
|
||||
profile_context_facepile_users profile_context_links_with_user_ids profile_grid_control_enabled
|
||||
profile_grid_thumbnail_fitting_style profile_pic_genai_tool_info profile_pic_id profile_pic_url profilo
|
||||
progressive_download_url progressive_identifier pronouns pubblicato pubblicazioni quando
|
||||
quick_response_emojis raccolta raccolte rank_token ranked_position reactions reel_media_background
|
||||
reel_media_seen_timestamp reel_type reels_media reels_on_the_rise_info regulated_news_in_locations
|
||||
related_ads_pivots_media_info remove_message_entrypoint rendered_width representation_id representations
|
||||
request_start_time_ms require reshare_count reshared_story_media_author result
|
||||
reusable_text_attribute_string reusable_text_info ring_creator_metadata riservato risorsa risultati
|
||||
ritratto rotation saved_collection_ids scade scans_profile scroll_behavior
|
||||
scrubber_spritesheet_info_candidates search_social_context search_social_context_snippet_type see_more
|
||||
seen seen_ranked_position segments seguiti seguito sequence_number server_metadata severity
|
||||
share_count_disabled share_enabled sharing_friction_info sharing_friction_payload shop_routing_user_id
|
||||
shopping_info short_drama_creator should_allow_audio_editing should_allow_restore
|
||||
should_have_inform_treatment should_have_sharing_friction should_mute_audio should_mute_audio_reason
|
||||
should_mute_audio_reason_type should_render_upsell should_request_ads
|
||||
should_show_author_pog_for_tagged_media_shared_to_profile_grid should_show_category
|
||||
should_show_playlists_in_profile_tab show_account_transparency_details show_achievements show_ring_award
|
||||
show_text_post_app_badge show_tips sigla smart_frame social_context social_context_facepile_users
|
||||
social_context_type social_context_users_count sort_options speed_selector sponsor_tags sprite_height
|
||||
sprite_urls sprite_width start start_cursor stato status sticker_data storie story_app_attribution
|
||||
story_bloks_stickers story_bloks_tappables story_countdowns story_cta story_feed_media story_hashtags
|
||||
story_link_stickers story_locations story_music_stickers story_questions story_sliders strong_id__
|
||||
subscribe_cta_visible subscriber_count subtype_name_for_REST__ successiva successivo supervision_info
|
||||
surface_nux_id taken_at tappable_elements teen_project_info template_info testo text
|
||||
text_post_app_badge_label text_post_app_is_private text_post_share_to_ig_story_stickers
|
||||
third_party_downloads_enabled threading_enabled thumbnail_duration thumbnail_height thumbnail_width
|
||||
thumbnails thumbnails_per_row time_at_flush_ms time_created timeline_pinned_user_ids
|
||||
timer_selector_seconds tipo title titolo top_likers total_clips_count total_thumbnail_num_per_sprite
|
||||
translated_langs_for_autodub transparency_label transparency_product transparency_product_enabled tray
|
||||
trend_rank tya_media_related_topics type ultima_storia unicode unified_feedback_enabled unseen_count
|
||||
unseen_wearables_media_igids unviewable_authors_infos upcoming_event url url_expiration_timestamp_us
|
||||
user userID user_activation_info user_id user_notes username users usertags valore versione
|
||||
video_dash_manifest video_duration video_id video_length video_sticker_locales video_versions view_count
|
||||
viewer viewer_count viewer_has_liked viewer_interaction_settings viewer_premium_reaction_asset_id
|
||||
viewers visibility visual_comment_reply_sticker_info voci wearable_attribution_info width x
|
||||
xdt_api__v1__discover__chaining xdt_api__v1__fbsearch__topsearch_connection
|
||||
xdt_api__v1__feed__reels_media xdt_api__v1__feed__reels_media__connection xdt_api__v1__feed__reels_tray
|
||||
xdt_api__v1__feed__user_timeline_graphql_connection xdt_api__v1__usertags__user_id__feed_connection
|
||||
xdt_mark_story_reel_seen xdt_viewer xpost_fb_creator_info y zip
|
||||
""";
|
||||
|
||||
private static readonly FrozenSet<string> CompoundOnlyWords = FrozenSet.Create(
|
||||
StringComparer.OrdinalIgnoreCase,
|
||||
"max", "mark", "basel", "cannes", "lynx", "feta", "poe", "drama", "magic", "rise", "vinyl", "horizon", "coppa",
|
||||
"csvqm", "tya", "rta", "ssc", "oa", "bc", "pog", "mezql", "c18", "mos");
|
||||
|
||||
private static readonly Lazy<Lists> Built = new(Build);
|
||||
|
||||
/// <summary>Words that pass only as a part of a key that also has a word of the list.</summary>
|
||||
public static IReadOnlySet<string> CompoundOnly => CompoundOnlyWords;
|
||||
|
||||
/// <summary>True for a word of the list (case ignored).</summary>
|
||||
public static bool IsWord(string word) => Built.Value.Words.Contains(word);
|
||||
|
||||
/// <summary>
|
||||
/// True for a whole key of the shipped reader vocabularies (<c>user</c>, <c>owner</c>, <c>image_versions2</c>), case
|
||||
/// ignored: the only keys the strict structure keeps among the entries of a map.
|
||||
/// </summary>
|
||||
public static bool IsKnownKey(string key) => Built.Value.Keys.Contains(key) && IsStructural(key);
|
||||
|
||||
/// <summary>
|
||||
/// True for a field of the closed list: a whole key of the reader vocabularies (<see cref="IsKnownKey"/>) or of the
|
||||
/// cleaned samples (<c>is_private</c>, <c>has_next_page</c>, <c>pubblicazioni</c>), case ignored, that is also
|
||||
/// structural. In the strict structure, a key with a plain value (text, number, true or false, null), and a key
|
||||
/// among the entries of a map, stays only when it is one of these.
|
||||
/// </summary>
|
||||
public static bool IsFieldKey(string key) =>
|
||||
(Built.Value.Keys.Contains(key) || Built.Value.SampleKeys.Contains(key)) && IsStructural(key);
|
||||
|
||||
/// <summary>True when <paramref name="key"/> may appear as it is in the strict key structure.</summary>
|
||||
public static bool IsStructural(string key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
if (key.Length == 0 || key.Length > 120 || KeyStructure.IsDataKey(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var parts = key.Split(['_', '-'], StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var words = Built.Value.Words;
|
||||
var listWord = false;
|
||||
foreach (var part in parts)
|
||||
{
|
||||
if (words.Contains(part))
|
||||
{
|
||||
listWord = true;
|
||||
}
|
||||
else if (!CompoundOnlyWords.Contains(part))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Compound-only words never stand on their own, nor together («max_mark»): at least one part is a word of the list.
|
||||
return listWord;
|
||||
}
|
||||
|
||||
private static Lists Build()
|
||||
{
|
||||
var words = new HashSet<string>(SampleWords.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries), StringComparer.OrdinalIgnoreCase);
|
||||
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var segment in PathPatterns.KnownSegments)
|
||||
{
|
||||
AddParts(words, segment);
|
||||
}
|
||||
|
||||
foreach (var file in new[] { "lettori.instagram.json", "lettori.prova.json" })
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(SiteMap.ReadEmbeddedText(file));
|
||||
AddVocabulary(words, keys, document.RootElement, 0);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or IOException)
|
||||
{
|
||||
// The sample words are enough: a vocabulary only adds detail.
|
||||
}
|
||||
}
|
||||
|
||||
words.ExceptWith(CompoundOnlyWords);
|
||||
var sampleKeys = SampleKeys.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).ToFrozenSet(StringComparer.OrdinalIgnoreCase);
|
||||
return new Lists(words.ToFrozenSet(StringComparer.OrdinalIgnoreCase), keys.ToFrozenSet(StringComparer.OrdinalIgnoreCase), sampleKeys);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The key names of a vocabulary file: every string of its lists, split at «.» (whole keys) and then at «_» and «-»
|
||||
/// (words).
|
||||
/// </summary>
|
||||
private static void AddVocabulary(HashSet<string> words, HashSet<string> keys, JsonElement element, int depth)
|
||||
{
|
||||
if (depth > 8)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
AddVocabulary(words, keys, property.Value, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
if (item.ValueKind == JsonValueKind.String && item.GetString() is { } path)
|
||||
{
|
||||
foreach (var key in path.Split('.', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (!KeyStructure.IsDataKey(key))
|
||||
{
|
||||
keys.Add(key);
|
||||
AddParts(words, key);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
AddVocabulary(words, keys, item, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record Lists(FrozenSet<string> Words, FrozenSet<string> Keys, FrozenSet<string> SampleKeys);
|
||||
|
||||
private static void AddParts(HashSet<string> words, string key)
|
||||
{
|
||||
foreach (var part in key.Split(['_', '-'], StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
words.Add(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Readers;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
@@ -10,6 +11,12 @@ namespace Febe.Core.Collection.Recipes;
|
||||
/// <param name="Result">What the reader recognized, detached from the body.</param>
|
||||
public sealed record CapturedRead(long Sequence, ResponseDescriptor Response, ReadResult Result);
|
||||
|
||||
/// <summary>
|
||||
/// Where the search answers stood at one moment (issue #37): the last search answer that arrived and the last request
|
||||
/// the page started. Pass it to <see cref="CaptureCollector.SearchSince"/>.
|
||||
/// </summary>
|
||||
public readonly record struct SearchAnswerMark(long Arrival, long Request);
|
||||
|
||||
/// <summary>
|
||||
/// Bridge between the response tap and the recipes (spec §6.2, §6.4): every JSON body the site sends is read by the
|
||||
/// <see cref="ShapeReader"/> as it arrives, and the recipes wait for what they expect after a gesture. Bodies are
|
||||
@@ -22,13 +29,19 @@ public sealed record CapturedRead(long Sequence, ResponseDescriptor Response, Re
|
||||
public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
{
|
||||
private const int MaxKept = 2000;
|
||||
private const int MaxSearchKept = 50;
|
||||
|
||||
private readonly ShapeReader _reader;
|
||||
private readonly IClock _clock;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<CapturedRead> _reads = [];
|
||||
private readonly List<CapturedRead> _searchReads = [];
|
||||
private readonly Dictionary<string, DateTimeOffset> _pending = new(StringComparer.Ordinal);
|
||||
private long _sequence;
|
||||
private long _searchSequence;
|
||||
private long _lastRequestOrder;
|
||||
private DateTimeOffset? _lastArrivalAt;
|
||||
private string? _viewerId;
|
||||
|
||||
public CaptureCollector(ShapeReader reader, IClock clock)
|
||||
{
|
||||
@@ -38,9 +51,30 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
|
||||
public ShapeReader Reader => _reader;
|
||||
|
||||
/// <summary>
|
||||
/// The recorder of the diagnostic report (issue #39), told what the readers did with every body, also the ones
|
||||
/// not kept (another host, unrelated); null: nothing is recorded.
|
||||
/// </summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
|
||||
/// <summary>How long a data response may stay «on its way» before it is forgotten (its body may never come).</summary>
|
||||
public TimeSpan PendingLifetime { get; init; } = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>
|
||||
/// Identifier of the connected account in the latest site answer that gave one (<see cref="ReadResult.ViewerId"/>),
|
||||
/// also an answer that is otherwise <see cref="ReadShape.Unrelated"/> and not kept.
|
||||
/// </summary>
|
||||
public string? ViewerId
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _viewerId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sequence number of the last read: pass it to <see cref="Since"/> to get what arrives after now.</summary>
|
||||
public long Mark()
|
||||
{
|
||||
@@ -59,6 +93,46 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where the search box answers stand now (issue #37): pass it to <see cref="SearchSince"/>. Search answers have
|
||||
/// their own buffer, so recipe windows (<see cref="Mark"/>, <see cref="Since"/>) never see them. Taken right before
|
||||
/// a key, it separates the requests the page started for the texts before that key from the ones after it.
|
||||
/// </summary>
|
||||
public SearchAnswerMark SearchMark()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return new SearchAnswerMark(_searchSequence, _lastRequestOrder);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Search box answers to requests the page started after <paramref name="mark"/>, oldest request first. An answer
|
||||
/// whose request order is unknown counts by its arrival instead.
|
||||
/// </summary>
|
||||
public IReadOnlyList<CapturedRead> SearchSince(SearchAnswerMark mark)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return [.. _searchReads
|
||||
.Where(r => r.Response.RequestOrder > 0 ? r.Response.RequestOrder > mark.Request : r.Sequence > mark.Arrival)
|
||||
.OrderBy(r => r.Response.RequestOrder)
|
||||
.ThenBy(r => r.Sequence)];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>When the body of the last response of the site was read (any kind, unrelated ones included).</summary>
|
||||
public DateTimeOffset? LastArrivalAt
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _lastArrivalAt;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Data responses whose body has not been read yet.</summary>
|
||||
public int Pending
|
||||
{
|
||||
@@ -135,7 +209,10 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Reads one body (also used by tests and the probe samples).</summary>
|
||||
/// <summary>
|
||||
/// Reads one body (also used by tests and the probe samples). Returns null, and keeps nothing, for responses that
|
||||
/// are not the site's or that are <see cref="ReadShape.Unrelated"/>.
|
||||
/// </summary>
|
||||
public CapturedRead? Accept(ResponseDescriptor response, JsonElement body)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
@@ -146,10 +223,44 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
|
||||
if (response.HostKind != HostKind.Site)
|
||||
{
|
||||
Observe(response, null, body);
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = _reader.Read(body);
|
||||
Observe(response, result, body);
|
||||
lock (_gate)
|
||||
{
|
||||
_lastArrivalAt = _clock.Now;
|
||||
if (result.ViewerId is { } viewerId)
|
||||
{
|
||||
_viewerId = viewerId;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.Search is not null)
|
||||
{
|
||||
// A search box answer goes to its own buffer: it never stops, fills or judges a recipe (issue #37).
|
||||
lock (_gate)
|
||||
{
|
||||
var found = new CapturedRead(++_searchSequence, response, result);
|
||||
_searchReads.Add(found);
|
||||
if (_searchReads.Count > MaxSearchKept)
|
||||
{
|
||||
_searchReads.RemoveRange(0, _searchReads.Count - MaxSearchKept);
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.Shape == ReadShape.Unrelated)
|
||||
{
|
||||
// Not about contents (promotions, logging): neither data nor an empty page, and not «something new
|
||||
// arrived» for SettleAsync, or a page that keeps logging would never look settled.
|
||||
return null;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
var read = new CapturedRead(++_sequence, response, result);
|
||||
@@ -163,10 +274,32 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tells the diagnostics what the readers made of a body; for an unknown shape, its strict key structure, taken
|
||||
/// now, while the document is alive. Never a reason to fail the reading.
|
||||
/// </summary>
|
||||
private void Observe(ResponseDescriptor response, ReadResult? result, JsonElement body)
|
||||
{
|
||||
if (Diagnostics is not { } diagnostics)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var structure = result?.Shape == ReadShape.Unrecognized ? KeyStructure.DescribeStrict(body) : null;
|
||||
diagnostics.ReadObserved(response, result, structure);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Diagnostics are optional: the reading goes on as if they were not there.
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnResponse(ResponseDescriptor response)
|
||||
{
|
||||
if (response.HostKind == HostKind.Site
|
||||
&& response.MimeType.Contains("json", StringComparison.OrdinalIgnoreCase)
|
||||
&& DataResponses.IsData(response.MimeType, response.ResourceType)
|
||||
&& response.Status is >= 200 and < 600 && response.Status != 204)
|
||||
{
|
||||
lock (_gate)
|
||||
@@ -176,6 +309,25 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnRequestStarted(long order)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (order > _lastRequestOrder)
|
||||
{
|
||||
_lastRequestOrder = order;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnBodyDropped(string requestId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_pending.Remove(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnNavigation(NavigationDescriptor navigation)
|
||||
{
|
||||
if (!navigation.SameDocument)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
@@ -44,6 +45,9 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
|
||||
public IFebeStorage Storage => storage;
|
||||
|
||||
/// <summary>The recorder of the diagnostic report (issue #39): files put in the download queue. Null: not recorded.</summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// A profile seen in the data. The account is identified by its numeric id; when its name changed, a followed
|
||||
/// profile is renamed (folder kept, notice raised) and a profile that is not followed becomes «Non raggiungibile»
|
||||
@@ -138,22 +142,29 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
var (result, queued, skipped) = await SaveCoreAsync(account, item, kind, ct).ConfigureAwait(false);
|
||||
Diagnostics?.FilesQueued(sessionId, kind, queued, result.Outcome.ToString(), skipped);
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task<(SaveResult Result, int Queued, int Skipped)> SaveCoreAsync(Account account, ContentItem item, EntryKind kind, CancellationToken ct)
|
||||
{
|
||||
if (!Wants(account, kind))
|
||||
{
|
||||
return new SaveResult(SaveOutcome.Excluded, null);
|
||||
return (new SaveResult(SaveOutcome.Excluded, null), 0, 0);
|
||||
}
|
||||
|
||||
var known = await storage.Entries.FindAsync(account.Id, kind, item.Id, ct).ConfigureAwait(false);
|
||||
if (known is not null)
|
||||
{
|
||||
await RefreshFilesAsync(known, item, fromHighlight: false, ct).ConfigureAwait(false);
|
||||
return new SaveResult(SaveOutcome.Known, known);
|
||||
return (new SaveResult(SaveOutcome.Known, known), 0, 0);
|
||||
}
|
||||
|
||||
if (kind is EntryKind.Post or EntryKind.Tagged
|
||||
&& account.Limits.Depth == HistoryDepth.FromDate && account.Limits.FromDate is { } from && item.TakenAt < from)
|
||||
{
|
||||
return new SaveResult(SaveOutcome.Excluded, null);
|
||||
return (new SaveResult(SaveOutcome.Excluded, null), 0, 0);
|
||||
}
|
||||
|
||||
if (kind != EntryKind.ProfilePicture
|
||||
@@ -166,7 +177,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
Caption = imported.Caption ?? item.Caption,
|
||||
};
|
||||
await storage.Entries.UpdateAsync(enriched, ct).ConfigureAwait(false);
|
||||
return new SaveResult(SaveOutcome.Enriched, enriched);
|
||||
return (new SaveResult(SaveOutcome.Enriched, enriched), 0, 0);
|
||||
}
|
||||
|
||||
var now = clock.Now;
|
||||
@@ -175,7 +186,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
var added = await storage.Entries.AddAsync(entry, media, ct).ConfigureAwait(false);
|
||||
if (!added.Created)
|
||||
{
|
||||
return new SaveResult(SaveOutcome.Known, added.Stored.Entry);
|
||||
return (new SaveResult(SaveOutcome.Known, added.Stored.Entry), 0, 0);
|
||||
}
|
||||
|
||||
if (!item.IsComplete && kind is EntryKind.Post or EntryKind.Tagged)
|
||||
@@ -183,7 +194,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
await QueueSinglePostAsync(added.Stored.Entry, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new SaveResult(SaveOutcome.Created, added.Stored.Entry);
|
||||
return (new SaveResult(SaveOutcome.Created, added.Stored.Entry), media.Count(m => m.State == MediaState.ToDownload), media.Count(m => m.State == MediaState.Skipped));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -201,6 +212,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
var added = await storage.Entries.AddAsync(picture.Entry, [picture.Media], ct).ConfigureAwait(false);
|
||||
if (added.Created)
|
||||
{
|
||||
Diagnostics?.FilesQueued(null, EntryKind.ProfilePicture, picture.Media.State == MediaState.ToDownload ? 1 : 0, nameof(SaveOutcome.Created));
|
||||
return new SaveResult(SaveOutcome.Created, added.Stored.Entry);
|
||||
}
|
||||
|
||||
@@ -259,6 +271,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
}
|
||||
}
|
||||
|
||||
Diagnostics?.FilesQueued(null, entry.Kind, changed, CollectionDiagnostics.CompletedOutcome);
|
||||
if ((entry.Code is null && item.Code is not null) || (entry.Caption is null && item.Caption is not null))
|
||||
{
|
||||
var latest = await storage.Entries.GetAsync(entry.Id, ct).ConfigureAwait(false) ?? entry;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
/// <summary>
|
||||
/// What the focus check of the site's search box says (issue #37). Never the text: only whether the box is on the
|
||||
/// page, whether the focus is in it, how many characters it holds and whether the caret is at the end.
|
||||
/// </summary>
|
||||
/// <param name="BoxFound">The search box is on the page and visible.</param>
|
||||
/// <param name="Focused">The focus is in the box.</param>
|
||||
/// <param name="Length">Characters in the box, only when the focus is in it (null otherwise).</param>
|
||||
/// <param name="CaretAtEnd">The caret is at the end of the text, with nothing selected.</param>
|
||||
public sealed record SearchFocus(bool BoxFound, bool Focused, int? Length, bool CaretAtEnd)
|
||||
{
|
||||
/// <summary>No box on the page.</summary>
|
||||
public static SearchFocus None { get; } = new(false, false, null, false);
|
||||
|
||||
/// <summary>The box has the focus and the caret is at the end: keys go where Febe wants them.</summary>
|
||||
public bool Ready => BoxFound && Focused && Length is not null && CaretAtEnd;
|
||||
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"BoxFound = {BoxFound}, Focused = {Focused}, Length = {Length}, CaretAtEnd = {CaretAtEnd}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Typing into the site's own search box (issue #37), with <c>Input.dispatchKeyEvent</c> only: letters, digits,
|
||||
/// «.», «_» and spaces, Backspace and End, never Enter, Tab or Escape. Separate from <see cref="IPageDriver"/>, which
|
||||
/// the recipes use: only the profile search types.
|
||||
/// </summary>
|
||||
public interface ISearchInput
|
||||
{
|
||||
/// <summary>The read-only focus check of the search box.</summary>
|
||||
Task<SearchFocus> FocusAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Presses End: the caret goes to the end of the text.</summary>
|
||||
Task EndKeyAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Presses Backspace <paramref name="count"/> times at a human rhythm; <paramref name="beforeKey"/> runs right
|
||||
/// before every key (the search notes where the page's requests stand).
|
||||
/// </summary>
|
||||
Task EraseAsync(int count, Action? beforeKey, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Types the characters <paramref name="next"/> gives, one at a time at a human rhythm, until it returns null.
|
||||
/// <paramref name="next"/> receives how many characters were typed so far, and may run its own checks (it is
|
||||
/// awaited before every key). Returns how many characters were typed. A character outside the closed key map stops
|
||||
/// the burst with <see cref="ArgumentException"/> before its key is sent.
|
||||
/// </summary>
|
||||
Task<int> TypeAsync(Func<int, CancellationToken, ValueTask<char?>> next, CancellationToken ct);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
@@ -9,6 +10,9 @@ namespace Febe.Core.Collection.Recipes;
|
||||
internal sealed class RecipeStopException(RecipeStatus status, string message) : Exception(message)
|
||||
{
|
||||
public RecipeStatus Status { get; } = status;
|
||||
|
||||
/// <summary>For a failure on an unexpected error: the type name of that exception (diagnostic report, never the message).</summary>
|
||||
public string? ErrorType { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -74,10 +78,20 @@ internal sealed class RecipeRun : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Asks the Governor for a counted action; stops in order when refused or when the session is over.</summary>
|
||||
public async Task PermitAsync(ActionKind kind, long? accountId)
|
||||
/// <summary>
|
||||
/// Asks the Governor for a counted action; stops in order when refused or when the session is over. With
|
||||
/// <paramref name="opensPage"/> (the next step opens a page), this is a turn point of the page (issue #37): when the
|
||||
/// profile search waits, it gets the page for one step first, and the checks run again after it.
|
||||
/// </summary>
|
||||
public async Task PermitAsync(ActionKind kind, long? accountId, bool opensPage = false)
|
||||
{
|
||||
ThrowIfSignal();
|
||||
if (opensPage && Env.PageTurns is { } turns && turns.EngineTurn is { } turn && await turns.YieldAsync(turn, Ct).ConfigureAwait(false))
|
||||
{
|
||||
// The page may have changed meanwhile: what follows opens a page anyway, but the state is looked at again.
|
||||
ThrowIfSignal();
|
||||
}
|
||||
|
||||
if (Env.Clock.Now > Session.PlannedEnd)
|
||||
{
|
||||
throw Stop(RecipeStatus.Denied, "La sessione è finita: la ricetta riprenderà alla prossima.");
|
||||
@@ -96,7 +110,20 @@ internal sealed class RecipeRun : IDisposable
|
||||
public async Task<PageLoad> OpenAsync(string page, IReadOnlyDictionary<string, string>? values = null)
|
||||
{
|
||||
var path = Env.SiteMap.BuildPath(page, values);
|
||||
var load = await Env.Driver.OpenAsync(path, Ct).ConfigureAwait(false);
|
||||
PageLoad load;
|
||||
try
|
||||
{
|
||||
load = await Env.Driver.OpenAsync(path, Ct).ConfigureAwait(false);
|
||||
Env.PageTurns?.NoteOpened(PageUser.Engine);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Env.Diagnostics?.PageOpened(Session.SessionId, page, ok: false);
|
||||
throw;
|
||||
}
|
||||
|
||||
// The page NAME of the site map, never the path: it holds the user name or the code.
|
||||
Env.Diagnostics?.PageOpened(Session.SessionId, page, load.Succeeded);
|
||||
ThrowIfSignal();
|
||||
if (!load.Succeeded)
|
||||
{
|
||||
@@ -114,6 +141,7 @@ internal sealed class RecipeRun : IDisposable
|
||||
{
|
||||
ThrowIfSignal();
|
||||
var result = await Env.Driver.ClickAsync(target, parameters, Ct).ConfigureAwait(false);
|
||||
Env.Diagnostics?.TargetClicked(Session.SessionId, target, result.Status);
|
||||
if (!result.Found)
|
||||
{
|
||||
ThrowIfSignal();
|
||||
@@ -167,6 +195,7 @@ internal sealed class RecipeRun : IDisposable
|
||||
{
|
||||
if (reads.Any(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)))
|
||||
{
|
||||
Env.Diagnostics?.StepJudged(Session.SessionId, CollectionDiagnostics.VerdictRecognized);
|
||||
_signals.ObserveNonEmptyPage();
|
||||
return true;
|
||||
}
|
||||
@@ -174,10 +203,12 @@ internal sealed class RecipeRun : IDisposable
|
||||
var unknown = reads.Where(r => r.Result.Shape == ReadShape.Unrecognized && r.Result.KeyStructure is not null).Select(r => r.Result.KeyStructure!).Distinct().ToList();
|
||||
if (unknown.Count > 0)
|
||||
{
|
||||
Env.Diagnostics?.StepJudged(Session.SessionId, CollectionDiagnostics.VerdictUnknown);
|
||||
UnknownShapes.AddRange(unknown);
|
||||
throw Stop(RecipeStatus.UnrecognizedFormat, "La risposta del sito ha una forma che i lettori non riconoscono.");
|
||||
}
|
||||
|
||||
Env.Diagnostics?.StepJudged(Session.SessionId, CollectionDiagnostics.VerdictEmpty);
|
||||
_signals.ObserveEmptyPage(where);
|
||||
ThrowIfSignal();
|
||||
return false;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
@@ -46,7 +47,7 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.Denied, $"{account.Username} è «Solo archivio»: non si contatta.");
|
||||
}
|
||||
|
||||
await run.PermitAsync(ActionKind.SinglePost, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.SinglePost, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Post, Values(("code", entry.Code))).ConfigureAwait(false);
|
||||
bool Matches(Readers.ContentItem c) => c.Id == entry.InstagramId || (c.Code is not null && c.Code == entry.Code);
|
||||
@@ -93,13 +94,17 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.FollowingPagesPerRun);
|
||||
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(
|
||||
byPage ? SitePages.FollowingFrom : SitePages.Following,
|
||||
byPage ? Values(("username", mine.Username), ("cursor", stored!)) : Values(("username", mine.Username))).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Profiles.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Profiles.Count > 0, null))
|
||||
|
||||
// Only followed profiles say the list came: the page also receives suggested profiles (not followed) and
|
||||
// Alberto's own profile, which would pass for a list that is not there.
|
||||
bool Listed(ReadResult r) => r.Profiles.Any(p => IsListed(p, mine));
|
||||
var reads = await WaitAndSettleAsync(run, mark, Listed).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, Listed, null))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
@@ -109,7 +114,9 @@ public sealed partial class RecipeRunner
|
||||
while (true)
|
||||
{
|
||||
read += await SaveFollowingPageAsync(run, reads, mine, read).ConfigureAwait(false);
|
||||
var page = LastPage(reads);
|
||||
|
||||
// The pagination of the list, never that of another answer (the suggestions, a post, the collections).
|
||||
var page = PageOf(reads, r => r.Profiles.Where(p => IsListed(p, mine)).Select(p => p.Id), r => r.Shape == ReadShape.Empty);
|
||||
if (catchingUp && ((page?.Cursor is { } c && string.Equals(c, stored, StringComparison.Ordinal)) || read >= readBefore))
|
||||
{
|
||||
catchingUp = false; // back where the last run stopped
|
||||
@@ -133,7 +140,7 @@ public sealed partial class RecipeRunner
|
||||
|
||||
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false);
|
||||
var counted = !catchingUp;
|
||||
reads = await ScrollForPageAsync(run, r => r.Profiles.Count > 0).ConfigureAwait(false);
|
||||
reads = await ScrollForPageAsync(run, Listed).ConfigureAwait(false);
|
||||
if (counted)
|
||||
{
|
||||
pages++;
|
||||
@@ -175,12 +182,20 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, progress);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A profile of the following list: not Alberto himself, and not one the answer says he does not follow (Instagram
|
||||
/// sends suggested profiles with «friendship_status.following: false», HAR of 21/10/2026). A profile that does not
|
||||
/// say is taken as listed: it came with the list.
|
||||
/// </summary>
|
||||
private static bool IsListed(ProfileInfo profile, Account mine) =>
|
||||
profile.IsFollowed != false && !profile.IsViewer && profile.Id != mine.InstagramId;
|
||||
|
||||
/// <summary>Stores one page of the following list in reading order; renamed followed accounts are recognized.</summary>
|
||||
private async Task<int> SaveFollowingPageAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, Account mine, int offset)
|
||||
{
|
||||
var now = Env.Clock.Now;
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
var profiles = reads.SelectMany(r => r.Result.Profiles).Where(p => !p.IsViewer && p.Id != mine.InstagramId && seen.Add(p.Id)).ToList();
|
||||
var profiles = reads.SelectMany(r => r.Result.Profiles).Where(p => IsListed(p, mine) && seen.Add(p.Id)).ToList();
|
||||
var records = new List<FollowingRecord>(profiles.Count);
|
||||
for (var i = 0; i < profiles.Count; i++)
|
||||
{
|
||||
|
||||
@@ -122,6 +122,13 @@ public sealed partial class RecipeRunner
|
||||
|
||||
/// <summary>Items already saved by the caller (they are not saved again).</summary>
|
||||
public HashSet<string> Processed { get; init; } = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// The reads the walk starts from answer a gesture of the walk itself (a resume page, a tab): a bare empty answer
|
||||
/// among them is its empty page. After opening the profile it is not: an empty answer there may be about
|
||||
/// something else (the collections of an account that has none).
|
||||
/// </summary>
|
||||
public bool StartsFromOwnAnswer { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -134,9 +141,9 @@ public sealed partial class RecipeRunner
|
||||
private async Task<RecipeStatus> ProfileCheckAsync(RecipeRun run)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
var (current, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
|
||||
var (current, reads) = await OpenProfileAsync(run, account, waitForGrid: true).ConfigureAwait(false);
|
||||
account = current;
|
||||
var profile = FindProfile(reads, account)!;
|
||||
var profile = AccountProfile(reads, account)!;
|
||||
|
||||
if (profile.LatestStoryAt is { } latest && latest > (account.LastStoriesCheckAt ?? DateTimeOffset.MinValue)
|
||||
&& account.ContentTypes.HasFlag(ContentTypes.Stories))
|
||||
@@ -174,7 +181,7 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
var page = LastPage(reads);
|
||||
var page = WalkPage(reads, account, walk, ownAnswer: false);
|
||||
if (!sawKnown && account.BackfillCompletedAt is null && account.BackfillCursor is null)
|
||||
{
|
||||
if (page?.HasMore == true && page.Cursor is { } cursor)
|
||||
@@ -218,7 +225,7 @@ public sealed partial class RecipeRunner
|
||||
var before = ParseTime(await settings.GetAsync(keys[2], run.Ct).ConfigureAwait(false));
|
||||
async Task ClearAsync() => await settings.SetManyAsync(keys.ToDictionary(k => k, _ => (string?)null), run.Ct).ConfigureAwait(false);
|
||||
|
||||
if (LastPage(reads)?.HasMore == false)
|
||||
if (WalkPage(reads, account, walk, ownAnswer: false)?.HasMore == false)
|
||||
{
|
||||
if (stored is not null || before is not null)
|
||||
{
|
||||
@@ -234,6 +241,7 @@ public sealed partial class RecipeRunner
|
||||
IReadOnlyList<CapturedRead> start = reads;
|
||||
ResumePoint? catchUpTo = null;
|
||||
var pages = 0;
|
||||
var ownStart = false;
|
||||
if (!tailIsNew)
|
||||
{
|
||||
if (stored is null)
|
||||
@@ -243,16 +251,17 @@ public sealed partial class RecipeRunner
|
||||
|
||||
if (Env.SiteMap.HasPage(walk.ResumePage))
|
||||
{
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", stored.Cursor))).ConfigureAwait(false);
|
||||
start = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(start, r => r.Contents.Count > 0 || r.Page is not null, null))
|
||||
start = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
|
||||
if (!run.Judge(start, r => IsWalkPage(r, account, walk), null))
|
||||
{
|
||||
return; // an empty page, counted: the gap stays for the next check
|
||||
}
|
||||
|
||||
pages = 1;
|
||||
ownStart = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -266,6 +275,7 @@ public sealed partial class RecipeRunner
|
||||
{
|
||||
CatchUpTo = catchUpTo,
|
||||
PagesRead = pages,
|
||||
StartsFromOwnAnswer = ownStart,
|
||||
MaxPages = Math.Max(1, Env.Options.GapPagesPerCheck),
|
||||
Stop = floor is { } f ? new KnownStop(true, f) : KnownStop.Any,
|
||||
CheckDownloads = true,
|
||||
@@ -345,14 +355,15 @@ public sealed partial class RecipeRunner
|
||||
IReadOnlyList<CapturedRead> reads;
|
||||
var pages = 0;
|
||||
ResumePoint? catchUpTo = null;
|
||||
var ownStart = true; // a resume page or a tab; not the profile as opened
|
||||
if (target is not null && Env.SiteMap.HasPage(walk.ResumePage))
|
||||
{
|
||||
// Resume where the last run stopped: the page of the site that starts after the stored point.
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", target.Cursor))).ConfigureAwait(false);
|
||||
reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
reads = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => IsWalkPage(r, account, walk), Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
@@ -361,15 +372,16 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
else
|
||||
{
|
||||
(account, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
|
||||
(account, reads) = await OpenProfileAsync(run, account, waitForGrid: walk.IsGrid).ConfigureAwait(false);
|
||||
ownStart = walk.TabTarget is not null;
|
||||
if (walk.TabTarget is { } tab)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.ClickAsync(tab, parameters).ConfigureAwait(false);
|
||||
await Env.Driver.WaitAfterLoadAsync(run.Ct).ConfigureAwait(false);
|
||||
reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, null))
|
||||
reads = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => IsWalkPage(r, account, walk), null))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
@@ -387,6 +399,7 @@ public sealed partial class RecipeRunner
|
||||
{
|
||||
CatchUpTo = catchUpTo,
|
||||
PagesRead = pages,
|
||||
StartsFromOwnAnswer = ownStart,
|
||||
MaxPages = maxPages,
|
||||
Stop = checkOnly ? KnownStop.Any : KnownStop.Never,
|
||||
CheckDownloads = !checkOnly,
|
||||
@@ -441,10 +454,12 @@ public sealed partial class RecipeRunner
|
||||
var pending = rules.CatchUpTo;
|
||||
var pages = rules.PagesRead;
|
||||
var catchUp = 0;
|
||||
var ownAnswer = rules.StartsFromOwnAnswer;
|
||||
IReadOnlySet<string>? seen = null; // the first page: only what its own answers bring
|
||||
while (true)
|
||||
{
|
||||
var items = PageItems(reads, account, walk);
|
||||
var page = LastPage(reads);
|
||||
var page = WalkPage(reads, account, walk, ownAnswer, seen);
|
||||
if (pending is not null && pending.IsReachedBy(page, items, i => walk.IsChronological && !IsPinned(i, items, walk)))
|
||||
{
|
||||
pending = null; // this page holds the stored point: from here on the walk goes on as usual
|
||||
@@ -483,7 +498,13 @@ public sealed partial class RecipeRunner
|
||||
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var counted = pending is null;
|
||||
reads = await ScrollForPageAsync(run, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
|
||||
// Only items of the walk not read yet say the next page came: an answer about something else that arrives
|
||||
// meanwhile (a post of another account, the collections), or one that brings again a post already read
|
||||
// (the page of that post), neither counts as it nor ends the walk with its pagination.
|
||||
reads = await ScrollForPageAsync(run, r => r.Contents.Any(c => IsWalkItem(c, account, walk) && !rules.Processed.Contains(c.Id))).ConfigureAwait(false);
|
||||
ownAnswer = true;
|
||||
seen = rules.Processed;
|
||||
if (counted)
|
||||
{
|
||||
pages++;
|
||||
@@ -561,7 +582,124 @@ public sealed partial class RecipeRunner
|
||||
|
||||
/// <summary>The posts of a walk page: of the account (tagged: of others), never a story or a collection item.</summary>
|
||||
private static IReadOnlyList<ContentItem> PageItems(IReadOnlyList<CapturedRead> reads, Account account, ProfileWalk walk) =>
|
||||
Contents(reads, c => IsPostLike(c) && (walk.Kind == EntryKind.Tagged ? !IsOwnedBy(c, account) : IsOwnedBy(c, account)));
|
||||
Contents(reads, c => IsWalkItem(c, account, walk));
|
||||
|
||||
/// <summary>An item of a walk: a post of the account (tagged: of another account), never a story or a collection item.</summary>
|
||||
private static bool IsWalkItem(ContentItem item, Account account, ProfileWalk walk) =>
|
||||
IsPostLike(item) && (walk.Kind == EntryKind.Tagged ? !IsOwnedBy(item, account) : IsOwnedBy(item, account));
|
||||
|
||||
/// <summary>An answer that brings items of the walk.</summary>
|
||||
private static bool CarriesWalk(ReadResult result, Account account, ProfileWalk walk) =>
|
||||
result.Contents.Any(c => IsWalkItem(c, account, walk));
|
||||
|
||||
/// <summary>
|
||||
/// An answer to a gesture of the walk (a resume page, a tab) that is a page of it on its own: it brings items of the
|
||||
/// walk, or it is an empty page of it (<see cref="IsEmptyWalkPage"/>).
|
||||
/// </summary>
|
||||
private static bool IsWalkPage(ReadResult result, Account account, ProfileWalk walk) =>
|
||||
CarriesWalk(result, account, walk) || IsEmptyWalkPage(result, account, walk, ownAnswer: true);
|
||||
|
||||
/// <summary>
|
||||
/// The end of a tab with nothing in it: a pagination and no item. With the profile of the account (the test site
|
||||
/// sends it with every page of the tab), when nothing else comes with it, or — on the grid — when that profile says
|
||||
/// it has no posts (the test site sends the collections with the first page of the grid). A bare empty answer only
|
||||
/// when it answers a gesture of the walk (<paramref name="ownAnswer"/>): on Instagram the collections of an account
|
||||
/// that has none are an empty connection with «has_next_page: false», as an empty grid would be, and they come
|
||||
/// with the profile too.
|
||||
/// </summary>
|
||||
private static bool IsEmptyWalkPage(ReadResult result, Account account, ProfileWalk walk, bool ownAnswer) =>
|
||||
result.Page is not null && result.Shape switch
|
||||
{
|
||||
ReadShape.Empty => ownAnswer,
|
||||
ReadShape.Recognized => ProfileIn(result, account) is { } profile
|
||||
&& ((result.Contents.Count == 0 && result.Highlights.Count == 0)
|
||||
|| (walk.IsGrid && profile.PostCount == 0 && !result.Contents.Any(IsPostLike))),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The pagination of a walk page: from the answer that brought the most items of the walk not read before
|
||||
/// (<paramref name="seen"/>: the pages already read); when none did, from the last empty page of the walk
|
||||
/// (<paramref name="ownAnswer"/>: the reads answer a gesture of the walk, <see cref="IsEmptyWalkPage"/>). Never from
|
||||
/// an answer about something else, nor from one that only brings again a post already read: on Instagram the page
|
||||
/// of a post says «more_available: false» of its single post and the collections say «has_next_page» of
|
||||
/// themselves (HAR of 21/10/2026), and either would end the walk, or mark the history complete, where the grid
|
||||
/// goes on.
|
||||
/// </summary>
|
||||
private static PageInfo? WalkPage(IReadOnlyList<CapturedRead> reads, Account account, ProfileWalk walk, bool ownAnswer, IReadOnlySet<string>? seen = null) =>
|
||||
PageOf(reads, r => r.Contents.Where(c => IsWalkItem(c, account, walk)).Select(c => c.Id), r => IsEmptyWalkPage(r, account, walk, ownAnswer), seen);
|
||||
|
||||
/// <summary>
|
||||
/// The pagination of a page of a list (a profile tab, the feed, the following list): from the answer that brings
|
||||
/// the most items of the list not met before — in <paramref name="seen"/>, or in an earlier answer of the same page
|
||||
/// with a pagination of its own — the last one on a tie; when none brings any, from the last empty page. An answer
|
||||
/// that only brings again items already met, or fewer new ones than another (the page of a single post next to the
|
||||
/// grid), never gives it.
|
||||
/// </summary>
|
||||
private static PageInfo? PageOf(IEnumerable<CapturedRead> reads, Func<ReadResult, IEnumerable<string>> itemIds, Func<ReadResult, bool> isEmptyPage, IReadOnlySet<string>? seen = null)
|
||||
{
|
||||
var met = new HashSet<string>(StringComparer.Ordinal);
|
||||
PageInfo? withItems = null;
|
||||
var most = 0;
|
||||
PageInfo? empty = null;
|
||||
foreach (var result in reads.Select(r => r.Result).Where(r => r.Page is not null))
|
||||
{
|
||||
var carried = 0;
|
||||
var fresh = 0;
|
||||
foreach (var id in itemIds(result))
|
||||
{
|
||||
carried++;
|
||||
if (met.Add(id) && seen?.Contains(id) != true)
|
||||
{
|
||||
fresh++;
|
||||
}
|
||||
}
|
||||
|
||||
if (fresh > 0)
|
||||
{
|
||||
if (fresh >= most)
|
||||
{
|
||||
most = fresh;
|
||||
withItems = result.Page;
|
||||
}
|
||||
}
|
||||
else if (carried == 0 && isEmptyPage(result))
|
||||
{
|
||||
empty = result.Page;
|
||||
}
|
||||
}
|
||||
|
||||
return withItems ?? empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The profile of the account as all the answers of the page describe it: the same profile can come in several
|
||||
/// of them (the profile itself, the author of the posts, the owner of the collections), each with part of its
|
||||
/// facts. The best described one is completed with what the others say; of the pictures, the largest.
|
||||
/// </summary>
|
||||
private static ProfileInfo? AccountProfile(IReadOnlyList<CapturedRead> reads, Account account)
|
||||
{
|
||||
if (FindProfile(reads, account) is not { } best)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var other in reads.SelectMany(r => r.Result.Profiles).Where(p => p.Id == best.Id).ToList())
|
||||
{
|
||||
best = best with
|
||||
{
|
||||
DisplayName = best.DisplayName ?? other.DisplayName,
|
||||
IsPrivate = best.IsPrivate ?? other.IsPrivate,
|
||||
IsFollowed = best.IsFollowed ?? other.IsFollowed,
|
||||
PostCount = best.PostCount ?? other.PostCount,
|
||||
Picture = other.Picture is { } picture && (best.Picture is null || picture.Area > best.Picture.Area) ? picture : best.Picture,
|
||||
LatestStoryAt = best.LatestStoryAt ?? other.LatestStoryAt,
|
||||
IsViewer = best.IsViewer || other.IsViewer,
|
||||
};
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Pinned on top of the profile: the vocabulary says so, or (newest first) the order of the page does.</summary>
|
||||
private bool IsPinned(ContentItem item, IReadOnlyList<ContentItem> page, ProfileWalk walk) =>
|
||||
@@ -591,28 +729,32 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the profile page (1 counted action) and reads its state: missing profile, a name now used by another
|
||||
/// account, private profile not followed (rule 6: not touched). Returns the updated account and the reads.
|
||||
/// Opens the profile page (1 counted action) and reads its state: missing profile (when the map has its marker), a
|
||||
/// name now used by another account, private profile not followed (rule 6: not touched). The profile, the posts
|
||||
/// and the collections may come in different answers, and not together: after the profile the page is left to
|
||||
/// settle, and with <paramref name="waitForGrid"/> the first page of posts is waited for too. Returns the updated
|
||||
/// account and everything the page received.
|
||||
/// </summary>
|
||||
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account)
|
||||
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account, bool waitForGrid = false)
|
||||
{
|
||||
var parameters = Values(("username", account.Username));
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
if ((await run.FindAsync(SiteTargets.ProfileNotFound, parameters).ConfigureAwait(false)).Found)
|
||||
if (Env.SiteMap.IsTargetConfigured(SiteTargets.ProfileNotFound)
|
||||
&& (await run.FindAsync(SiteTargets.ProfileNotFound, parameters).ConfigureAwait(false)).Found)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.NotFound).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"Il profilo {account.Username} non esiste o non è più disponibile.");
|
||||
}
|
||||
|
||||
var reads = await run.WaitForDataAsync(mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
var reads = await WaitAndSettleAsync(run, mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => ProfileIn(r, account) is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
var profile = FindProfile(reads, account)!;
|
||||
var profile = AccountProfile(reads, account)!;
|
||||
if (account.InstagramId is { } known && profile.Id != known)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.Renamed).ConfigureAwait(false);
|
||||
@@ -634,9 +776,58 @@ public sealed partial class RecipeRunner
|
||||
account = await Env.Storage.Accounts.GetAsync(account.Id, run.Ct).ConfigureAwait(false) ?? account;
|
||||
}
|
||||
|
||||
if (waitForGrid)
|
||||
{
|
||||
reads = await WaitForGridAsync(run, mark, account, reads).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return (account, reads);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for <paramref name="expected"/> after <paramref name="mark"/>, then lets the page settle and returns
|
||||
/// everything that arrived since the mark: what one page shows can come in several answers, the expected one not
|
||||
/// always last, and stopping at the first that matches would lose the others. When the expected data does not
|
||||
/// come, returns what came, to be judged.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<CapturedRead>> WaitAndSettleAsync(RecipeRun run, long mark, Func<ReadResult, bool> expected)
|
||||
{
|
||||
var reads = await run.WaitForDataAsync(mark, expected).ConfigureAwait(false);
|
||||
if (!reads.Any(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)))
|
||||
{
|
||||
return reads;
|
||||
}
|
||||
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
return Env.Capture.Since(mark);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first page of the grid, when it did not come with the profile: the page may ask for it only after drawing
|
||||
/// the profile, later than it takes to settle. Waits for posts of the account or an empty grid that is surely its
|
||||
/// own (<see cref="IsEmptyWalkPage"/>: a bare empty answer may be the collections), then lets the page settle again.
|
||||
/// Nothing is judged here (the profile came): a profile without posts that does not say so only costs the wait.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<CapturedRead>> WaitForGridAsync(RecipeRun run, long mark, Account account, IReadOnlyList<CapturedRead> reads)
|
||||
{
|
||||
var walk = ProfileWalk.Posts;
|
||||
bool Arrived(IReadOnlyList<CapturedRead> list) => PageItems(list, account, walk).Count > 0 || WalkPage(list, account, walk, ownAnswer: false) is not null;
|
||||
if (Arrived(reads))
|
||||
{
|
||||
return reads;
|
||||
}
|
||||
|
||||
var arrived = await Env.Capture.WaitAsync(mark, list => run.Signal is not null || Arrived(list), Env.Options.DataTimeout, Env.Options.Poll, run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
if (!Arrived(arrived))
|
||||
{
|
||||
return arrived;
|
||||
}
|
||||
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
return Env.Capture.Since(mark);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scrolls with bursts until a new page of data that satisfies <paramref name="expected"/> arrives, at most
|
||||
/// <see cref="RecipeOptions.BurstsPerPage"/> bursts. Only the expected data ends the bursts: a response the page
|
||||
@@ -674,9 +865,6 @@ public sealed partial class RecipeRunner
|
||||
/// <summary>Outcome message of a page that arrived without data (three in a row raise a throttle signal).</summary>
|
||||
private const string EmptyPageMessage = "La pagina è arrivata vuota: nessun dato da leggere.";
|
||||
|
||||
private static PageInfo? LastPage(IEnumerable<CapturedRead> reads) =>
|
||||
reads.Where(r => r.Result.Page is not null).Select(r => r.Result.Page).LastOrDefault();
|
||||
|
||||
private static DateTimeOffset? ParseTime(string? value) =>
|
||||
DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var time) ? time : null;
|
||||
|
||||
|
||||
@@ -14,37 +14,64 @@ public sealed partial class RecipeRunner
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> FollowingSweepAsync(RecipeRun run)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.Home, null).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.Home, null, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Home).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Profiles.Count > 0).ConfigureAwait(false);
|
||||
run.Judge(reads, r => r.Contents.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Home));
|
||||
|
||||
// The feed and the stories bar may come in different answers: after the first, the page is left to settle.
|
||||
var reads = await WaitAndSettleAsync(run, mark, HomeArrived).ConfigureAwait(false);
|
||||
run.Judge(reads, HomeArrived, Env.SiteMap.BuildPath(SitePages.Home));
|
||||
|
||||
var processed = 0;
|
||||
var sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false);
|
||||
var hasMore = reads.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? true;
|
||||
var hasMore = FeedPage(reads)?.HasMore ?? true;
|
||||
|
||||
// Everything after the last read taken, so that nothing arriving while the posts are saved is missed.
|
||||
var seen = reads.Count > 0 ? reads[^1].Sequence : mark;
|
||||
for (var burst = 0; burst < Env.Options.SweepMaxBursts && !sawKnown && hasMore; burst++)
|
||||
{
|
||||
var before = Env.Capture.Mark();
|
||||
await Env.Driver.ScrollBurstAsync(run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
var more = Env.Capture.Since(before);
|
||||
var more = Env.Capture.Since(seen);
|
||||
if (more.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
seen = more[^1].Sequence;
|
||||
var met = Contents(reads, IsPostLike).Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
|
||||
reads = [.. reads, .. more];
|
||||
sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false);
|
||||
hasMore = more.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? hasMore;
|
||||
hasMore = FeedPage(more, met)?.HasMore ?? hasMore;
|
||||
}
|
||||
|
||||
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The home arrived: posts, an account of the stories bar (it says when its latest story was published) or a page
|
||||
/// of the feed. Profiles alone do not say it: Instagram also sends suggested profiles, not followed (HAR of
|
||||
/// 21/10/2026), and they would pass for a home that is not there.
|
||||
/// </summary>
|
||||
private static bool HomeArrived(ReadResult result) =>
|
||||
result.Contents.Count > 0 || result.Profiles.Any(p => p.LatestStoryAt is not null) || result.Page is not null;
|
||||
|
||||
/// <summary>
|
||||
/// The pagination of the feed: from the answer that brought the most posts not met before (<paramref name="met"/>:
|
||||
/// the earlier answers of the run); when none did, from an answer that brought no contents nor collections (an
|
||||
/// empty feed). Never from an answer that brought only stories or collection items (the collections say
|
||||
/// «has_next_page» of themselves), nor from one that only brings again a post already met (the page of that post
|
||||
/// says «more_available: false» of itself).
|
||||
/// </summary>
|
||||
private static PageInfo? FeedPage(IReadOnlyList<CapturedRead> reads, IReadOnlySet<string>? met = null) =>
|
||||
PageOf(
|
||||
reads,
|
||||
r => r.Contents.Where(IsPostLike).Select(c => c.Id),
|
||||
r => (r.Shape is ReadShape.Empty or ReadShape.Recognized) && r.Contents.Count == 0 && r.Highlights.Count == 0,
|
||||
met);
|
||||
|
||||
/// <summary>Saves the posts not processed yet; returns true once known content has been met.</summary>
|
||||
private Task<bool> ProcessSweepReadsAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, ref int processed)
|
||||
{
|
||||
@@ -101,11 +128,20 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Alberto's own profile («Tu») from the data the page receives (H10), the first time it is seen.
|
||||
/// Alberto's own profile («Tu») from the data the page receives (H10), the first time it is seen: an answer that
|
||||
/// presents it with its name, or — Instagram's way, whose «xdt_viewer.user» gives only an identifier (HAR of
|
||||
/// 21/10/2026) — the identifier from one answer of the run and the profile with that identifier, name included,
|
||||
/// from any answer of the run (his own entry in the stories bar, for instance).
|
||||
/// </summary>
|
||||
private async Task EnsureMineAsync(IReadOnlyList<CapturedRead> reads, RecipeRun run)
|
||||
{
|
||||
if (reads.Select(r => r.Result.Viewer).FirstOrDefault(v => v is not null) is not { } viewer)
|
||||
var viewer = reads.Select(r => r.Result.Viewer).FirstOrDefault(v => v is not null);
|
||||
if (viewer is null && (reads.Select(r => r.Result.ViewerId).FirstOrDefault(id => id is not null) ?? Env.Capture.ViewerId) is { } viewerId)
|
||||
{
|
||||
viewer = reads.SelectMany(r => r.Result.Profiles).FirstOrDefault(p => p.Id == viewerId);
|
||||
}
|
||||
|
||||
if (viewer is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
@@ -11,6 +12,17 @@ public sealed partial class RecipeRunner
|
||||
/// <summary>A story stays on offer for a day (spec §4.3: «storie attive nelle 24 ore»).</summary>
|
||||
private static readonly TimeSpan StoryLifetime = TimeSpan.FromHours(24);
|
||||
|
||||
/// <summary>
|
||||
/// Without the item in the address, how long before a video ends the gesture that leaves it («next», or close) starts
|
||||
/// at the latest: the pointer travel and the pause on the target of §7.7 (up to 1.2 s) with room to spare, multiplied
|
||||
/// by mood and pace like the gesture. The viewer moves on by itself when the video ends, and the address would not
|
||||
/// say so: a «next» pressed after that would skip an item.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan VideoClickLead = TimeSpan.FromSeconds(1.5);
|
||||
|
||||
/// <summary>The placeholder of a viewer address that names the item shown; optional (Instagram's highlight viewer has none).</summary>
|
||||
private const string ItemKey = "id";
|
||||
|
||||
/// <summary>
|
||||
/// Storie di un account (spec §6.3): checks that the budget allows at least ten stories, opens the viewer from the
|
||||
/// stories bar (when the home is on screen) or from the profile, watches the stories one by one with the timings of
|
||||
@@ -33,13 +45,15 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
var parameters = Values(("username", account.Username));
|
||||
var fromBar = Env.SiteMap.IsTargetConfigured(SiteTargets.HomeStory)
|
||||
// After a search step the home page may be covered by the site's search panel: the profile is opened instead.
|
||||
var fromBar = Env.PageTurns?.SearchTouchedPage != true
|
||||
&& Env.SiteMap.IsTargetConfigured(SiteTargets.HomeStory)
|
||||
&& Env.SiteMap.Match(SitePages.Home, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is not null
|
||||
&& (await run.FindAsync(SiteTargets.HomeStory, parameters).ConfigureAwait(false)).Found;
|
||||
|
||||
if (!fromBar)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
@@ -66,7 +80,7 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.TargetNotFound, $"{ring.Message} Il profilo di {account.Username} dice però che c'è una storia attiva: la mappa dei bersagli va controllata.");
|
||||
}
|
||||
|
||||
await StoriesCheckedAsync(account, run).ConfigureAwait(false);
|
||||
await StoriesCheckedAsync(account, run.Ct).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed; // no active stories: nothing to open
|
||||
}
|
||||
}
|
||||
@@ -77,13 +91,14 @@ public sealed partial class RecipeRunner
|
||||
var opened = await OpenViewerAsync(run, target, parameters, SitePages.StoryViewer).ConfigureAwait(false);
|
||||
var watched = await WatchViewerAsync(run, SitePages.StoryViewer, "username", account.Username, account, viewerMark, opened).ConfigureAwait(false);
|
||||
var shown = watched.Shown;
|
||||
var ct = watched.StoreToken(run);
|
||||
|
||||
var stories = Contents(Env.Capture.Since(viewerMark), c => IsOwnedBy(c, account));
|
||||
foreach (var id in shown)
|
||||
{
|
||||
if (stories.FirstOrDefault(s => s.Id == id) is { } story)
|
||||
{
|
||||
var saved = await Writer.SaveAsync(account, story, EntryKind.Story, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
var saved = await Writer.SaveAsync(account, story, EntryKind.Story, run.Session.SessionId, ct).ConfigureAwait(false);
|
||||
if (saved.Outcome == SaveOutcome.Created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
@@ -91,12 +106,8 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
await StoriesCheckedAsync(account, run).ConfigureAwait(false);
|
||||
if (watched.Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
}
|
||||
|
||||
await StoriesCheckedAsync(account, ct).ConfigureAwait(false);
|
||||
watched.ThrowIfStopped();
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
@@ -105,10 +116,15 @@ public sealed partial class RecipeRunner
|
||||
/// StoryView permit per content shown) and closes the viewer after the last one. A content that is a story already
|
||||
/// saved is referenced, not downloaded again (H9).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Collections are compared in the form of their address: Instagram writes «highlight:1790…» in its data and
|
||||
/// «/stories/highlights/1790…/» in the address (HAR of 21/10/2026); the reader keeps the second, and the requested
|
||||
/// identifier is taken in either form.
|
||||
/// </remarks>
|
||||
private async Task<RecipeStatus> HighlightAsync(RecipeRun run)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
if (run.Request.HighlightId is not { Length: > 0 } highlightId)
|
||||
if (run.Request.HighlightId is not { Length: > 0 } requested)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "«Raccolta in evidenza» ha bisogno dell'identificativo della raccolta.");
|
||||
}
|
||||
@@ -118,26 +134,38 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, $"«Storie in evidenza» è spento per {account.Username}.");
|
||||
}
|
||||
|
||||
var highlightId = ShapeReader.HighlightId(requested);
|
||||
await EnsureStoryBudgetAsync(run, account).ConfigureAwait(false);
|
||||
var parameters = Values(("username", account.Username));
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Highlights.Count > 0 || ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Highlights.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
|
||||
// Only this account's profile or collections say the page arrived: profiles suggested beside it do not.
|
||||
var reads = await run.WaitForDataAsync(mark, r => OwnProfileOrCollectionsIn(r, account)).ConfigureAwait(false);
|
||||
if (!reads.Any(r => r.Result.Highlights.Any(h => h.Id == highlightId && IsHighlightOf(h, account))))
|
||||
{
|
||||
// The collections may come in an answer of their own, after the profile: let the page settle first.
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
reads = Env.Capture.Since(mark);
|
||||
}
|
||||
|
||||
if (!run.Judge(reads, r => OwnProfileOrCollectionsIn(r, account), Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
if (FindProfile(reads, account) is { } profile)
|
||||
{
|
||||
account = await Writer.ApplyProfileAsync(account, profile, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => h.Owner is null || h.Owner.Id == account.InstagramId).ToList();
|
||||
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => IsHighlightOf(h, account)).ToList();
|
||||
var collections = await Writer.UpsertHighlightsAsync(account, listed, run.Ct).ConfigureAwait(false);
|
||||
if (!collections.TryGetValue(highlightId, out var highlight))
|
||||
{
|
||||
var known = await Env.Storage.Highlights.FindAsync(account.Id, highlightId, run.Ct).ConfigureAwait(false);
|
||||
var known = await Env.Storage.Highlights.FindAsync(account.Id, highlightId, run.Ct).ConfigureAwait(false)
|
||||
?? (requested == highlightId ? null : await Env.Storage.Highlights.FindAsync(account.Id, requested, run.Ct).ConfigureAwait(false));
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, known is null
|
||||
? "La raccolta non è nel profilo."
|
||||
: $"La raccolta «{known.Title}» non è più nel profilo: i suoi file restano.");
|
||||
@@ -145,11 +173,13 @@ public sealed partial class RecipeRunner
|
||||
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
var viewerMark = Env.Capture.Mark();
|
||||
var opened = await OpenViewerAsync(run, SiteTargets.ProfileHighlight, Values(("id", highlightId), ("username", account.Username)), SitePages.HighlightViewer).ConfigureAwait(false);
|
||||
var target = Values(("id", highlightId), ("username", account.Username), ("title", highlight.Title));
|
||||
var opened = await OpenViewerAsync(run, SiteTargets.ProfileHighlight, target, SitePages.HighlightViewer).ConfigureAwait(false);
|
||||
var watched = await WatchViewerAsync(run, SitePages.HighlightViewer, "highlight", highlightId, account, viewerMark, opened).ConfigureAwait(false);
|
||||
var shown = watched.Shown;
|
||||
var ct = watched.StoreToken(run);
|
||||
|
||||
var items = Contents(Env.Capture.Since(viewerMark), c => c.HighlightId == highlightId);
|
||||
var items = Contents(Env.Capture.Since(viewerMark), c => InCollection(c, highlightId));
|
||||
var ordered = new List<long>();
|
||||
foreach (var id in shown)
|
||||
{
|
||||
@@ -158,7 +188,7 @@ public sealed partial class RecipeRunner
|
||||
continue;
|
||||
}
|
||||
|
||||
var (entry, created) = await Writer.LinkHighlightItemAsync(account, highlight, item, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
var (entry, created) = await Writer.LinkHighlightItemAsync(account, highlight, item, run.Session.SessionId, ct).ConfigureAwait(false);
|
||||
if (created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
@@ -172,15 +202,11 @@ public sealed partial class RecipeRunner
|
||||
|
||||
if (items.Count > 0 && items.All(i => shown.Contains(i.Id)) && ordered.Count == items.Count)
|
||||
{
|
||||
await Env.Storage.Highlights.SetItemsAsync(highlight.Id, ordered, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Env.Storage.Highlights.UpsertAsync(highlight with { LastCheckedAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false);
|
||||
if (watched.Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
await Env.Storage.Highlights.SetItemsAsync(highlight.Id, ordered, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Env.Storage.Highlights.UpsertAsync(highlight with { LastCheckedAt = Env.Clock.Now }, ct).ConfigureAwait(false);
|
||||
watched.ThrowIfStopped();
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
@@ -196,15 +222,29 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Clicks what opens a viewer and waits for it; one more click if the first one went unnoticed.</summary>
|
||||
private async Task<IReadOnlyDictionary<string, string>> OpenViewerAsync(RecipeRun run, string target, IReadOnlyDictionary<string, string> parameters, string viewerPage)
|
||||
/// <summary>
|
||||
/// Clicks what opens a viewer and waits for it; one more click if the first one went unnoticed. Returns the address
|
||||
/// shown and when the first click started (the first item cannot have come on screen before). When the click takes
|
||||
/// the page to an address the map does not take for the viewer (its shape in the map may be wrong), what opened is
|
||||
/// closed like a viewer before the recipe stops: left open, it would move on by itself to other accounts.
|
||||
/// </summary>
|
||||
private async Task<ViewerOpening> OpenViewerAsync(RecipeRun run, string target, IReadOnlyDictionary<string, string> parameters, string viewerPage)
|
||||
{
|
||||
var before = await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false);
|
||||
var clickedAt = Env.Clock.Now;
|
||||
for (var attempt = 0; attempt < 2; attempt++)
|
||||
{
|
||||
await run.ClickAsync(target, parameters).ConfigureAwait(false);
|
||||
if (await WaitForViewerAsync(run, viewerPage, previous: null).ConfigureAwait(false) is { } opened)
|
||||
{
|
||||
return opened;
|
||||
return new ViewerOpening(opened, clickedAt);
|
||||
}
|
||||
|
||||
if (!string.Equals(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false), before, StringComparison.Ordinal))
|
||||
{
|
||||
// The click was noticed, but what opened has not the shape of the viewer: no second click on it.
|
||||
await CloseAsync(run, path => !string.Equals(path, before, StringComparison.Ordinal)).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, $"Dopo il clic l'indirizzo non ha la forma «{viewerPage}» della mappa {Env.SiteMap.Source ?? Env.SiteMap.Site}: ciò che si è aperto è stato chiuso. La forma va controllata.");
|
||||
}
|
||||
|
||||
if (!(await run.FindAsync(target, parameters).ConfigureAwait(false)).Found)
|
||||
@@ -217,141 +257,384 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Watches a viewer that shows <paramref name="opened"/>: reads the item shown from the address of the page, waits
|
||||
/// the time of §7.7, asks a StoryView permit before each «next» (and after the fact when the viewer moved on by
|
||||
/// itself) and closes the viewer after the last item of <paramref name="owner"/>, or as soon as it shows something
|
||||
/// else. On any stop other than a signal the viewer is closed first. Returns the identifiers shown, in order.
|
||||
/// Watches a viewer that shows <paramref name="opened"/>: on each item it first asks the StoryView permit for the
|
||||
/// item after it (before it can come on screen, by a click or by itself), then waits the time of §7.7, and closes
|
||||
/// the viewer after the last item of <paramref name="owner"/>, or as soon as it shows something else. The item
|
||||
/// shown is read from the address when the address carries it (<see cref="FollowAddressAsync"/>), otherwise counted
|
||||
/// (<see cref="FollowCountAsync"/>). On any stop other than a signal, an unexpected error included, the viewer is
|
||||
/// closed first; a viewer that stays open stops the run as a target not found. A cancellation leaves the page as it
|
||||
/// is. Returns the identifiers shown, in order, each under its permit.
|
||||
/// </summary>
|
||||
private async Task<ViewerResult> WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, IReadOnlyDictionary<string, string> opened)
|
||||
private async Task<ViewerResult> WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, ViewerOpening opened)
|
||||
{
|
||||
var shown = new List<string>();
|
||||
var counted = new HashSet<string>(StringComparer.Ordinal);
|
||||
var pendingPermit = true; // asked before the click that opened the viewer
|
||||
var position = opened;
|
||||
var stuck = 0;
|
||||
var viewer = new ViewerWatch(viewerPage, ownerKey, owner, account, mark);
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
try
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!string.Equals(position[ownerKey], owner, StringComparison.OrdinalIgnoreCase))
|
||||
if (!opened.Position.ContainsKey(ownerKey))
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
await Writer.EventAsync(
|
||||
"visualizzatore-altro-account",
|
||||
viewerPage == SitePages.StoryViewer
|
||||
? $"Dopo le storie di {account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano."
|
||||
: $"Il visualizzatore è passato a un'altra raccolta di {account.Username}: chiuso senza salvarla.",
|
||||
EventSeverity.Warning,
|
||||
account.Id,
|
||||
run.Session.SessionId,
|
||||
run.Ct).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, null);
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, $"La forma dell'indirizzo «{viewerPage}» nella mappa {Env.SiteMap.Source ?? Env.SiteMap.Site} non dice di chi è il visualizzatore: manca «{{{ownerKey}}}».");
|
||||
}
|
||||
|
||||
var id = position["id"];
|
||||
if (counted.Add(id))
|
||||
if (opened.Position.ContainsKey(ItemKey))
|
||||
{
|
||||
if (!pendingPermit)
|
||||
{
|
||||
// The viewer moved on by itself: this item was shown without asking first; ask now.
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
pendingPermit = false;
|
||||
shown.Add(id);
|
||||
await FollowAddressAsync(run, viewer, opened.Position, shown).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await FollowCountAsync(run, viewer, opened, shown).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The list of the account arrives with the viewer (H4): it tells which item is the last one.
|
||||
var list = await ViewerListAsync(run, mark, viewerPage, owner, account).ConfigureAwait(false);
|
||||
var item = list.FirstOrDefault(i => i.Id == id);
|
||||
var video = item?.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration;
|
||||
await Env.Driver.WaitAsync(StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier), run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return new ViewerResult(shown, null); // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!SamePosition(current, position))
|
||||
{
|
||||
position = current; // it moved on by itself while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
var index = list.FindIndex(i => i.Id == id);
|
||||
if (list.Count > 0 && index == list.Count - 1)
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, null);
|
||||
}
|
||||
|
||||
if (!pendingPermit)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
pendingPermit = true;
|
||||
}
|
||||
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
var next = await WaitForViewerAsync(run, viewerPage, previous: current).ConfigureAwait(false);
|
||||
if (next is null)
|
||||
{
|
||||
return new ViewerResult(shown, null); // closed after the last item
|
||||
}
|
||||
|
||||
if (SamePosition(next, current))
|
||||
{
|
||||
if (++stuck >= 2)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti.");
|
||||
}
|
||||
|
||||
continue; // the click went unnoticed: watch a little more and try again
|
||||
}
|
||||
|
||||
stuck = 0;
|
||||
position = next;
|
||||
return new ViewerResult(shown, null);
|
||||
}
|
||||
}
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
if (stop.Status != RecipeStatus.StoppedBySignal)
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
// Leave no viewer open: it would move on by itself to other accounts. After a signal the page stays as it is.
|
||||
try
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
}
|
||||
catch (RecipeStopException)
|
||||
{
|
||||
}
|
||||
var stillOpen = stop.Status == RecipeStatus.StoppedBySignal ? null : await TryCloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, Worse(stop, stillOpen));
|
||||
}
|
||||
|
||||
return new ViewerResult(shown, stop);
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Not even an unexpected error leaves the viewer open; what was shown until then is saved all the same.
|
||||
var stillOpen = await TryCloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
var failure = new RecipeStopException(RecipeStatus.Failed, $"Errore imprevisto in «{Name(run.Request.Kind)}» ({ex.GetType().Name}): {ex.Message}") { ErrorType = ex.GetType().Name };
|
||||
return new ViewerResult(shown, Worse(failure, stillOpen));
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException cancelled)
|
||||
{
|
||||
// A pause, the session closed by a signal, Alberto taking the browser: the page is left as it is, what was
|
||||
// shown under its permit is saved all the same, then the cancellation goes on.
|
||||
return new ViewerResult(shown, null, ExceptionDispatchInfo.Capture(cancelled));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a viewer showed, and why it stopped early (the caller saves what was shown, then stops).</summary>
|
||||
private sealed record ViewerResult(List<string> Shown, RecipeStopException? Stop);
|
||||
/// <summary>
|
||||
/// Follows a viewer whose address carries the item shown (the test site: «/storie/{username}/{id}/»): every
|
||||
/// position is read from the address, so an item the viewer skipped or showed by itself is known for what it is.
|
||||
/// The permit asked on an item covers the next one, also when it comes by itself; an item that comes by itself
|
||||
/// after what the list gave as the last one had no permit: the viewer is closed and it is not saved.
|
||||
/// </summary>
|
||||
private async Task FollowAddressAsync(RecipeRun run, ViewerWatch viewer, IReadOnlyDictionary<string, string> opened, List<string> shown)
|
||||
{
|
||||
var counted = new HashSet<string>(StringComparer.Ordinal);
|
||||
var permitted = true; // asked before the click that opened the viewer: for the first item on screen
|
||||
var position = opened;
|
||||
var stuck = 0;
|
||||
while (true)
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!viewer.ShowsOwner(position))
|
||||
{
|
||||
await LeaveOtherOwnerAsync(run, viewer).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var id = position[ItemKey];
|
||||
if (counted.Add(id))
|
||||
{
|
||||
if (!permitted)
|
||||
{
|
||||
await CloseEarlyAsync(run, viewer, viewer.Page == SitePages.StoryViewer
|
||||
? $"Il visualizzatore è andato avanti da solo dopo quella che per la pagina era l'ultima storia di {viewer.Account.Username}: chiuso, la storia in più non si salva."
|
||||
: $"Il visualizzatore è andato avanti da solo dopo quello che per la pagina era l'ultimo contenuto della raccolta di {viewer.Account.Username}: chiuso, il contenuto in più non si salva.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
permitted = false;
|
||||
shown.Add(id);
|
||||
}
|
||||
|
||||
var since = Env.Clock.Now;
|
||||
|
||||
// The list of the account arrives with the viewer (H4): it tells which item is the last one.
|
||||
var list = await ViewerListAsync(run, viewer).ConfigureAwait(false);
|
||||
var index = list.FindIndex(i => i.Id == id);
|
||||
var last = list.Count > 0 && index == list.Count - 1;
|
||||
if (!last && !permitted)
|
||||
{
|
||||
// The permit for the item after this one, before it can come on screen.
|
||||
await run.PermitAsync(ActionKind.StoryView, viewer.Account.Id).ConfigureAwait(false);
|
||||
permitted = true;
|
||||
}
|
||||
|
||||
await WatchAsync(run, index < 0 ? null : VideoDuration(list[index]), since, latest: null).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return; // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!SamePosition(current, position))
|
||||
{
|
||||
position = current; // it moved on by itself while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
if (last)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
var next = await WaitForViewerAsync(run, viewer.Page, previous: current).ConfigureAwait(false);
|
||||
if (next is null)
|
||||
{
|
||||
return; // closed after the last item
|
||||
}
|
||||
|
||||
if (SamePosition(next, current))
|
||||
{
|
||||
if (++stuck >= 2)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti.");
|
||||
}
|
||||
|
||||
continue; // the click went unnoticed: watch a little more and try again
|
||||
}
|
||||
|
||||
stuck = 0;
|
||||
position = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Follows a viewer whose address does not say which item is shown: Instagram's highlight viewer stays on
|
||||
/// «/stories/highlights/{id}/» from one item to the next (HAR of 21/10/2026). The items are counted against the
|
||||
/// list the page received for the owner: the first one shown is the first of the list, and each click on «next»
|
||||
/// moves one on. A move the viewer makes by itself cannot be seen, so it is never counted: a video, which moves the
|
||||
/// viewer on when it ends, is left before then (<see cref="VideoClickLead"/>), and when that is no longer possible
|
||||
/// (the Governor's wait for the permit took its time) the viewer is closed without clicking «next», the items after
|
||||
/// it not saved. A photo is never taken as over, because how long the site keeps it is not in the data: should the
|
||||
/// viewer leave one by itself, the count falls behind and its last «next» takes the viewer to another collection,
|
||||
/// where it is closed. A click the page ignores would put the count ahead: nothing in the address or in the data
|
||||
/// tells it yet (to be measured live).
|
||||
/// </summary>
|
||||
private async Task FollowCountAsync(RecipeRun run, ViewerWatch viewer, ViewerOpening opened, List<string> shown)
|
||||
{
|
||||
var position = opened.Position;
|
||||
var index = 0;
|
||||
var appearedAfter = opened.ClickedAt; // the item at «index» did not come on screen before this
|
||||
while (true)
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!viewer.ShowsOwner(position))
|
||||
{
|
||||
await LeaveOtherOwnerAsync(run, viewer).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var since = Env.Clock.Now;
|
||||
var list = await ViewerListAsync(run, viewer).ConfigureAwait(false);
|
||||
if (index >= list.Count)
|
||||
{
|
||||
// The page described nothing (more) for this owner: which item is on screen cannot be told.
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// On screen under the permit asked before it could come: before opening, or on the item before it.
|
||||
var item = list[index];
|
||||
if (!shown.Contains(item.Id, StringComparer.Ordinal))
|
||||
{
|
||||
shown.Add(item.Id);
|
||||
}
|
||||
|
||||
var last = index == list.Count - 1;
|
||||
var video = VideoDuration(item);
|
||||
DateTimeOffset? leaveBy = video is { } duration && duration > TimeSpan.Zero
|
||||
? appearedAfter + duration - TimeSpan.FromTicks((long)(VideoClickLead.Ticks * Env.Driver.WaitMultiplier))
|
||||
: null;
|
||||
if (!last)
|
||||
{
|
||||
// The permit for the item after this one, before it can come on screen; asked only while the viewer
|
||||
// surely has not moved on by itself, and the item still has to be left in time once it is granted.
|
||||
if (!Passed(leaveBy))
|
||||
{
|
||||
await run.PermitAsync(ActionKind.StoryView, viewer.Account.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Passed(leaveBy))
|
||||
{
|
||||
await CloseEarlyAsync(run, viewer, viewer.Page == SitePages.StoryViewer
|
||||
? $"Una storia video di {viewer.Account.Username} poteva essere già finita, con il visualizzatore andato avanti da solo: chiuso senza cliccare «avanti», le storie successive non si salvano questa volta."
|
||||
: $"Un video della raccolta di {viewer.Account.Username} poteva essere già finito, con il visualizzatore andato avanti da solo: chiuso senza cliccare «avanti», i contenuti successivi non si salvano questa volta.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await WatchAsync(run, video, since, leaveBy).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return; // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!viewer.ShowsOwner(current))
|
||||
{
|
||||
position = current; // it moved on by itself to another owner while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
if (last)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var pressedAfter = Env.Clock.Now;
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
index++;
|
||||
appearedAfter = pressedAfter;
|
||||
position = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (position is null)
|
||||
{
|
||||
return; // the viewer closed: the item after was not shown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True once <paramref name="moment"/> has come (never for none).</summary>
|
||||
private bool Passed(DateTimeOffset? moment) => moment is { } end && Env.Clock.Now >= end;
|
||||
|
||||
/// <summary>
|
||||
/// Waits the time of §7.7 on an item on screen since <paramref name="since"/>: what the recipe waited meanwhile (the
|
||||
/// Governor's spacing before the permit for the next item) is part of it. Never past <paramref name="latest"/>.
|
||||
/// </summary>
|
||||
private async Task WatchAsync(RecipeRun run, TimeSpan? video, DateTimeOffset since, DateTimeOffset? latest)
|
||||
{
|
||||
var until = since + StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier);
|
||||
if (latest is { } end && end < until)
|
||||
{
|
||||
until = end;
|
||||
}
|
||||
|
||||
var wait = until - Env.Clock.Now;
|
||||
if (wait > TimeSpan.Zero)
|
||||
{
|
||||
await Env.Driver.WaitAsync(wait, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static TimeSpan? VideoDuration(ContentItem item) => item.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration;
|
||||
|
||||
/// <summary>The viewer went on to another account or collection: closed, and the event recorded.</summary>
|
||||
private async Task LeaveOtherOwnerAsync(RecipeRun run, ViewerWatch viewer)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
await Writer.EventAsync(
|
||||
"visualizzatore-altro-account",
|
||||
viewer.Page == SitePages.StoryViewer
|
||||
? $"Dopo le storie di {viewer.Account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano."
|
||||
: $"Il visualizzatore è passato a un'altra raccolta di {viewer.Account.Username}: chiuso senza salvarla.",
|
||||
EventSeverity.Warning,
|
||||
viewer.Account.Id,
|
||||
run.Session.SessionId,
|
||||
run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The viewer may be on an item not shown under a permit, or not known: closed before the end, without clicking
|
||||
/// «next», and the event recorded. What it may show now is not saved.
|
||||
/// </summary>
|
||||
private async Task CloseEarlyAsync(RecipeRun run, ViewerWatch viewer, string why)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
await Writer.EventAsync("visualizzatore-chiuso-prima", why, EventSeverity.Info, viewer.Account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the viewer on the way out of a stop, unless a signal says to leave the page as it is; never throws, but
|
||||
/// for a cancellation. Returns why the viewer may still be open (it did not close with its command), otherwise null.
|
||||
/// </summary>
|
||||
private async Task<RecipeStopException?> TryCloseViewerAsync(RecipeRun run, string viewerPage)
|
||||
{
|
||||
try
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
// After a signal the page stays as it is; otherwise the command was not found or the viewer did not close.
|
||||
return stop.Status == RecipeStatus.TargetNotFound ? stop : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Whether it closed is not known (the browser may be gone): the stop being reported is the first one.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The stop to report: a viewer left open outranks a milder first stop, as a target not found, which makes the
|
||||
/// session stop and put the page at rest.
|
||||
/// </summary>
|
||||
private static RecipeStopException Worse(RecipeStopException first, RecipeStopException? stillOpen) =>
|
||||
stillOpen is null || first.Status == RecipeStatus.TargetNotFound
|
||||
? first
|
||||
: RecipeRun.Stop(RecipeStatus.TargetNotFound, $"{first.Message} {stillOpen.Message}");
|
||||
|
||||
/// <summary>The address a viewer opened on, and when the click that opened it started.</summary>
|
||||
private sealed record ViewerOpening(IReadOnlyDictionary<string, string> Position, DateTimeOffset ClickedAt);
|
||||
|
||||
/// <summary>
|
||||
/// What a viewer showed, and why it stopped early: a stop, or a cancellation. The caller saves what was shown, then
|
||||
/// goes on with the stop (<see cref="ThrowIfStopped"/>).
|
||||
/// </summary>
|
||||
private sealed record ViewerResult(List<string> Shown, RecipeStopException? Stop, ExceptionDispatchInfo? Cancelled = null)
|
||||
{
|
||||
/// <summary>The token to store what was shown with: stopped early, the run's own may be cancelled already, or a moment later (storage only).</summary>
|
||||
public CancellationToken StoreToken(RecipeRun run) => Stop is null && Cancelled is null ? run.Ct : CancellationToken.None;
|
||||
|
||||
/// <summary>Goes on with the cancellation or the stop, once what was shown is stored.</summary>
|
||||
public void ThrowIfStopped()
|
||||
{
|
||||
Cancelled?.Throw();
|
||||
if (Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A viewer being watched: its page, the placeholder of its owner in the address, the owner, the account, the mark of its data.</summary>
|
||||
private sealed record ViewerWatch(string Page, string OwnerKey, string Owner, Account Account, long Mark)
|
||||
{
|
||||
/// <summary>True when the address still shows the owner watched (an account, or a collection).</summary>
|
||||
public bool ShowsOwner(IReadOnlyDictionary<string, string> position) =>
|
||||
position.TryGetValue(OwnerKey, out var shown) && string.Equals(shown, Owner, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static bool SamePosition(IReadOnlyDictionary<string, string> a, IReadOnlyDictionary<string, string> b) =>
|
||||
a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var v) && string.Equals(v, p.Value, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The items of the viewer for the owner, as received (waits for them the first time).</summary>
|
||||
private async Task<List<ContentItem>> ViewerListAsync(RecipeRun run, long mark, string viewerPage, string owner, Account account)
|
||||
/// <summary>
|
||||
/// The items of the viewer for the owner, as received (waits for them the first time). The stories of an account are
|
||||
/// only what looks like a story (it expires and is in no collection): a post of the account arriving meanwhile (the
|
||||
/// grid comes in an answer of its own, also after the viewer opened) would hide which story is the last one, or,
|
||||
/// counted by position, move every position after it.
|
||||
/// </summary>
|
||||
private async Task<List<ContentItem>> ViewerListAsync(RecipeRun run, ViewerWatch viewer)
|
||||
{
|
||||
Func<ContentItem, bool> belongs = viewerPage == SitePages.StoryViewer
|
||||
? c => IsOwnedBy(c, account)
|
||||
: c => c.HighlightId == owner;
|
||||
var present = Contents(Env.Capture.Since(mark), belongs);
|
||||
Func<ContentItem, bool> belongs = viewer.Page == SitePages.StoryViewer
|
||||
? c => IsOwnedBy(c, viewer.Account) && c.ExpiresAt is not null && c.HighlightId is null
|
||||
: c => InCollection(c, viewer.Owner);
|
||||
var present = Contents(Env.Capture.Since(viewer.Mark), belongs);
|
||||
if (present.Count > 0)
|
||||
{
|
||||
return present;
|
||||
}
|
||||
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Any(belongs)).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(viewer.Mark, r => r.Contents.Any(belongs)).ConfigureAwait(false);
|
||||
run.Judge(reads, r => r.Contents.Any(belongs), null);
|
||||
return Contents(reads, belongs);
|
||||
}
|
||||
@@ -383,10 +666,20 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Closes the viewer with its command and waits until it is gone.</summary>
|
||||
private async Task CloseViewerAsync(RecipeRun run, string viewerPage)
|
||||
/// <summary>Closes the viewer with its command and waits until it is gone; stops the run when it stays open.</summary>
|
||||
private Task CloseViewerAsync(RecipeRun run, string viewerPage) =>
|
||||
CloseAsync(run, path => Env.SiteMap.Match(viewerPage, path) is not null);
|
||||
|
||||
/// <summary>
|
||||
/// Clicks «viewer-close» while the address says something is open (<paramref name="isOpen"/>) and waits until it is
|
||||
/// gone. Never after a signal (the page stays as it is). A command that is not found, or a viewer still open after
|
||||
/// <see cref="RecipeOptions.ViewerTimeout"/>, stops the run as a target not found: the session then stops and the
|
||||
/// page is put at rest.
|
||||
/// </summary>
|
||||
private async Task CloseAsync(RecipeRun run, Func<string, bool> isOpen)
|
||||
{
|
||||
if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null)
|
||||
run.ThrowIfSignal();
|
||||
if (!isOpen(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -399,19 +692,20 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
var deadline = Env.Clock.Now + Env.Options.ViewerTimeout;
|
||||
while (Env.Clock.Now < deadline)
|
||||
while (isOpen(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)))
|
||||
{
|
||||
if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null)
|
||||
if (Env.Clock.Now >= deadline)
|
||||
{
|
||||
return;
|
||||
run.ThrowIfSignal();
|
||||
throw RecipeRun.Stop(RecipeStatus.TargetNotFound, $"Il visualizzatore non si è chiuso con «{SiteTargets.ViewerClose}»: il bersaglio della mappa va controllato.");
|
||||
}
|
||||
|
||||
await Env.Clock.Delay(Env.Options.Poll, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StoriesCheckedAsync(Account account, RecipeRun run) =>
|
||||
await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastStoriesCheckAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false);
|
||||
private async Task StoriesCheckedAsync(Account account, CancellationToken ct) =>
|
||||
await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastStoriesCheckAt = Env.Clock.Now }, ct).ConfigureAwait(false);
|
||||
|
||||
private async Task MarkUnreachableAsync(RecipeRun run, Account account, UnreachableReason reason)
|
||||
{
|
||||
@@ -433,4 +727,18 @@ public sealed partial class RecipeRunner
|
||||
|
||||
private static ProfileInfo? ProfileIn(ReadResult result, Account account) =>
|
||||
result.Profiles.FirstOrDefault(p => (account.InstagramId is { } id && p.Id == id) || string.Equals(p.Username, account.Username, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The profile of the account, or one of its collections: what says that its profile page arrived.</summary>
|
||||
private static bool OwnProfileOrCollectionsIn(ReadResult result, Account account) =>
|
||||
ProfileIn(result, account) is not null || result.Highlights.Any(h => IsHighlightOf(h, account));
|
||||
|
||||
/// <summary>A collection of the account: its owner is the account, or the answer does not say whose it is.</summary>
|
||||
private static bool IsHighlightOf(HighlightInfo highlight, Account account) =>
|
||||
highlight.Owner is not { } owner
|
||||
|| (account.InstagramId is { } id && owner.Id == id)
|
||||
|| string.Equals(owner.Username, account.Username, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>An item received inside collection <paramref name="highlightId"/> (both in the form of the address).</summary>
|
||||
private static bool InCollection(ContentItem item, string highlightId) =>
|
||||
item.HighlightId is { } id && string.Equals(ShapeReader.HighlightId(id), highlightId, StringComparison.Ordinal);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
@@ -40,6 +41,15 @@ public sealed record RecipeEnvironment
|
||||
public ICircuitBreaker? Breaker { get; init; }
|
||||
|
||||
public RecipeOptions Options { get; init; } = new();
|
||||
|
||||
/// <summary>The recorder of the diagnostic report (issue #39). Null: nothing is recorded.</summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The turns of the page shared with the profile search (issue #37): recipes give the page to the search before an
|
||||
/// action that opens a page, when the search waits. Null: no search, no turn points.
|
||||
/// </summary>
|
||||
public PageTurns? PageTurns { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -50,18 +60,20 @@ public sealed record RecipeEnvironment
|
||||
/// Common rules: the Governor is asked before every counted action and a refusal stops the recipe in order; a stop
|
||||
/// signal stops it where it is and leaves the page as it is; a missing target stops it with a report, never with
|
||||
/// coordinates; an unknown response shape stops it with <see cref="RecipeStatus.UnrecognizedFormat"/> and an event
|
||||
/// that carries only the key structure. Recipes refuse to run on a site whose map or reader vocabulary is still a
|
||||
/// skeleton (the first Instagram files, to be filled after M0).
|
||||
/// that carries only the key structure. A recipe refuses to run, as <see cref="RecipeStatus.NotConfigured"/>, while the
|
||||
/// site's map lacks a page or target it needs or the reader vocabulary is not usable (Instagram's targets, H11).
|
||||
/// </remarks>
|
||||
public sealed partial class RecipeRunner : IRecipeRunner
|
||||
{
|
||||
private readonly Lock _refusalsGate = new();
|
||||
private readonly HashSet<RecipeKind> _refusalsReported = [];
|
||||
private long? _sessionId;
|
||||
private RecipeKind? _lastKind;
|
||||
|
||||
public RecipeRunner(RecipeEnvironment environment)
|
||||
{
|
||||
Env = environment ?? throw new ArgumentNullException(nameof(environment));
|
||||
Writer = new CollectionWriter(environment.Storage, environment.Clock);
|
||||
Writer = new CollectionWriter(environment.Storage, environment.Clock) { Diagnostics = environment.Diagnostics };
|
||||
}
|
||||
|
||||
public RecipeEnvironment Env { get; }
|
||||
@@ -83,15 +95,19 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
_ => kind.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>Pages and targets a recipe cannot work without.</summary>
|
||||
/// <summary>
|
||||
/// Pages and targets a recipe cannot work without. «profile-not-found» is not among them: it is looked up only when
|
||||
/// the map sets it, and without it a profile that does not exist gives no data, judged like any page that arrives
|
||||
/// empty.
|
||||
/// </summary>
|
||||
public static (IReadOnlyList<string> Pages, IReadOnlyList<string> Targets) Requirements(RecipeKind kind) => kind switch
|
||||
{
|
||||
RecipeKind.FollowingSweep => ([SitePages.Home], []),
|
||||
RecipeKind.AccountStories => ([SitePages.Profile, SitePages.StoryViewer], [SiteTargets.ProfileStoryRing, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
|
||||
RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], [SiteTargets.ProfileNotFound]),
|
||||
RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], []),
|
||||
RecipeKind.Highlight => ([SitePages.Profile, SitePages.HighlightViewer], [SiteTargets.ProfileHighlight, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
|
||||
RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabTagged]),
|
||||
RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabReels]),
|
||||
RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileTabTagged]),
|
||||
RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileTabReels]),
|
||||
RecipeKind.SinglePost => ([SitePages.Post], []),
|
||||
RecipeKind.FollowingList => ([SitePages.Following], []),
|
||||
_ => ([], []),
|
||||
@@ -112,24 +128,29 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
ArgumentNullException.ThrowIfNull(session);
|
||||
var name = Name(request.Kind);
|
||||
|
||||
var (pages, targets) = Requirements(request.Kind);
|
||||
var missing = Env.SiteMap.Missing(pages, targets);
|
||||
if (missing.Count > 0)
|
||||
// A map or a vocabulary that lacks what the recipe needs is a state of the configuration, not a failure of the
|
||||
// recipe: nothing is done, nothing counts towards suspension, and it is said once per recipe and process (the
|
||||
// engine stops planning it, NotConfiguredReason).
|
||||
if (Refusal(request.Kind) is { } refusal)
|
||||
{
|
||||
var message = $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}). Va completata con i campioni della sonda di M0 (ipotesi H11).";
|
||||
await Writer.EventAsync("mappa-incompleta", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
return new RecipeOutcome(RecipeStatus.TargetNotFound, 0, 0, message);
|
||||
}
|
||||
bool first;
|
||||
lock (_refusalsGate)
|
||||
{
|
||||
first = _refusalsReported.Add(request.Kind);
|
||||
}
|
||||
|
||||
if (Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable)
|
||||
{
|
||||
var message = $"«{name}» non può girare: {unusable}";
|
||||
await Writer.EventAsync("lettori-incompleti", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
return new RecipeOutcome(RecipeStatus.UnrecognizedFormat, 0, 0, message);
|
||||
if (first)
|
||||
{
|
||||
await Writer.EventAsync(refusal.Code, refusal.Message + SessionComposer.NotConfiguredTail, EventSeverity.Warning, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Env.Diagnostics?.RecipeEnded(session.SessionId, request.Kind, RecipeStatus.NotConfigured, null, 0, 0);
|
||||
return new RecipeOutcome(RecipeStatus.NotConfigured, 0, 0, refusal.Message);
|
||||
}
|
||||
|
||||
if (Env.Breaker is { } breaker && !breaker.State.AllowsSiteActions)
|
||||
{
|
||||
Env.Diagnostics?.RecipeEnded(session.SessionId, request.Kind, RecipeStatus.Denied, breaker.State.LastSignal?.Code, 0, 0);
|
||||
return new RecipeOutcome(RecipeStatus.Denied, 0, 0, "L'interruttore è aperto: nessuna azione verso il sito.");
|
||||
}
|
||||
|
||||
@@ -143,6 +164,7 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
using var run = new RecipeRun(this, request, session, ct);
|
||||
RecipeStatus status;
|
||||
string? text = null;
|
||||
string? errorType = null;
|
||||
try
|
||||
{
|
||||
await CheckSessionCookieAsync(run).ConfigureAwait(false);
|
||||
@@ -164,6 +186,7 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
{
|
||||
status = stop.Status;
|
||||
text = stop.Message;
|
||||
errorType = stop.ErrorType;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
@@ -180,6 +203,7 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
{
|
||||
status = RecipeStatus.Failed;
|
||||
text = $"Errore imprevisto in «{name}» ({ex.GetType().Name}): {ex.Message}";
|
||||
errorType = ex.GetType().Name;
|
||||
}
|
||||
|
||||
if (run.Signal is { } signal && status is not (RecipeStatus.StoppedBySignal or RecipeStatus.Cancelled))
|
||||
@@ -197,6 +221,17 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
// The timeline is a convenience: failing to write it never changes how the recipe ended.
|
||||
}
|
||||
|
||||
// The report takes the status and the code of the signal, never the message (it may name an account). A recipe
|
||||
// cancelled because the breaker stopped (a signal reported straight to it, like the session cookie lost) gets
|
||||
// the breaker's code too.
|
||||
var breakerState = Env.Breaker?.State;
|
||||
var signalCode = run.Signal?.Code ?? status switch
|
||||
{
|
||||
RecipeStatus.StoppedBySignal => breakerState?.LastSignal?.Code,
|
||||
RecipeStatus.Cancelled when breakerState is { AllowsSiteActions: false } => breakerState.LastSignal?.Code,
|
||||
_ => null,
|
||||
};
|
||||
Env.Diagnostics?.RecipeEnded(session.SessionId, request.Kind, status, signalCode, run.Actions, run.NewEntries, status == RecipeStatus.Failed ? errorType : null);
|
||||
_lastKind = request.Kind;
|
||||
return new RecipeOutcome(status, run.Actions, run.NewEntries, text)
|
||||
{
|
||||
@@ -206,6 +241,28 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public string? NotConfiguredReason(RecipeKind kind) => Refusal(kind)?.Message;
|
||||
|
||||
/// <summary>
|
||||
/// Why the site's configuration does not let <paramref name="kind"/> run, with the code of its timeline line: pages
|
||||
/// or targets missing from the map, or a reader vocabulary that cannot be relied on. Null when it can run.
|
||||
/// </summary>
|
||||
private (string Code, string Message)? Refusal(RecipeKind kind)
|
||||
{
|
||||
var name = Name(kind);
|
||||
var (pages, targets) = Requirements(kind);
|
||||
var missing = Env.SiteMap.Missing(pages, targets);
|
||||
if (missing.Count > 0)
|
||||
{
|
||||
return ("mappa-incompleta", $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}).");
|
||||
}
|
||||
|
||||
return Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable
|
||||
? ("lettori-incompleti", $"«{name}» non può girare: {unusable}")
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rest page (spec §6.1). After a verification request or a disconnection the page is left as it is, so that
|
||||
/// Alberto sees what happened (spec §7.6): resting is skipped while the breaker says so.
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>
|
||||
/// Asks the site for one operation of the catalog (issue #36, spec §6.0) and returns its answer. The only way the
|
||||
/// engine talks to the site without the browser: the HTTP implementation (tappa S2) is the one class of Febe that
|
||||
/// contacts <c>www.instagram.com</c> (rule 3), the test double answers from the cleaned samples.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <list type="bullet">
|
||||
/// <item>Every call needs a <see cref="Permit"/> the Governor granted for that very request (rule 8, §7.4): a permit per
|
||||
/// request, never one for several. An implementation refuses, with <see cref="SiteRequestRefusedException"/> and before
|
||||
/// anything leaves, a permit that is missing, not granted or already presented once (<see cref="SpentPermits"/>), a
|
||||
/// permit of another category than the operation's (<see cref="SiteOperation.Category"/>), an operation that is not in
|
||||
/// the catalog, not configured or with a header or field still <see cref="ValueSourceKind.Pending"/>, and values that
|
||||
/// do not match the operation's placeholders or would change its path. <see cref="SiteRequestGuard"/> does all of
|
||||
/// these checks.</item>
|
||||
/// <item>One request at a time: an implementation never sends two together and makes a second call wait (or refuse)
|
||||
/// until the first has its answer; the minimum spacing of §7.7 is the Governor's.</item>
|
||||
/// <item>Only reads: the catalog refuses writes when it loads (<see cref="RequestCatalog"/>).</item>
|
||||
/// <item>Redirects are never followed: a 3xx comes back as a <see cref="SiteAnswer"/> with <see cref="SiteAnswer.IsRedirect"/>.</item>
|
||||
/// <item>Logs name only the operation or the shape of the path and the status (rule 10).</item>
|
||||
/// </list>
|
||||
/// Cancellation throws <see cref="OperationCanceledException"/>. The answer goes to the readers through
|
||||
/// <see cref="ResponseDelivery"/>, like the captured ones.
|
||||
/// </remarks>
|
||||
public interface ISiteRequester
|
||||
{
|
||||
Task<SiteAnswer> SendAsync(SiteRequest request, Permit permit, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A request that must not leave: no granted permit, a permit already used, another category, an operation outside
|
||||
/// the catalog or not configured, values that do not match. The message is in Italian and names only the operation and
|
||||
/// value names.
|
||||
/// </summary>
|
||||
public sealed class SiteRequestRefusedException : InvalidOperationException
|
||||
{
|
||||
public SiteRequestRefusedException()
|
||||
{
|
||||
}
|
||||
|
||||
public SiteRequestRefusedException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public SiteRequestRefusedException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The permits a site client was already shown (rule 8, §7.4: a permit per request). By reference, not by value: two
|
||||
/// permits the Governor granted one after the other are two, even when their fields are equal. Holds them weakly, so a
|
||||
/// long run does not keep them alive.
|
||||
/// </summary>
|
||||
public sealed class SpentPermits
|
||||
{
|
||||
private static readonly object Marker = new();
|
||||
private readonly ConditionalWeakTable<Permit, object> _spent = new();
|
||||
|
||||
/// <summary>Marks <paramref name="permit"/> as used; false when it was used before.</summary>
|
||||
public bool TrySpend(Permit permit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(permit);
|
||||
return _spent.TryAdd(permit, Marker);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The checks every <see cref="ISiteRequester"/> makes before a request leaves.</summary>
|
||||
public static class SiteRequestGuard
|
||||
{
|
||||
/// <summary>
|
||||
/// The catalog operation <paramref name="request"/> asks for, when it may leave with <paramref name="permit"/>. A
|
||||
/// granted permit is spent as soon as it is shown, also when the request is then refused: the Governor has already
|
||||
/// counted it.
|
||||
/// </summary>
|
||||
/// <exception cref="SiteRequestRefusedException">It must not leave (see <see cref="ISiteRequester"/>).</exception>
|
||||
public static SiteOperation Check(RequestCatalog catalog, SiteRequest request, Permit? permit, SpentPermits spent)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(catalog);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(spent);
|
||||
if (permit is null || !permit.Granted)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: il Governatore non ha dato il permesso.");
|
||||
}
|
||||
|
||||
if (!spent.TrySpend(permit))
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: il permesso è già stato usato (un permesso per richiesta).");
|
||||
}
|
||||
|
||||
if (!catalog.TryGet(request.Operation, out var operation))
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: l'operazione non è in {catalog.Source}.");
|
||||
}
|
||||
|
||||
if (!operation.IsConfigured)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: l'operazione non è configurata ({operation.NotConfiguredReason}).");
|
||||
}
|
||||
|
||||
// The catalog never loads a configured operation with pending sources; checked again so no path relies on it.
|
||||
if (operation.PendingValues.Count > 0)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: intestazioni o campi senza una fonte stabilita.");
|
||||
}
|
||||
|
||||
if (permit.Kind != operation.Category)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: il permesso è per {permit.Kind}, l'operazione conta come {operation.Category}.");
|
||||
}
|
||||
|
||||
if (operation.CheckValues(request) is { } problem)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: {problem}");
|
||||
}
|
||||
|
||||
return operation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,869 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>Whether an operation is a GraphQL query of the site or a plain address.</summary>
|
||||
public enum OperationKind
|
||||
{
|
||||
/// <summary>A GraphQL query: POST of a form to one of the GraphQL entry points, named by its friendly name.</summary>
|
||||
GraphQl,
|
||||
|
||||
/// <summary>A plain address read with GET (e.g. <c>/api/v1/media/{numero}/info/</c>).</summary>
|
||||
Rest,
|
||||
}
|
||||
|
||||
/// <summary>Where the value of a header or of a form field comes from.</summary>
|
||||
public enum ValueSourceKind
|
||||
{
|
||||
/// <summary>A constant, as the request shapes show it (<c>x-asbd-id: 359341</c>).</summary>
|
||||
Constant,
|
||||
|
||||
/// <summary>The value of a cookie of the saved session (<c>x-csrftoken</c> is the cookie <c>csrftoken</c>).</summary>
|
||||
Cookie,
|
||||
|
||||
/// <summary>A value the saved session holds (§6.0): user agent, tokens, account, application, claim, doc_id.</summary>
|
||||
Session,
|
||||
|
||||
/// <summary>The name of the operation (<c>x-fb-friendly-name</c>, <c>fb_api_req_friendly_name</c>).</summary>
|
||||
Operation,
|
||||
|
||||
/// <summary>The variables of the operation, filled with the values of the case (form field <c>variables</c>).</summary>
|
||||
Variables,
|
||||
|
||||
/// <summary>Computed by the HTTP stack (<c>content-length</c>).</summary>
|
||||
Computed,
|
||||
|
||||
/// <summary>
|
||||
/// Not settled yet: the request shapes show the name but not where its value comes from (a value of the page, of
|
||||
/// the browser, or a name the probe removed). The site client cannot send it until it is settled (tappa S4).
|
||||
/// </summary>
|
||||
Pending,
|
||||
}
|
||||
|
||||
/// <summary>Where one header or form field of an operation takes its value from.</summary>
|
||||
/// <param name="Kind">The kind of source.</param>
|
||||
/// <param name="Argument">The constant, the cookie name or the session field; null for the other kinds.</param>
|
||||
public sealed record ValueSource(ValueSourceKind Kind, string? Argument)
|
||||
{
|
||||
/// <summary>The session fields a header or field may take (§6.0, what «Ho finito» copies).</summary>
|
||||
public static IReadOnlySet<string> SessionFields { get; } = new[]
|
||||
{
|
||||
"user_agent", "lsd", "fb_dtsg", "app_id", "claim", "account_id", "doc_id",
|
||||
}.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The text form of the catalog file: <c>constant:…</c>, <c>cookie:…</c>, <c>session:…</c>, <c>operation</c>, <c>variables</c>, <c>computed</c>, <c>pending</c>.</summary>
|
||||
public override string ToString() => Kind switch
|
||||
{
|
||||
ValueSourceKind.Constant => $"constant:{Argument}",
|
||||
ValueSourceKind.Cookie => $"cookie:{Argument}",
|
||||
ValueSourceKind.Session => $"session:{Argument}",
|
||||
ValueSourceKind.Operation => "operation",
|
||||
ValueSourceKind.Variables => "variables",
|
||||
ValueSourceKind.Computed => "computed",
|
||||
_ => "pending",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One operation of <c>richieste.<sito>.json</c>: what the site client may ask (issue #36, spec §6.0). Written from
|
||||
/// the real request shapes of <c>febe-sonda richieste</c> (§14.5) and documented by a cleaned sample of its answer
|
||||
/// (rule 9). It holds no value of a session: the <c>doc_id</c> of a GraphQL query, the tokens and the account are read
|
||||
/// from the page at login (tappa S4) and named here only by their source.
|
||||
/// </summary>
|
||||
public sealed partial class SiteOperation
|
||||
{
|
||||
internal SiteOperation(
|
||||
string name,
|
||||
OperationKind kind,
|
||||
string method,
|
||||
string path,
|
||||
ActionKind category,
|
||||
bool isConfigured,
|
||||
string? notConfiguredReason,
|
||||
IReadOnlyDictionary<string, string> parameters,
|
||||
IReadOnlyDictionary<string, ValueSource> headers,
|
||||
IReadOnlyDictionary<string, ValueSource> body,
|
||||
JsonElement? variables,
|
||||
IReadOnlyList<string> rootFields,
|
||||
string? sample,
|
||||
IReadOnlySet<string> required,
|
||||
IReadOnlySet<string> optional)
|
||||
{
|
||||
Name = name;
|
||||
Kind = kind;
|
||||
Method = method;
|
||||
Path = path;
|
||||
Category = category;
|
||||
IsConfigured = isConfigured;
|
||||
NotConfiguredReason = notConfiguredReason;
|
||||
Parameters = parameters;
|
||||
Headers = headers;
|
||||
Body = body;
|
||||
Variables = variables;
|
||||
RootFields = rootFields;
|
||||
Sample = sample;
|
||||
RequiredValues = required;
|
||||
OptionalValues = optional;
|
||||
PathShape = Placeholder().Replace(path, m => CaseValues.ShapeOf(m.Groups[1].Value));
|
||||
PathValues = Placeholder().Matches(path).Select(m => m.Groups[1].Value).ToFrozenSet(StringComparer.Ordinal);
|
||||
PendingValues = [.. headers.Where(h => h.Value.Kind == ValueSourceKind.Pending).Select(h => h.Key)
|
||||
.Concat(body.Where(b => b.Value.Kind == ValueSourceKind.Pending).Select(b => b.Key))];
|
||||
}
|
||||
|
||||
/// <summary>The name a <see cref="SiteRequest"/> asks for: for GraphQL the friendly name of the site's query.</summary>
|
||||
public string Name { get; }
|
||||
|
||||
public OperationKind Kind { get; }
|
||||
|
||||
/// <summary><c>GET</c> or <c>POST</c> (POST only for GraphQL queries).</summary>
|
||||
public string Method { get; }
|
||||
|
||||
/// <summary>The path, with the values of the case as <c>{account_id}</c>, <c>{media_id}</c>…</summary>
|
||||
public string Path { get; }
|
||||
|
||||
/// <summary>The path as the log may show it (<c>/api/v1/media/{numero}/info/</c>): never a value.</summary>
|
||||
public string PathShape { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The category of the Governor the request counts in (§7.4: a permit per request, in the category of what it
|
||||
/// asks). Mapped on the existing categories, the budgets per request are recomputed in tappa S3: the profile header
|
||||
/// and the list of a profile's collections count as <see cref="ActionKind.ProfileOpen"/>; a page of posts, reels or
|
||||
/// tagged contents as <see cref="ActionKind.BackfillPage"/> (the first page too); stories and highlights as
|
||||
/// <see cref="ActionKind.StoryView"/>; a single post as <see cref="ActionKind.SinglePost"/>; the search box as
|
||||
/// <see cref="ActionKind.ProfileSearch"/>; the home as <see cref="ActionKind.Home"/>; the followed list as
|
||||
/// <see cref="ActionKind.FollowingListPage"/>. The file names the category, but the code pins the one budget outside
|
||||
/// the sessions: <see cref="ActionKind.ProfileSearch"/> only for an operation that carries <c>{search_text}</c> and no
|
||||
/// account or content, and every operation carrying <c>{search_text}</c> counts there.
|
||||
/// </summary>
|
||||
public ActionKind Category { get; }
|
||||
|
||||
/// <summary>
|
||||
/// False when the shapes do not tell everything the request needs (a variable whose name the probe removed, a
|
||||
/// value the shapes do not show, a header or field whose source is still <see cref="ValueSourceKind.Pending"/>):
|
||||
/// the site client refuses it (rule 9: what is not known is not guessed). A configured operation has no
|
||||
/// <see cref="PendingValues"/>: the catalog refuses the file otherwise.
|
||||
/// </summary>
|
||||
public bool IsConfigured { get; }
|
||||
|
||||
/// <summary>Why it is not configured, in Italian; null when it is.</summary>
|
||||
public string? NotConfiguredReason { get; }
|
||||
|
||||
/// <summary>Query string of a plain address: name and template (<c>{cursor}</c>, <c>{cursor?}</c> when optional, <c>constant:…</c>).</summary>
|
||||
public IReadOnlyDictionary<string, string> Parameters { get; }
|
||||
|
||||
/// <summary>The names of the headers and where each value comes from. Cookies are not a header here: they come from the saved session.</summary>
|
||||
public IReadOnlyDictionary<string, ValueSource> Headers { get; }
|
||||
|
||||
/// <summary>The form fields of a GraphQL query and where each value comes from.</summary>
|
||||
public IReadOnlyDictionary<string, ValueSource> Body { get; }
|
||||
|
||||
/// <summary>The template of the variables of a GraphQL query: constants as the shapes show them, <c>"{name}"</c> for a value of the case.</summary>
|
||||
public JsonElement? Variables { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Fields every answer must have (dotted paths from the root, e.g. <c>data.user</c>): a JSON without them stops the
|
||||
/// session and warns (§6.0, §7.6). From the request shapes (<c>campo_radice</c>) or the cleaned sample.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> RootFields { get; }
|
||||
|
||||
/// <summary>The cleaned sample of <c>tests/Febe.Tests/campioni/<sito></c> that documents the answer (file name without extension).</summary>
|
||||
public string? Sample { get; }
|
||||
|
||||
/// <summary>Values of the case the request must carry.</summary>
|
||||
public IReadOnlySet<string> RequiredValues { get; }
|
||||
|
||||
/// <summary>Values of the case the request may carry (optional query parameters).</summary>
|
||||
public IReadOnlySet<string> OptionalValues { get; }
|
||||
|
||||
/// <summary>Headers and form fields whose source is not settled yet (<see cref="ValueSourceKind.Pending"/>).</summary>
|
||||
public IReadOnlyList<string> PendingValues { get; }
|
||||
|
||||
/// <summary>Why <paramref name="request"/> does not fit this operation (in Italian, names only), or null.</summary>
|
||||
public string? CheckValues(SiteRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var missing = RequiredValues.Where(v => !request.Values.ContainsKey(v)).Order(StringComparer.Ordinal).ToList();
|
||||
if (missing.Count > 0)
|
||||
{
|
||||
return $"manca il valore {string.Join(", ", missing.Select(m => $"«{m}»"))}.";
|
||||
}
|
||||
|
||||
var extra = request.Values.Keys.Where(v => !RequiredValues.Contains(v) && !OptionalValues.Contains(v)).Order(StringComparer.Ordinal).ToList();
|
||||
if (extra.Count > 0)
|
||||
{
|
||||
return $"il valore {string.Join(", ", extra.Select(e => $"«{e}»"))} non serve a questa operazione.";
|
||||
}
|
||||
|
||||
// A value that fills a segment of the path must stay that segment: nothing the HTTP stack would read as another
|
||||
// segment, a query or a step up («/», «?», «#», «%», «.», «..»).
|
||||
var unsafeInPath = PathValues.Where(v => request.Values.TryGetValue(v, out var value) && !IsPlainSegment(value)).Order(StringComparer.Ordinal).ToList();
|
||||
return unsafeInPath.Count > 0
|
||||
? $"il valore {string.Join(", ", unsafeInPath.Select(v => $"«{v}»"))} non può stare nel percorso (contiene «/», «?», «#», «%», spazi o è fatto solo di punti)."
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>Values of the case that fill a segment of <see cref="Path"/>.</summary>
|
||||
public IReadOnlySet<string> PathValues { get; }
|
||||
|
||||
private static bool IsPlainSegment(string value) =>
|
||||
value.Length > 0
|
||||
&& value.Trim('.').Length > 0
|
||||
&& !value.Any(c => c is '/' or '\\' or '?' or '#' or '%' or ';' || char.IsWhiteSpace(c) || char.IsControl(c));
|
||||
|
||||
/// <summary>True when the answer has every field of <see cref="RootFields"/> (not null).</summary>
|
||||
public bool HasRootFields(JsonElement root)
|
||||
{
|
||||
foreach (var field in RootFields)
|
||||
{
|
||||
var node = root;
|
||||
foreach (var part in field.Split('.'))
|
||||
{
|
||||
if (node.ValueKind != JsonValueKind.Object || !node.TryGetProperty(part, out node))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (node.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The name, the shape of the path and the state: what the log may show.</summary>
|
||||
public override string ToString() => $"{Name} ({Method} {PathShape}{(IsConfigured ? string.Empty : ", non configurata")})";
|
||||
|
||||
[GeneratedRegex(@"\{([a-z_]+)\??\}", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Placeholder();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The operations the site client may ask (issue #36, spec §6.0), loaded from <c>richieste.<sito>.json</c> like the
|
||||
/// other configuration files: a copy embedded in Febe, an editable copy in the Data folder that wins.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The file only narrows: the refusals are in the code, so an edited copy cannot lift them. At load time the catalog
|
||||
/// refuses, with an Italian message naming the file and the operation:
|
||||
/// <list type="bullet">
|
||||
/// <item>any operation whose name contains <c>Mutation</c> (the site's writes; the request shapes show them as
|
||||
/// <c>…Mutation</c>), and the GraphQL families of chat, inbox, presence, promotions and telemetry
|
||||
/// (<see cref="ForbiddenNamePrefixes"/>, <see cref="ForbiddenNameParts"/>);</item>
|
||||
/// <item>the paths of telemetry, navigation and the site's own scripts (<see cref="ForbiddenPathPrefixes"/>), any path
|
||||
/// with a host or a query string, any segment that is empty, <c>.</c> or <c>..</c> (the HTTP stack would rewrite it),
|
||||
/// any character outside letters, digits and <c>/_.-{}</c>, any path whose first segment is a value, GraphQL outside
|
||||
/// its two entry points and a plain address that points at one of them;</item>
|
||||
/// <item>a plain address that is not read with GET, a GraphQL query without its variables, a header <c>cookie</c>,
|
||||
/// <c>host</c> or <c>authorization</c>, an unknown key, source, category or value name, the category «ricerca» for
|
||||
/// anything but a search (<see cref="SiteOperation.Category"/>).</item>
|
||||
/// </list>
|
||||
/// An operation is «configured» only when the shapes tell everything it needs, every header and field included (no
|
||||
/// <see cref="ValueSourceKind.Pending"/>); otherwise the file says why, and the site client refuses it.
|
||||
/// </remarks>
|
||||
public sealed partial class RequestCatalog
|
||||
{
|
||||
/// <summary>Written by the probe in place of a name that elsewhere was a value: the real name is unknown.</summary>
|
||||
public const string RemovedName = "(nome tolto)";
|
||||
|
||||
/// <summary>Written in a template in place of a value the shapes do not show.</summary>
|
||||
public const string RemovedValue = "(valore tolto)";
|
||||
|
||||
/// <summary>The two GraphQL entry points seen in the request shapes.</summary>
|
||||
public static IReadOnlySet<string> GraphQlPaths { get; } = new[] { "/api/graphql", "/graphql/query" }.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Paths never asked, also when an edited file lists them: telemetry, navigation and scripts of the page, chat.</summary>
|
||||
public static IReadOnlyList<string> ForbiddenPathPrefixes { get; } =
|
||||
[
|
||||
"/logging_client_events", "/ajax/bz", "/ajax/bulk-route-definitions/", "/ajax/navigation/", "/ajax/", "/ws/",
|
||||
"/api/v1/web/", "/api/v1/discover/web/", "/api/v1/direct_v2/", "/api/v1/qp/",
|
||||
];
|
||||
|
||||
/// <summary>Beginnings of the GraphQL names of chat, inbox, presence, promotions, telemetry and ads, never asked.</summary>
|
||||
public static IReadOnlyList<string> ForbiddenNamePrefixes { get; } =
|
||||
[
|
||||
"IGD", "IGPresence", "PolarisDirect", "useIGDSystem", "QuickPromotion", "PolarisAPIGetFrCookie", "useFeatureLimits",
|
||||
"PolarisStoriesV3Seen", "PolarisStoriesV3AdsPool", "usePolarisLike", "usePolarisRegisterInRecentSearches",
|
||||
"PolarisProfileDirectOrPartnershipInbox",
|
||||
];
|
||||
|
||||
/// <summary>Parts of a name that make it a write or a chat operation wherever they stand.</summary>
|
||||
public static IReadOnlyList<string> ForbiddenNameParts { get; } = ["Mutation", "Inbox", "Msys", "Presence"];
|
||||
|
||||
private static readonly FrozenSet<string> ForbiddenHeaders = new[]
|
||||
{
|
||||
"cookie", "host", "authorization", "proxy-authorization", "connection", "transfer-encoding", "set-cookie",
|
||||
}.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
private readonly FrozenDictionary<string, SiteOperation> _byName;
|
||||
|
||||
private RequestCatalog(string site, IReadOnlyList<SiteOperation> operations, string? source)
|
||||
{
|
||||
Site = site;
|
||||
Operations = operations;
|
||||
Source = source ?? $"richieste.{site}.json";
|
||||
_byName = operations.ToFrozenDictionary(o => o.Name, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>The site name of the file (<c>instagram</c>, <c>prova</c>).</summary>
|
||||
public string Site { get; }
|
||||
|
||||
/// <summary>Every operation, in the order of the file.</summary>
|
||||
public IReadOnlyList<SiteOperation> Operations { get; }
|
||||
|
||||
/// <summary>Where it came from (file path or embedded name), for messages.</summary>
|
||||
public string Source { get; }
|
||||
|
||||
/// <summary>The configured operations.</summary>
|
||||
public IEnumerable<SiteOperation> Configured => Operations.Where(o => o.IsConfigured);
|
||||
|
||||
public bool TryGet(string name, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out SiteOperation? operation) =>
|
||||
_byName.TryGetValue(name, out operation);
|
||||
|
||||
/// <summary>The Instagram catalog (embedded <c>richieste.instagram.json</c>).</summary>
|
||||
public static RequestCatalog LoadInstagram() => LoadEmbedded("richieste.instagram.json");
|
||||
|
||||
/// <summary>The catalog of the local test site (embedded <c>richieste.prova.json</c>).</summary>
|
||||
public static RequestCatalog LoadTestSite() => LoadEmbedded("richieste.prova.json");
|
||||
|
||||
/// <summary>Loads <paramref name="path"/> when it exists, otherwise the embedded file with the same name.</summary>
|
||||
public static RequestCatalog LoadOrEmbedded(string? path, string embeddedName) =>
|
||||
!string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName);
|
||||
|
||||
public static RequestCatalog Load(string path) => Parse(File.ReadAllText(path), path);
|
||||
|
||||
public static RequestCatalog LoadEmbedded(string fileName) => Parse(SiteMap.ReadEmbeddedText(fileName), fileName);
|
||||
|
||||
/// <exception cref="InvalidDataException">The file is not valid or lists something the catalog refuses.</exception>
|
||||
public static RequestCatalog Parse(string json, string? source = null)
|
||||
{
|
||||
var name = source ?? "richieste";
|
||||
CatalogFile? file;
|
||||
try
|
||||
{
|
||||
file = JsonSerializer.Deserialize(json, RequestCatalogJsonContext.Default.CatalogFile);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{name}: file non valido (riga {(ex.LineNumber ?? 0) + 1}): {ex.Message.Split('.')[0]}.", ex);
|
||||
}
|
||||
|
||||
if (file is null || string.IsNullOrWhiteSpace(file.Site))
|
||||
{
|
||||
throw new InvalidDataException($"{name}: manca «site».");
|
||||
}
|
||||
|
||||
if (file.Operations is null)
|
||||
{
|
||||
throw new InvalidDataException($"{name}: manca l'elenco «operations».");
|
||||
}
|
||||
|
||||
var operations = new List<SiteOperation>(file.Operations.Count);
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
for (var i = 0; i < file.Operations.Count; i++)
|
||||
{
|
||||
var dto = file.Operations[i] ?? throw new InvalidDataException($"{name}, operazione {(i + 1).ToString(CultureInfo.InvariantCulture)}: voce vuota.");
|
||||
var operation = ToOperation(dto, $"{name}, operazione {(i + 1).ToString(CultureInfo.InvariantCulture)}");
|
||||
if (!names.Add(operation.Name))
|
||||
{
|
||||
throw new InvalidDataException($"{name}: l'operazione «{operation.Name}» compare due volte.");
|
||||
}
|
||||
|
||||
operations.Add(operation);
|
||||
}
|
||||
|
||||
return new RequestCatalog(file.Site.Trim(), operations, source);
|
||||
}
|
||||
|
||||
/// <summary>Why the code refuses an operation with this name, whatever the file says; null when it does not.</summary>
|
||||
public static string? RefusalOfName(string operationName)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operationName);
|
||||
foreach (var part in ForbiddenNameParts)
|
||||
{
|
||||
if (operationName.Contains(part, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return part == "Mutation"
|
||||
? "è una scrittura («Mutation»): Febe chiede solo letture (regola 6)"
|
||||
: $"è della famiglia di chat, messaggi o presenza («{part}»), che Febe non chiede mai";
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var prefix in ForbiddenNamePrefixes)
|
||||
{
|
||||
if (operationName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return $"è della famiglia «{prefix}» (chat, messaggi, presenza, promozioni, pubblicità o telemetria), che Febe non chiede mai";
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Why the code refuses this path, whatever the file says; null when it does not.</summary>
|
||||
public static string? RefusalOfPath(string path)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(path);
|
||||
if (!path.StartsWith('/') || path.StartsWith("//", StringComparison.Ordinal) || path.Contains("://", StringComparison.Ordinal)
|
||||
|| path.Contains('\\', StringComparison.Ordinal))
|
||||
{
|
||||
return "un percorso comincia con una sola «/» e non nomina un host: Febe chiede solo al sito";
|
||||
}
|
||||
|
||||
if (path.IndexOfAny(['?', '#']) >= 0)
|
||||
{
|
||||
return "un percorso non porta parametri: vanno in «parameters»";
|
||||
}
|
||||
|
||||
if (path.Contains("..", StringComparison.Ordinal) || !PathCharacters().IsMatch(path))
|
||||
{
|
||||
return "il percorso contiene caratteri non ammessi";
|
||||
}
|
||||
|
||||
// The prefixes are compared on the text: no segment the HTTP stack or the server would rewrite («/./», «//»), so
|
||||
// the path that leaves is the one checked here.
|
||||
var segments = path.Split('/');
|
||||
for (var i = 1; i < segments.Length; i++)
|
||||
{
|
||||
if ((segments[i].Length == 0 && i < segments.Length - 1) || segments[i] == ".")
|
||||
{
|
||||
return "un percorso non ha segmenti vuoti («//») né «.»: il percorso che parte è quello scritto";
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var prefix in ForbiddenPathPrefixes)
|
||||
{
|
||||
if (path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
|
||||
|| path.Equals(prefix.TrimEnd('/'), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return $"«{prefix}» è telemetria, navigazione o chat della pagina, che Febe non chiede mai";
|
||||
}
|
||||
}
|
||||
|
||||
var first = path.Split('/', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
|
||||
if (first is null || first.StartsWith('{'))
|
||||
{
|
||||
return "il primo segmento del percorso dev'essere una parola fissa del sito, non un valore";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static SiteOperation ToOperation(OperationDto dto, string where)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dto.Name))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: manca «name».");
|
||||
}
|
||||
|
||||
var name = dto.Name.Trim();
|
||||
where = $"{where} («{name}»)";
|
||||
if (!OperationName().IsMatch(name))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: il nome contiene caratteri non ammessi.");
|
||||
}
|
||||
|
||||
if (RefusalOfName(name) is { } refusedName)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: rifiutata, {refusedName}.");
|
||||
}
|
||||
|
||||
var kind = dto.Kind?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"graphql" => OperationKind.GraphQl,
|
||||
"rest" => OperationKind.Rest,
|
||||
_ => throw new InvalidDataException($"{where}: tipo «{dto.Kind}» sconosciuto (ammessi: graphql, rest)."),
|
||||
};
|
||||
|
||||
var method = dto.Method?.Trim().ToUpperInvariant();
|
||||
var path = dto.Path?.Trim() ?? throw new InvalidDataException($"{where}: manca «path».");
|
||||
if (RefusalOfPath(path) is { } refusedPath)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: rifiutata, {refusedPath}.");
|
||||
}
|
||||
|
||||
var category = ParseCategory(dto.Category, where);
|
||||
var required = new SortedSet<string>(StringComparer.Ordinal);
|
||||
var optional = new SortedSet<string>(StringComparer.Ordinal);
|
||||
foreach (var segment in path.Split('/', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (segment.Contains('{', StringComparison.Ordinal) || segment.Contains('}', StringComparison.Ordinal))
|
||||
{
|
||||
required.Add(CaseValue(segment, where, allowOptional: false, out _));
|
||||
}
|
||||
}
|
||||
|
||||
var parameters = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var (key, value) in dto.Parameters ?? new Dictionary<string, string?>())
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key) || key == RemovedName || !FieldName().IsMatch(key))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: parametro «{key}» non ammesso.");
|
||||
}
|
||||
|
||||
if (value is null || value.Length == 0)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: il parametro «{key}» non dice il suo valore.");
|
||||
}
|
||||
|
||||
if (value.StartsWith('{'))
|
||||
{
|
||||
var caseValue = CaseValue(value, where, allowOptional: true, out var isOptional);
|
||||
(isOptional ? optional : required).Add(caseValue);
|
||||
}
|
||||
else if (!value.StartsWith("constant:", StringComparison.Ordinal) || value.Length == "constant:".Length)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: il parametro «{key}» vale «{{valore del caso}}» o «constant:…».");
|
||||
}
|
||||
|
||||
parameters[key] = value;
|
||||
}
|
||||
|
||||
var headers = Sources(dto.Headers, where, "intestazione", isBody: false);
|
||||
foreach (var header in headers.Keys)
|
||||
{
|
||||
if (ForbiddenHeaders.Contains(header))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: l'intestazione «{header}» non si scrive nel modello (i cookie vengono dalla sessione salvata, l'host è quello del sito).");
|
||||
}
|
||||
}
|
||||
|
||||
if (headers.TryGetValue("user-agent", out var userAgent) && userAgent != new ValueSource(ValueSourceKind.Session, "user_agent"))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «user-agent» è quello del browser, copiato tale e quale («session:user_agent», regola 4).");
|
||||
}
|
||||
|
||||
var body = Sources(dto.Body, where, "campo", isBody: true);
|
||||
JsonElement? variables = null;
|
||||
var removedInVariables = false;
|
||||
if (kind == OperationKind.GraphQl)
|
||||
{
|
||||
if (method != "POST")
|
||||
{
|
||||
throw new InvalidDataException($"{where}: una richiesta GraphQL si fa con POST.");
|
||||
}
|
||||
|
||||
if (!GraphQlPaths.Contains(path))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: una richiesta GraphQL va a {string.Join(" o ", GraphQlPaths)}.");
|
||||
}
|
||||
|
||||
if (parameters.Count > 0)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: una richiesta GraphQL non ha parametri nell'indirizzo.");
|
||||
}
|
||||
|
||||
RequireSource(body, "variables", new ValueSource(ValueSourceKind.Variables, null), where);
|
||||
RequireSource(body, "doc_id", new ValueSource(ValueSourceKind.Session, "doc_id"), where);
|
||||
RequireSource(body, "fb_api_req_friendly_name", new ValueSource(ValueSourceKind.Operation, null), where);
|
||||
if (headers.TryGetValue("x-fb-friendly-name", out var friendly) && friendly.Kind != ValueSourceKind.Operation)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «x-fb-friendly-name» è il nome dell'operazione («operation»).");
|
||||
}
|
||||
|
||||
if (dto.Variables is not { ValueKind: JsonValueKind.Object } template)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: manca «variables» (un oggetto, come nelle forme delle richieste).");
|
||||
}
|
||||
|
||||
removedInVariables = Template(template, where, required, depth: 0);
|
||||
variables = template.Clone();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (method != "GET")
|
||||
{
|
||||
throw new InvalidDataException($"{where}: un indirizzo semplice si legge solo con GET (sola lettura).");
|
||||
}
|
||||
|
||||
// A GET to a GraphQL entry point would skip the checks of a GraphQL query (doc_id from the session, the
|
||||
// friendly name that is the operation's and that the refusal of «Mutation» looks at).
|
||||
if (path.Split('/').Any(s => s.Contains("graphql", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: rifiutata, una richiesta GraphQL si scrive con «kind»: «graphql», non come indirizzo semplice.");
|
||||
}
|
||||
|
||||
if (body.Count > 0 || dto.Variables is { ValueKind: not JsonValueKind.Null and not JsonValueKind.Undefined })
|
||||
{
|
||||
throw new InvalidDataException($"{where}: una lettura con GET non ha «body» né «variables».");
|
||||
}
|
||||
}
|
||||
|
||||
// The search budget belongs to no session and spares the collection caps (§7.4): only a search may count there,
|
||||
// and a search counts nowhere else, whatever an edited copy says.
|
||||
var searches = required.Contains(CaseValues.SearchText) || optional.Contains(CaseValues.SearchText);
|
||||
if (category == ActionKind.ProfileSearch
|
||||
&& (!required.Contains(CaseValues.SearchText) || required.Concat(optional).Any(v => v is not (CaseValues.SearchText or CaseValues.Cursor))))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: rifiutata, la categoria «ricerca» è solo di una ricerca, che porta «{{{CaseValues.SearchText}}}» e nessun account o contenuto.");
|
||||
}
|
||||
|
||||
if (searches && category != ActionKind.ProfileSearch)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: rifiutata, un'operazione che porta «{{{CaseValues.SearchText}}}» è una ricerca (categoria «ricerca»).");
|
||||
}
|
||||
|
||||
var rootFields = (dto.RootFields ?? []).Select(f => f?.Trim() ?? string.Empty).ToList();
|
||||
if (rootFields.Any(f => !RootField().IsMatch(f)))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «rootFields» elenca campi come «data.user», separati da punti.");
|
||||
}
|
||||
|
||||
var sample = string.IsNullOrWhiteSpace(dto.Sample) ? null : dto.Sample.Trim();
|
||||
if (sample is not null && !SampleName().IsMatch(sample))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «sample» è il nome di un campione ripulito, come «000005-post-video».");
|
||||
}
|
||||
|
||||
var configured = dto.Configured ?? throw new InvalidDataException($"{where}: manca «configured» (true o false).");
|
||||
var reason = string.IsNullOrWhiteSpace(dto.Reason) ? null : dto.Reason.Trim();
|
||||
if (configured)
|
||||
{
|
||||
if (reason is not null)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «reason» si scrive solo per un'operazione non configurata.");
|
||||
}
|
||||
|
||||
if (removedInVariables)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: le variabili hanno un nome o un valore tolto dalla sonda: non può essere configurata (regola 9).");
|
||||
}
|
||||
|
||||
// Every header and field the model lists leaves with its value, or the request is not the browser's (rule 4):
|
||||
// one whose source is not settled, or whose name the probe removed, keeps the operation not configured.
|
||||
var pending = headers.Where(h => h.Value.Kind == ValueSourceKind.Pending).Select(h => h.Key)
|
||||
.Concat(body.Where(b => b.Value.Kind == ValueSourceKind.Pending).Select(b => b.Key)).ToList();
|
||||
if (pending.Count > 0)
|
||||
{
|
||||
throw new InvalidDataException(
|
||||
$"{where}: {pending.Count.ToString(CultureInfo.InvariantCulture)} intestazioni o campi hanno la fonte «pending» (come {string.Join(", ", pending.Take(3).Select(p => $"«{p}»"))}): non può essere configurata finché non si sa da dove vengono i valori (regola 9).");
|
||||
}
|
||||
|
||||
if (sample is null || rootFields.Count == 0)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: un'operazione configurata dice il campione della risposta («sample») e i campi attesi («rootFields»).");
|
||||
}
|
||||
}
|
||||
else if (reason is null)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: un'operazione non configurata dice perché («reason»).");
|
||||
}
|
||||
|
||||
return new SiteOperation(
|
||||
name, kind, method!, path, category, configured, reason, parameters.ToFrozenDictionary(StringComparer.Ordinal),
|
||||
headers.ToFrozenDictionary(StringComparer.Ordinal), body.ToFrozenDictionary(StringComparer.Ordinal), variables,
|
||||
rootFields, sample, required.ToFrozenSet(StringComparer.Ordinal), optional.ToFrozenSet(StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
private static Dictionary<string, ValueSource> Sources(Dictionary<string, string?>? entries, string where, string what, bool isBody)
|
||||
{
|
||||
var result = new Dictionary<string, ValueSource>(StringComparer.Ordinal);
|
||||
foreach (var (key, text) in entries ?? new Dictionary<string, string?>())
|
||||
{
|
||||
var isRemoved = key == RemovedName;
|
||||
if (!isRemoved && (isBody ? !FieldName().IsMatch(key) : !HeaderName().IsMatch(key)))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: {what} «{key}» non ammesso{(isBody ? string.Empty : " (nomi in minuscolo)")}.");
|
||||
}
|
||||
|
||||
var source = ParseSource(text, $"{where}, {what} «{key}»");
|
||||
if (isRemoved && source.Kind != ValueSourceKind.Pending)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: un {what} con il nome tolto dalla sonda vale solo «pending».");
|
||||
}
|
||||
|
||||
if (source.Kind == ValueSourceKind.Variables && !(isBody && key == "variables"))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «variables» è la fonte del solo campo «variables».");
|
||||
}
|
||||
|
||||
result[key] = source;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ValueSource ParseSource(string? text, string where)
|
||||
{
|
||||
var value = text ?? string.Empty;
|
||||
var colon = value.IndexOf(':', StringComparison.Ordinal);
|
||||
var head = colon < 0 ? value : value[..colon];
|
||||
var argument = colon < 0 ? null : value[(colon + 1)..];
|
||||
switch (head)
|
||||
{
|
||||
case "constant" when !string.IsNullOrEmpty(argument):
|
||||
return new ValueSource(ValueSourceKind.Constant, argument);
|
||||
case "cookie" when argument is not null && CookieName().IsMatch(argument):
|
||||
return new ValueSource(ValueSourceKind.Cookie, argument);
|
||||
case "session" when argument is not null && ValueSource.SessionFields.Contains(argument):
|
||||
return new ValueSource(ValueSourceKind.Session, argument);
|
||||
case "operation" when argument is null:
|
||||
return new ValueSource(ValueSourceKind.Operation, null);
|
||||
case "variables" when argument is null:
|
||||
return new ValueSource(ValueSourceKind.Variables, null);
|
||||
case "computed" when argument is null:
|
||||
return new ValueSource(ValueSourceKind.Computed, null);
|
||||
case "pending" when argument is null:
|
||||
return new ValueSource(ValueSourceKind.Pending, null);
|
||||
default:
|
||||
throw new InvalidDataException(
|
||||
$"{where}: fonte «{value}» sconosciuta (ammesse: constant:…, cookie:…, session:{string.Join("|", ValueSource.SessionFields.Order(StringComparer.Ordinal))}, operation, variables, computed, pending).");
|
||||
}
|
||||
}
|
||||
|
||||
private static void RequireSource(Dictionary<string, ValueSource> body, string field, ValueSource expected, string where)
|
||||
{
|
||||
if (!body.TryGetValue(field, out var actual) || actual != expected)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: una richiesta GraphQL ha il campo «{field}» con la fonte «{expected}».");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Checks a variables template; collects its values of the case; true when it holds removed names or values.</summary>
|
||||
private static bool Template(JsonElement element, string where, SortedSet<string> required, int depth)
|
||||
{
|
||||
if (depth > 16)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: «variables» è troppo profondo.");
|
||||
}
|
||||
|
||||
var removed = false;
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
removed |= property.Name == RemovedName;
|
||||
removed |= Template(property.Value, where, required, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
removed |= Template(item, where, required, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.String:
|
||||
var text = element.GetString()!;
|
||||
if (text == RemovedValue)
|
||||
{
|
||||
removed = true;
|
||||
}
|
||||
else if (text.StartsWith('{') || text.EndsWith('}'))
|
||||
{
|
||||
required.Add(CaseValue(text, where, allowOptional: false, out _));
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
private static string CaseValue(string text, string where, bool allowOptional, out bool isOptional)
|
||||
{
|
||||
var match = CaseValuePattern().Match(text);
|
||||
isOptional = match.Success && match.Groups[2].Success;
|
||||
if (!match.Success || (isOptional && !allowOptional) || !CaseValues.All.Contains(match.Groups[1].Value))
|
||||
{
|
||||
throw new InvalidDataException(
|
||||
$"{where}: «{text}» non è un valore del caso (ammessi: {string.Join(", ", CaseValues.All.Order(StringComparer.Ordinal).Select(v => $"{{{v}}}"))}{(allowOptional ? ", con «?» se facoltativo" : string.Empty)}).");
|
||||
}
|
||||
|
||||
return match.Groups[1].Value;
|
||||
}
|
||||
|
||||
private static ActionKind ParseCategory(string? value, string where) => value?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"home" => ActionKind.Home,
|
||||
"profilo" => ActionKind.ProfileOpen,
|
||||
"storia" => ActionKind.StoryView,
|
||||
"storico" => ActionKind.BackfillPage,
|
||||
"post" => ActionKind.SinglePost,
|
||||
"seguiti" => ActionKind.FollowingListPage,
|
||||
"ricerca" => ActionKind.ProfileSearch,
|
||||
_ => throw new InvalidDataException($"{where}: categoria «{value}» sconosciuta (ammesse: home, profilo, storia, storico, post, seguiti, ricerca)."),
|
||||
};
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z][A-Za-z0-9_.-]{0,127}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex OperationName();
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z0-9/_.{}-]+$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex PathCharacters();
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z_][A-Za-z0-9_]{0,63}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex FieldName();
|
||||
|
||||
[GeneratedRegex(@"^[a-z][a-z0-9-]{0,63}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex HeaderName();
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z0-9_.-]{1,64}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex CookieName();
|
||||
|
||||
[GeneratedRegex(@"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex RootField();
|
||||
|
||||
[GeneratedRegex(@"^[0-9]{6}-[a-z0-9-]+$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex SampleName();
|
||||
|
||||
[GeneratedRegex(@"^\{([a-z_]+)(\?)?\}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex CaseValuePattern();
|
||||
}
|
||||
|
||||
internal sealed class CatalogFile
|
||||
{
|
||||
public string? Site { get; set; }
|
||||
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<OperationDto?>? Operations { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class OperationDto
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
|
||||
public string? Kind { get; set; }
|
||||
|
||||
public string? Method { get; set; }
|
||||
|
||||
public string? Path { get; set; }
|
||||
|
||||
public string? Category { get; set; }
|
||||
|
||||
public bool? Configured { get; set; }
|
||||
|
||||
public string? Reason { get; set; }
|
||||
|
||||
public Dictionary<string, string?>? Parameters { get; set; }
|
||||
|
||||
public Dictionary<string, string?>? Headers { get; set; }
|
||||
|
||||
public Dictionary<string, string?>? Body { get; set; }
|
||||
|
||||
public JsonElement? Variables { get; set; }
|
||||
|
||||
public List<string?>? RootFields { get; set; }
|
||||
|
||||
public string? Sample { get; set; }
|
||||
|
||||
public List<string>? Shapes { get; set; }
|
||||
|
||||
public string? Note { get; set; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true,
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow)]
|
||||
[JsonSerializable(typeof(CatalogFile))]
|
||||
internal sealed partial class RequestCatalogJsonContext : JsonSerializerContext;
|
||||
@@ -0,0 +1,195 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Febe.Core.Collection.Privacy;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>
|
||||
/// What the site answered to one <see cref="SiteRequest"/> (issue #36, spec §6.0), with what the stop signals of §7.6
|
||||
/// need: the status, the declared type, whether it was a redirect and where to (the shape of the path only, never
|
||||
/// followed), and the names of the cookies the site set or deleted. The body lives in memory only, for the time of the
|
||||
/// reading (§6.2).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It never holds a value of a header or of a cookie: the site client keeps the renewed cookies and the
|
||||
/// <c>x-ig-www-claim</c> in the saved session itself (decision of 16 November 2026) and reports here only that they
|
||||
/// came. Its text (<see cref="ToString"/>) shows the operation, the shape of the path, the status, the type and the
|
||||
/// sizes, never the body, the cookies, a query string or the variables (rule 10).
|
||||
/// </remarks>
|
||||
public sealed class SiteAnswer
|
||||
{
|
||||
/// <param name="operation">
|
||||
/// The catalog operation that was asked: its name and its <see cref="SiteOperation.PathShape"/> are what the answer
|
||||
/// shows, so the path with its values (an identifier, a user name) can never be passed in its place.
|
||||
/// </param>
|
||||
/// <param name="status">HTTP status.</param>
|
||||
/// <param name="mimeType">Declared type (parameters such as the charset are dropped).</param>
|
||||
/// <param name="body">The body, decoded (memory only).</param>
|
||||
/// <param name="redirectTo">For a redirect, the <c>Location</c> as the site sent it: only the shape of its path is kept.</param>
|
||||
/// <param name="cookiesSet">Names of the cookies the site set (<c>Set-Cookie</c> with a value).</param>
|
||||
/// <param name="cookiesDeleted">Names of the cookies the site deleted (<c>Set-Cookie</c> expired or empty).</param>
|
||||
/// <param name="setsClaim">True when the site sent a new <c>x-ig-www-claim</c> (<c>x-ig-set-www-claim</c>).</param>
|
||||
/// <param name="retryAfter">What a <c>Retry-After</c> asked to wait, when the site sent one.</param>
|
||||
/// <exception cref="ArgumentException">A cookie name that is not a plain name (a value must never slip in).</exception>
|
||||
public SiteAnswer(
|
||||
SiteOperation operation,
|
||||
int status,
|
||||
string? mimeType,
|
||||
ReadOnlyMemory<byte> body,
|
||||
string? redirectTo = null,
|
||||
IEnumerable<string>? cookiesSet = null,
|
||||
IEnumerable<string>? cookiesDeleted = null,
|
||||
bool setsClaim = false,
|
||||
TimeSpan? retryAfter = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operation);
|
||||
Operation = operation.Name;
|
||||
PathShape = operation.PathShape;
|
||||
Status = status;
|
||||
MimeType = (mimeType ?? string.Empty).Split(';')[0].Trim().ToLowerInvariant();
|
||||
Body = body;
|
||||
IsRedirect = status is >= 300 and < 400;
|
||||
RedirectPathShape = IsRedirect || redirectTo is not null ? ShapeOfLocation(redirectTo) : null;
|
||||
CookiesSet = Names(cookiesSet, nameof(cookiesSet));
|
||||
CookiesDeleted = Names(cookiesDeleted, nameof(cookiesDeleted));
|
||||
SetsClaim = setsClaim;
|
||||
RetryAfter = retryAfter;
|
||||
}
|
||||
|
||||
/// <summary>Name of the catalog operation that was asked.</summary>
|
||||
public string Operation { get; }
|
||||
|
||||
/// <summary>Shape of the path asked (<c>/api/v1/media/{numero}/info/</c>): what the log may show.</summary>
|
||||
public string PathShape { get; }
|
||||
|
||||
public int Status { get; }
|
||||
|
||||
/// <summary>Declared type, lower case, without parameters.</summary>
|
||||
public string MimeType { get; }
|
||||
|
||||
/// <summary>The body (memory only, never logged).</summary>
|
||||
public ReadOnlyMemory<byte> Body { get; }
|
||||
|
||||
/// <summary>True for a 3xx: a signal (§7.6), never an address to visit.</summary>
|
||||
public bool IsRedirect { get; }
|
||||
|
||||
/// <summary>
|
||||
/// For a redirect, the shape of the path it pointed to (<c>/accounts/login/</c>, <c>/challenge/{testo}/</c>):
|
||||
/// words of the site kept, everything else <c>{numero}</c> or <c>{testo}</c>, no host, no query string. Empty when
|
||||
/// the site sent no <c>Location</c>.
|
||||
/// </summary>
|
||||
public string? RedirectPathShape { get; }
|
||||
|
||||
/// <summary>Names of the cookies the site set.</summary>
|
||||
public IReadOnlyList<string> CookiesSet { get; }
|
||||
|
||||
/// <summary>Names of the cookies the site deleted (§7.6: the session cookie deleted is a Disconnessione).</summary>
|
||||
public IReadOnlyList<string> CookiesDeleted { get; }
|
||||
|
||||
/// <summary>True when the site sent a new <c>x-ig-www-claim</c> (kept by the site client in the saved session, never here).</summary>
|
||||
public bool SetsClaim { get; }
|
||||
|
||||
/// <summary>What a <c>Retry-After</c> asked to wait (§7.6, Rallentamento).</summary>
|
||||
public TimeSpan? RetryAfter { get; }
|
||||
|
||||
/// <summary>True when the declared type is JSON, or JavaScript as Instagram serves its GraphQL data (<see cref="DataResponses.IsData"/>).</summary>
|
||||
public bool IsDeclaredData => DataResponses.IsData(MimeType, "Fetch");
|
||||
|
||||
/// <summary>True for an HTML document (§7.6: an HTML where the catalog expects JSON stops the session).</summary>
|
||||
public bool IsHtml => MimeType is "text/html" or "application/xhtml+xml";
|
||||
|
||||
/// <summary>True when the site deleted the cookie <paramref name="name"/>.</summary>
|
||||
public bool Deletes(string name) => CookiesDeleted.Contains(name, StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// The shape of the path of a <c>Location</c> (absolute or relative): no scheme, no host, no query string, values
|
||||
/// replaced by <see cref="PathPatterns"/>. Empty for a missing one.
|
||||
/// </summary>
|
||||
public static string ShapeOfLocation(string? location)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(location))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var text = location.Trim();
|
||||
var cut = text.IndexOfAny(['?', '#']);
|
||||
if (cut >= 0)
|
||||
{
|
||||
text = text[..cut];
|
||||
}
|
||||
|
||||
var scheme = text.IndexOf("://", StringComparison.Ordinal);
|
||||
if (scheme >= 0)
|
||||
{
|
||||
var slash = text.IndexOf('/', scheme + 3);
|
||||
text = slash >= 0 ? text[slash..] : "/";
|
||||
}
|
||||
else if (text.StartsWith("//", StringComparison.Ordinal))
|
||||
{
|
||||
var slash = text.IndexOf('/', 2);
|
||||
text = slash >= 0 ? text[slash..] : "/";
|
||||
}
|
||||
|
||||
if (!text.StartsWith('/'))
|
||||
{
|
||||
text = "/" + text;
|
||||
}
|
||||
|
||||
return PathPatterns.Of(text);
|
||||
}
|
||||
|
||||
/// <summary>Operation, path shape, status, type and sizes: never the body, the cookies or a value.</summary>
|
||||
public override string ToString()
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
text.Append(CultureInfo.InvariantCulture, $"Risposta a «{Operation}» ({PathShape}): stato {Status}");
|
||||
text.Append(MimeType.Length == 0 ? ", senza tipo" : $", {MimeType}");
|
||||
text.Append(CultureInfo.InvariantCulture, $", {Body.Length} byte");
|
||||
if (IsRedirect)
|
||||
{
|
||||
text.Append(RedirectPathShape is { Length: > 0 } shape ? $", rinvio a {shape} (non seguito)" : ", rinvio senza indirizzo (non seguito)");
|
||||
}
|
||||
|
||||
if (CookiesSet.Count > 0 || CookiesDeleted.Count > 0)
|
||||
{
|
||||
text.Append(CultureInfo.InvariantCulture, $", cookie impostati {CookiesSet.Count}, cancellati {CookiesDeleted.Count}");
|
||||
}
|
||||
|
||||
if (SetsClaim)
|
||||
{
|
||||
text.Append(", nuovo claim");
|
||||
}
|
||||
|
||||
if (RetryAfter is { } wait)
|
||||
{
|
||||
text.Append(CultureInfo.InvariantCulture, $", attendere {(long)wait.TotalSeconds} s");
|
||||
}
|
||||
|
||||
return text.Append('.').ToString();
|
||||
}
|
||||
|
||||
private static string[] Names(IEnumerable<string>? names, string parameter)
|
||||
{
|
||||
if (names is null)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var list = new List<string>();
|
||||
foreach (var name in names)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name) || name.Any(c => c is '=' or ';' or ',' or '"' || char.IsWhiteSpace(c) || char.IsControl(c)))
|
||||
{
|
||||
throw new ArgumentException("Un nome di cookie non è un nome semplice: qui vanno solo i nomi, mai i valori.", parameter);
|
||||
}
|
||||
|
||||
if (!list.Contains(name, StringComparer.Ordinal))
|
||||
{
|
||||
list.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
return [.. list];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using System.Collections.Frozen;
|
||||
using Febe.Core.Collection.Privacy;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>
|
||||
/// Names of the values of the case that a <see cref="SiteRequest"/> may carry (spec §6.0: «variabili con i soli valori
|
||||
/// del caso»): who or what is asked for, and where a list goes on. A closed list: everything else a request carries
|
||||
/// comes from the catalog (<see cref="RequestCatalog"/>) or from the saved session, never from the caller.
|
||||
/// </summary>
|
||||
public static class CaseValues
|
||||
{
|
||||
/// <summary>Numeric identifier of an account on the site.</summary>
|
||||
public const string AccountId = "account_id";
|
||||
|
||||
/// <summary>User name of an account.</summary>
|
||||
public const string Username = "username";
|
||||
|
||||
/// <summary>Cursor of the next page, as the previous answer gave it.</summary>
|
||||
public const string Cursor = "cursor";
|
||||
|
||||
/// <summary>Text typed in the search box.</summary>
|
||||
public const string SearchText = "search_text";
|
||||
|
||||
/// <summary>Numeric identifier of a content (post, reel, story).</summary>
|
||||
public const string MediaId = "media_id";
|
||||
|
||||
/// <summary>Short code of a post, as in its address.</summary>
|
||||
public const string Code = "code";
|
||||
|
||||
/// <summary>Identifier of a highlight (collection of stories).</summary>
|
||||
public const string HighlightId = "highlight_id";
|
||||
|
||||
/// <summary>Every name of the list.</summary>
|
||||
public static IReadOnlySet<string> All { get; } = new[] { AccountId, Username, Cursor, SearchText, MediaId, Code, HighlightId }
|
||||
.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The shape a value takes in a logged path (<see cref="PathPatterns"/>): never the value itself.</summary>
|
||||
public static string ShapeOf(string name) => name is AccountId or MediaId ? PathPatterns.Number : PathPatterns.Text;
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="value"/> has the form of the value <paramref name="name"/>: digits for identifiers,
|
||||
/// the characters of a user name, a short code or a highlight; for a cursor or a searched text, no control
|
||||
/// character. So a value can never carry a path, a query or a step up into the request it fills.
|
||||
/// </summary>
|
||||
public static bool HasForm(string name, string value)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(name);
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
return name switch
|
||||
{
|
||||
AccountId or MediaId => value.Length <= 32 && value.Length > 0 && value.All(char.IsAsciiDigit),
|
||||
Username => value.Length <= 64 && value.Trim('.').Length > 0 && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_'),
|
||||
Code => value.Length is > 0 and <= 64 && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-'),
|
||||
HighlightId => value.Length is > 0 and <= 64 && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-' or ':'),
|
||||
Cursor or SearchText => value.Length is > 0 and <= 4096 && !value.Any(char.IsControl),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One request to the site (issue #36, spec §6.0): which operation of the catalog, and the values of the case by name.
|
||||
/// Nothing else: method, path, headers, body and constants come from <c>richieste.<sito>.json</c>, the session
|
||||
/// values from the saved session. Callers never pass raw headers, bodies or addresses.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Its text (<see cref="ToString"/>) names the operation and the names of the values, never the values: user names,
|
||||
/// identifiers, cursors and searched texts stay out of logs (rule 10).
|
||||
/// </remarks>
|
||||
public sealed class SiteRequest
|
||||
{
|
||||
/// <param name="operation">Name of the catalog operation (<see cref="SiteOperation.Name"/>).</param>
|
||||
/// <param name="values">Values of the case, by a name of <see cref="CaseValues"/>.</param>
|
||||
/// <exception cref="ArgumentException">An unknown value name, an empty value, or one without its form (<see cref="CaseValues.HasForm"/>).</exception>
|
||||
public SiteRequest(string operation, IReadOnlyDictionary<string, string>? values = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(operation);
|
||||
var copy = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var (name, value) in values ?? new Dictionary<string, string>())
|
||||
{
|
||||
if (!CaseValues.All.Contains(name))
|
||||
{
|
||||
throw new ArgumentException($"Valore «{name}» sconosciuto: una richiesta porta solo {string.Join(", ", CaseValues.All.Order(StringComparer.Ordinal))}.", nameof(values));
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
throw new ArgumentException($"Il valore «{name}» è vuoto.", nameof(values));
|
||||
}
|
||||
|
||||
if (!CaseValues.HasForm(name, value))
|
||||
{
|
||||
// Never the value in the message: it may be a user name or a searched text (rule 10).
|
||||
throw new ArgumentException($"Il valore «{name}» non ha la forma attesa (cifre per gli identificativi; mai un percorso o una query).", nameof(values));
|
||||
}
|
||||
|
||||
copy[name] = value;
|
||||
}
|
||||
|
||||
Operation = operation.Trim();
|
||||
Values = copy.ToFrozenDictionary(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Name of the catalog operation.</summary>
|
||||
public string Operation { get; }
|
||||
|
||||
/// <summary>Values of the case, by name (never logged).</summary>
|
||||
public IReadOnlyDictionary<string, string> Values { get; }
|
||||
|
||||
/// <summary>A request for <paramref name="operation"/> with the given values.</summary>
|
||||
public static SiteRequest For(string operation, params (string Name, string Value)[] values) =>
|
||||
new(operation, values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal));
|
||||
|
||||
/// <summary>The operation and the names of the values, never the values.</summary>
|
||||
public override string ToString() =>
|
||||
Values.Count == 0
|
||||
? $"Richiesta «{Operation}»"
|
||||
: $"Richiesta «{Operation}» (valori: {string.Join(", ", Values.Keys.Order(StringComparer.Ordinal))})";
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// Hands the body of one site answer to the <see cref="IResponseConsumer"/>s (spec §6.2, §6.4), whatever brought it:
|
||||
/// the response tap of the browser, or the site client of issue #36 (§6.0). Captured and requested answers reach the
|
||||
/// readers and the stop signals the same way.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A data body is parsed as one JSON answer; a page document is split into the JSON blocks it embeds
|
||||
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>), each an answer of its own. One answer at a time: each
|
||||
/// <see cref="JsonDocument"/> is disposed before the next is parsed. A consumer that fails stops neither the others nor
|
||||
/// the next answer. Bodies stay in memory and are never logged: the warnings name only the consumer's type.
|
||||
/// Thread-safe (the counters are atomic); the caller decides the order of the answers.
|
||||
/// </remarks>
|
||||
public sealed class ResponseDelivery
|
||||
{
|
||||
/// <summary>The depth a body may reach: Instagram's answers go deeper than the default 64.</summary>
|
||||
public const int MaxDepth = 256;
|
||||
|
||||
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = MaxDepth };
|
||||
|
||||
private readonly string _logPrefix;
|
||||
private readonly Action<string, Exception?> _warn;
|
||||
private long _jsonBodies;
|
||||
private long _parseErrors;
|
||||
|
||||
/// <param name="logPrefix">First word of the warnings, in Italian («Cattura», «Client del sito»).</param>
|
||||
/// <param name="warn">Receives the warnings (message and exception); null discards them.</param>
|
||||
public ResponseDelivery(string logPrefix, Action<string, Exception?>? warn = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(logPrefix);
|
||||
_logPrefix = logPrefix;
|
||||
_warn = warn ?? ((_, _) => { });
|
||||
}
|
||||
|
||||
/// <summary>JSON answers handed to the consumers (a page document counts once per block).</summary>
|
||||
public long JsonBodies => Interlocked.Read(ref _jsonBodies);
|
||||
|
||||
/// <summary>Data bodies that were not JSON after all (e.g. Instagram's «for (;;);» answers, or deeper than <see cref="MaxDepth"/>).</summary>
|
||||
public long ParseErrors => Interlocked.Read(ref _parseErrors);
|
||||
|
||||
/// <summary>
|
||||
/// The body of a data answer, as one answer. Returns how many answers reached the consumers: 0 when it is not
|
||||
/// JSON (the caller tells it as <see cref="BodyDropReason.NotJson"/>), otherwise 1.
|
||||
/// </summary>
|
||||
public async Task<int> DeliverBodyAsync(ResponseDescriptor descriptor, ReadOnlyMemory<byte> body, IReadOnlyList<IResponseConsumer> consumers, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(descriptor);
|
||||
ArgumentNullException.ThrowIfNull(consumers);
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(body, BodyOptions);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Not JSON after all (e.g. Instagram's «for (;;);» answers of /ajax/, which carry no contents): skipped.
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
return 0;
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
await DeliverAsync(descriptor, document, consumers, ct).ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The JSON blocks a page document embeds, each handed to the consumers as an answer of its own with the document's
|
||||
/// descriptor, so that a pagination stays with the block that carries it. Returns how many blocks reached the
|
||||
/// consumers; a document without any (the caller tells it as <see cref="BodyDropReason.NoJsonBlock"/>) is not data,
|
||||
/// and not a parse error.
|
||||
/// </summary>
|
||||
public async Task<int> DeliverDocumentAsync(ResponseDescriptor descriptor, ReadOnlyMemory<byte> document, IReadOnlyList<IResponseConsumer> consumers, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(descriptor);
|
||||
ArgumentNullException.ThrowIfNull(consumers);
|
||||
var delivered = 0;
|
||||
foreach (var block in DataResponses.EmbeddedJsonBlocks(Encoding.UTF8.GetString(document.Span)))
|
||||
{
|
||||
using (block)
|
||||
{
|
||||
delivered++;
|
||||
await DeliverAsync(descriptor, block, consumers, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return delivered;
|
||||
}
|
||||
|
||||
private async Task DeliverAsync(ResponseDescriptor descriptor, JsonDocument body, IReadOnlyList<IResponseConsumer> consumers, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _jsonBodies);
|
||||
foreach (var consumer in consumers)
|
||||
{
|
||||
try
|
||||
{
|
||||
await consumer.ConsumeAsync(descriptor, body, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
|
||||
{
|
||||
_warn($"{_logPrefix}: errore in un lettore ({consumer.GetType().Name}).", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
namespace Febe.Core.Collection.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Times and bounds of the profile search (issue #37). Waits marked «× ritmo» are multiplied by the gesture pace of the
|
||||
/// caution profile; every value is an option so that the tests can shorten them.
|
||||
/// </summary>
|
||||
public sealed record ProfileSearchOptions
|
||||
{
|
||||
public static ProfileSearchOptions Default { get; } = new();
|
||||
|
||||
/// <summary>How long the wanted text must stay still before Febe types it (× ritmo).</summary>
|
||||
public TimeSpan EngineDebounce { get; init; } = TimeSpan.FromMilliseconds(350);
|
||||
|
||||
/// <summary>After a step, how long the search keeps the page waiting for the next letter (× ritmo).</summary>
|
||||
public TimeSpan HoldWindow { get; init; } = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>Longest the search keeps the page in one go, however Alberto keeps typing.</summary>
|
||||
public TimeSpan MaxHold { get; init; } = TimeSpan.FromSeconds(20);
|
||||
|
||||
/// <summary>Least wait after the last key before an answer is taken (covers the site's own debounce, × ritmo).</summary>
|
||||
public TimeSpan MinAnswerWait { get; init; } = TimeSpan.FromMilliseconds(700);
|
||||
|
||||
/// <summary>No data response for this long: the page is quiet (× ritmo).</summary>
|
||||
public TimeSpan Quiet { get; init; } = TimeSpan.FromMilliseconds(600);
|
||||
|
||||
/// <summary>Longest wait for the answer after the last key.</summary>
|
||||
public TimeSpan AnswerTimeout { get; init; } = TimeSpan.FromSeconds(8);
|
||||
|
||||
/// <summary>Longest wait for the page to be quiet before the page goes back to the engine.</summary>
|
||||
public TimeSpan ReleaseSettle { get; init; } = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>Longest one step may take (above the load timeout of a page plus the waits).</summary>
|
||||
public TimeSpan StepGuard { get; init; } = TimeSpan.FromSeconds(60);
|
||||
|
||||
/// <summary>After the dialog closes, how long before the page goes to rest.</summary>
|
||||
public TimeSpan EndGrace { get; init; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>With the dialog open and nothing typed for this long, the page goes to rest.</summary>
|
||||
public TimeSpan IdleRest { get; init; } = TimeSpan.FromMinutes(3);
|
||||
|
||||
/// <summary>After the dialog closes, results and cached answers are forgotten after this long.</summary>
|
||||
public TimeSpan DropHitsAfter { get; init; } = TimeSpan.FromMinutes(10);
|
||||
|
||||
/// <summary>Keys of one burst under one permit of the Governor.</summary>
|
||||
public int KeysPerPermit { get; init; } = 40;
|
||||
|
||||
/// <summary>A focus check every this many keys.</summary>
|
||||
public int FocusCheckEvery { get; init; } = 4;
|
||||
|
||||
/// <summary>How often the waits look at the page and the answers.</summary>
|
||||
public TimeSpan Poll { get; init; } = TimeSpan.FromMilliseconds(100);
|
||||
|
||||
/// <summary>Wait after the «Cerca» button before clicking the box (× ritmo).</summary>
|
||||
public TimeSpan PanelWaitMin { get; init; } = TimeSpan.FromMilliseconds(400);
|
||||
|
||||
/// <summary>Upper bound of <see cref="PanelWaitMin"/>.</summary>
|
||||
public TimeSpan PanelWaitMax { get; init; } = TimeSpan.FromMilliseconds(1000);
|
||||
|
||||
/// <summary>Texts whose answer Febe remembers (no new search on the site for them).</summary>
|
||||
public int CachedTexts { get; init; } = 40;
|
||||
|
||||
/// <summary>How long a remembered answer holds.</summary>
|
||||
public TimeSpan CachedAnswerLifetime { get; init; } = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>Photos fetched for each answer (the first results).</summary>
|
||||
public int PhotosPerAnswer { get; init; } = 8;
|
||||
|
||||
/// <summary>Photos kept in memory.</summary>
|
||||
public int MaxPhotos { get; init; } = 400;
|
||||
|
||||
/// <summary>Bytes of photos kept in memory.</summary>
|
||||
public long MaxPhotoBytes { get; init; } = 8L * 1024 * 1024;
|
||||
|
||||
/// <summary>A photo older than this is forgotten.</summary>
|
||||
public TimeSpan PhotoLifetime { get; init; } = TimeSpan.FromDays(3);
|
||||
|
||||
/// <summary>Long side of the photos kept (pixels).</summary>
|
||||
public int PhotoLongSide { get; init; } = 160;
|
||||
|
||||
/// <summary>Largest photo file Febe downloads.</summary>
|
||||
public long PhotoMaxDownload { get; init; } = 512 * 1024;
|
||||
|
||||
/// <summary>Photos downloaded at the same time.</summary>
|
||||
public int PhotoConcurrency { get; init; } = 2;
|
||||
|
||||
/// <summary>A signed photo address waiting in the queue is dropped after this long.</summary>
|
||||
public TimeSpan PhotoAddressLifetime { get; init; } = TimeSpan.FromMinutes(10);
|
||||
|
||||
/// <summary>Small pause between two photos of the same worker (bounds).</summary>
|
||||
public TimeSpan PhotoPauseMin { get; init; } = TimeSpan.FromMilliseconds(150);
|
||||
|
||||
/// <summary>Upper bound of <see cref="PhotoPauseMin"/>.</summary>
|
||||
public TimeSpan PhotoPauseMax { get; init; } = TimeSpan.FromMilliseconds(600);
|
||||
}
|
||||
@@ -0,0 +1,637 @@
|
||||
using System.Text;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Pacing;
|
||||
|
||||
namespace Febe.Core.Collection.Search;
|
||||
|
||||
/// <summary>
|
||||
/// How one search step ended. <paramref name="Typed"/> is the text the answer belongs to (what Febe typed), never
|
||||
/// printed; <paramref name="Denial"/> is the Governor's refusal when there was one.
|
||||
/// </summary>
|
||||
public sealed record SearchStepResult(SearchOutcome Outcome, string Typed, string? Message, SearchAnswer? Answer = null, Permit? Denial = null)
|
||||
{
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Outcome = {Outcome}, TypedLength = {Typed.Length}, Hits = {Answer?.Hits.Count}, Denial = {Denial?.Reason}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The browser half of the profile search (issue #37): one step on the site's own search box.</summary>
|
||||
public interface IProfileSearchRunner
|
||||
{
|
||||
/// <summary>Why the search cannot run on this site (missing targets or reader), in Italian; null when it can.</summary>
|
||||
string? NotConfiguredReason { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Types the wanted text into the site's search box and reads the answer. <paramref name="wanted"/> gives the
|
||||
/// current wanted text (already normalized and typable), or null when it is not wanted any more: the step stops
|
||||
/// between two keys. Every gesture follows a permit of the Governor.
|
||||
/// </summary>
|
||||
Task<SearchStepResult> SearchAsync(Func<string?> wanted, CancellationToken ct);
|
||||
|
||||
/// <summary>Waits, briefly, for the page to be quiet before it goes back to the engine.</summary>
|
||||
Task SettleAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>The rest page (spec §6.1), unless the breaker says to leave the page as it is.</summary>
|
||||
Task RestAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>A multiplier of the waits (mood × ritmo).</summary>
|
||||
double WaitMultiplier { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One search step on the site (issue #37, design §1.5.3): be on the site (home, under a permit), focus the box
|
||||
/// (open the panel, click the box, End), type in bursts (one permit each) with the closed key map, then take the
|
||||
/// answer to the request the page started last after the last key. It never clicks a result and never presses Enter.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The answers have no echo of the text (cleaned sample 000002): while Febe types, the page may ask for the texts
|
||||
/// before the last key, and their answers may arrive after the right one. So Febe notes where the page's requests
|
||||
/// stand right before every key it sends (<see cref="CaptureCollector.SearchMark"/>), and only an answer to a request
|
||||
/// started after the last key belongs to the text in the box. A page that answers a text again from its own memory
|
||||
/// sends no request: the answer Febe read for that text on the same page is used.
|
||||
/// </remarks>
|
||||
public sealed class ProfileSearchRunner : IProfileSearchRunner
|
||||
{
|
||||
private readonly IPageDriver _driver;
|
||||
private readonly ISearchInput _input;
|
||||
private readonly CaptureCollector _capture;
|
||||
private readonly SiteMap _siteMap;
|
||||
private readonly IGovernor _governor;
|
||||
private readonly IStopSignals _signals;
|
||||
private readonly ICircuitBreaker _breaker;
|
||||
private readonly IClock _clock;
|
||||
private readonly IRandomSource _random;
|
||||
private readonly PageTurns _turns;
|
||||
private readonly ProfileSearchOptions _options;
|
||||
private readonly Func<bool> _userIsDriving;
|
||||
private readonly CollectionDiagnostics? _diagnostics;
|
||||
|
||||
/// <summary>Most answers remembered for one page (see <see cref="_pageAnswers"/>).</summary>
|
||||
private const int MaxPageAnswers = 40;
|
||||
|
||||
/// <summary>What Febe typed into the box on the page of <see cref="_typedGeneration"/> (its own record; never logged).</summary>
|
||||
private string _typed = string.Empty;
|
||||
|
||||
/// <summary>The page (<see cref="PageTurns.Generation"/>) that <see cref="_typed"/>, <see cref="_keyMark"/> and <see cref="_pageAnswers"/> belong to.</summary>
|
||||
private long _typedGeneration = -1;
|
||||
|
||||
/// <summary>Where the page's requests stood right before the last key Febe sent on this page.</summary>
|
||||
private SearchAnswerMark? _keyMark;
|
||||
|
||||
/// <summary>The answers read on this page, by text: the page answers a text again from its memory, without a request.</summary>
|
||||
private readonly Dictionary<string, SearchAnswer> _pageAnswers = new(StringComparer.Ordinal);
|
||||
|
||||
public ProfileSearchRunner(
|
||||
IPageDriver driver,
|
||||
ISearchInput input,
|
||||
CaptureCollector capture,
|
||||
SiteMap siteMap,
|
||||
IGovernor governor,
|
||||
IStopSignals signals,
|
||||
ICircuitBreaker breaker,
|
||||
IClock clock,
|
||||
IRandomSource random,
|
||||
PageTurns turns,
|
||||
ProfileSearchOptions? options = null,
|
||||
Func<bool>? userIsDriving = null,
|
||||
CollectionDiagnostics? diagnostics = null)
|
||||
{
|
||||
_driver = driver ?? throw new ArgumentNullException(nameof(driver));
|
||||
_input = input ?? throw new ArgumentNullException(nameof(input));
|
||||
_capture = capture ?? throw new ArgumentNullException(nameof(capture));
|
||||
_siteMap = siteMap ?? throw new ArgumentNullException(nameof(siteMap));
|
||||
_governor = governor ?? throw new ArgumentNullException(nameof(governor));
|
||||
_signals = signals ?? throw new ArgumentNullException(nameof(signals));
|
||||
_breaker = breaker ?? throw new ArgumentNullException(nameof(breaker));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_random = random ?? throw new ArgumentNullException(nameof(random));
|
||||
_turns = turns ?? throw new ArgumentNullException(nameof(turns));
|
||||
_options = options ?? ProfileSearchOptions.Default;
|
||||
_userIsDriving = userIsDriving ?? (() => false);
|
||||
_diagnostics = diagnostics;
|
||||
}
|
||||
|
||||
public double WaitMultiplier => _driver.WaitMultiplier;
|
||||
|
||||
public string? NotConfiguredReason
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!_siteMap.HasPage(SitePages.Home) || !_siteMap.IsTargetConfigured(SiteTargets.SearchOpen) || !_siteMap.IsTargetConfigured(SiteTargets.SearchBox))
|
||||
{
|
||||
return "Febe non sa ancora dove sta «Cerca» su questo sito: per ora vedi solo i profili che segui.";
|
||||
}
|
||||
|
||||
return _capture.Reader.Vocabulary.Search.IsSet
|
||||
? null
|
||||
: "Febe non sa ancora leggere le risposte della ricerca di questo sito: per ora vedi solo i profili che segui.";
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<SearchStepResult> SearchAsync(Func<string?> wanted, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(wanted);
|
||||
if (wanted() is not { } first)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.Interrupted, string.Empty, null);
|
||||
}
|
||||
|
||||
if (NotConfiguredReason is { } reason)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.NotConfigured, first, reason);
|
||||
}
|
||||
|
||||
if (Stop(first) is { } stop)
|
||||
{
|
||||
return stop;
|
||||
}
|
||||
|
||||
// 1. Be on the site: outside a session the page is the rest page.
|
||||
if (!await _driver.IsOnSiteAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
var home = await OpenHomeAsync(first, ct).ConfigureAwait(false);
|
||||
if (home is not null)
|
||||
{
|
||||
return home;
|
||||
}
|
||||
}
|
||||
else if (_turns.Generation != _typedGeneration)
|
||||
{
|
||||
// A page was opened since (by the engine, between two steps): Febe's record of the box no longer holds.
|
||||
ForgetPage();
|
||||
}
|
||||
|
||||
// 2. Focus the box.
|
||||
var focus = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
if (!focus.Ready)
|
||||
{
|
||||
var focused = await FocusBoxAsync(first, focus, ct).ConfigureAwait(false);
|
||||
if (focused.Result is not null)
|
||||
{
|
||||
return focused.Result;
|
||||
}
|
||||
|
||||
focus = focused.Focus;
|
||||
}
|
||||
|
||||
// 3. Bursts of keys, then the answer.
|
||||
var passes = 0;
|
||||
while (true)
|
||||
{
|
||||
var text = wanted();
|
||||
if (text is null)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.Interrupted, _typed, null);
|
||||
}
|
||||
|
||||
if (Stop(text) is { } stopped)
|
||||
{
|
||||
return stopped;
|
||||
}
|
||||
|
||||
if (focus.Length != _typed.Length)
|
||||
{
|
||||
// The site restored a text, or Alberto typed in the box: Febe's record is reset and the box erased.
|
||||
if (++passes > 3)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.FocusLost, text, "Febe non riesce a scrivere nella casella «Cerca»: riprova fra poco.");
|
||||
}
|
||||
|
||||
var unknown = focus.Length ?? 0;
|
||||
var cleared = await BurstAsync(text, unknown, wanted, ct).ConfigureAwait(false);
|
||||
if (cleared.Result is not null)
|
||||
{
|
||||
return cleared.Result;
|
||||
}
|
||||
|
||||
focus = cleared.Focus;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!string.Equals(_typed, text, StringComparison.Ordinal))
|
||||
{
|
||||
var prefix = CommonPrefix(_typed, text);
|
||||
var burst = await BurstAsync(text, _typed.Length - prefix, wanted, ct).ConfigureAwait(false);
|
||||
if (burst.Result is not null)
|
||||
{
|
||||
return burst.Result;
|
||||
}
|
||||
|
||||
focus = burst.Focus;
|
||||
continue;
|
||||
}
|
||||
|
||||
// The box holds the wanted text: read the answer.
|
||||
var answer = await ReadAnswerAsync(text, wanted, ct).ConfigureAwait(false);
|
||||
if (answer is not null)
|
||||
{
|
||||
return answer;
|
||||
}
|
||||
|
||||
// The text changed before any answer came: next burst.
|
||||
focus = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
if (!focus.Ready)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.FocusLost, text, "La casella «Cerca» di Instagram non è più attiva: riprova.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Task SettleAsync(CancellationToken ct) =>
|
||||
_capture.SettleAsync(Scaled(_options.Quiet), _options.ReleaseSettle, _options.Poll, ct);
|
||||
|
||||
public async Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
ForgetPage();
|
||||
if (_breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected)
|
||||
{
|
||||
// Left as it is, so that Alberto sees what happened (spec §7.6).
|
||||
return;
|
||||
}
|
||||
|
||||
await _driver.RestAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<SearchStepResult?> OpenHomeAsync(string text, CancellationToken ct)
|
||||
{
|
||||
if (_userIsDriving())
|
||||
{
|
||||
return NotPossible(text);
|
||||
}
|
||||
|
||||
if (await _driver.HasSessionCookieAsync(ct).ConfigureAwait(false) is false)
|
||||
{
|
||||
// The same stop path as the recipes: a missing session cookie is a disconnection (§7.6).
|
||||
_signals.ObserveSessionCookie(false);
|
||||
return new SearchStepResult(SearchOutcome.NotConnected, text, "Instagram ha chiuso la sessione di Febe: riconnetti il browser per cercare.");
|
||||
}
|
||||
|
||||
if (await PermitAsync(ct).ConfigureAwait(false) is { } denied)
|
||||
{
|
||||
return Denied(text, denied);
|
||||
}
|
||||
|
||||
if (_userIsDriving())
|
||||
{
|
||||
return NotPossible(text);
|
||||
}
|
||||
|
||||
PageLoad load;
|
||||
try
|
||||
{
|
||||
load = await _driver.OpenAsync(_siteMap.BuildPath(SitePages.Home), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_diagnostics?.PageOpened(null, SitePages.Home, ok: false);
|
||||
throw;
|
||||
}
|
||||
|
||||
_turns.NoteOpened(PageUser.Search);
|
||||
ForgetPage();
|
||||
_diagnostics?.PageOpened(null, SitePages.Home, load.Succeeded);
|
||||
if (!load.Succeeded)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.PageNotLoaded, text, "La pagina di Instagram non si è caricata: la ricerca riprova al prossimo testo.");
|
||||
}
|
||||
|
||||
if (Stop(text) is { } stop)
|
||||
{
|
||||
return stop;
|
||||
}
|
||||
|
||||
if (!await _driver.IsOnSiteAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.PageNotLoaded, text, "Instagram ha portato il browser fuori dal sito: la ricerca si ferma.");
|
||||
}
|
||||
|
||||
await _driver.WaitAfterLoadAsync(ct).ConfigureAwait(false);
|
||||
return Stop(text);
|
||||
}
|
||||
|
||||
private async Task<(SearchStepResult? Result, SearchFocus Focus)> FocusBoxAsync(string text, SearchFocus focus, CancellationToken ct)
|
||||
{
|
||||
if (await PermitAsync(ct).ConfigureAwait(false) is { } denied)
|
||||
{
|
||||
return (Denied(text, denied), focus);
|
||||
}
|
||||
|
||||
if (!focus.BoxFound)
|
||||
{
|
||||
var open = await ClickAsync(SiteTargets.SearchOpen, ct).ConfigureAwait(false);
|
||||
if (!open.Found && open.Status != TargetCheckStatus.NotConfigured)
|
||||
{
|
||||
// One recovery: the page may be a viewer or a list left by a recipe.
|
||||
if (_userIsDriving())
|
||||
{
|
||||
return (NotPossible(text), focus);
|
||||
}
|
||||
|
||||
if (await PermitAsync(ct).ConfigureAwait(false) is { } again)
|
||||
{
|
||||
return (Denied(text, again), focus);
|
||||
}
|
||||
|
||||
if (await OpenHomeAfterPermitAsync(text, ct).ConfigureAwait(false) is { } failed)
|
||||
{
|
||||
return (failed, focus);
|
||||
}
|
||||
|
||||
open = await ClickAsync(SiteTargets.SearchOpen, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!open.Found)
|
||||
{
|
||||
return (new SearchStepResult(SearchOutcome.TargetMissing, text, "Febe non trova «Cerca» sulla pagina di Instagram."), focus);
|
||||
}
|
||||
|
||||
_turns.NoteSearchUsedPage();
|
||||
await _driver.WaitAsync(Scaled(_random.Between(_options.PanelWaitMin, _options.PanelWaitMax)), ct).ConfigureAwait(false);
|
||||
if (Stop(text) is { } stop)
|
||||
{
|
||||
return (stop, focus);
|
||||
}
|
||||
}
|
||||
|
||||
var box = await ClickAsync(SiteTargets.SearchBox, ct).ConfigureAwait(false);
|
||||
if (!box.Found)
|
||||
{
|
||||
return (new SearchStepResult(SearchOutcome.TargetMissing, text, "Febe non trova la casella «Cerca» sulla pagina di Instagram."), focus);
|
||||
}
|
||||
|
||||
_turns.NoteSearchUsedPage();
|
||||
|
||||
// The click may put the caret anywhere in a text already there.
|
||||
await _input.EndKeyAsync(ct).ConfigureAwait(false);
|
||||
focus = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
return focus.Ready
|
||||
? (null, focus)
|
||||
: (new SearchStepResult(SearchOutcome.FocusLost, text, "La casella «Cerca» di Instagram non ha preso il cursore: Febe non scrive."), focus);
|
||||
}
|
||||
|
||||
private async Task<SearchStepResult?> OpenHomeAfterPermitAsync(string text, CancellationToken ct)
|
||||
{
|
||||
var load = await _driver.OpenAsync(_siteMap.BuildPath(SitePages.Home), ct).ConfigureAwait(false);
|
||||
_turns.NoteOpened(PageUser.Search);
|
||||
ForgetPage();
|
||||
_diagnostics?.PageOpened(null, SitePages.Home, load.Succeeded);
|
||||
if (!load.Succeeded)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.PageNotLoaded, text, "La pagina di Instagram non si è caricata: la ricerca riprova al prossimo testo.");
|
||||
}
|
||||
|
||||
await _driver.WaitAfterLoadAsync(ct).ConfigureAwait(false);
|
||||
return Stop(text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One burst under one permit: <paramref name="erase"/> Backspaces, then the letters of the wanted text while it
|
||||
/// keeps extending what is typed, at most <see cref="ProfileSearchOptions.KeysPerPermit"/> keys.
|
||||
/// </summary>
|
||||
private async Task<(SearchStepResult? Result, SearchFocus Focus)> BurstAsync(string text, int erase, Func<string?> wanted, CancellationToken ct)
|
||||
{
|
||||
if (await PermitAsync(ct).ConfigureAwait(false) is { } denied)
|
||||
{
|
||||
return (Denied(text, denied), SearchFocus.None);
|
||||
}
|
||||
|
||||
// The permit may have waited (spacing, the gap from the engine): the focus is looked at again right before the
|
||||
// first key of the burst (§6.3).
|
||||
var before = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
if (!before.Ready)
|
||||
{
|
||||
return (FocusLost(text), before);
|
||||
}
|
||||
|
||||
var keys = 0;
|
||||
if (erase == 0 && before.Length != _typed.Length)
|
||||
{
|
||||
// The box changed meanwhile: the caller erases it first.
|
||||
return (null, before);
|
||||
}
|
||||
|
||||
if (erase > 0)
|
||||
{
|
||||
var count = Math.Min(erase, _options.KeysPerPermit);
|
||||
await _input.EraseAsync(count, NoteKey, ct).ConfigureAwait(false);
|
||||
keys += count;
|
||||
var after = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
if (!after.Focused || after.Length is not { } length)
|
||||
{
|
||||
return (FocusLost(text), after);
|
||||
}
|
||||
|
||||
if (length == before.Length)
|
||||
{
|
||||
return (KeysNotReceived(text), after);
|
||||
}
|
||||
|
||||
if (before.Length == _typed.Length && length == _typed.Length - count)
|
||||
{
|
||||
_typed = _typed[..length];
|
||||
}
|
||||
else
|
||||
{
|
||||
// The box held a text Febe did not type: now it holds what is left of it, unknown.
|
||||
_typed = length == 0 ? string.Empty : _typed;
|
||||
if (length != 0)
|
||||
{
|
||||
return (null, after);
|
||||
}
|
||||
}
|
||||
|
||||
if (erase > count || keys >= _options.KeysPerPermit)
|
||||
{
|
||||
return (null, after);
|
||||
}
|
||||
}
|
||||
|
||||
var startLength = _typed.Length;
|
||||
var lost = false;
|
||||
var typed = await _input.TypeAsync(
|
||||
async (index, token) =>
|
||||
{
|
||||
var current = wanted();
|
||||
if (current is null || keys >= _options.KeysPerPermit || current.Length <= _typed.Length || !current.StartsWith(_typed, StringComparison.Ordinal))
|
||||
{
|
||||
// Not wanted any more, done, at the end of the burst, or an erase is needed: the burst ends.
|
||||
return null;
|
||||
}
|
||||
|
||||
if (index > 0 && index % _options.FocusCheckEvery == 0)
|
||||
{
|
||||
var check = await _input.FocusAsync(token).ConfigureAwait(false);
|
||||
if (!check.Ready || check.Length != _typed.Length)
|
||||
{
|
||||
lost = true;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
var c = current[_typed.Length];
|
||||
NoteKey();
|
||||
_typed += c;
|
||||
keys++;
|
||||
return c;
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
|
||||
var focus = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
if (typed > 0 && focus.Focused && focus.Length == startLength)
|
||||
{
|
||||
// Not one key reached the box (seen at the end or at a focus check in between).
|
||||
_typed = _typed[..startLength];
|
||||
return (KeysNotReceived(text), focus);
|
||||
}
|
||||
|
||||
if (lost || !focus.Focused || focus.Length is null)
|
||||
{
|
||||
return (FocusLost(text), focus);
|
||||
}
|
||||
|
||||
return (null, focus);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The answer to the text in the box: an answer to a request the page started after the last key, or, when the
|
||||
/// page sends no request for a text it already answered on this page, the answer Febe read then. Null when the text
|
||||
/// changed before any answer came.
|
||||
/// </summary>
|
||||
private async Task<SearchStepResult?> ReadAnswerAsync(string text, Func<string?> wanted, CancellationToken ct)
|
||||
{
|
||||
var mark = _keyMark ?? _capture.SearchMark();
|
||||
var start = _clock.Now;
|
||||
var least = start + Scaled(_options.MinAnswerWait);
|
||||
var deadline = start + _options.AnswerTimeout;
|
||||
var quiet = Scaled(_options.Quiet);
|
||||
while (true)
|
||||
{
|
||||
if (Stop(text) is { } stop)
|
||||
{
|
||||
return stop;
|
||||
}
|
||||
|
||||
var answers = _capture.SearchSince(mark);
|
||||
var now = _clock.Now;
|
||||
var current = wanted();
|
||||
if (!string.Equals(current, text, StringComparison.Ordinal))
|
||||
{
|
||||
// Alberto kept typing: an answer already here is for this text and is kept, otherwise the next burst
|
||||
// starts at once.
|
||||
return answers.Count > 0 ? Answered(text, answers) : null;
|
||||
}
|
||||
|
||||
var settled = _capture.Pending == 0 && (_capture.LastArrivalAt is not { } last || now - last >= quiet);
|
||||
if (answers.Count > 0 && (answers[^1].Response.RequestOrder > 0 || (now >= least && settled)))
|
||||
{
|
||||
// A request started after the last key is for this text: no need to wait more. Without the order of
|
||||
// the requests (an older browser event stream), the page must be quiet first.
|
||||
return Answered(text, answers);
|
||||
}
|
||||
|
||||
if (answers.Count == 0 && now >= least && settled && _pageAnswers.TryGetValue(text, out var remembered))
|
||||
{
|
||||
// The page answered this text from its memory: no request, the results Febe read before on this page.
|
||||
return Result(text, remembered);
|
||||
}
|
||||
|
||||
if (now >= deadline)
|
||||
{
|
||||
return answers.Count > 0
|
||||
? Answered(text, answers)
|
||||
: _pageAnswers.TryGetValue(text, out var late)
|
||||
? Result(text, late)
|
||||
: new SearchStepResult(SearchOutcome.NoAnswer, text, "Instagram non ha mandato risultati per questo testo: scrivi un'altra lettera o riprova.");
|
||||
}
|
||||
|
||||
await _clock.Delay(_options.Poll, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private SearchStepResult Answered(string text, IReadOnlyList<CapturedRead> answers)
|
||||
{
|
||||
// The answer to the request started last (SearchSince orders them): earlier ones may belong to a text the page
|
||||
// asked for while Febe was still typing.
|
||||
var answer = answers[^1].Result.Search!;
|
||||
if (!_pageAnswers.ContainsKey(text) && _pageAnswers.Count >= MaxPageAnswers)
|
||||
{
|
||||
_pageAnswers.Clear();
|
||||
}
|
||||
|
||||
_pageAnswers[text] = answer;
|
||||
return Result(text, answer);
|
||||
}
|
||||
|
||||
private static SearchStepResult Result(string text, SearchAnswer answer) =>
|
||||
answer.Hits.Count == 0
|
||||
? new SearchStepResult(SearchOutcome.Empty, text, "Nessun profilo trovato su Instagram.", answer)
|
||||
: new SearchStepResult(SearchOutcome.Ready, text, null, answer);
|
||||
|
||||
/// <summary>Right before a key: from here on, the page's requests are for the text with this key.</summary>
|
||||
private void NoteKey() => _keyMark = _capture.SearchMark();
|
||||
|
||||
/// <summary>A new page (opened, rested, or opened by the engine): nothing Febe knew of the box holds.</summary>
|
||||
private void ForgetPage()
|
||||
{
|
||||
_typed = string.Empty;
|
||||
_keyMark = null;
|
||||
_pageAnswers.Clear();
|
||||
_typedGeneration = _turns.Generation;
|
||||
}
|
||||
|
||||
private async Task<TargetCheck> ClickAsync(string target, CancellationToken ct)
|
||||
{
|
||||
var check = await _driver.ClickAsync(target, null, ct).ConfigureAwait(false);
|
||||
_diagnostics?.TargetClicked(null, target, check.Status);
|
||||
return check;
|
||||
}
|
||||
|
||||
/// <summary>A permit of the Governor for one search action; the refusal when denied.</summary>
|
||||
private async Task<Permit?> PermitAsync(CancellationToken ct)
|
||||
{
|
||||
var permit = await _governor.RequestAsync(ActionKind.ProfileSearch, null, ct).ConfigureAwait(false);
|
||||
return permit.Granted ? null : permit;
|
||||
}
|
||||
|
||||
private SearchStepResult? Stop(string text)
|
||||
{
|
||||
var state = _breaker.State;
|
||||
if (!state.AllowsSiteActions)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.Stopped, text, Governor.BreakerMessage(state, _clock.Now, _clock.LocalZone));
|
||||
}
|
||||
|
||||
return _userIsDriving() ? NotPossible(text) : null;
|
||||
}
|
||||
|
||||
private static SearchStepResult Denied(string text, Permit permit) => new(SearchOutcome.Denied, text, permit.Message, Denial: permit);
|
||||
|
||||
private static SearchStepResult NotPossible(string text) =>
|
||||
new(SearchOutcome.NotPossible, text, "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito.");
|
||||
|
||||
private static SearchStepResult FocusLost(string text) =>
|
||||
new(SearchOutcome.FocusLost, text, "La casella «Cerca» di Instagram non è più attiva: Febe smette di scrivere.");
|
||||
|
||||
private static SearchStepResult KeysNotReceived(string text) =>
|
||||
new(SearchOutcome.KeysNotReceived, text, "Il browser di Febe non riceve i tasti: la ricerca su Instagram non funziona su questo computer.");
|
||||
|
||||
private TimeSpan Scaled(TimeSpan value) => value * Math.Max(0.1, _driver.WaitMultiplier);
|
||||
|
||||
private static int CommonPrefix(string a, string b)
|
||||
{
|
||||
var n = Math.Min(a.Length, b.Length);
|
||||
var i = 0;
|
||||
while (i < n && a[i] == b[i])
|
||||
{
|
||||
i++;
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Collection.Search;
|
||||
|
||||
/// <summary>What the profile search is doing for the wanted text (issue #37). The interface shows it in Italian.</summary>
|
||||
public enum SearchState
|
||||
{
|
||||
/// <summary>Nothing wanted (empty box, dialog closed).</summary>
|
||||
Idle,
|
||||
|
||||
/// <summary>The text is not one Febe types on the site (several names, too short, other characters): local suggestions only.</summary>
|
||||
LocalOnly,
|
||||
|
||||
/// <summary>Waiting for the page: a collection step holds it, or the search spacing.</summary>
|
||||
Waiting,
|
||||
|
||||
/// <summary>Febe is typing on the site or waiting for its answer.</summary>
|
||||
Searching,
|
||||
|
||||
/// <summary>The site answered with profiles.</summary>
|
||||
Ready,
|
||||
|
||||
/// <summary>The site answered with no profile.</summary>
|
||||
Empty,
|
||||
|
||||
/// <summary>No answer of the site came for this text (it may have answered from its own memory).</summary>
|
||||
NoAnswer,
|
||||
|
||||
/// <summary>Alberto is using Febe's browser: the search on the site waits.</summary>
|
||||
NotPossible,
|
||||
|
||||
/// <summary>Outside the active window Febe does not open the site.</summary>
|
||||
OutsideWindow,
|
||||
|
||||
/// <summary>The breaker is open (spec §7.6), or the search's own budget is used up.</summary>
|
||||
Stopped,
|
||||
|
||||
/// <summary>The browser or the engine is not up.</summary>
|
||||
Unavailable,
|
||||
|
||||
/// <summary>The map of the site lacks the search targets, or the readers lack the search answer (H11).</summary>
|
||||
NotConfigured,
|
||||
|
||||
/// <summary>The text holds a character Febe never types (a control character).</summary>
|
||||
Refused,
|
||||
|
||||
/// <summary>A step went wrong; the next text tries again.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>Closed list of how one search step ended: diagnostics count these names, never a text (issue #37).</summary>
|
||||
public enum SearchOutcome
|
||||
{
|
||||
Ready,
|
||||
Empty,
|
||||
NoAnswer,
|
||||
Cached,
|
||||
Refused,
|
||||
Stopped,
|
||||
NotConfigured,
|
||||
NotConnected,
|
||||
OutsideWindow,
|
||||
TargetMissing,
|
||||
FocusLost,
|
||||
KeysNotReceived,
|
||||
PageNotLoaded,
|
||||
BrowserNotResponding,
|
||||
Interrupted,
|
||||
NotPossible,
|
||||
Denied,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One profile the search found or knows. Never printed with its values: the record prints only counts and flags.
|
||||
/// </summary>
|
||||
/// <param name="Position">Order in the site's answer, from 0.</param>
|
||||
/// <param name="InstagramId">The site's identifier of the profile.</param>
|
||||
/// <param name="Username">User name, lowercase.</param>
|
||||
/// <param name="DisplayName">Full name, when the site gives one.</param>
|
||||
/// <param name="IsVerified">Verified mark, when the site says.</param>
|
||||
/// <param name="PhotoKey">Key of the photo in Febe's memory cache (32 hex characters), when it is there.</param>
|
||||
/// <param name="PhotoReady">True once the photo is in the cache.</param>
|
||||
public sealed record SearchHit(int Position, string InstagramId, string Username, string? DisplayName, bool? IsVerified, string? PhotoKey, bool PhotoReady)
|
||||
{
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Position = {Position}, HasDisplayName = {DisplayName is not null}, IsVerified = {IsVerified}, PhotoReady = {PhotoReady}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the search shows now. <paramref name="Owner"/> is the random id of the window that wrote the text last;
|
||||
/// <paramref name="Text"/> is the text Febe typed (or would type), as the interface labels results «per "testo"».
|
||||
/// </summary>
|
||||
public sealed record SearchView(long Version, string Owner, string Text, SearchState State, string? Message, IReadOnlyList<SearchHit> Hits, DateTimeOffset? RetryAfter)
|
||||
{
|
||||
public static SearchView Initial { get; } = new(0, string.Empty, string.Empty, SearchState.Idle, null, [], null);
|
||||
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Version = {Version}, State = {State}, Hits = {Hits.Count}, TextLength = {Text.Length}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The profile search as the interface sees it (issue #37): one wanted text at a time (the last window that writes
|
||||
/// wins), the latest view for polling, and the photos of the results from Febe's memory.
|
||||
/// </summary>
|
||||
public interface IProfileSearch
|
||||
{
|
||||
/// <summary>Sets the wanted text of window <paramref name="client"/> and returns at once.</summary>
|
||||
SearchView Update(string client, string text);
|
||||
|
||||
/// <summary>The latest view.</summary>
|
||||
SearchView Current { get; }
|
||||
|
||||
/// <summary>The dialog of window <paramref name="client"/> closed; ignored when another window wrote last.</summary>
|
||||
void End(string client);
|
||||
|
||||
/// <summary>The last result seen with this user name (for adding it with its identifier), server side only.</summary>
|
||||
SearchHit? Known(string username);
|
||||
|
||||
/// <summary>A photo of the memory cache by its key.</summary>
|
||||
bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Cryptography;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Collection.Search;
|
||||
|
||||
/// <summary>
|
||||
/// The photos of the search results, in memory only (issue #37): no file on disk reveals whom Alberto searched for and
|
||||
/// nothing survives a restart. Bounded by count and bytes (least recently used goes first), entries expire, and every
|
||||
/// photo has a random key of 32 hex characters that says nothing about the profile.
|
||||
/// </summary>
|
||||
/// <remarks>Not the library: rule 11 (the library never deletes files by itself) is not touched.</remarks>
|
||||
public sealed class SearchPhotoCache
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly IClock _clock;
|
||||
private readonly ProfileSearchOptions _options;
|
||||
private readonly Dictionary<string, LinkedListNode<Entry>> _byKey = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, LinkedListNode<Entry>> _byProfile = new(StringComparer.Ordinal);
|
||||
private readonly LinkedList<Entry> _lru = new();
|
||||
private long _bytes;
|
||||
|
||||
public SearchPhotoCache(IClock clock, ProfileSearchOptions? options = null)
|
||||
{
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_options = options ?? ProfileSearchOptions.Default;
|
||||
}
|
||||
|
||||
/// <summary>Photos in memory.</summary>
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _byKey.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Bytes in memory.</summary>
|
||||
public long Bytes
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A short hash of the file name of a photo address (the signature in the query is left out).</summary>
|
||||
public static string FileHash(Uri address)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(address);
|
||||
var name = address.AbsolutePath;
|
||||
var slash = name.LastIndexOf('/');
|
||||
name = slash >= 0 ? name[(slash + 1)..] : name;
|
||||
return Convert.ToHexStringLower(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(name)))[..16];
|
||||
}
|
||||
|
||||
/// <summary>The key of the photo of this profile, when it is in memory (any picture).</summary>
|
||||
public string? KeyOf(string instagramId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(instagramId);
|
||||
lock (_gate)
|
||||
{
|
||||
DropExpiredLocked();
|
||||
return _byProfile.TryGetValue(instagramId, out var node) ? node.Value.Key : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when this very picture (same file name) of the profile is already in memory.</summary>
|
||||
public bool Has(string instagramId, string fileHash)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
DropExpiredLocked();
|
||||
return _byProfile.TryGetValue(instagramId, out var node) && node.Value.FileHash == fileHash;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Keeps a photo (already a small JPEG); a new picture of the same profile replaces the old one.</summary>
|
||||
/// <returns>The key of the photo.</returns>
|
||||
public string Put(string instagramId, string fileHash, byte[] jpeg)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(instagramId);
|
||||
ArgumentNullException.ThrowIfNull(fileHash);
|
||||
ArgumentNullException.ThrowIfNull(jpeg);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_byProfile.TryGetValue(instagramId, out var old))
|
||||
{
|
||||
RemoveLocked(old);
|
||||
}
|
||||
|
||||
var key = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16));
|
||||
var node = _lru.AddFirst(new Entry(key, instagramId, fileHash, jpeg, _clock.Now));
|
||||
_byKey[key] = node;
|
||||
_byProfile[instagramId] = node;
|
||||
_bytes += jpeg.Length;
|
||||
while ((_byKey.Count > _options.MaxPhotos || _bytes > _options.MaxPhotoBytes) && _lru.Last is { } last && !ReferenceEquals(last, node))
|
||||
{
|
||||
RemoveLocked(last);
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A photo by its key, as a read-only stream.</summary>
|
||||
public bool TryOpen(string key, [NotNullWhen(true)] out Stream? stream)
|
||||
{
|
||||
stream = null;
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
DropExpiredLocked();
|
||||
if (!_byKey.TryGetValue(key, out var node))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_lru.Remove(node);
|
||||
_lru.AddFirst(node);
|
||||
stream = new MemoryStream(node.Value.Jpeg, writable: false);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forgets every photo (disconnection, «Scollega», the dialog forgotten).</summary>
|
||||
public void Clear()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_byKey.Clear();
|
||||
_byProfile.Clear();
|
||||
_lru.Clear();
|
||||
_bytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void DropExpiredLocked()
|
||||
{
|
||||
var limit = _clock.Now - _options.PhotoLifetime;
|
||||
var node = _lru.Last;
|
||||
while (node is not null)
|
||||
{
|
||||
var previous = node.Previous;
|
||||
if (node.Value.At < limit)
|
||||
{
|
||||
RemoveLocked(node);
|
||||
}
|
||||
|
||||
node = previous;
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveLocked(LinkedListNode<Entry> node)
|
||||
{
|
||||
_lru.Remove(node);
|
||||
_byKey.Remove(node.Value.Key);
|
||||
if (_byProfile.TryGetValue(node.Value.InstagramId, out var current) && ReferenceEquals(current, node))
|
||||
{
|
||||
_byProfile.Remove(node.Value.InstagramId);
|
||||
}
|
||||
|
||||
_bytes -= node.Value.Jpeg.Length;
|
||||
}
|
||||
|
||||
private sealed record Entry(string Key, string InstagramId, string FileHash, byte[] Jpeg, DateTimeOffset At)
|
||||
{
|
||||
private bool PrintMembers(System.Text.StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Bytes = {Jpeg.Length}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Pacing;
|
||||
|
||||
namespace Febe.Core.Collection.Search;
|
||||
|
||||
/// <summary>A photo to fetch: the profile and its picture (the signed address stays in memory, never logged).</summary>
|
||||
public sealed record SearchPhotoRequest(string InstagramId, Uri Address)
|
||||
{
|
||||
private bool PrintMembers(System.Text.StringBuilder builder)
|
||||
{
|
||||
builder.Append("Photo");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fetches the photos of the search results (issue #37, design §3) from the CDN through the browser's file fetcher,
|
||||
/// two at a time with small random pauses, and keeps them small in <see cref="SearchPhotoCache"/>. Each photo asks the
|
||||
/// Governor for a <see cref="ActionKind.DataDownload"/> permit and counts its bytes in the daily data budget; a CDN
|
||||
/// status that is a stop signal (§7.6) goes to the signal detector, as the download queue does, and empties the queue.
|
||||
/// It works only while the breaker allows site actions and the page is on the site.
|
||||
/// </summary>
|
||||
public sealed class SearchPhotoQueue : IAsyncDisposable
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly SearchPhotoCache _cache;
|
||||
private readonly IFileFetcher _fetcher;
|
||||
private readonly IGovernor _governor;
|
||||
private readonly IDataBudget _budget;
|
||||
private readonly ICircuitBreaker _breaker;
|
||||
private readonly SignalDetector? _signals;
|
||||
private readonly IClock _clock;
|
||||
private readonly IRandomSource _random;
|
||||
private readonly ProfileSearchOptions _options;
|
||||
private readonly Func<bool> _onSite;
|
||||
private readonly LinkedList<(SearchPhotoRequest Request, DateTimeOffset At)> _queue = new();
|
||||
private readonly HashSet<string> _queued = new(StringComparer.Ordinal);
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly List<Task> _workers = [];
|
||||
private int _running;
|
||||
private long _generation;
|
||||
|
||||
public SearchPhotoQueue(
|
||||
SearchPhotoCache cache,
|
||||
IFileFetcher fetcher,
|
||||
IGovernor governor,
|
||||
IDataBudget budget,
|
||||
ICircuitBreaker breaker,
|
||||
IClock clock,
|
||||
IRandomSource random,
|
||||
ProfileSearchOptions? options = null,
|
||||
SignalDetector? signals = null,
|
||||
Func<bool>? onSite = null)
|
||||
{
|
||||
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
|
||||
_fetcher = fetcher ?? throw new ArgumentNullException(nameof(fetcher));
|
||||
_governor = governor ?? throw new ArgumentNullException(nameof(governor));
|
||||
_budget = budget ?? throw new ArgumentNullException(nameof(budget));
|
||||
_breaker = breaker ?? throw new ArgumentNullException(nameof(breaker));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_random = random ?? throw new ArgumentNullException(nameof(random));
|
||||
_options = options ?? ProfileSearchOptions.Default;
|
||||
_signals = signals;
|
||||
_onSite = onSite ?? (() => true);
|
||||
}
|
||||
|
||||
/// <summary>A photo landed in the cache: the profile and the key.</summary>
|
||||
public event Action<string, string>? PhotoReady;
|
||||
|
||||
/// <summary>What happened to a photo («scaricata», «rifiutata», «saltata»): for the diagnostic report.</summary>
|
||||
public event Action<string>? Settled;
|
||||
|
||||
/// <summary>The recorder of the diagnostic report. Null: nothing is recorded.</summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
|
||||
/// <summary>Photos waiting.</summary>
|
||||
public int Waiting
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _queue.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Adds the photos of an answer; those already in memory with the same file name are skipped.</summary>
|
||||
public void Enqueue(IEnumerable<SearchPhotoRequest> photos)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(photos);
|
||||
var now = _clock.Now;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_lifetime.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var photo in photos)
|
||||
{
|
||||
if (_cache.Has(photo.InstagramId, SearchPhotoCache.FileHash(photo.Address)) || !_queued.Add(photo.InstagramId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_queue.AddLast((photo, now));
|
||||
}
|
||||
|
||||
while (_running < _options.PhotoConcurrency && _queue.Count > _running)
|
||||
{
|
||||
_running++;
|
||||
_workers.RemoveAll(t => t.IsCompleted);
|
||||
_workers.Add(Task.Run(() => WorkAsync(_lifetime.Token)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drops every photo waiting (rest page, stop signal, «Scollega»); one being fetched is not kept.</summary>
|
||||
public void Clear()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_queue.Clear();
|
||||
_queued.Clear();
|
||||
_generation++;
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Task[] workers;
|
||||
lock (_gate)
|
||||
{
|
||||
_queue.Clear();
|
||||
_queued.Clear();
|
||||
workers = [.. _workers];
|
||||
}
|
||||
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(workers).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Stopping.
|
||||
}
|
||||
|
||||
_lifetime.Dispose();
|
||||
}
|
||||
|
||||
private async Task WorkAsync(CancellationToken ct)
|
||||
{
|
||||
var counted = true;
|
||||
try
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
SearchPhotoRequest request;
|
||||
long generation;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_queue.First is not { } first)
|
||||
{
|
||||
_running--;
|
||||
counted = false;
|
||||
return;
|
||||
}
|
||||
|
||||
_queue.RemoveFirst();
|
||||
request = first.Value.Request;
|
||||
generation = _generation;
|
||||
if (_clock.Now - first.Value.At > _options.PhotoAddressLifetime)
|
||||
{
|
||||
_queued.Remove(request.InstagramId);
|
||||
Report("saltata");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await FetchAsync(request, generation, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// An optional photo: the initials stay. Only the type would be worth noting, and it is not text.
|
||||
Report("rifiutata");
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_queued.Remove(request.InstagramId);
|
||||
}
|
||||
}
|
||||
|
||||
await _clock.Delay(_random.Between(_options.PhotoPauseMin, _options.PhotoPauseMax), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
// Stopping.
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (counted)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_running = Math.Max(0, _running - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FetchAsync(SearchPhotoRequest request, long generation, CancellationToken ct)
|
||||
{
|
||||
if (!_breaker.State.AllowsSiteActions || !_onSite())
|
||||
{
|
||||
Clear();
|
||||
Report("saltata");
|
||||
return;
|
||||
}
|
||||
|
||||
var permit = await _governor.RequestAsync(ActionKind.DataDownload, null, ct).ConfigureAwait(false);
|
||||
if (!permit.Granted)
|
||||
{
|
||||
// The daily data budget is used up: the initials stay.
|
||||
Clear();
|
||||
Report("saltata");
|
||||
return;
|
||||
}
|
||||
|
||||
using var buffer = new MemoryStream();
|
||||
var result = await _fetcher.FetchAsync(request.Address, buffer, new FetchOptions(MaxBytes: _options.PhotoMaxDownload), ct).ConfigureAwait(false);
|
||||
if (result.BudgetBytes > 0)
|
||||
{
|
||||
await _budget.RecordAsync(result.BudgetBytes, null, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
if (result.HttpStatus is { } status && _signals?.ObserveDownload(request.Address, status) is not null)
|
||||
{
|
||||
// A stop signal of the CDN (e.g. 429): no more photos.
|
||||
Clear();
|
||||
}
|
||||
|
||||
Report("rifiutata");
|
||||
return;
|
||||
}
|
||||
|
||||
buffer.Position = 0;
|
||||
var jpeg = ThumbnailStore.EncodeSmallJpeg(buffer, _options.PhotoLongSide);
|
||||
if (jpeg is null)
|
||||
{
|
||||
Report("rifiutata");
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (generation != _generation)
|
||||
{
|
||||
// Cleared meanwhile (rest page, stop): the photo is not kept.
|
||||
Report("saltata");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var key = _cache.Put(request.InstagramId, SearchPhotoCache.FileHash(request.Address), jpeg);
|
||||
Report("scaricata");
|
||||
PhotoReady?.Invoke(request.InstagramId, key);
|
||||
}
|
||||
|
||||
private void Report(string outcome)
|
||||
{
|
||||
Diagnostics?.SearchPhotoSettled(outcome);
|
||||
Settled?.Invoke(outcome);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
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();
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Core.Collection.Privacy;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
@@ -31,10 +32,13 @@ public static class SitePages
|
||||
/// <summary>The same list resuming after {cursor} (optional).</summary>
|
||||
public const string FollowingFrom = "followingFrom";
|
||||
|
||||
/// <summary>Shape of the address of the story viewer: {username} and {id} of the story shown.</summary>
|
||||
/// <summary>Shape of the address of the story viewer: {username}, and {id} of the story shown when the address carries it.</summary>
|
||||
public const string StoryViewer = "storyViewer";
|
||||
|
||||
/// <summary>Shape of the address of the highlight viewer: {highlight} and {id} of the item shown.</summary>
|
||||
/// <summary>
|
||||
/// Shape of the address of the highlight viewer: {highlight}, and {id} of the item shown when the address carries it
|
||||
/// (Instagram's does not: «/stories/highlights/{highlight}/» stays the same from item to item).
|
||||
/// </summary>
|
||||
public const string HighlightViewer = "highlightViewer";
|
||||
|
||||
public static IReadOnlyList<string> All { get; } =
|
||||
@@ -68,8 +72,14 @@ public static class SiteTargets
|
||||
/// <summary>The command that closes the viewer.</summary>
|
||||
public const string ViewerClose = "viewer-close";
|
||||
|
||||
/// <summary>The command that opens the site's search panel («Cerca» in the side column; issue #37).</summary>
|
||||
public const string SearchOpen = "search-open";
|
||||
|
||||
/// <summary>The search box of that panel, where the profile search types (issue #37).</summary>
|
||||
public const string SearchBox = "search-box";
|
||||
|
||||
public static IReadOnlyList<string> All { get; } =
|
||||
[HomeStory, ProfileStoryRing, ProfileNotFound, ProfileTabPosts, ProfileTabReels, ProfileTabTagged, ProfileHighlight, ViewerNext, ViewerClose];
|
||||
[HomeStory, ProfileStoryRing, ProfileNotFound, ProfileTabPosts, ProfileTabReels, ProfileTabTagged, ProfileHighlight, ViewerNext, ViewerClose, SearchOpen, SearchBox];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -82,6 +92,11 @@ public sealed partial class SiteMap
|
||||
private readonly Dictionary<string, string> _pages;
|
||||
private readonly HashSet<string> _configuredTargets;
|
||||
private readonly HashSet<string> _knownTargets;
|
||||
private readonly IReadOnlyList<(string Name, Regex Shape)> _classifier;
|
||||
private readonly HashSet<string> _literals;
|
||||
|
||||
/// <summary>The fixed words and the placeholder names of the shipped maps (the only ones a report may show).</summary>
|
||||
private static readonly Lazy<(HashSet<string> Words, HashSet<string> Placeholders)> Shipped = new(LoadShippedWords);
|
||||
|
||||
public SiteMap(string site, IReadOnlyDictionary<string, string?> pages, IEnumerable<string> configuredTargets, IEnumerable<string> knownTargets, string? source = null)
|
||||
{
|
||||
@@ -90,6 +105,20 @@ public sealed partial class SiteMap
|
||||
_pages = pages.Where(p => !string.IsNullOrWhiteSpace(p.Value)).ToDictionary(p => p.Key, p => p.Value!.Trim(), StringComparer.Ordinal);
|
||||
_configuredTargets = new HashSet<string>(configuredTargets, StringComparer.Ordinal);
|
||||
_knownTargets = new HashSet<string>(knownTargets, StringComparer.Ordinal);
|
||||
|
||||
// More literal segments first (the highlight viewer before the story viewer, whose {username} would take
|
||||
// «highlights»), shapes without a query before the same shape with one, then the order of SitePages.All: a page
|
||||
// made only of placeholders (the profile, «/{username}/») comes after every page with a word of its own.
|
||||
_classifier = [.. _pages
|
||||
.Select(p => (Name: p.Key, Pattern: p.Value, Shape: p.Value.Split('?')[0]))
|
||||
.OrderByDescending(p => LiteralSegments(p.Shape))
|
||||
.ThenBy(p => p.Pattern.Contains('?', StringComparison.Ordinal) ? 1 : 0)
|
||||
.ThenBy(p => IndexOfPage(p.Name))
|
||||
.ThenBy(p => p.Name, StringComparer.Ordinal)
|
||||
.Select(p => (p.Name, new Regex(ShapeRegex(p.Shape, out _), RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(100))))];
|
||||
_literals = new HashSet<string>(
|
||||
_pages.Values.SelectMany(v => v.Split('?')[0].Split('/', StringSplitOptions.RemoveEmptyEntries)).Where(segment => !Placeholder().IsMatch(segment)),
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public string Site { get; }
|
||||
@@ -141,26 +170,8 @@ public sealed partial class SiteMap
|
||||
return null;
|
||||
}
|
||||
|
||||
var shape = pattern.Split('?')[0];
|
||||
var names = new List<string>();
|
||||
var regex = new StringBuilder("^");
|
||||
var last = 0;
|
||||
foreach (Match m in Placeholder().Matches(shape))
|
||||
{
|
||||
regex.Append(Regex.Escape(shape[last..m.Index]));
|
||||
regex.Append("([^/]+)");
|
||||
names.Add(m.Groups[1].Value);
|
||||
last = m.Index + m.Length;
|
||||
}
|
||||
|
||||
regex.Append(Regex.Escape(shape[last..]));
|
||||
if (!shape.EndsWith('/'))
|
||||
{
|
||||
regex.Append("/?");
|
||||
}
|
||||
|
||||
regex.Append('$');
|
||||
var match = Regex.Match(path, regex.ToString(), RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(100));
|
||||
var regex = ShapeRegex(pattern.Split('?')[0], out var names);
|
||||
var match = Regex.Match(path, regex, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(100));
|
||||
if (!match.Success)
|
||||
{
|
||||
return null;
|
||||
@@ -175,10 +186,79 @@ public sealed partial class SiteMap
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which page of the map an address path has the shape of, or null when none (data endpoints, pages the map does not
|
||||
/// know). Pages with more words of their own are tried first, so «/stories/highlights/1/» is the highlight viewer
|
||||
/// and not the story viewer of someone called «highlights»; the profile, made only of a placeholder, comes last.
|
||||
/// A placeholder never takes a fixed word of the site (<see cref="PathPatterns.IsKnownSegment"/>) or of a map:
|
||||
/// «/challenge/», «/explore/», «/reels/» are not profiles. Only the page NAME comes out: never the values (issue #39).
|
||||
/// </summary>
|
||||
public string? Classify(string? path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var (name, shape) in _classifier)
|
||||
{
|
||||
try
|
||||
{
|
||||
var match = shape.Match(path);
|
||||
if (match.Success && !TakesAWord(match))
|
||||
{
|
||||
return name;
|
||||
}
|
||||
}
|
||||
catch (RegexMatchTimeoutException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The shape of the address of page <paramref name="name"/> for a report: without its query, with its
|
||||
/// {placeholders} and no value (e.g. «/{username}/»); null when the page is not set. A map may come from Alberto's
|
||||
/// data folder, so the shape is reduced like any path: only the fixed words of the site and of the shipped maps
|
||||
/// and their placeholders stay, any other segment becomes {numero} or {testo} («/alberto.rossi/following/» written
|
||||
/// in place of «/{username}/following/» gives «/{testo}/following/»).
|
||||
/// </summary>
|
||||
public string? PatternOf(string name) =>
|
||||
_pages.TryGetValue(name, out var pattern) ? ReportShape(pattern.Split('?')[0]) : null;
|
||||
|
||||
/// <summary>A page shape reduced for a report (<see cref="PatternOf"/>).</summary>
|
||||
public static string ReportShape(string shape)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(shape);
|
||||
var (words, placeholders) = Shipped.Value;
|
||||
var segments = shape.Split('/');
|
||||
for (var i = 0; i < segments.Length; i++)
|
||||
{
|
||||
var segment = segments[i];
|
||||
if (segment.Length == 0 || PathPatterns.IsKnownSegment(segment) || words.Contains(segment))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var whole = Placeholder().Match(segment);
|
||||
if (whole.Success && whole.Length == segment.Length && placeholders.Contains(whole.Groups[1].Value))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
segments[i] = PathPatterns.Of("/" + segment)[1..];
|
||||
}
|
||||
|
||||
return string.Join('/', segments);
|
||||
}
|
||||
|
||||
/// <summary>The target map of the local test site (embedded <c>bersagli.prova.json</c>).</summary>
|
||||
public static SiteMap LoadTestSite() => LoadEmbedded("bersagli.prova.json");
|
||||
|
||||
/// <summary>The Instagram skeleton (embedded <c>bersagli.instagram.json</c>): every entry is still unset (H11).</summary>
|
||||
/// <summary>The Instagram map (embedded <c>bersagli.instagram.json</c>): the pages seen in real traffic, targets still unset (H11).</summary>
|
||||
public static SiteMap LoadInstagram() => LoadEmbedded("bersagli.instagram.json");
|
||||
|
||||
public static SiteMap LoadOrEmbedded(string? path, string embeddedName) =>
|
||||
@@ -258,6 +338,85 @@ public sealed partial class SiteMap
|
||||
}
|
||||
}
|
||||
|
||||
private static string ShapeRegex(string shape, out List<string> names)
|
||||
{
|
||||
names = [];
|
||||
var regex = new StringBuilder("^");
|
||||
var last = 0;
|
||||
foreach (Match m in Placeholder().Matches(shape))
|
||||
{
|
||||
regex.Append(Regex.Escape(shape[last..m.Index]));
|
||||
regex.Append("([^/]+)");
|
||||
names.Add(m.Groups[1].Value);
|
||||
last = m.Index + m.Length;
|
||||
}
|
||||
|
||||
regex.Append(Regex.Escape(shape[last..]));
|
||||
if (!shape.EndsWith('/'))
|
||||
{
|
||||
regex.Append("/?");
|
||||
}
|
||||
|
||||
regex.Append('$');
|
||||
return regex.ToString();
|
||||
}
|
||||
|
||||
/// <summary>True when a placeholder of the match took a fixed word of the site or of a map (not a value, so not this page).</summary>
|
||||
private bool TakesAWord(Match match)
|
||||
{
|
||||
var shippedWords = Shipped.Value.Words;
|
||||
for (var i = 1; i < match.Groups.Count; i++)
|
||||
{
|
||||
var value = match.Groups[i].Value;
|
||||
if (PathPatterns.IsKnownSegment(value) || PathPatterns.IsKnownSegment(value.ToLowerInvariant())
|
||||
|| _literals.Contains(value) || shippedWords.Contains(value))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static (HashSet<string> Words, HashSet<string> Placeholders) LoadShippedWords()
|
||||
{
|
||||
var words = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var placeholders = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var file in new[] { "bersagli.instagram.json", "bersagli.prova.json" })
|
||||
{
|
||||
foreach (var pattern in LoadEmbedded(file)._pages.Values)
|
||||
{
|
||||
// The names of the values the recipes fill in, in the path or in the query («{cursor}»).
|
||||
placeholders.UnionWith(Placeholder().Matches(pattern).Select(m => m.Groups[1].Value));
|
||||
foreach (var segment in pattern.Split('?')[0].Split('/', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (!Placeholder().IsMatch(segment))
|
||||
{
|
||||
words.Add(segment);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (words, placeholders);
|
||||
}
|
||||
|
||||
private static int LiteralSegments(string shape) =>
|
||||
shape.Split('/', StringSplitOptions.RemoveEmptyEntries).Count(segment => !Placeholder().IsMatch(segment));
|
||||
|
||||
private static int IndexOfPage(string name)
|
||||
{
|
||||
for (var i = 0; i < SitePages.All.Count; i++)
|
||||
{
|
||||
if (SitePages.All[i] == name)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return int.MaxValue;
|
||||
}
|
||||
|
||||
private static bool IsConfigured(JsonElement target)
|
||||
{
|
||||
foreach (var key in new[] { "role", "name", "href" })
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"note": "SCHELETRO della prima versione (specifica §6.3, ipotesi H11). Elenca solo le pagine e i bersagli di cui le ricette hanno bisogno, tutti VUOTI: si compilano con i campioni della sonda di M0 (docs/prove-dal-vivo.md, docs/sonda/esito.md). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.",
|
||||
"note": "Mappa di Instagram, aggiornata il 25 ottobre 2026 (specifica §6.3). PAGINE: compilate solo quelle che hanno una prova reale nel file HAR del browser di Alberto del 21 ottobre 2026, cioè i modelli di indirizzo che Instagram stesso manda al browser (/ajax/bulk-route-definitions/) e i percorsi del Referer delle richieste fatte dalla pagina: home, profile, post, storyViewer, highlightViewer. Restano vuote, senza prove: following e followingFrom (quindi «Elenco dei seguiti» non gira), profileFrom, reelsFrom e taggedFrom (facoltative). Le parti facoltative dei modelli di Instagram ({?tab}, {?initial_media_id}) non si scrivono: qui ogni segnaposto vale esattamente un segmento. BERSAGLI: tutti ancora VUOTI (ipotesi H11). Il HAR aveva solo risposte Fetch/XHR: nessun documento e nessun attributo degli elementi (ruoli, nomi accessibili, collegamenti). Si compilano con docs/prove-dal-vivo.md, parte A bis (tools/bersagli/raccogli-bersagli.js). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.",
|
||||
"pages": {
|
||||
"home": { "path": "", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti." },
|
||||
"profile": { "path": "", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}." },
|
||||
"profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Se resta vuota lo storico riprende scorrendo." },
|
||||
"reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel." },
|
||||
"taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati." },
|
||||
"post": { "path": "", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code}." },
|
||||
"following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}." },
|
||||
"followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa." },
|
||||
"storyViewer": { "path": "", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata." },
|
||||
"highlightViewer": { "path": "", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} e {id}." }
|
||||
"home": { "path": "/", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti. Prova: modello «/» (PolarisFeedRoute) nelle definizioni delle pagine. Che cosa arrivi caricandola (H1) non è nel HAR e resta da provare." },
|
||||
"profile": { "path": "/{username}/", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}. Prova: modello /{username}/{?tab}/{?view_type}/{?igshid}/ (PolarisProfilePostsTabRoute), senza le parti facoltative. I valori di {?tab} non si vedono nel campione." },
|
||||
"profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Nessuna prova di un indirizzo del genere: resta vuota e lo storico riprende scorrendo." },
|
||||
"reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel. Nessuna prova: la scheda non è nel campione." },
|
||||
"taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati. Nessuna prova: la scheda non è nel campione." },
|
||||
"post": { "path": "/p/{code}/", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code} (11 caratteri). Prova: il percorso /p/{code}/ nel Referer delle richieste della pagina di un post. Instagram usa anche /{username}/reel/{code}/ (modello /{username}/{permalink_key}/{shortcode}/): Febe apre la forma /p/." },
|
||||
"following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}. Nessuna prova nel campione: resta vuota e «Elenco dei seguiti» non gira finché non arriva (parte A bis)." },
|
||||
"followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa. Nessuna prova." },
|
||||
"storyViewer": { "path": "/stories/{username}/{id}/", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata. Prova: modello /stories/{username}/{?initial_media_id}/ (PolarisStoriesV3Route). DA CONFERMARE che l'indirizzo segua ogni storia (l'{id} cambia a ogni avanzamento) e che porti l'{id} fin dall'apertura: senza {id} questa forma non corrisponde e la ricetta si ferma dicendo che il visualizzatore non si è aperto. Anche /stories/highlights/<cifre>/ ha questa forma, con username «highlights»: per le Storie di un account è «un altro account» e il visualizzatore si chiude; la ricetta delle raccolte legge solo highlightViewer." },
|
||||
"highlightViewer": { "path": "/stories/highlights/{highlight}/", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} sono le 17 cifre dell'identificativo (nei dati «highlight:<cifre>», ridotto alle cifre dal lettore). Prova: il Referer delle richieste fatte guardando una raccolta e il modello /stories/highlights/{highlight_reel_id}/ (PolarisStoriesV3HighlightsRoute). Non c'è l'{id} del contenuto mostrato: l'indirizzo resta lo stesso mentre si guarda, quindi la posizione nella raccolta non si legge dall'indirizzo." }
|
||||
},
|
||||
"targets": {
|
||||
"home-story": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Voce della barra delle storie per un account ({username})." },
|
||||
@@ -22,6 +22,8 @@
|
||||
"profile-tab-tagged": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Scheda dei post in cui l'account è taggato." },
|
||||
"profile-highlight": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Una raccolta in evidenza ({id})." },
|
||||
"viewer-next": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Zona o comando per andare alla storia successiva." },
|
||||
"viewer-close": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Comando per chiudere il visualizzatore." }
|
||||
"viewer-close": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Comando per chiudere il visualizzatore." },
|
||||
"search-open": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Il comando «Cerca» della colonna laterale, che apre il pannello di ricerca (ricerca dei profili, issue #37)." },
|
||||
"search-box": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "La casella del pannello «Cerca», dove la ricerca dei profili scrive. Mai cliccare un risultato." }
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@
|
||||
"profile-tab-tagged": { "role": "tab", "name": "^taggati$" },
|
||||
"profile-highlight": { "role": "link", "href": "/evidenza/{id}/" },
|
||||
"viewer-next": { "role": "button", "name": "^storia successiva$" },
|
||||
"viewer-close": { "role": "button", "name": "^chiudi$" }
|
||||
"viewer-close": { "role": "button", "name": "^chiudi$" },
|
||||
"search-open": { "role": "button", "name": "^cerca$", "note": "Il comando «Cerca» della colonna laterale: apre il pannello di ricerca." },
|
||||
"search-box": { "role": "searchbox", "name": "^cerca$", "note": "La casella del pannello di ricerca, dove la ricerca dei profili scrive." }
|
||||
}
|
||||
}
|
||||
@@ -1,51 +1,68 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"status": "ipotesi",
|
||||
"note": "IPOTESI, DA CONFERMARE CON I CAMPIONI DI M0 (specifica §6.4, regola 10). Contiene solo gli indizi che la specifica stessa elenca in §6.4 (pk, code, taken_at, image_versions2.candidates, video_versions, carousel_media); ogni altro concetto è vuoto e si compila sui campioni ripuliti della sonda. Finché lo stato è «ipotesi» o manca un concetto necessario, le ricette si rifiutano di girare su Instagram.",
|
||||
"status": "confermato",
|
||||
"note": "Vocabolario dei lettori per Instagram, compilato il 25 ottobre 2026 sulle risposte reali che il browser di Alberto ha ricevuto il 21 ottobre (file HAR) e completato il 12 novembre con quelle del secondo HAR (scheda del profilo, post del profilo, raccolte del profilo, storie), ripulite con «febe-sonda ripulisci» e conservate in tests/Febe.Tests/campioni/instagram (regola 10). Ogni concetto dice da quali campioni viene; quelli senza riscontro restano vuoti o sono segnati come indizio. I dati di storie e raccolte arrivano come «text/javascript», non come JSON dichiarato: la cattura li legge lo stesso (DataResponses). «viewer»: xdt_viewer.user, visto in raccolta-in-evidenza, descrive l'account collegato con il solo identificativo, senza nome; nel blocco incorporato nella pagina iniziale (vassoio-storie, 12 novembre) ha anche username e profile_pic_url, e il lettore lo legge come Viewer (H10, da provare con la raccolta vera).",
|
||||
"content": {
|
||||
"note": "Indizi di §6.4: chiavi viste in passato, non uno schema. Ipotesi, da confermare con i campioni di M0.",
|
||||
"note": "Un contenuto (XDTMediaDict): post, reel, storia o contenuto di una raccolta. Visti in post-video (/api/v1/media/…/info/), raccolta-in-evidenza, raccolta-pagina-successiva, post-del-profilo (reel e serie) e storie-di-un-profilo. Le griglie delle schede Reel e Con tag (reel-del-profilo, con-tag) sono anteprime senza taken_at né video_versions: non sono contenuti, il contenuto intero arriva da post-del-profilo o da /api/v1/media/…/info/. «user» dei contenuti di una storia ha solo l'identificativo, senza nome: l'autore si eredita dalla raccolta o dalla serie di storie che li contiene. La didascalia è un oggetto con il testo in «text». Serie (carousel_media, media_type 8): i figli sono contenuti con le loro image_versions2 e video_versions, visti in post-del-profilo (6 foto) e serie-con-video (20 figli, uno video).",
|
||||
"id": ["pk"],
|
||||
"code": ["code"],
|
||||
"takenAt": ["taken_at"],
|
||||
"caption": [],
|
||||
"caption": ["caption.text"],
|
||||
"images": ["image_versions2.candidates"],
|
||||
"videos": ["video_versions"],
|
||||
"children": ["carousel_media"],
|
||||
"childCount": [],
|
||||
"owner": [],
|
||||
"childCount": ["carousel_media_count"],
|
||||
"owner": ["user", "owner"],
|
||||
"pinned": [],
|
||||
"expiresAt": [],
|
||||
"duration": []
|
||||
"expiresAt": ["expiring_at"],
|
||||
"duration": ["video_duration"]
|
||||
},
|
||||
"version": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H5).",
|
||||
"url": [],
|
||||
"width": [],
|
||||
"height": [],
|
||||
"note": "Una versione: candidates di image_versions2 (url, width, height, da 10 a 14 per contenuto) e video_versions (type 101, 102, 103 e url; dimensioni solo nei post, non nelle storie). Se il video ha l'audio lo dice il contenuto (has_audio), non la versione: hasAudio resta vuoto e ogni versione conta come file completo (H5 da confermare scaricando).",
|
||||
"url": ["url"],
|
||||
"width": ["width"],
|
||||
"height": ["height"],
|
||||
"hasAudio": []
|
||||
},
|
||||
"profile": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H10).",
|
||||
"id": [],
|
||||
"username": [],
|
||||
"displayName": [],
|
||||
"isPrivate": [],
|
||||
"isFollowed": [],
|
||||
"postCount": [],
|
||||
"picture": [],
|
||||
"latestStoryAt": []
|
||||
"note": "Un profilo (XDTUserDict): visto come autore di un post (user, owner), come proprietario di una raccolta, nella ricerca e nei profili suggeriti. friendship_status.following dice se Alberto lo segue; latest_reel_media è la data dell'ultima storia; media_count, il numero dei post, compare solo nella scheda del profilo (scheda-profilo, PolarisProfilePageContentQuery). Nel vassoio delle storie (vassoio-storie, incorporato nella pagina iniziale) ogni voce ha l'utente con nome e foto ma senza nome per esteso.",
|
||||
"id": ["pk", "id"],
|
||||
"username": ["username"],
|
||||
"displayName": ["full_name"],
|
||||
"isPrivate": ["is_private"],
|
||||
"isFollowed": ["friendship_status.following"],
|
||||
"postCount": ["media_count"],
|
||||
"picture": ["hd_profile_pic_url_info", "hd_profile_pic_versions", "profile_pic_url"],
|
||||
"latestStoryAt": ["latest_reel_media"]
|
||||
},
|
||||
"highlight": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H9).",
|
||||
"id": [],
|
||||
"title": [],
|
||||
"owner": [],
|
||||
"items": []
|
||||
"note": "Una raccolta in evidenza (XDTReelDict con reel_type highlight_reel): id «highlight:<numero>», title, user e i contenuti in items. Vista in raccolta-in-evidenza e raccolta-pagina-successiva. L'elenco delle raccolte di un profilo (raccolte-del-profilo, PolarisProfileStoryHighlightsTrayContentQuery) ha id, title, user e la copertina in cover_media.cropped_image_version, senza contenuti.",
|
||||
"id": ["id"],
|
||||
"title": ["title"],
|
||||
"owner": ["user"],
|
||||
"items": ["items"],
|
||||
"cover": ["cover_media.cropped_image_version"]
|
||||
},
|
||||
"page": {
|
||||
"note": "Da compilare con i campioni di M0 (H3).",
|
||||
"hasMore": [],
|
||||
"cursor": []
|
||||
"note": "page_info delle connessioni GraphQL (has_next_page, end_cursor) e more_available delle risposte REST. Visti in raccolta-in-evidenza e post-video.",
|
||||
"hasMore": ["has_next_page", "more_available"],
|
||||
"cursor": ["end_cursor"]
|
||||
},
|
||||
"viewer": []
|
||||
"search": {
|
||||
"note": "Risposta della casella di ricerca (PolarisSearchBoxRefetchableQuery, campione ricerca-profili): xdt_api__v1__fbsearch__topsearch_connection con users[] { position, user }. Niente is_private né friendship_status: «Privato» e «Seguito» vengono solo dai dati di Febe. Hashtag e luoghi si ignorano. Non si leggono mai search_social_context (nomi di chi segui in comune), rank_token, ai_agent_owner_username, attribution_label_text. La foto piccola viene prima: basta per un suggerimento.",
|
||||
"root": ["xdt_api__v1__fbsearch__topsearch_connection"],
|
||||
"items": ["users"],
|
||||
"position": ["position"],
|
||||
"profile": ["user"],
|
||||
"id": ["pk", "id"],
|
||||
"username": ["username"],
|
||||
"displayName": ["full_name"],
|
||||
"picture": ["profile_pic_url", "hd_profile_pic_url_info"],
|
||||
"verified": ["is_verified"]
|
||||
},
|
||||
"relevance": {
|
||||
"note": "Una risposta che non contiene nessuna di queste chiavi non parla di contenuti né di profili e si ignora: promozioni, registri, il segno «storia vista», le definizioni delle pagine. Senza questo elenco ognuna conterebbe come «formato non riconosciuto».",
|
||||
"keys": ["image_versions2", "video_versions", "carousel_media", "taken_at", "username"]
|
||||
},
|
||||
"viewer": ["xdt_viewer.user"]
|
||||
}
|
||||
@@ -44,5 +44,17 @@
|
||||
"hasMore": ["altro"],
|
||||
"cursor": ["dopo"]
|
||||
},
|
||||
"search": {
|
||||
"note": "La casella di ricerca del sito di prova risponde nella forma del campione ripulito di Instagram (ricerca-profili, PolarisSearchBoxRefetchableQuery), eccezione voluta alla regola «formato nostro, chiavi italiane» (tools/Febe.SitoDiProva/LEGGIMI.md): xdt_api__v1__fbsearch__topsearch_connection con users[] { position, user }. Niente is_private né friendship_status: «Privato» e «Seguito» vengono solo dai dati di Febe. Hashtag e luoghi si ignorano. Non si leggono mai search_social_context (nomi di chi segui in comune), rank_token, ai_agent_owner_username, attribution_label_text. La foto piccola viene prima: basta per un suggerimento.",
|
||||
"root": ["xdt_api__v1__fbsearch__topsearch_connection"],
|
||||
"items": ["users"],
|
||||
"position": ["position"],
|
||||
"profile": ["user"],
|
||||
"id": ["pk", "id"],
|
||||
"username": ["username"],
|
||||
"displayName": ["full_name"],
|
||||
"picture": ["profile_pic_url", "hd_profile_pic_url_info"],
|
||||
"verified": ["is_verified"]
|
||||
},
|
||||
"viewer": ["io"]
|
||||
}
|
||||
@@ -0,0 +1,750 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id qui: si legge dai moduli della pagina all'accesso (tappa S4). Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, lsd, fb_dtsg, app_id, claim, account_id, doc_id), operation, variables, computed, pending (nome noto, fonte ancora da stabilire: tappa S4). Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
|
||||
"operations": [
|
||||
{
|
||||
"name": "PolarisSearchBoxRefetchableQuery",
|
||||
"kind": "graphql",
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "ricerca",
|
||||
"configured": false,
|
||||
"reason": "le forme non mostrano i valori di context, include_reel e search_surface (testi, che la sonda toglie), né da dove vengono rank_token e search_session_id",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
"content-length": "computed",
|
||||
"content-type": "constant:application/x-www-form-urlencoded",
|
||||
"priority": "pending",
|
||||
"referer": "pending",
|
||||
"sec-ch-ua": "pending",
|
||||
"sec-ch-ua-mobile": "pending",
|
||||
"sec-ch-ua-platform": "pending",
|
||||
"sec-fetch-dest": "constant:empty",
|
||||
"sec-fetch-mode": "constant:cors",
|
||||
"sec-fetch-site": "constant:same-origin",
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
"x-ig-max-touch-points": "pending"
|
||||
},
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"server_timestamps": "constant:true",
|
||||
"variables": "variables"
|
||||
},
|
||||
"variables": {
|
||||
"data": {
|
||||
"context": "(valore tolto)",
|
||||
"include_reel": "(valore tolto)",
|
||||
"query": "{search_text}",
|
||||
"rank_token": "(valore tolto)",
|
||||
"search_session_id": "(valore tolto)",
|
||||
"search_surface": "(valore tolto)"
|
||||
},
|
||||
"hasQuery": true
|
||||
},
|
||||
"rootFields": [
|
||||
"data.xdt_api__v1__fbsearch__topsearch_connection"
|
||||
],
|
||||
"sample": "000002-ricerca-profili",
|
||||
"shapes": [
|
||||
"2026-11-12",
|
||||
"2026-11-16"
|
||||
],
|
||||
"note": "include_reel è un testo, non un vero/falso (la sonda scrive i vero/falso del JSON come true/false). La x-ig-max-touch-points c'è solo nelle forme del 12/11."
|
||||
},
|
||||
{
|
||||
"name": "PolarisProfilePageContentQuery",
|
||||
"kind": "graphql",
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "profilo",
|
||||
"configured": false,
|
||||
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9); la variabile senza nome è un vero/falso di valore non noto",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
"content-length": "computed",
|
||||
"content-type": "constant:application/x-www-form-urlencoded",
|
||||
"priority": "pending",
|
||||
"referer": "pending",
|
||||
"sec-ch-ua": "pending",
|
||||
"sec-ch-ua-mobile": "pending",
|
||||
"sec-ch-ua-platform": "pending",
|
||||
"sec-fetch-dest": "constant:empty",
|
||||
"sec-fetch-mode": "constant:cors",
|
||||
"sec-fetch-site": "constant:same-origin",
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
"x-ig-max-touch-points": "pending"
|
||||
},
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"server_timestamps": "constant:true",
|
||||
"variables": "variables"
|
||||
},
|
||||
"variables": {
|
||||
"(nome tolto)": "(valore tolto)",
|
||||
"__relay_internal__pv__PolarisShortDramaEnabledrelayprovider": true,
|
||||
"__relay_internal__pv__PolarisWebSchoolsEnabledrelayprovider": false,
|
||||
"enable_integrity_filters": true,
|
||||
"id": "{account_id}"
|
||||
},
|
||||
"rootFields": [
|
||||
"data.user"
|
||||
],
|
||||
"sample": "000009-scheda-profilo",
|
||||
"shapes": [
|
||||
"2026-11-12",
|
||||
"2026-11-16"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "PolarisProfilePostsQuery",
|
||||
"kind": "graphql",
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "storico",
|
||||
"configured": false,
|
||||
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
"content-length": "computed",
|
||||
"content-type": "constant:application/x-www-form-urlencoded",
|
||||
"priority": "pending",
|
||||
"referer": "pending",
|
||||
"sec-ch-ua": "pending",
|
||||
"sec-ch-ua-mobile": "pending",
|
||||
"sec-ch-ua-platform": "pending",
|
||||
"sec-fetch-dest": "constant:empty",
|
||||
"sec-fetch-mode": "constant:cors",
|
||||
"sec-fetch-site": "constant:same-origin",
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
"x-ig-max-touch-points": "pending"
|
||||
},
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"server_timestamps": "constant:true",
|
||||
"variables": "variables"
|
||||
},
|
||||
"variables": {
|
||||
"(nome tolto)": false,
|
||||
"__relay_internal__pv__PolarisSEOIsCrawlerrelayprovider": false,
|
||||
"__relay_internal__pv__PolarisShortDramaEnabledrelayprovider": true,
|
||||
"data": {
|
||||
"count": 12,
|
||||
"include_reel_media_seen_timestamp": true,
|
||||
"include_relationship_info": true,
|
||||
"latest_besties_reel_media": true,
|
||||
"latest_reel_media": true
|
||||
},
|
||||
"username": "{username}"
|
||||
},
|
||||
"rootFields": [
|
||||
"data.xdt_api__v1__feed__user_timeline_graphql_connection"
|
||||
],
|
||||
"sample": "000010-post-del-profilo",
|
||||
"shapes": [
|
||||
"2026-11-12",
|
||||
"2026-11-16"
|
||||
],
|
||||
"note": "Solo la prima pagina: le forme non hanno ancora una pagina successiva (nessun cursore nelle variabili). Anche 000016-serie-con-video viene da questa operazione (stesso indirizzo di 000010 nel descrittore)."
|
||||
},
|
||||
{
|
||||
"name": "PolarisProfileReelsTabContentQuery",
|
||||
"kind": "graphql",
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "storico",
|
||||
"configured": false,
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
"content-length": "computed",
|
||||
"content-type": "constant:application/x-www-form-urlencoded",
|
||||
"priority": "pending",
|
||||
"referer": "pending",
|
||||
"sec-ch-ua": "pending",
|
||||
"sec-ch-ua-mobile": "pending",
|
||||
"sec-ch-ua-platform": "pending",
|
||||
"sec-fetch-dest": "constant:empty",
|
||||
"sec-fetch-mode": "constant:cors",
|
||||
"sec-fetch-site": "constant:same-origin",
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
"x-ig-max-touch-points": "pending"
|
||||
},
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"server_timestamps": "constant:true",
|
||||
"variables": "variables"
|
||||
},
|
||||
"variables": {
|
||||
"__relay_internal__pv__PolarisShortDramaEnabledrelayprovider": true,
|
||||
"data": {
|
||||
"include_feed_video": true,
|
||||
"page_size": 12,
|
||||
"target_user_id": "{account_id}"
|
||||
},
|
||||
"user_id": "{account_id}"
|
||||
},
|
||||
"rootFields": [
|
||||
"data.fetch__XDTUserDict.clips_connection"
|
||||
],
|
||||
"sample": "000011-reel-del-profilo",
|
||||
"shapes": [
|
||||
"2026-11-12"
|
||||
],
|
||||
"note": "Solo la prima pagina. Vista solo nelle forme del 12/11."
|
||||
},
|
||||
{
|
||||
"name": "PolarisProfileTaggedTabContentQuery",
|
||||
"kind": "graphql",
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "storico",
|
||||
"configured": false,
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
"content-length": "computed",
|
||||
"content-type": "constant:application/x-www-form-urlencoded",
|
||||
"priority": "pending",
|
||||
"referer": "pending",
|
||||
"sec-ch-ua": "pending",
|
||||
"sec-ch-ua-mobile": "pending",
|
||||
"sec-ch-ua-platform": "pending",
|
||||
"sec-fetch-dest": "constant:empty",
|
||||
"sec-fetch-mode": "constant:cors",
|
||||
"sec-fetch-site": "constant:same-origin",
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
"x-ig-max-touch-points": "pending"
|
||||
},
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"server_timestamps": "constant:true",
|
||||
"variables": "variables"
|
||||
},
|
||||
"variables": {
|
||||
"__relay_internal__pv__PolarisSEOIsCrawlerrelayprovider": false,
|
||||
"__relay_internal__pv__PolarisShortDramaEnabledrelayprovider": true,
|
||||
"count": 12,
|
||||
"user_id": "{account_id}"
|
||||
},
|
||||
"rootFields": [
|
||||
"data.xdt_api__v1__usertags__user_id__feed_connection"
|
||||
],
|
||||
"sample": "000012-con-tag",
|
||||
"shapes": [
|
||||
"2026-11-12"
|
||||
],
|
||||
"note": "Solo la prima pagina. Vista solo nelle forme del 12/11."
|
||||
},
|
||||
{
|
||||
"name": "PolarisProfileStoryHighlightsTrayContentQuery",
|
||||
"kind": "graphql",
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "profilo",
|
||||
"configured": false,
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
"content-length": "computed",
|
||||
"content-type": "constant:application/x-www-form-urlencoded",
|
||||
"priority": "pending",
|
||||
"referer": "pending",
|
||||
"sec-ch-ua": "pending",
|
||||
"sec-ch-ua-mobile": "pending",
|
||||
"sec-ch-ua-platform": "pending",
|
||||
"sec-fetch-dest": "constant:empty",
|
||||
"sec-fetch-mode": "constant:cors",
|
||||
"sec-fetch-site": "constant:same-origin",
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
"x-ig-max-touch-points": "pending"
|
||||
},
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"server_timestamps": "constant:true",
|
||||
"variables": "variables"
|
||||
},
|
||||
"variables": {
|
||||
"user_id": "{account_id}"
|
||||
},
|
||||
"rootFields": [
|
||||
"data.highlights"
|
||||
],
|
||||
"sample": "000013-raccolte-del-profilo",
|
||||
"shapes": [
|
||||
"2026-11-12",
|
||||
"2026-11-16"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "PolarisStoriesV3ReelPageStandaloneQuery",
|
||||
"kind": "graphql",
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "storia",
|
||||
"configured": false,
|
||||
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
"content-length": "computed",
|
||||
"content-type": "constant:application/x-www-form-urlencoded",
|
||||
"priority": "pending",
|
||||
"referer": "pending",
|
||||
"sec-ch-ua": "pending",
|
||||
"sec-ch-ua-mobile": "pending",
|
||||
"sec-ch-ua-platform": "pending",
|
||||
"sec-fetch-dest": "constant:empty",
|
||||
"sec-fetch-mode": "constant:cors",
|
||||
"sec-fetch-site": "constant:same-origin",
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
"x-ig-max-touch-points": "pending"
|
||||
},
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"fb_api_analytics_tags": "pending",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"qpl_active_flow_ids": "pending",
|
||||
"server_timestamps": "constant:true",
|
||||
"variables": "variables"
|
||||
},
|
||||
"variables": {
|
||||
"(nome tolto)": true,
|
||||
"reel_ids_arr": [
|
||||
"{account_id}"
|
||||
]
|
||||
},
|
||||
"rootFields": [
|
||||
"data.xdt_api__v1__feed__reels_media"
|
||||
],
|
||||
"sample": "000014-storie-di-un-profilo",
|
||||
"shapes": [
|
||||
"2026-11-12"
|
||||
],
|
||||
"note": "reel_ids_arr è un elenco di numeri: che sia l'identificativo dell'account è da confermare. Vista solo nelle forme del 12/11."
|
||||
},
|
||||
{
|
||||
"name": "PolarisStoriesV3HighlightsPageQuery",
|
||||
"kind": "graphql",
|
||||
"method": "POST",
|
||||
"path": "/graphql/query",
|
||||
"category": "storia",
|
||||
"configured": false,
|
||||
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
"content-length": "computed",
|
||||
"content-type": "constant:application/x-www-form-urlencoded",
|
||||
"priority": "pending",
|
||||
"referer": "pending",
|
||||
"sec-ch-ua": "pending",
|
||||
"sec-ch-ua-mobile": "pending",
|
||||
"sec-ch-ua-platform": "pending",
|
||||
"sec-fetch-dest": "constant:empty",
|
||||
"sec-fetch-mode": "constant:cors",
|
||||
"sec-fetch-site": "constant:same-origin",
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-bloks-version-id": "constant:e9f7142825abe6e3e169776ae34e2fc4aeb2fa7ccdf139d43730b2f13505e200",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
"x-ig-max-touch-points": "pending",
|
||||
"x-root-field-name": "constant:xdt_api__v1__feed__reels_media__connection"
|
||||
},
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"server_timestamps": "constant:true",
|
||||
"variables": "variables"
|
||||
},
|
||||
"variables": {
|
||||
"(nome tolto)": true,
|
||||
"first": 3,
|
||||
"initial_reel_id": "{highlight_id}",
|
||||
"last": 2,
|
||||
"reel_ids": [
|
||||
"{highlight_id}"
|
||||
]
|
||||
},
|
||||
"rootFields": [
|
||||
"data.xdt_api__v1__feed__reels_media__connection"
|
||||
],
|
||||
"sample": "000006-raccolta-in-evidenza",
|
||||
"shapes": [
|
||||
"2026-11-12"
|
||||
],
|
||||
"note": "reel_ids è l'elenco delle raccolte che la pagina chiede insieme: la forma ne mostra la struttura, non quante. rootFields dal campo_radice delle forme. Vista solo nelle forme del 12/11."
|
||||
},
|
||||
{
|
||||
"name": "PolarisStoriesV3HighlightsPagePaginationQuery",
|
||||
"kind": "graphql",
|
||||
"method": "POST",
|
||||
"path": "/graphql/query",
|
||||
"category": "storia",
|
||||
"configured": false,
|
||||
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9); anche il valore di first non è noto (un numero che cambia)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
"content-length": "computed",
|
||||
"content-type": "constant:application/x-www-form-urlencoded",
|
||||
"priority": "pending",
|
||||
"referer": "pending",
|
||||
"sec-ch-ua": "pending",
|
||||
"sec-ch-ua-mobile": "pending",
|
||||
"sec-ch-ua-platform": "pending",
|
||||
"sec-fetch-dest": "constant:empty",
|
||||
"sec-fetch-mode": "constant:cors",
|
||||
"sec-fetch-site": "constant:same-origin",
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-bloks-version-id": "constant:e9f7142825abe6e3e169776ae34e2fc4aeb2fa7ccdf139d43730b2f13505e200",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
"x-ig-max-touch-points": "pending",
|
||||
"x-root-field-name": "constant:xdt_api__v1__feed__reels_media__connection"
|
||||
},
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"fb_api_analytics_tags": "pending",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"qpl_active_flow_ids": "pending",
|
||||
"server_timestamps": "constant:true",
|
||||
"variables": "variables"
|
||||
},
|
||||
"variables": {
|
||||
"(nome tolto)": true,
|
||||
"after": "{cursor}",
|
||||
"before": null,
|
||||
"first": "(valore tolto)",
|
||||
"initial_reel_id": "{highlight_id}",
|
||||
"is_highlight": true,
|
||||
"last": null,
|
||||
"reel_ids": [
|
||||
"{highlight_id}"
|
||||
]
|
||||
},
|
||||
"rootFields": [
|
||||
"data.xdt_api__v1__feed__reels_media__connection"
|
||||
],
|
||||
"sample": "000007-raccolta-pagina-successiva",
|
||||
"shapes": [
|
||||
"2026-11-12"
|
||||
],
|
||||
"note": "rootFields dal campo_radice delle forme. Vista solo nelle forme del 12/11."
|
||||
},
|
||||
{
|
||||
"name": "media-info",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/api/v1/media/{media_id}/info/",
|
||||
"category": "post",
|
||||
"configured": false,
|
||||
"reason": "il percorso è noto, ma intestazioni della pagina e del browser (come referer, sec-ch-ua e quella con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
"priority": "pending",
|
||||
"referer": "pending",
|
||||
"sec-ch-ua": "pending",
|
||||
"sec-ch-ua-mobile": "pending",
|
||||
"sec-ch-ua-platform": "pending",
|
||||
"sec-fetch-dest": "constant:empty",
|
||||
"sec-fetch-mode": "constant:cors",
|
||||
"sec-fetch-site": "constant:same-origin",
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
"x-ig-max-touch-points": "pending",
|
||||
"x-ig-www-claim": "session:claim",
|
||||
"x-requested-with": "constant:XMLHttpRequest",
|
||||
"x-web-session-id": "pending"
|
||||
},
|
||||
"rootFields": [
|
||||
"items"
|
||||
],
|
||||
"sample": "000005-post-video",
|
||||
"shapes": [
|
||||
"2026-11-12"
|
||||
],
|
||||
"note": "Un post singolo per identificativo (GET, nessun parametro). Vista solo nelle forme del 12/11, 2 volte."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
{
|
||||
"site": "prova",
|
||||
"note": "Operazioni che il client del sito chiederà al sito di prova locale (tools/Febe.SitoDiProva, specifica §14.2) dalla tappa S2 di #36: le stesse risposte JSON che la pagina chiede a /dati/, documentate dai campioni ripuliti di tests/Febe.Tests/campioni/prova. Il sito di prova non controlla le intestazioni; le regole di rifiuto sono le stesse di Instagram (nel codice). La scrittura /dati/ricerche-recenti (POST) non c'è e non può esserci: un indirizzo semplice si legge solo con GET.",
|
||||
"operations": [
|
||||
{
|
||||
"name": "inizio",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/inizio",
|
||||
"category": "home",
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
},
|
||||
"rootFields": [
|
||||
"contenuti"
|
||||
],
|
||||
"sample": "000001-inizio"
|
||||
},
|
||||
{
|
||||
"name": "inizio-altri",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/inizio/altri",
|
||||
"category": "home",
|
||||
"configured": false,
|
||||
"reason": "manca il campione ripulito della risposta in tests/Febe.Tests/campioni/prova",
|
||||
"parameters": {
|
||||
"dopo": "{cursor}"
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "profilo",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/profilo/{username}",
|
||||
"category": "profilo",
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
"scheda": "constant:post"
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
},
|
||||
"rootFields": [
|
||||
"profilo"
|
||||
],
|
||||
"sample": "000002-profilo-pubblico",
|
||||
"note": "Anche 000004-profilo-privato-non-seguito: lo stato del profilo, senza contenuti."
|
||||
},
|
||||
{
|
||||
"name": "profilo-altri",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/profilo/{username}/altri",
|
||||
"category": "storico",
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
"dopo": "{cursor}",
|
||||
"scheda": "constant:post"
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
},
|
||||
"rootFields": [
|
||||
"contenuti",
|
||||
"pagina"
|
||||
],
|
||||
"sample": "000003-profilo-pagina-successiva",
|
||||
"note": "Anche 000010-pagina-vuota."
|
||||
},
|
||||
{
|
||||
"name": "taggati",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/profilo/{username}",
|
||||
"category": "storico",
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
"scheda": "constant:taggati"
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
},
|
||||
"rootFields": [
|
||||
"contenuti"
|
||||
],
|
||||
"sample": "000009-taggati"
|
||||
},
|
||||
{
|
||||
"name": "reel",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/profilo/{username}",
|
||||
"category": "storico",
|
||||
"configured": false,
|
||||
"reason": "manca il campione ripulito della risposta in tests/Febe.Tests/campioni/prova",
|
||||
"parameters": {
|
||||
"scheda": "constant:reel"
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "post",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/post/{code}",
|
||||
"category": "post",
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
},
|
||||
"rootFields": [
|
||||
"contenuto"
|
||||
],
|
||||
"sample": "000005-post-serie"
|
||||
},
|
||||
{
|
||||
"name": "storie",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/storie/{username}",
|
||||
"category": "storia",
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
},
|
||||
"rootFields": [
|
||||
"storie"
|
||||
],
|
||||
"sample": "000006-storie"
|
||||
},
|
||||
{
|
||||
"name": "evidenza",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/evidenza/{highlight_id}",
|
||||
"category": "storia",
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
},
|
||||
"rootFields": [
|
||||
"raccolta"
|
||||
],
|
||||
"sample": "000007-raccolta"
|
||||
},
|
||||
{
|
||||
"name": "seguiti",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/seguiti",
|
||||
"category": "seguiti",
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
"dopo": "{cursor?}"
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
},
|
||||
"rootFields": [
|
||||
"seguiti"
|
||||
],
|
||||
"sample": "000008-seguiti",
|
||||
"note": "La prima pagina senza «dopo»."
|
||||
},
|
||||
{
|
||||
"name": "cerca",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/cerca",
|
||||
"category": "ricerca",
|
||||
"configured": false,
|
||||
"reason": "manca il campione ripulito della risposta in tests/Febe.Tests/campioni/prova",
|
||||
"parameters": {
|
||||
"testo": "{search_text}"
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -66,6 +66,7 @@ public sealed record CautionProfile
|
||||
[ActionKind.BackfillPage] = new(20, 100),
|
||||
[ActionKind.SinglePost] = new(10, 60),
|
||||
[ActionKind.FollowingListPage] = new(15, 60),
|
||||
[ActionKind.ProfileSearch] = new(240, 1200),
|
||||
},
|
||||
DataPerDayBytes = 4 * GB,
|
||||
BackfillPostsPerAccountPerDay = 300,
|
||||
@@ -90,6 +91,7 @@ public sealed record CautionProfile
|
||||
[ActionKind.BackfillPage] = new(30, 180),
|
||||
[ActionKind.SinglePost] = new(15, 100),
|
||||
[ActionKind.FollowingListPage] = new(20, 90),
|
||||
[ActionKind.ProfileSearch] = new(300, 1500),
|
||||
},
|
||||
DataPerDayBytes = 8 * GB,
|
||||
BackfillPostsPerAccountPerDay = 500,
|
||||
@@ -114,6 +116,7 @@ public sealed record CautionProfile
|
||||
[ActionKind.BackfillPage] = new(45, 300),
|
||||
[ActionKind.SinglePost] = new(20, 160),
|
||||
[ActionKind.FollowingListPage] = new(30, 150),
|
||||
[ActionKind.ProfileSearch] = new(360, 1800),
|
||||
},
|
||||
DataPerDayBytes = 16 * GB,
|
||||
BackfillPostsPerAccountPerDay = 800,
|
||||
|
||||
@@ -403,6 +403,8 @@ public static class EngineEventCodes
|
||||
public const string ManualCheck = "controlla-ora";
|
||||
public const string RecipeFailed = "ricetta-fallita";
|
||||
public const string SettingsChanged = "impostazioni-motore";
|
||||
public const string RecipeNotConfigured = "configurazione-incompleta";
|
||||
public const string CollectionConfigurationChanged = "configurazione-raccolta";
|
||||
|
||||
/// <summary>Prefix of the per-recipe lines («Appena fatto»): "ricetta." + recipe kind.</summary>
|
||||
public const string RecipePrefix = "ricetta.";
|
||||
|
||||
@@ -74,6 +74,12 @@ public enum RecipeStatus
|
||||
|
||||
/// <summary>Unexpected error; message says what happened.</summary>
|
||||
Failed,
|
||||
|
||||
/// <summary>
|
||||
/// Refused before anything was done: the target map or the reader vocabulary of the site does not have what the
|
||||
/// recipe needs yet. A state of the configuration, not a failure of the recipe: it never counts towards suspension.
|
||||
/// </summary>
|
||||
NotConfigured,
|
||||
}
|
||||
|
||||
/// <summary>Result of a recipe run, used by the scheduler to plan what comes next.</summary>
|
||||
@@ -115,6 +121,13 @@ public interface IRecipeRunner
|
||||
|
||||
/// <summary>Puts the browser on the empty rest page (end of session, pauses, night).</summary>
|
||||
Task RestAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="kind"/> cannot run on the configuration of the site in use (target map, reader vocabulary),
|
||||
/// in Italian; null when it can, or when the runner cannot tell. The engine does not plan such a recipe: running it
|
||||
/// would only end in <see cref="RecipeStatus.NotConfigured"/>.
|
||||
/// </summary>
|
||||
string? NotConfiguredReason(RecipeKind kind) => null;
|
||||
}
|
||||
|
||||
/// <summary>Daily byte budget for CDN downloads (category «dati scaricati», spec §7.4).</summary>
|
||||
|
||||