Compare commits
25
Commits
v0.1.1
..
fbc40fb5a1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,49 @@
|
||||
# Novità
|
||||
|
||||
## 0.1.2 (in preparazione)
|
||||
|
||||
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
|
||||
|
||||
@@ -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/`).
|
||||
@@ -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.1, 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
|
||||
|
||||
|
||||
@@ -279,3 +279,37 @@ 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) |
|
||||
+6
-2
@@ -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
|
||||
|
||||
|
||||
+4
-3
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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:
|
||||
|
||||
+97
-16
@@ -96,7 +96,7 @@ ramo un push nuovo annulla l'esecuzione in corso; su `main` ogni unione arriva f
|
||||
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».
|
||||
|
||||
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 +129,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 +169,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 +283,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,110 @@ 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**.
|
||||
|
||||
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).
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
+30
-20
@@ -1,24 +1,30 @@
|
||||
# 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.
|
||||
|
||||
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 +34,18 @@ 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`, `postCount` e
|
||||
`version.hasAudio`; le serie (`carousel_media`) sono una chiave vista ma sempre vuota nei campioni.
|
||||
- `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.
|
||||
+88
-8
@@ -1,10 +1,50 @@
|
||||
# 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 25 ottobre 2026, versione 0.1.1 (anteprima), 0.1.2 in preparazione.
|
||||
|
||||
## In breve
|
||||
|
||||
**25 ottobre 2026: Febe legge le risposte vere di Instagram** (ramo `correzione/lettura-instagram`).
|
||||
|
||||
- **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`, che manca ancora.
|
||||
- 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, 76 saltate su Windows
|
||||
(Chromium e Xvfb), da rivedere nella CI.
|
||||
|
||||
**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 +56,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 +94,35 @@ 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
|
||||
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.
|
||||
l'immagine, ma non la pubblicano (lo dicono con un avviso), e la pulizia non tocca il registro. Il 21/10 mancava
|
||||
ancora. Aggiunto il segreto, si rilancia il flusso del tag `v0.1.1`: l'immagine esce e le note della release si
|
||||
correggono.
|
||||
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**: leggere l'elenco della prova del 21/10 (Actions ▸ pulizia, esecuzione #28, «Solo prova») prima della
|
||||
prima pulizia vera, lunedì 26/10 alle 4:17. Attenzione soprattutto allo store delle immagini scritto all'inizio e
|
||||
alle righe «toglierei il nome …» delle immagini in uso con più nomi (app di Unraid).
|
||||
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 +137,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.
|
||||
|
||||
@@ -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,6 +2,7 @@ using System.Globalization;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
@@ -372,6 +373,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
runner.Target = Pipeline.Runner;
|
||||
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));
|
||||
@@ -412,6 +414,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.
|
||||
|
||||
@@ -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,22 +46,26 @@ 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 static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 };
|
||||
|
||||
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 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 Task? _worker;
|
||||
@@ -181,7 +194,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);
|
||||
}
|
||||
}
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
@@ -240,16 +260,21 @@ 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 void OnLoadingFinished(JsonElement p)
|
||||
{
|
||||
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId
|
||||
|| !_inFlight.TryRemove(requestId, out var descriptor))
|
||||
|| !_inFlight.TryRemove(requestId, out var pending))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -258,17 +283,19 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
if (length > _options.MaxBodyBytes)
|
||||
{
|
||||
Interlocked.Increment(ref _skipped);
|
||||
NotifyDropped(requestId);
|
||||
return;
|
||||
}
|
||||
|
||||
_queue.Writer.TryWrite(descriptor);
|
||||
_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 { } requestId
|
||||
&& _inFlight.TryRemove(requestId, out _))
|
||||
{
|
||||
_inFlight.TryRemove(requestId, out _);
|
||||
NotifyDropped(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,8 +311,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);
|
||||
}
|
||||
}
|
||||
Publish(frame.TryGetProperty("url", out var u) ? u.GetString() : null, sameDocument: false);
|
||||
}
|
||||
|
||||
@@ -325,64 +360,128 @@ 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];
|
||||
try
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
if (consumers.Length == 0)
|
||||
/// <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);
|
||||
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);
|
||||
return;
|
||||
}
|
||||
|
||||
var delivered = bytes is null ? 0
|
||||
: pending.IsPageDocument ? await ConsumeDocumentAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false)
|
||||
: await ConsumeBodyAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false);
|
||||
if (delivered == 0)
|
||||
{
|
||||
NotifyDropped(descriptor.RequestId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The body of a data response, as one answer. Returns how many answers reached the consumers (0 or 1).</summary>
|
||||
private async Task<int> ConsumeBodyAsync(ResponseDescriptor descriptor, byte[] bytes, IResponseConsumer[] consumers, CancellationToken ct)
|
||||
{
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(bytes, 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
|
||||
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>). One block at a time: each is disposed before the next is parsed.
|
||||
/// Returns how many blocks reached the consumers; a document without any is not data, and not a parse error.
|
||||
/// </summary>
|
||||
private async Task<int> ConsumeDocumentAsync(ResponseDescriptor descriptor, byte[] bytes, IResponseConsumer[] consumers, CancellationToken ct)
|
||||
{
|
||||
var delivered = 0;
|
||||
foreach (var block in DataResponses.EmbeddedJsonBlocks(Encoding.UTF8.GetString(bytes)))
|
||||
{
|
||||
using (block)
|
||||
{
|
||||
continue;
|
||||
delivered++;
|
||||
await DeliverAsync(descriptor, block, consumers, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
JsonDocument? document;
|
||||
return delivered;
|
||||
}
|
||||
|
||||
private async Task DeliverAsync(ResponseDescriptor descriptor, JsonDocument body, IResponseConsumer[] consumers, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _jsonBodies);
|
||||
foreach (var consumer in consumers)
|
||||
{
|
||||
try
|
||||
{
|
||||
document = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
|
||||
await consumer.ConsumeAsync(descriptor, body, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !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
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
_log.Warn($"Cattura: errore in un lettore ({consumer.GetType().Name}).", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<JsonDocument?> FetchBodyAsync(string requestId, CancellationToken ct)
|
||||
/// <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 +501,39 @@ 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);
|
||||
return null;
|
||||
}
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
/// <summary>Tells the observers that a body they may be waiting for will not come.</summary>
|
||||
private void NotifyDropped(string requestId)
|
||||
{
|
||||
foreach (var observer in SnapshotObservers())
|
||||
{
|
||||
try
|
||||
{
|
||||
observer.OnBodyDropped(requestId);
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -23,8 +23,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);
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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"],
|
||||
|
||||
@@ -69,4 +69,13 @@ 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)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -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,12 @@ 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; }
|
||||
}
|
||||
@@ -185,6 +185,15 @@ public sealed record ReaderVocabulary
|
||||
/// <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.
|
||||
@@ -319,6 +328,7 @@ public sealed record ReaderVocabulary
|
||||
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items) },
|
||||
Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) },
|
||||
Viewer = K(file.Viewer),
|
||||
Relevance = [.. (file.Relevance?.Keys ?? []).Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k.Trim()).Distinct(StringComparer.Ordinal)],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -342,6 +352,15 @@ internal sealed class VocabularyFile
|
||||
public PageDto? Page { 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
|
||||
|
||||
@@ -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,6 +36,12 @@ 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.Contents.Count > 0 || walk.Highlights.Count > 0 || profiles.Count > 0)
|
||||
@@ -46,12 +54,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 +107,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 +139,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))
|
||||
{
|
||||
@@ -160,8 +183,26 @@ public sealed class ShapeReader
|
||||
_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 +363,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 +540,9 @@ 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>Merges what different parts of a response say about the same profile.</summary>
|
||||
public void AddProfile(ProfileInfo profile)
|
||||
{
|
||||
|
||||
@@ -29,6 +29,7 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
private readonly List<CapturedRead> _reads = [];
|
||||
private readonly Dictionary<string, DateTimeOffset> _pending = new(StringComparer.Ordinal);
|
||||
private long _sequence;
|
||||
private string? _viewerId;
|
||||
|
||||
public CaptureCollector(ShapeReader reader, IClock clock)
|
||||
{
|
||||
@@ -41,6 +42,21 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
/// <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()
|
||||
{
|
||||
@@ -135,7 +151,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);
|
||||
@@ -150,6 +169,21 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
|
||||
var result = _reader.Read(body);
|
||||
if (result.ViewerId is { } viewerId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_viewerId = viewerId;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -166,7 +200,7 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
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 +210,14 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
}
|
||||
|
||||
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.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
@@ -98,8 +99,12 @@ public sealed partial class RecipeRunner
|
||||
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)
|
||||
@@ -246,13 +254,14 @@ public sealed partial class RecipeRunner
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).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);
|
||||
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);
|
||||
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;
|
||||
|
||||
|
||||
@@ -17,34 +17,61 @@ public sealed partial class RecipeRunner
|
||||
await run.PermitAsync(ActionKind.Home, null).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
|
||||
@@ -66,7 +78,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 +89,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 +104,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 +114,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 +132,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);
|
||||
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 +171,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 +186,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 +200,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 +220,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 +255,383 @@ 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);
|
||||
return new ViewerResult(shown, Worse(RecipeRun.Stop(RecipeStatus.Failed, $"Errore imprevisto in «{Name(run.Request.Kind)}» ({ex.GetType().Name}): {ex.Message}"), 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 +663,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 +689,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 +724,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);
|
||||
}
|
||||
@@ -50,11 +50,13 @@ 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;
|
||||
|
||||
@@ -83,15 +85,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,20 +118,23 @@ 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);
|
||||
}
|
||||
|
||||
return new RecipeOutcome(RecipeStatus.NotConfigured, 0, 0, refusal.Message);
|
||||
}
|
||||
|
||||
if (Env.Breaker is { } breaker && !breaker.State.AllowsSiteActions)
|
||||
@@ -206,6 +215,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.
|
||||
|
||||
@@ -31,10 +31,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; } =
|
||||
@@ -178,7 +181,7 @@ public sealed partial class SiteMap
|
||||
/// <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) =>
|
||||
|
||||
@@ -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})." },
|
||||
|
||||
@@ -1,51 +1,55 @@
|
||||
{
|
||||
"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), 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, quindi da solo non basta a riconoscerlo (H10 resta aperta).",
|
||||
"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 e raccolta-pagina-successiva. «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): chiave vista ma sempre vuota nei campioni, il formato dei figli è un indizio di §6.4 da confermare con un campione di un post con più file.",
|
||||
"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": [],
|
||||
"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. Il numero dei post non compare in nessun campione: resta vuoto.",
|
||||
"id": ["pk", "id"],
|
||||
"username": ["username"],
|
||||
"displayName": ["full_name"],
|
||||
"isPrivate": ["is_private"],
|
||||
"isFollowed": ["friendship_status.following"],
|
||||
"postCount": [],
|
||||
"picture": [],
|
||||
"latestStoryAt": []
|
||||
"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.",
|
||||
"id": ["id"],
|
||||
"title": ["title"],
|
||||
"owner": ["user"],
|
||||
"items": ["items"]
|
||||
},
|
||||
"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": []
|
||||
"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"]
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -259,6 +259,11 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
}
|
||||
|
||||
var kind = CheckPolicy.WantsProfileChecks(account) ? EngineTaskKind.ProfileCheck : EngineTaskKind.AccountStories;
|
||||
if (_composer.NotConfiguredReason(CheckPolicy.RecipeOf(kind)) is { } notConfigured)
|
||||
{
|
||||
return new CheckNowResult(CheckNowStatus.Refused, notConfigured + " Il controllo non parte.");
|
||||
}
|
||||
|
||||
var category = kind == EngineTaskKind.ProfileCheck ? ActionKind.ProfileOpen : ActionKind.StoryView;
|
||||
var budget = await _s.Governor.EvaluateBudgetAsync(category, accountId, ct).ConfigureAwait(false);
|
||||
if (!budget.Granted && budget.Reason != DenialReason.AccountNotContactable)
|
||||
@@ -397,6 +402,49 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
return resumed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The collection configuration in use: <paramref name="fingerprint"/> of the reader vocabulary and target map of the
|
||||
/// site as loaded. When it differs from the stored one — or none is stored yet, the first start that knows it —
|
||||
/// every suspension and consecutive failure of the recipes is cleared once, since they were counted against other
|
||||
/// files, with one line in the timeline when there was something to clear; then the fingerprint is stored. Called at
|
||||
/// start-up, before <see cref="StartAsync"/>. True when the configuration had changed.
|
||||
/// </summary>
|
||||
public async Task<bool> ApplyCollectionConfigurationAsync(string fingerprint, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint);
|
||||
var settings = _s.Storage.Settings;
|
||||
if (string.Equals(await settings.GetAsync(EngineSettingKeys.CollectionConfiguration, ct).ConfigureAwait(false), fingerprint, StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await _health.LoadAsync(ct).ConfigureAwait(false);
|
||||
var (suspended, hadFailures) = await _health.ResetAllAsync(ct).ConfigureAwait(false);
|
||||
if (suspended.Count > 0)
|
||||
{
|
||||
var names = string.Join(", ", suspended.Select(k => "«" + ItalianText.Capitalize(SessionComposer.RecipeName(k)) + "»"));
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Info,
|
||||
EngineEventCodes.CollectionConfigurationChanged,
|
||||
$"La configurazione della raccolta è cambiata: le ricette sospese ripartono ({names}).",
|
||||
ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (hadFailures)
|
||||
{
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Info,
|
||||
EngineEventCodes.CollectionConfigurationChanged,
|
||||
"La configurazione della raccolta è cambiata: i problemi delle ricette contati finora non valgono più.",
|
||||
ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Stored last: if Febe stops in between, the next start clears again, which changes nothing.
|
||||
await settings.SetAsync(EngineSettingKeys.CollectionConfiguration, fingerprint, ct).ConfigureAwait(false);
|
||||
Wake();
|
||||
_s.Events.Publish(EngineNotificationKind.StateChanged);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Stores and applies new engine settings, then replans.</summary>
|
||||
public async Task ApplySettingsAsync(EngineSettings settings, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -45,6 +45,12 @@ public static class EngineSettingKeys
|
||||
|
||||
/// <summary>Last completed Giro dei seguiti, Unix milliseconds (it read the stories bar of every followed account).</summary>
|
||||
public const string LastSweep = "motore.ultimo-giro";
|
||||
|
||||
/// <summary>
|
||||
/// Fingerprint of the collection configuration the suspensions and failure counts refer to (reader vocabulary and
|
||||
/// target map of the site, as loaded): when it changes they are cleared once.
|
||||
/// </summary>
|
||||
public const string CollectionConfiguration = "motore.configurazione-raccolta";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -28,6 +28,7 @@ public sealed record RecentAction(
|
||||
RecipeStatus.AccountUnreachable => "Non raggiungibile",
|
||||
RecipeStatus.Cancelled => "Interrotto",
|
||||
RecipeStatus.Failed => "Errore",
|
||||
RecipeStatus.NotConfigured => "Da configurare",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ namespace Febe.Core.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Consecutive failures per recipe and suspended recipes (spec §6.4: after three «formato non riconosciuto» in a row
|
||||
/// the recipe is suspended and the interface says so). Persisted in the settings table.
|
||||
/// the recipe is suspended and the interface says so). Persisted in the settings table. A refusal because the
|
||||
/// configuration of the site is incomplete (<see cref="RecipeStatus.NotConfigured"/>) is not a failure and never
|
||||
/// reaches it; a change of that configuration clears it (<see cref="ResetAllAsync"/>).
|
||||
/// </summary>
|
||||
internal sealed class RecipeHealth
|
||||
{
|
||||
@@ -110,6 +112,26 @@ internal sealed class RecipeHealth
|
||||
return removed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The collection configuration changed: every suspension and every consecutive failure goes, since they were
|
||||
/// counted against other files. Returns the recipes that were suspended and whether any failure was counted.
|
||||
/// </summary>
|
||||
public async Task<(IReadOnlyList<RecipeKind> Suspended, bool HadFailures)> ResetAllAsync(CancellationToken ct)
|
||||
{
|
||||
RecipeKind[] suspended;
|
||||
bool hadFailures;
|
||||
lock (_gate)
|
||||
{
|
||||
suspended = [.. _suspended.Keys.Order()];
|
||||
hadFailures = _failures.Count > 0;
|
||||
_suspended.Clear();
|
||||
_failures.Clear();
|
||||
}
|
||||
|
||||
await SaveAsync(ct).ConfigureAwait(false);
|
||||
return (suspended, hadFailures);
|
||||
}
|
||||
|
||||
private Task SaveAsync(CancellationToken ct)
|
||||
{
|
||||
string failures;
|
||||
|
||||
@@ -14,6 +14,9 @@ namespace Febe.Core.Engine;
|
||||
/// </summary>
|
||||
internal sealed class SessionComposer
|
||||
{
|
||||
/// <summary>What every line about a recipe the configuration does not let run adds (the runner's included).</summary>
|
||||
internal const string NotConfiguredTail = " Febe non la avvia finché la configurazione non è completa, e non la conta fra i problemi della ricetta.";
|
||||
|
||||
private static readonly TimeSpan DefaultWindow = TimeSpan.FromHours(16);
|
||||
|
||||
private readonly EngineServices _s;
|
||||
@@ -24,6 +27,13 @@ internal sealed class SessionComposer
|
||||
private readonly Lock _noticeGate = new();
|
||||
private readonly HashSet<(string Code, long? Account, DateOnly Day)> _notices = [];
|
||||
|
||||
// Recipes the configuration of the site does not let run. The configuration is loaded once per process, so what a
|
||||
// run learned holds until the end, and each recipe is said once (_notConfiguredSaid), not at every session.
|
||||
private readonly Lock _configurationGate = new();
|
||||
private readonly Dictionary<RecipeKind, string> _notConfigured = [];
|
||||
private readonly HashSet<RecipeKind> _notConfiguredSaid = [];
|
||||
private readonly List<string> _notConfiguredToSay = [];
|
||||
|
||||
// The interface calls SyncQueueAsync while a session may be running. A recipe's task is Running in the database
|
||||
// between its start and its bookkeeping, and then has its successor: under this gate the queue is looked at only
|
||||
// when every task is pending, in flight (_inFlight) or already replaced by its successor, never in between.
|
||||
@@ -102,6 +112,7 @@ internal sealed class SessionComposer
|
||||
|
||||
// Normally the next sweep will cover them: explicit checks only when no sweep can run, or after a long gap.
|
||||
var sweepUnavailable = _health.IsSuspended(RecipeKind.FollowingSweep)
|
||||
|| NotConfiguredReason(RecipeKind.FollowingSweep) is not null
|
||||
|| !(await _s.Governor.EvaluateBudgetAsync(ActionKind.Home, null, ct).ConfigureAwait(false)).Granted;
|
||||
var factor = sweepUnavailable ? 1 : 2;
|
||||
var uncovered = accounts.Values
|
||||
@@ -184,9 +195,9 @@ internal sealed class SessionComposer
|
||||
/// <summary>
|
||||
/// Keeps the queue in step with the accounts: a profile check and a story check (as the account wants them) for
|
||||
/// every contactable account, a look at each highlight collection on its profile, a backfill task for every account
|
||||
/// «Storico in corso», a Giro dei seguiti when someone is followed; pending planned tasks of accounts that may not be
|
||||
/// contacted are cancelled. Commands of Alberto are left alone, and so is the task of the recipe in progress: its
|
||||
/// own bookkeeping plans the next one.
|
||||
/// «Storico in corso», a Giro dei seguiti when someone is followed; pending planned tasks the account no longer wants,
|
||||
/// or of accounts that may not be contacted, are cancelled (a «Post singolo» only in the second case). Commands of
|
||||
/// Alberto are left alone, and so is the task of the recipe in progress: its own bookkeeping plans the next one.
|
||||
/// </summary>
|
||||
public async Task<Dictionary<long, Account>> SyncQueueAsync(CancellationToken ct)
|
||||
{
|
||||
@@ -212,7 +223,14 @@ internal sealed class SessionComposer
|
||||
{
|
||||
var tasks = byAccount[account.Id].Where(t => !t.IsManual).ToList();
|
||||
var wanted = WantedKinds(account);
|
||||
foreach (var task in tasks.Where(t => t.Kind != EngineTaskKind.HighlightCheck && !wanted.ContainsKey(t.Kind) && !(t.Kind == EngineTaskKind.AccountStories && t.Priority >= Options.FlaggedStoriesPriority && CheckPolicy.IsContactable(account))))
|
||||
|
||||
// Nothing is planned that the configuration of the site does not let run: it would only be refused.
|
||||
foreach (var kind in wanted.Keys.Where(k => !CanRun(CheckPolicy.RecipeOf(k))).ToList())
|
||||
{
|
||||
wanted.Remove(kind);
|
||||
}
|
||||
|
||||
foreach (var task in tasks.Where(t => !Keeps(t, account, wanted)))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
@@ -233,12 +251,13 @@ internal sealed class SessionComposer
|
||||
}
|
||||
|
||||
var anyFollowed = accounts.Values.Any(a => a.IsFollowed && CheckPolicy.IsContactable(a));
|
||||
var sweepWanted = anyFollowed && CanRun(RecipeKind.FollowingSweep);
|
||||
var sweeps = pending.Where(t => t.Kind == EngineTaskKind.FollowingSweep && !t.IsManual).ToList();
|
||||
if (anyFollowed && sweeps.Count == 0)
|
||||
if (sweepWanted && sweeps.Count == 0)
|
||||
{
|
||||
await EnsureSweepTaskAsync(_s.Runtime.NextSessionAt ?? now, ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (!anyFollowed)
|
||||
else if (!sweepWanted)
|
||||
{
|
||||
foreach (var sweep in sweeps)
|
||||
{
|
||||
@@ -246,9 +265,28 @@ internal sealed class SessionComposer
|
||||
}
|
||||
}
|
||||
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
return accounts;
|
||||
}
|
||||
|
||||
/// <summary>Whether <see cref="SyncQueueLockedAsync"/> leaves a pending planned task of the account where it is.</summary>
|
||||
private bool Keeps(EngineTask task, Account account, Dictionary<EngineTaskKind, DateTimeOffset?> wanted) => task.Kind switch
|
||||
{
|
||||
// One per collection: SyncHighlightsAsync.
|
||||
EngineTaskKind.HighlightCheck => true,
|
||||
|
||||
// Queued by the collection, not by the settings of the account: a series the grid did not give whole, an
|
||||
// address that expired (spec §6.5 point 5). Nothing would queue it again, so it waits while the recipe cannot
|
||||
// run, and goes only with an account that may not be contacted.
|
||||
EngineTaskKind.SinglePost => CheckPolicy.IsContactable(account),
|
||||
|
||||
// Flagged by the stories bar: kept until it runs, when it can.
|
||||
EngineTaskKind.AccountStories when task.Priority >= Options.FlaggedStoriesPriority =>
|
||||
wanted.ContainsKey(task.Kind) || (CheckPolicy.IsContactable(account) && CanRun(RecipeKind.AccountStories)),
|
||||
|
||||
_ => wanted.ContainsKey(task.Kind),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// «Raccolta in evidenza» (spec §6.3) for an account that wants «Storie in evidenza»: one task per collection the
|
||||
/// profile check found (payload: its Instagram identifier), due at once for a collection never looked at, then
|
||||
@@ -270,6 +308,11 @@ internal sealed class SessionComposer
|
||||
}
|
||||
}
|
||||
|
||||
if (collections.Count > 0 && !CanRun(RecipeKind.Highlight))
|
||||
{
|
||||
collections.Clear();
|
||||
}
|
||||
|
||||
foreach (var task in planned.Where(t => t.Payload is null || !collections.ContainsKey(t.Payload)))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
@@ -295,11 +338,73 @@ internal sealed class SessionComposer
|
||||
private bool InFlight(long accountId, EngineTaskKind kind, string? payload) =>
|
||||
_inFlight is { } task && task.AccountId == accountId && task.Kind == kind && (payload is null || task.Payload == payload);
|
||||
|
||||
/// <summary>The Giro dei seguiti shown in the queue at the next session.</summary>
|
||||
public Task EnsureSweepTaskAsync(DateTimeOffset dueAt, CancellationToken ct) =>
|
||||
Store.Tasks.EnqueueAsync(
|
||||
/// <summary>The Giro dei seguiti shown in the queue at the next session (when the configuration lets it run).</summary>
|
||||
public async Task EnsureSweepTaskAsync(DateTimeOffset dueAt, CancellationToken ct)
|
||||
{
|
||||
if (!CanRun(RecipeKind.FollowingSweep))
|
||||
{
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await Store.Tasks.EnqueueAsync(
|
||||
new EngineTask { Kind = EngineTaskKind.FollowingSweep, DueAt = dueAt, CreatedAt = Clock.Now },
|
||||
ct);
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why the configuration of the site in use (target map, reader vocabulary) does not let <paramref name="kind"/>
|
||||
/// run, as the runner says or as a run of it said; null when it can.
|
||||
/// </summary>
|
||||
internal string? NotConfiguredReason(RecipeKind kind)
|
||||
{
|
||||
lock (_configurationGate)
|
||||
{
|
||||
if (_notConfigured.TryGetValue(kind, out var known))
|
||||
{
|
||||
return known;
|
||||
}
|
||||
}
|
||||
|
||||
return _runner.NotConfiguredReason(kind);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// False when the configuration does not let <paramref name="kind"/> run. The first time, its reason is kept to be
|
||||
/// said in the timeline (<see cref="SayNotConfiguredAsync"/>): once per recipe and process, not at every session.
|
||||
/// </summary>
|
||||
private bool CanRun(RecipeKind kind)
|
||||
{
|
||||
if (NotConfiguredReason(kind) is not { } reason)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
lock (_configurationGate)
|
||||
{
|
||||
if (_notConfiguredSaid.Add(kind))
|
||||
{
|
||||
_notConfiguredToSay.Add(reason);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private async Task SayNotConfiguredAsync()
|
||||
{
|
||||
string[] reasons;
|
||||
lock (_configurationGate)
|
||||
{
|
||||
reasons = [.. _notConfiguredToSay];
|
||||
_notConfiguredToSay.Clear();
|
||||
}
|
||||
|
||||
foreach (var reason in reasons)
|
||||
{
|
||||
await _s.Events.WriteAsync(EventSeverity.Warning, EngineEventCodes.RecipeNotConfigured, reason + NotConfiguredTail, ct: CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private Dictionary<EngineTaskKind, DateTimeOffset?> WantedKinds(Account account)
|
||||
{
|
||||
@@ -314,7 +419,7 @@ internal sealed class SessionComposer
|
||||
if (profile)
|
||||
{
|
||||
// A profile that is not followed shows its stories only on its page: one visit serves both checks.
|
||||
wanted[EngineTaskKind.ProfileCheck] = !account.IsFollowed && stories
|
||||
wanted[EngineTaskKind.ProfileCheck] = VisitServesStories(account)
|
||||
? Earliest(account.NextProfileCheckAt, account.NextStoriesCheckAt)
|
||||
: account.NextProfileCheckAt;
|
||||
}
|
||||
@@ -336,7 +441,21 @@ internal sealed class SessionComposer
|
||||
private static DateTimeOffset? Earliest(DateTimeOffset? a, DateTimeOffset? b) =>
|
||||
a is null || b is null ? null : a < b ? a : b;
|
||||
|
||||
private static bool IsStoryWork(EngineTask task, Dictionary<long, Account> accounts, DateTimeOffset now)
|
||||
/// <summary>
|
||||
/// Whether a visit of the profile also checks its stories, so that it comes at the shorter of the two intervals: a
|
||||
/// profile that is not followed, with «Storie» on, while the configuration lets «Storie di un account» run. Without
|
||||
/// it the visit is a plain profile check (story times are left as they are, for when the stories can run).
|
||||
/// </summary>
|
||||
private bool VisitServesStories(Account account) =>
|
||||
!account.IsFollowed && CheckPolicy.WantsStories(account) && CanRun(RecipeKind.AccountStories);
|
||||
|
||||
/// <summary>Interval of a visit of the profile (<see cref="CheckPolicy.VisitInterval"/> only when it serves the stories).</summary>
|
||||
private TimeSpan VisitInterval(Account account, TimeSpan window) =>
|
||||
VisitServesStories(account)
|
||||
? CheckPolicy.VisitInterval(account, window, Options.MinimumStoryChecksPerDay)
|
||||
: CheckPolicy.ProfileCheckInterval(account);
|
||||
|
||||
private bool IsStoryWork(EngineTask task, Dictionary<long, Account> accounts, DateTimeOffset now)
|
||||
{
|
||||
if (task.Kind == EngineTaskKind.AccountStories)
|
||||
{
|
||||
@@ -347,8 +466,7 @@ internal sealed class SessionComposer
|
||||
return task.Kind == EngineTaskKind.ProfileCheck
|
||||
&& task.AccountId is { } id
|
||||
&& accounts.TryGetValue(id, out var account)
|
||||
&& !account.IsFollowed
|
||||
&& CheckPolicy.WantsStories(account)
|
||||
&& VisitServesStories(account)
|
||||
&& (account.NextStoriesCheckAt is null || account.NextStoriesCheckAt <= now);
|
||||
}
|
||||
|
||||
@@ -361,7 +479,7 @@ internal sealed class SessionComposer
|
||||
{
|
||||
var interval = task.Kind == EngineTaskKind.AccountStories
|
||||
? CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay)
|
||||
: CheckPolicy.VisitInterval(account, window, Options.MinimumStoryChecksPerDay);
|
||||
: VisitInterval(account, window);
|
||||
items.Add((task, CheckPolicy.SelectionWeight(account, now - task.DueAt, interval)));
|
||||
}
|
||||
else
|
||||
@@ -545,6 +663,15 @@ internal sealed class SessionComposer
|
||||
|
||||
var now = Clock.Now;
|
||||
var flagged = new HashSet<long>(outcome.AccountsWithStories);
|
||||
|
||||
// No check is queued that the configuration does not let run: it would only wait, and go at the next session.
|
||||
// Nothing is lost: until their stories are checked, every sweep flags these accounts again.
|
||||
if (flagged.Count > 0 && !CanRun(RecipeKind.AccountStories))
|
||||
{
|
||||
flagged.Clear();
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var id in flagged)
|
||||
{
|
||||
if (accounts.TryGetValue(id, out var account) && CheckPolicy.IsContactable(account) && CheckPolicy.WantsStories(account))
|
||||
@@ -615,6 +742,12 @@ internal sealed class SessionComposer
|
||||
return;
|
||||
}
|
||||
|
||||
if (!CanRun(RecipeKind.Backfill))
|
||||
{
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var now = Clock.Now;
|
||||
var zone = Clock.LocalZone;
|
||||
var today = LocalCalendar.Today(now, zone);
|
||||
@@ -683,6 +816,25 @@ internal sealed class SessionComposer
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!CanRun(request.Kind))
|
||||
{
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
if (task is { IsManual: true })
|
||||
{
|
||||
// A command of Alberto that cannot be carried out with these files: dropped, and he is told why.
|
||||
await Store.Tasks.CancelAsync(task.Id, Clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Warning,
|
||||
EngineEventCodes.RecipeNotConfigured,
|
||||
$"La tua richiesta ({RecipeName(request.Kind)}{Of(account)}) è annullata: {NotConfiguredReason(request.Kind)}",
|
||||
account?.Id,
|
||||
state.Context.SessionId,
|
||||
CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
var category = CheckPolicy.CategoryOf(request.Kind);
|
||||
if (state.Exhausted.Contains(category))
|
||||
{
|
||||
@@ -875,6 +1027,26 @@ internal sealed class SessionComposer
|
||||
$"Formato non riconosciuto durante {RecipeName(kind)}{Of(account)}: Instagram potrebbe aver cambiato le sue risposte.", now).ConfigureAwait(false);
|
||||
break;
|
||||
|
||||
case RecipeStatus.NotConfigured:
|
||||
// Not a failure: the files of the site do not let it run. Never counted towards suspension, not tried
|
||||
// again in this process (the runner has said why); a command of Alberto is dropped, planned work waits.
|
||||
lock (_configurationGate)
|
||||
{
|
||||
_notConfigured.TryAdd(kind, outcome.Message ?? $"«{ItalianText.Capitalize(RecipeName(kind))}» non può girare con la configurazione attuale.");
|
||||
_notConfiguredSaid.Add(kind);
|
||||
}
|
||||
|
||||
if (task is { IsManual: true })
|
||||
{
|
||||
writes.Add(Store.Tasks.CancelAsync(task.Id, now, ct));
|
||||
}
|
||||
else if (task is not null)
|
||||
{
|
||||
await RequeueAsync(task, "Configurazione incompleta", now).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case RecipeStatus.AccountUnreachable:
|
||||
if (task is not null)
|
||||
{
|
||||
@@ -955,9 +1127,10 @@ internal sealed class SessionComposer
|
||||
{
|
||||
case RecipeKind.ProfileCheck:
|
||||
{
|
||||
// A profile not followed is visited at the earlier of its post check and its story check.
|
||||
// A profile not followed is visited at the earlier of its post check and its story check (while the
|
||||
// stories can run: otherwise only for its posts).
|
||||
var next = now + CheckPolicy.NextCheckDelay(_s.Random, CheckPolicy.ProfileCheckInterval(account));
|
||||
DateTimeOffset? storiesNext = !account.IsFollowed && CheckPolicy.WantsStories(account)
|
||||
DateTimeOffset? storiesNext = VisitServesStories(account)
|
||||
? now + CheckPolicy.NextStoryCheckDelay(_s.Random, CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay))
|
||||
: null;
|
||||
state.LastVisitNext = storiesNext;
|
||||
@@ -1164,6 +1337,7 @@ internal sealed class SessionComposer
|
||||
RecipeStatus.UnrecognizedFormat => "Formato non riconosciuto",
|
||||
RecipeStatus.AccountUnreachable => "Non raggiungibile",
|
||||
RecipeStatus.Cancelled => "Interrotto",
|
||||
RecipeStatus.NotConfigured => "Configurazione della raccolta incompleta",
|
||||
_ => "Non riuscito",
|
||||
};
|
||||
return (title, detail);
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Threading.Channels;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
using Febe.Web.Library;
|
||||
using Febe.Web.Native;
|
||||
@@ -24,8 +25,8 @@ public static class EngineApi
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
|
||||
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
|
||||
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct) =>
|
||||
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
|
||||
|
||||
endpoints.MapPost("/api/engine/pause", async (IEngineControl control, CancellationToken ct) =>
|
||||
{
|
||||
@@ -78,13 +79,19 @@ public static class EngineApi
|
||||
endpoints.MapGet("/api/eventi", StreamAsync);
|
||||
}
|
||||
|
||||
/// <summary>The engine as the interface needs it.</summary>
|
||||
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct)
|
||||
/// <summary>
|
||||
/// The engine as the interface needs it. The link comes from the session cookie, never from whether «Tu» is known:
|
||||
/// the name of the connected account may come much later (H10), and meanwhile the sidebar says «Collegato» with
|
||||
/// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so; when it does not run
|
||||
/// (or there is none in this process) the connection is asked.
|
||||
/// </summary>
|
||||
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(monitor);
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(tracker);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(connection);
|
||||
var snapshot = await monitor.GetSnapshotAsync(ct).ConfigureAwait(false);
|
||||
var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
|
||||
var state = snapshot.Mode switch
|
||||
@@ -92,9 +99,10 @@ public static class EngineApi
|
||||
EngineMode.NotConnected => "notConnected",
|
||||
EngineMode.StoppedForVerification => "verification",
|
||||
EngineMode.Disconnected => "disconnected",
|
||||
_ => mine is null ? "notConnected" : "connected",
|
||||
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.Connected ? "connected" : "notConnected",
|
||||
_ => "connected",
|
||||
};
|
||||
var connection = state == "notConnected"
|
||||
var link = state == "notConnected"
|
||||
? new ConnectionDto(state, null, null, null)
|
||||
: new ConnectionDto(state, mine?.Username, mine?.DisplayName, null);
|
||||
|
||||
@@ -109,7 +117,7 @@ public static class EngineApi
|
||||
canResume = snapshot.Mode == EngineMode.Paused;
|
||||
}
|
||||
|
||||
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, connection, canResume);
|
||||
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, link, canResume);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -123,7 +131,8 @@ public static class EngineApi
|
||||
IFebeStorage storage,
|
||||
BrowserUseTracker tracker,
|
||||
LibraryChanges library,
|
||||
IClock clock)
|
||||
IClock clock,
|
||||
IConnectionService connection)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var response = context.Response;
|
||||
@@ -235,7 +244,7 @@ public static class EngineApi
|
||||
|
||||
async Task SendEngineAsync()
|
||||
{
|
||||
var dto = await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false);
|
||||
var dto = await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false);
|
||||
await WriteAsync(response, "event: motore\ndata: " + JsonSerializer.Serialize(dto, FebeJsonContext.Default.EngineDto) + "\n\n", ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ using Febe.Browser.Download;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
|
||||
namespace Febe.Tests.Browser;
|
||||
@@ -59,6 +61,174 @@ public sealed class CaptureUnitTests
|
||||
Assert.AreEqual(2, cdp.Sent.Count(c => c.Method == "Network.getResponseBody"), "Only JSON bodies are fetched.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task JavaScriptAnswersOfThePageAreDataButScriptFilesAreNot()
|
||||
{
|
||||
// Instagram serves its GraphQL data as «text/javascript» (HAR of 21/10/2026).
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
cdp.Responder = (method, p) => method switch
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "g1" => new JsonObject { ["body"] = """{"data":{"x":[1]}}""", ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "a1" => new JsonObject { ["body"] = """for (;;);{"payload":{}}""", ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" => new JsonObject { ["body"] = "var x = 1;", ["base64Encoded"] = false },
|
||||
_ => null,
|
||||
};
|
||||
var consumer = new CollectingConsumer();
|
||||
var observer = new CollectingObserver();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock);
|
||||
tap.AddConsumer(consumer);
|
||||
tap.AddObserver(observer);
|
||||
await tap.StartAsync();
|
||||
|
||||
cdp.Raise("Network.responseReceived", Received("g1", "http://127.0.0.1:5000/graphql/query", 200, "text/javascript; charset=utf-8", "XHR"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "g1", ["encodedDataLength"] = 20 });
|
||||
cdp.Raise("Network.responseReceived", Received("s1", "http://127.0.0.1:5001/bundle.js", 200, "text/javascript", "Script"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "s1", ["encodedDataLength"] = 10 });
|
||||
cdp.Raise("Network.responseReceived", Received("a1", "http://127.0.0.1:5000/ajax/navigation/", 200, "text/javascript", "XHR"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "a1", ["encodedDataLength"] = 24 });
|
||||
|
||||
await WaitUntilAsync(() => consumer.Items.Count == 1 && observer.Dropped.Contains("a1"));
|
||||
Assert.AreEqual("""{"data":{"x":[1]}}""", consumer.Items.Single().Json);
|
||||
Assert.AreEqual("XHR", consumer.Items.Single().Descriptor.ResourceType);
|
||||
Assert.IsFalse(cdp.Sent.Any(c => c.Method == "Network.getResponseBody" && c.Parameters?["requestId"]?.GetValue<string>() == "s1"), "A script file is never fetched.");
|
||||
Assert.AreEqual(1, tap.Stats.ParseErrors, "«for (;;);» is not JSON: skipped, and its waiters are told.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EveryJsonBlockOfThePageDocumentIsAnAnswerOfItsOwn()
|
||||
{
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
var tooDeep = new string('[', 300) + new string(']', 300);
|
||||
var html = $$"""
|
||||
<html><head><script type="application/json" data-sjs>{"a":1}</script><script>var b = 2;</script>
|
||||
<script type="application/json">{ non è json </script><script type="application/json">{{tooDeep}}</script>
|
||||
<script type="application/json"> </script></head>
|
||||
<body><script type="application/json">{"c":[3]}</script></body></html>
|
||||
""";
|
||||
cdp.Responder = (method, p) => method switch
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "L7" => new JsonObject { ["body"] = html, ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "r10" => new JsonObject { ["body"] = """{"d":4}""", ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" => new JsonObject { ["body"] = "<html><body>niente</body></html>", ["base64Encoded"] = false },
|
||||
_ => null,
|
||||
};
|
||||
var failing = new FailingConsumer();
|
||||
var consumer = new CollectingConsumer();
|
||||
var observer = new CollectingObserver();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock);
|
||||
tap.AddConsumer(failing);
|
||||
tap.AddConsumer(consumer);
|
||||
tap.AddObserver(observer);
|
||||
await tap.StartAsync();
|
||||
|
||||
// The frame commits the new document before its body has finished loading: the body is still read.
|
||||
cdp.Raise("Network.responseReceived", Document("L7", "http://127.0.0.1:5000/marta.prova/"));
|
||||
cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["loaderId"] = "L7", ["url"] = "http://127.0.0.1:5000/marta.prova/" } });
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L7", ["encodedDataLength"] = html.Length });
|
||||
|
||||
// A document without embedded JSON gives nothing; one of another host is not even fetched. A data answer after
|
||||
// them: the worker reads in order, so once it has arrived the documents have been dealt with.
|
||||
cdp.Raise("Network.responseReceived", Document("L8", "http://127.0.0.1:5000/vuota/"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L8", ["encodedDataLength"] = 30 });
|
||||
cdp.Raise("Network.responseReceived", Document("L9", "https://esterno.example/"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L9", ["encodedDataLength"] = 30 });
|
||||
cdp.Raise("Network.responseReceived", Received("r10", "http://127.0.0.1:5000/api/dopo", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "r10", ["encodedDataLength"] = 7 });
|
||||
await WaitUntilAsync(() => consumer.Items.Any(i => i.Descriptor.RequestId == "r10"));
|
||||
|
||||
// One answer per valid block, in the order of the document, each with the document's descriptor: a block that
|
||||
// is not JSON, is too deep or is blank is left out without being a parse error.
|
||||
var blocks = consumer.Items.Where(i => i.Descriptor.RequestId == "L7").ToList();
|
||||
CollectionAssert.AreEqual(new[] { """{"a":1}""", """{"c":[3]}""" }, blocks.Select(b => b.Json).ToArray());
|
||||
Assert.IsTrue(blocks.All(b => b.Descriptor.IsMainFrameDocument && b.Descriptor.MimeType == "text/html" && b.Descriptor.Path == "/marta.prova/"));
|
||||
Assert.AreEqual(0, tap.Stats.ParseErrors);
|
||||
Assert.AreEqual(3, tap.Stats.JsonBodies, "Two blocks and the answer after them.");
|
||||
|
||||
// A reader that fails on a block stops neither the other readers, nor the next block, nor the next answer.
|
||||
Assert.AreEqual(3, failing.Calls);
|
||||
|
||||
// Those who wait for a body are told once when nothing reached the readers, never when blocks did.
|
||||
Assert.IsFalse(observer.Dropped.Contains("L7"));
|
||||
Assert.AreEqual(1, observer.Dropped.Count(id => id == "L8"));
|
||||
Assert.IsFalse(cdp.Sent.Any(c => c.Method == "Network.getResponseBody" && c.Parameters?["requestId"]?.GetValue<string>() == "L9"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThePaginationOfAnEmbeddedBlockStaysWithTheBlockThatCarriesIt()
|
||||
{
|
||||
// Two real answers (cleaned samples of the HAR of 21/10/2026) embedded in one page document: first the
|
||||
// collections, which say «has_next_page: true» of themselves, then a post, which says «more_available: false»
|
||||
// of itself. Read as one answer, the post took the first pagination of the document, the collections'.
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
var html = $"""
|
||||
<!DOCTYPE html><html><head><script type="application/json">{SampleBody("raccolta-in-evidenza")}</script></head>
|
||||
<body><script type="application/json">{SampleBody("post-video")}</script></body></html>
|
||||
""";
|
||||
cdp.Responder = (method, p) => method switch
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "L7" => new JsonObject { ["body"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(html)), ["base64Encoded"] = true },
|
||||
"Network.getResponseBody" => new JsonObject { ["body"] = """{"segni":[1]}""", ["base64Encoded"] = false },
|
||||
_ => null,
|
||||
};
|
||||
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadInstagram()), clock);
|
||||
var after = new CollectingConsumer();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock);
|
||||
tap.AddConsumer(capture);
|
||||
tap.AddObserver(capture);
|
||||
tap.AddConsumer(after);
|
||||
await tap.StartAsync();
|
||||
|
||||
cdp.Raise("Network.responseReceived", Document("L7", "http://127.0.0.1:5000/marta.prova/"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L7", ["encodedDataLength"] = html.Length });
|
||||
cdp.Raise("Network.responseReceived", Received("r2", "http://127.0.0.1:5000/api/dopo", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "r2", ["encodedDataLength"] = 7 });
|
||||
await WaitUntilAsync(() => after.Items.Any(i => i.Descriptor.RequestId == "r2"));
|
||||
|
||||
var reads = capture.Since(0);
|
||||
Assert.AreEqual(2, reads.Count, "One read per block (the answer after them is not about contents).");
|
||||
Assert.IsTrue(reads.All(r => r.Response.RequestId == "L7" && r.Response.IsMainFrameDocument));
|
||||
var collections = reads[0].Result;
|
||||
Assert.AreEqual(2, collections.Highlights.Count);
|
||||
Assert.AreEqual(true, collections.Page?.HasMore);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(collections.Page?.Cursor));
|
||||
var post = reads[1].Result;
|
||||
Assert.AreEqual(0, post.Highlights.Count);
|
||||
Assert.AreEqual(1, post.Contents.Count);
|
||||
Assert.AreEqual(false, post.Page?.HasMore, "The post's own pagination, not the collections'.");
|
||||
Assert.IsNull(post.Page?.Cursor);
|
||||
Assert.AreEqual(0, capture.Pending, "Nothing is left on its way.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task BodiesThatWillNotComeAreReportedToObservers()
|
||||
{
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
cdp.Responder = (method, _) => method == "Page.getFrameTree"
|
||||
? new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } }
|
||||
: null;
|
||||
var observer = new CollectingObserver();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock, options: new ResponseTapOptions { MaxBodyBytes = 100 });
|
||||
tap.AddConsumer(new CollectingConsumer());
|
||||
tap.AddObserver(observer);
|
||||
await tap.StartAsync();
|
||||
|
||||
cdp.Raise("Network.responseReceived", Received("big", "http://127.0.0.1:5000/a", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "big", ["encodedDataLength"] = 1000 });
|
||||
cdp.Raise("Network.responseReceived", Received("fail", "http://127.0.0.1:5000/b", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFailed", new JsonObject { ["requestId"] = "fail" });
|
||||
cdp.Raise("Network.responseReceived", Received("old", "http://127.0.0.1:5000/c", 200, "application/json"));
|
||||
cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["loaderId"] = "L2", ["url"] = "http://127.0.0.1:5000/altra/" } });
|
||||
|
||||
CollectionAssert.AreEquivalent(new[] { "big", "fail", "old" }, observer.Dropped.ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MainFrameNavigationsAreReported()
|
||||
{
|
||||
@@ -229,15 +399,25 @@ public sealed class CaptureUnitTests
|
||||
Assert.IsFalse(gate.IsDriving);
|
||||
}
|
||||
|
||||
private static JsonObject Received(string id, string url, int status, string mime) => new()
|
||||
private static JsonObject Received(string id, string url, int status, string mime, string type = "Fetch") => new()
|
||||
{
|
||||
["requestId"] = id,
|
||||
["loaderId"] = "L1",
|
||||
["frameId"] = "F1",
|
||||
["type"] = "Fetch",
|
||||
["type"] = type,
|
||||
["response"] = new JsonObject { ["url"] = url, ["status"] = status, ["mimeType"] = mime },
|
||||
};
|
||||
|
||||
/// <summary>The response of a main-frame navigation: its request id is the loader id.</summary>
|
||||
private static JsonObject Document(string loader, string url) => new()
|
||||
{
|
||||
["requestId"] = loader,
|
||||
["loaderId"] = loader,
|
||||
["frameId"] = "F1",
|
||||
["type"] = "Document",
|
||||
["response"] = new JsonObject { ["url"] = url, ["status"] = 200, ["mimeType"] = "text/html; charset=utf-8" },
|
||||
};
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition)
|
||||
{
|
||||
for (var i = 0; i < 300 && !condition(); i++)
|
||||
@@ -248,17 +428,39 @@ public sealed class CaptureUnitTests
|
||||
Assert.IsTrue(condition(), "Condition not reached in time.");
|
||||
}
|
||||
|
||||
/// <summary>The body of a cleaned Instagram sample (<c>tests/campioni/instagram</c>), as JSON text.</summary>
|
||||
private static string SampleBody(string name)
|
||||
{
|
||||
var file = Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), $"*-{name}.json").Single();
|
||||
using var sample = JsonDocument.Parse(File.ReadAllText(file));
|
||||
return sample.RootElement.GetProperty("corpo").GetRawText();
|
||||
}
|
||||
|
||||
private sealed class CollectingConsumer : IResponseConsumer
|
||||
{
|
||||
public ConcurrentBag<(ResponseDescriptor Descriptor, string Json)> Items { get; } = [];
|
||||
/// <summary>In arrival order.</summary>
|
||||
public ConcurrentQueue<(ResponseDescriptor Descriptor, string Json)> Items { get; } = new();
|
||||
|
||||
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
|
||||
{
|
||||
Items.Add((response, body.RootElement.GetRawText()));
|
||||
Items.Enqueue((response, body.RootElement.GetRawText()));
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FailingConsumer : IResponseConsumer
|
||||
{
|
||||
private int _calls;
|
||||
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
|
||||
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
throw new InvalidOperationException("Lettore di prova che fallisce sempre.");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class CollectingObserver : IResponseObserver
|
||||
{
|
||||
public ConcurrentQueue<ResponseDescriptor> Responses { get; } = new();
|
||||
@@ -267,7 +469,11 @@ public sealed class CaptureUnitTests
|
||||
|
||||
public void OnResponse(ResponseDescriptor response) => Responses.Enqueue(response);
|
||||
|
||||
public ConcurrentQueue<string> Dropped { get; } = new();
|
||||
|
||||
public void OnNavigation(NavigationDescriptor navigation) => Navigations.Enqueue(navigation);
|
||||
|
||||
public void OnBodyDropped(string requestId) => Dropped.Enqueue(requestId);
|
||||
}
|
||||
|
||||
private sealed class SyncProgress(List<long> values) : IProgress<long>
|
||||
|
||||
@@ -34,11 +34,46 @@ public sealed class CollectionUnitTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheInstagramMapIsASkeletonWithEveryEntryEmpty()
|
||||
public void TheInstagramMapHasThePagesSeenInRealTrafficAndNoTargetYet()
|
||||
{
|
||||
var map = SiteMap.LoadInstagram();
|
||||
Assert.AreEqual("instagram", map.Site);
|
||||
Assert.AreEqual(SitePages.All.Count + SiteTargets.All.Count, map.Missing(SitePages.All, SiteTargets.All).Count, "Nothing is filled in before M0.");
|
||||
|
||||
// Pages: only those with evidence in the HAR of 21 October 2026 (Instagram's own route templates and the
|
||||
// Referer of the page's requests). The others have none and stay empty.
|
||||
string[] filled = [SitePages.Home, SitePages.Profile, SitePages.Post, SitePages.StoryViewer, SitePages.HighlightViewer];
|
||||
string[] empty = [SitePages.ProfileFrom, SitePages.ReelsFrom, SitePages.TaggedFrom, SitePages.Following, SitePages.FollowingFrom];
|
||||
CollectionAssert.AreEquivalent(SitePages.All.ToArray(), filled.Concat(empty).ToArray(), "Every page is decided.");
|
||||
Assert.IsTrue(filled.All(map.HasPage));
|
||||
CollectionAssert.AreEquivalent(empty.Select(p => $"pagina «{p}»").ToArray(), map.Missing(SitePages.All, []).ToArray());
|
||||
|
||||
Assert.AreEqual("/", map.BuildPath(SitePages.Home));
|
||||
Assert.AreEqual("/mario.rossi/", map.BuildPath(SitePages.Profile, new Dictionary<string, string> { ["username"] = "mario.rossi" }));
|
||||
Assert.AreEqual("/p/Abc_12-xYz9/", map.BuildPath(SitePages.Post, new Dictionary<string, string> { ["code"] = "Abc_12-xYz9" }));
|
||||
Assert.IsNotNull(map.Match(SitePages.Home, "/"));
|
||||
Assert.IsNull(map.Match(SitePages.Home, "/mario.rossi/"));
|
||||
Assert.AreEqual("mario.rossi", map.Match(SitePages.Profile, "/mario.rossi/")!["username"]);
|
||||
|
||||
// Viewers: matched only, never opened. The story viewer carries the account and the story shown.
|
||||
var story = map.Match(SitePages.StoryViewer, "/stories/mario/3456789012345678901/");
|
||||
Assert.AreEqual("mario", story!["username"]);
|
||||
Assert.AreEqual("3456789012345678901", story["id"]);
|
||||
Assert.IsNull(map.Match(SitePages.StoryViewer, "/stories/mario/"), "Without the story id the shape does not match (to be confirmed live).");
|
||||
Assert.IsNull(map.Match(SitePages.HighlightViewer, "/stories/mario/3456789012345678901/"));
|
||||
|
||||
// The highlight viewer: the 17 digits of the collection and no item id (the address stays the same while watching).
|
||||
var highlight = map.Match(SitePages.HighlightViewer, "/stories/highlights/17841400000000000/");
|
||||
CollectionAssert.AreEquivalent(new[] { "highlight" }, highlight!.Keys.ToArray());
|
||||
Assert.AreEqual("17841400000000000", highlight["highlight"]);
|
||||
|
||||
// Overlap: a highlight address also has the story viewer's shape, with «highlights» as user name. The story
|
||||
// recipe then sees «another account» and closes; the highlight recipe reads only its own page.
|
||||
Assert.AreEqual("highlights", map.Match(SitePages.StoryViewer, "/stories/highlights/17841400000000000/")!["username"]);
|
||||
|
||||
// Targets: none has evidence yet (the HAR had no documents and no element attributes).
|
||||
var missingTargets = map.Missing([], SiteTargets.All);
|
||||
Assert.AreEqual(SiteTargets.All.Count, missingTargets.Count);
|
||||
Assert.IsTrue(missingTargets.All(m => m.EndsWith("(vuoto)", StringComparison.Ordinal)), "Every target is listed, still empty.");
|
||||
|
||||
// The browser layer reads the same file: every target is a placeholder and is never looked up in the page.
|
||||
var targets = TargetMap.LoadEmbedded("bersagli.instagram.json");
|
||||
@@ -49,47 +84,77 @@ public sealed class CollectionUnitTests
|
||||
Assert.AreEqual(TargetStatus.NotConfigured, lookup.Status);
|
||||
Assert.AreEqual(0, cdp.Sent.Count, "A placeholder never reaches the page.");
|
||||
StringAssert.Contains(lookup.Message, "H11");
|
||||
|
||||
// The copy next to the executable is the same map.
|
||||
var copy = SiteMap.Load(Path.Combine(AppContext.BaseDirectory, "config", "bersagli.instagram.json"));
|
||||
CollectionAssert.AreEquivalent(map.Missing(SitePages.All, SiteTargets.All).ToArray(), copy.Missing(SitePages.All, SiteTargets.All).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecipesRefuseToRunOnInstagramWhileTheMapOrTheReadersAreSkeletons()
|
||||
public async Task OnInstagramOnlyRecipesThatNeedNoTargetGetPastTheMap()
|
||||
{
|
||||
using var temp = new TempFolder("ricette");
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var clock = new VirtualClock();
|
||||
var governor = new PermissiveGovernor();
|
||||
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
|
||||
RecipeEnvironment Environment(SiteMap map, ReaderVocabulary vocabulary) => new()
|
||||
|
||||
// The Instagram vocabulary is confirmed on real samples. To see which recipes get past the map without letting
|
||||
// any of them reach the page, the runs use a copy marked as a hypothesis: the readers' gate comes right after
|
||||
// the map's and stops them there.
|
||||
Assert.IsTrue(ReaderVocabulary.LoadInstagram().IsUsable, ReaderVocabulary.LoadInstagram().UnusableReason);
|
||||
var stopper = ReaderVocabulary.LoadInstagram() with { Status = VocabularyStatus.Hypothesis };
|
||||
Task<RecipeOutcome> RunAsync(RecipeKind kind) => new RecipeRunner(new RecipeEnvironment
|
||||
{
|
||||
Driver = new UntouchableDriver(),
|
||||
Capture = new CaptureCollector(new ShapeReader(vocabulary), clock),
|
||||
Capture = new CaptureCollector(new ShapeReader(stopper), clock),
|
||||
Governor = governor,
|
||||
Signals = new SignalDetector(SignalRules.LoadDefault(), new RecordingBreaker(), clock),
|
||||
Storage = db,
|
||||
SiteMap = map,
|
||||
SiteMap = SiteMap.LoadInstagram(),
|
||||
Clock = clock,
|
||||
Random = new SeededRandom(1),
|
||||
};
|
||||
}).RunAsync(new RecipeRequest(kind, 1), session, CancellationToken.None);
|
||||
|
||||
foreach (var kind in Enum.GetValues<RecipeKind>().Where(k => k != RecipeKind.FollowingSweep))
|
||||
static void Refused(RecipeKind kind, RecipeOutcome outcome, string missing)
|
||||
{
|
||||
var outcome = await new RecipeRunner(Environment(SiteMap.LoadInstagram(), ReaderVocabulary.LoadTestSite()))
|
||||
.RunAsync(new RecipeRequest(kind, 1), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.TargetNotFound, outcome.Status, kind.ToString());
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, outcome.Status, kind.ToString());
|
||||
StringAssert.Contains(outcome.Message, "mappa dei bersagli non è ancora compilata");
|
||||
StringAssert.Contains(outcome.Message, missing, kind.ToString());
|
||||
}
|
||||
|
||||
var sweep = await new RecipeRunner(Environment(SiteMap.LoadInstagram(), ReaderVocabulary.LoadTestSite()))
|
||||
.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
|
||||
StringAssert.Contains(sweep.Message, "pagina «home»");
|
||||
static void Passed(RecipeKind kind, RecipeOutcome outcome)
|
||||
{
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, outcome.Status, $"{kind}: {outcome.Message}");
|
||||
StringAssert.Contains(outcome.Message, "ipotesi", kind.ToString());
|
||||
}
|
||||
|
||||
var readers = await new RecipeRunner(Environment(SiteMap.LoadTestSite(), ReaderVocabulary.LoadInstagram()))
|
||||
.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.UnrecognizedFormat, readers.Status);
|
||||
StringAssert.Contains(readers.Message, "ipotesi");
|
||||
// Recipes that click something: every target is still empty (H11), while their pages are all there.
|
||||
foreach (var kind in new[] { RecipeKind.AccountStories, RecipeKind.Highlight, RecipeKind.Tagged, RecipeKind.Reels })
|
||||
{
|
||||
var outcome = await RunAsync(kind);
|
||||
Refused(kind, outcome, "(vuoto)");
|
||||
Assert.IsFalse(outcome.Message!.Contains("pagina «", StringComparison.Ordinal), $"{kind}: {outcome.Message}");
|
||||
}
|
||||
|
||||
// Recipes that only open pages.
|
||||
Passed(RecipeKind.FollowingSweep, await RunAsync(RecipeKind.FollowingSweep));
|
||||
Passed(RecipeKind.SinglePost, await RunAsync(RecipeKind.SinglePost));
|
||||
|
||||
// The profile check and the backfill need no target: the «not found» marker is looked up only when configured.
|
||||
foreach (var kind in new[] { RecipeKind.ProfileCheck, RecipeKind.Backfill })
|
||||
{
|
||||
Assert.IsFalse(RecipeRunner.Requirements(kind).Targets.Contains(SiteTargets.ProfileNotFound), kind.ToString());
|
||||
Passed(kind, await RunAsync(kind));
|
||||
}
|
||||
|
||||
// No evidence of the address of the following list.
|
||||
Refused(RecipeKind.FollowingList, await RunAsync(RecipeKind.FollowingList), $"pagina «{SitePages.Following}»");
|
||||
|
||||
Assert.AreEqual(0, governor.Requests.Count, "No permit asked, no gesture, no page.");
|
||||
Assert.IsTrue((await db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "mappa-incompleta"));
|
||||
var events = await db.Events.ListAsync(new EventQuery());
|
||||
Assert.IsTrue(events.Any(e => e.Code == "mappa-incompleta"));
|
||||
Assert.IsTrue(events.Any(e => e.Code == "lettori-incompleti"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Sonda;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The tools with which Alberto provides evidence from his own browser: the conversion of a HAR into the probe's raw
|
||||
/// format (<c>febe-sonda da-har</c>) and the targets snippet for the DevTools console. The HAR is synthetic, written by
|
||||
/// the test: invented generic values, nothing that claims to be Instagram's format.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class HarImportTests
|
||||
{
|
||||
private const string FirstBody = """{"dati":{"elementi":[{"numero":"5512345678","nome":"mario.rossi","larghezza":1080}]}}""";
|
||||
private const string SecondBody = """{"stato":"ok","persone":[{"nome":"lucia.bianchi"}]}""";
|
||||
private const string EmbeddedBlock = """{"profilo":{"nome":"mario.rossi","privato":false}}""";
|
||||
private const string SecondEmbeddedBlock = """{"pagina":{"altre":false},"elementi":[]}""";
|
||||
|
||||
/// <summary>The request parameter that names a GraphQL operation (the only part of a request body ever read).</summary>
|
||||
private const string Operation = HarImporter.OperationParameter;
|
||||
|
||||
[TestMethod]
|
||||
public void OnlyDataAnswersOfTheSiteAndEmbeddedDataAreKeptWithoutHeadersCookiesOrQueries()
|
||||
{
|
||||
using var temp = new TempFolder("har");
|
||||
var har = temp.Combine("prova.har");
|
||||
File.WriteAllText(har, SyntheticHar().ToJsonString());
|
||||
var raw = temp.Combine("grezzi");
|
||||
|
||||
var report = HarImporter.Import(har, raw);
|
||||
Assert.AreEqual(new HarImportReport(Entries: 12, DataResponses: 4, Documents: 1, DocumentBlocks: 2, OtherHosts: 2, NotData: 2, WithoutBody: 1, NotJson: 1, DocumentsWithoutData: 1), report);
|
||||
Assert.AreEqual(6, report.Written);
|
||||
|
||||
// Flat files named by number and kind: a GraphQL operation name only when it is one, never a path.
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { "000001-ProvaElencoQuery.json", "000002-risposta.json", "000003-ProvaPaginaSuccessivaQuery.json", "000004-risposta.json", "000005-documento.json", "000006-documento.json", "LEGGIMI.txt" },
|
||||
Directory.GetFiles(raw).Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray());
|
||||
|
||||
// Headers, cookies, query strings and request bodies never reach the output.
|
||||
foreach (var file in Directory.GetFiles(raw))
|
||||
{
|
||||
var text = File.ReadAllText(file);
|
||||
foreach (var secret in new[] { "segreto", "sessionid", "cookie", "igsh", "variables", "pacchetto", "nascosto", "payload", "esterno" })
|
||||
{
|
||||
Assert.IsFalse(text.Contains(secret, StringComparison.OrdinalIgnoreCase), $"{Path.GetFileName(file)}: {secret}");
|
||||
}
|
||||
}
|
||||
|
||||
var first = Sample(raw, "000001-ProvaElencoQuery.json");
|
||||
var descriptor = first["descrittore"]!;
|
||||
Assert.AreEqual("https://www.instagram.com/graphql/query", descriptor["indirizzo"]!.GetValue<string>());
|
||||
Assert.AreEqual("sito", descriptor["host"]!.GetValue<string>());
|
||||
Assert.AreEqual(200, descriptor["stato"]!.GetValue<int>());
|
||||
Assert.AreEqual("text/javascript", descriptor["tipo"]!.GetValue<string>(), "Lower case, no parameters.");
|
||||
Assert.AreEqual("XHR", descriptor["risorsa"]!.GetValue<string>());
|
||||
Assert.AreEqual("2026-10-21T15:35:04Z", descriptor["quando"]!.GetValue<string>(), "UTC, to the second.");
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(FirstBody), first["corpo"]), "The base64 body, decoded and parsed.");
|
||||
CollectionAssert.AreEquivalent(new[] { "descrittore", "corpo" }, first.AsObject().Select(p => p.Key).ToArray());
|
||||
|
||||
var second = Sample(raw, "000002-risposta.json");
|
||||
Assert.AreEqual("https://www.instagram.com/api/v1/prova/mario.rossi/info/", second["descrittore"]!["indirizzo"]!.GetValue<string>());
|
||||
Assert.AreEqual("Fetch", second["descrittore"]!["risorsa"]!.GetValue<string>());
|
||||
Assert.AreEqual("application/json", second["descrittore"]!["tipo"]!.GetValue<string>());
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(SecondBody), second["corpo"]));
|
||||
|
||||
// A page document: one sample per valid JSON block it embeds, in order and with the document's descriptor, as
|
||||
// Febe's capture hands them to the readers; nothing of its scripts.
|
||||
var page = Sample(raw, "000005-documento.json");
|
||||
Assert.AreEqual("Document", page["descrittore"]!["risorsa"]!.GetValue<string>());
|
||||
Assert.AreEqual("text/html", page["descrittore"]!["tipo"]!.GetValue<string>());
|
||||
Assert.AreEqual("https://www.instagram.com/mario.rossi/", page["descrittore"]!["indirizzo"]!.GetValue<string>());
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(EmbeddedBlock), page["corpo"]));
|
||||
var nextBlock = Sample(raw, "000006-documento.json");
|
||||
Assert.IsTrue(JsonNode.DeepEquals(page["descrittore"], nextBlock["descrittore"]));
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(SecondEmbeddedBlock), nextBlock["corpo"]));
|
||||
|
||||
// The folder is a raw folder like the probe's: «ripulisci» and «verifica» work on it unchanged.
|
||||
var clean = temp.Combine("ripuliti");
|
||||
var cleaned = new SampleSanitizer(key: new byte[32]).SanitizeFolder(raw, clean);
|
||||
Assert.AreEqual(6, cleaned.Files);
|
||||
var verify = SampleVerifier.Verify(raw, clean);
|
||||
Assert.IsTrue(verify.Passed, string.Join("; ", verify.Leaks.Select(l => $"{l.CleanFile} {l.Length} {l.Kind}")));
|
||||
Assert.IsFalse(File.ReadAllText(Path.Combine(clean, "000001-ProvaElencoQuery.json")).Contains("mario", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheConversionRefusesRepositoriesUsedFoldersAndFilesThatAreNotAHar()
|
||||
{
|
||||
using var temp = new TempFolder("har");
|
||||
var har = temp.Combine("prova.har");
|
||||
File.WriteAllText(har, SyntheticHar().ToJsonString());
|
||||
|
||||
// Raw output inside a repository: refused before anything is written.
|
||||
Directory.CreateDirectory(temp.Combine("progetto", ".git"));
|
||||
var inside = temp.Combine("progetto", "grezzi");
|
||||
StringAssert.Contains(Assert.ThrowsExactly<InvalidOperationException>(() => HarImporter.Import(har, inside)).Message, "fuori dal repository");
|
||||
Assert.IsFalse(Directory.Exists(inside));
|
||||
|
||||
// The HAR itself holds cookies: it is not read from inside a repository either.
|
||||
var harInside = temp.Combine("progetto", "prova.har");
|
||||
File.Copy(har, harInside);
|
||||
Assert.ThrowsExactly<InvalidOperationException>(() => HarImporter.Import(harInside, temp.Combine("altrove")));
|
||||
|
||||
// A folder that is already in use: refused, nothing is mixed or overwritten.
|
||||
var used = Directory.CreateDirectory(temp.Combine("usata")).FullName;
|
||||
File.WriteAllText(Path.Combine(used, "000001-risposta.json"), "{}");
|
||||
StringAssert.Contains(Assert.ThrowsExactly<InvalidOperationException>(() => HarImporter.Import(har, used)).Message, "non è vuota");
|
||||
Assert.AreEqual("{}", File.ReadAllText(Path.Combine(used, "000001-risposta.json")));
|
||||
|
||||
Assert.ThrowsExactly<FileNotFoundException>(() => HarImporter.Import(temp.Combine("manca.har"), temp.Combine("nuova1")));
|
||||
File.WriteAllText(temp.Combine("non-har.har"), """{"altro":[]}""");
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => HarImporter.Import(temp.Combine("non-har.har"), temp.Combine("nuova2")));
|
||||
File.WriteAllText(temp.Combine("rotto.har"), "{\"log\":");
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => HarImporter.Import(temp.Combine("rotto.har"), temp.Combine("nuova3")));
|
||||
File.WriteAllText(temp.Combine("elenco.har"), "[1,2]");
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => HarImporter.Import(temp.Combine("elenco.har"), temp.Combine("nuova4")));
|
||||
Assert.IsFalse(Directory.Exists(temp.Combine("nuova4")), "Nothing is created for a file that is not a HAR.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OnlyNamesOfTheSiteCodeNameAFile()
|
||||
{
|
||||
Assert.AreEqual("PolarisStoriesV3HighlightsPageQuery", HarImporter.OperationName("PolarisStoriesV3HighlightsPageQuery"));
|
||||
Assert.AreEqual("usePolarisRegisterInRecentSearchesMutation", HarImporter.OperationName(" usePolarisRegisterInRecentSearchesMutation "));
|
||||
Assert.AreEqual("ProvaAggiornamentiSubscription", HarImporter.OperationName("ProvaAggiornamentiSubscription"));
|
||||
foreach (var value in new[] { null, "", "Query", "mario.rossi", "mario_rossi", "Pagina di mario Query", "Profilo12345Query", "/mario.rossi/Query", "ProvaElenco" })
|
||||
{
|
||||
Assert.IsNull(HarImporter.OperationName(value), value ?? "null");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheTargetsSnippetOnlyListensAndReads()
|
||||
{
|
||||
var path = Febe.Tests.Desktop.Support.Repository.PathOf("tools", "bersagli", "raccogli-bersagli.js");
|
||||
var script = File.ReadAllText(path);
|
||||
|
||||
// The same deny-list as Febe's own page scripts: no gesture, no DOM change, no request, no cookie or storage.
|
||||
Febe.Browser.Cdp.ReadOnlyScriptGuard.EnsureReadOnly(script);
|
||||
foreach (var word in new[] { "preventDefault", "stopPropagation", "stopImmediatePropagation", "postMessage", "document.cookie", "cookieStore", "Storage", "indexedDB", "fetch(", "XMLHttpRequest", "sendBeacon", "WebSocket", "new Image", "innerHTML", "outerHTML", "classList", ".style", "setAttribute", "removeAttribute", "eval(", "Function(", "open(" })
|
||||
{
|
||||
Assert.IsFalse(script.Contains(word, StringComparison.Ordinal), word);
|
||||
}
|
||||
|
||||
// One capturing click listener, and the function that copies the records.
|
||||
foreach (var part in new[] { "addEventListener('click', onClick, { capture: true, passive: true })", "globalThis.febeBersagli = ", "copy(text)" })
|
||||
{
|
||||
Assert.IsTrue(script.Contains(part, StringComparison.Ordinal), part);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, script.Split("addEventListener").Length - 1, "A single listener.");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(Path.GetDirectoryName(path)!, "LEGGIMI.md")));
|
||||
}
|
||||
|
||||
private static JsonNode Sample(string folder, string name) => JsonNode.Parse(File.ReadAllText(Path.Combine(folder, name)))!;
|
||||
|
||||
private static string Base64(string text) => Convert.ToBase64String(Encoding.UTF8.GetBytes(text));
|
||||
|
||||
private static JsonObject SyntheticHar()
|
||||
{
|
||||
static JsonArray Headers(params (string Name, string Value)[] headers) =>
|
||||
[.. headers.Select(h => (JsonNode)new JsonObject { ["name"] = h.Name, ["value"] = h.Value })];
|
||||
|
||||
static JsonObject Entry(string resourceType, string method, string url, int status, JsonObject content, JsonObject? postData = null, string started = "2026-10-21T17:35:04.512+02:00")
|
||||
{
|
||||
var request = new JsonObject
|
||||
{
|
||||
["method"] = method,
|
||||
["url"] = url,
|
||||
["httpVersion"] = "h3",
|
||||
["headers"] = Headers(("Cookie", "sessionid=segreto-cookie; ds_user_id=segreto-cookie"), ("X-Prova", "segreto-intestazione")),
|
||||
["queryString"] = new JsonArray(new JsonObject { ["name"] = "variables", ["value"] = "segreto-indirizzo" }),
|
||||
["cookies"] = new JsonArray(new JsonObject { ["name"] = "sessionid", ["value"] = "segreto-cookie" }),
|
||||
["headersSize"] = -1,
|
||||
["bodySize"] = 0,
|
||||
};
|
||||
if (postData is not null)
|
||||
{
|
||||
request["postData"] = postData;
|
||||
}
|
||||
|
||||
return new JsonObject
|
||||
{
|
||||
["_resourceType"] = resourceType,
|
||||
["startedDateTime"] = started,
|
||||
["time"] = 123.4,
|
||||
["request"] = request,
|
||||
["response"] = new JsonObject
|
||||
{
|
||||
["status"] = status,
|
||||
["statusText"] = "",
|
||||
["httpVersion"] = "h3",
|
||||
["headers"] = Headers(("Set-Cookie", "prova=segreto-risposta"), ("Content-Type", "text/plain; segreto-intestazione")),
|
||||
["cookies"] = new JsonArray(new JsonObject { ["name"] = "prova", ["value"] = "segreto-risposta" }),
|
||||
["content"] = content,
|
||||
["redirectURL"] = "",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
static JsonObject Content(string mime, string? text, bool base64 = false)
|
||||
{
|
||||
var content = new JsonObject { ["size"] = text?.Length ?? 0, ["mimeType"] = mime };
|
||||
if (text is not null)
|
||||
{
|
||||
content["text"] = base64 ? Base64(text) : text;
|
||||
if (base64)
|
||||
{
|
||||
content["encoding"] = "base64";
|
||||
}
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
static JsonObject Form(string text, params (string Name, string Value)[] parameters)
|
||||
{
|
||||
var form = new JsonObject { ["mimeType"] = "application/x-www-form-urlencoded", ["text"] = text };
|
||||
if (parameters.Length > 0)
|
||||
{
|
||||
form["params"] = Headers(parameters);
|
||||
}
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
var page = $$"""
|
||||
<!DOCTYPE html><html><head>
|
||||
<script>var nascosto = "segreto-script";</script>
|
||||
<script type="application/json" data-prova="1">{{EmbeddedBlock}}</script>
|
||||
<script type="application/json">{ "rotto": </script>
|
||||
</head><body><p>segreto-testo-della-pagina</p><script type="application/json">{{SecondEmbeddedBlock}}</script></body></html>
|
||||
""";
|
||||
|
||||
return new JsonObject
|
||||
{
|
||||
["log"] = new JsonObject
|
||||
{
|
||||
["version"] = "1.2",
|
||||
["creator"] = new JsonObject { ["name"] = "WebInspector", ["version"] = "537.36" },
|
||||
["pages"] = new JsonArray(),
|
||||
["entries"] = new JsonArray(
|
||||
Entry("xhr", "POST", "https://www.instagram.com/graphql/query?variables=segreto-indirizzo", 200, Content("text/javascript; charset=utf-8", FirstBody, base64: true),
|
||||
Form($"av=segreto-corpo&{Operation}=ProvaElencoQuery&variables=segreto-corpo", ("av", "segreto-corpo"), (Operation, "ProvaElencoQuery"), ("variables", "segreto-corpo"))),
|
||||
Entry("fetch", "GET", "https://www.instagram.com/api/v1/prova/mario.rossi/info/?segreto=1", 200, Content("application/json", SecondBody)),
|
||||
Entry("xhr", "POST", "https://www.instagram.com/graphql/query", 200, Content("application/json", """{"pagina":{"cursore":"QVFIUjBz","altre":true}}"""),
|
||||
Form($"{Operation}=ProvaPaginaSuccessivaQuery&x=segreto-corpo")),
|
||||
Entry("xhr", "POST", "https://www.instagram.com/api/graphql", 200, Content("text/javascript", """{"dati":{"vuoto":null}}"""),
|
||||
Form($"{Operation}=mario.rossi", (Operation, "mario.rossi"))),
|
||||
Entry("script", "GET", "https://www.instagram.com/static/pacchetto.js", 200, Content("text/javascript", "console.log('segreto-script')")),
|
||||
Entry("image", "GET", "https://scontent.cdninstagram.com/v/foto.jpg?firma=segreto-indirizzo", 200, Content("image/jpeg", "segreto-immagine", base64: true)),
|
||||
Entry("document", "GET", "https://www.instagram.com/mario.rossi/?igsh=segreto-indirizzo", 200, Content("text/html; charset=utf-8", page)),
|
||||
Entry("xhr", "POST", "https://www.instagram.com/ajax/prova/", 200, Content("text/javascript", """for (;;);{"payload":{"segreto":1}}""")),
|
||||
Entry("document", "GET", "https://www.instagram.com/altro/", 200, Content("text/html", "<html><body>segreto-senza-dati</body></html>")),
|
||||
Entry("xhr", "GET", "https://www.instagram.com/api/v1/vuota/", 200, Content("application/json", null)),
|
||||
Entry("fetch", "GET", "https://esterno.example/api/?segreto=1", 200, Content("application/json", """{"segreto":1}""")),
|
||||
Entry("fetch", "GET", "https://scontent.cdninstagram.com/v/dati.json", 200, Content("application/json", """{"segreto":1}"""))),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The reader with the Instagram vocabulary on the cleaned real samples of <c>tests/campioni/instagram</c>: answers
|
||||
/// Alberto's browser received on 21 October 2026 (HAR), cleaned with «febe-sonda ripulisci» and checked with
|
||||
/// «febe-sonda verifica» (spec §14.5, rule 10). Values are fakes of the same shape: the tests check shapes, sizes,
|
||||
/// dates and counts.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class InstagramReaderTests
|
||||
{
|
||||
private static readonly ReaderVocabulary Vocabulary = ReaderVocabulary.LoadInstagram();
|
||||
private static readonly ShapeReader Reader = new(Vocabulary);
|
||||
|
||||
private static string SampleFile(string name) =>
|
||||
Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), $"*-{name}.json").Single();
|
||||
|
||||
private static ReadResult ReadSample(string name)
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(SampleFile(name)));
|
||||
return Reader.Read(document.RootElement.GetProperty("corpo"));
|
||||
}
|
||||
|
||||
private static string SampleBody(string name)
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(SampleFile(name)));
|
||||
return document.RootElement.GetProperty("corpo").GetRawText();
|
||||
}
|
||||
|
||||
private static string MimeOf(string name)
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(SampleFile(name)));
|
||||
return document.RootElement.GetProperty("descrittore").GetProperty("tipo").GetString()!;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheInstagramVocabularyIsConfirmedAndUsable()
|
||||
{
|
||||
Assert.AreEqual(VocabularyStatus.Confirmed, Vocabulary.Status);
|
||||
Assert.IsTrue(Vocabulary.IsUsable, Vocabulary.UnusableReason);
|
||||
Assert.AreEqual(0, Vocabulary.MissingConcepts.Count);
|
||||
Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "lettori.instagram.json")), "Editable without recompiling.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryKeyOfTheVocabularyComesFromTheRealSamples()
|
||||
{
|
||||
// Rule 10: the format is not invented. Every path of lettori.instagram.json exists, as nested keys, somewhere in
|
||||
// the cleaned samples; every relevance key is a key of the samples.
|
||||
var paths = new HashSet<string>(StringComparer.Ordinal);
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var file in Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), "*.json"))
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(file));
|
||||
Collect(document.RootElement.GetProperty("corpo"), paths, names);
|
||||
}
|
||||
|
||||
var concepts = new[]
|
||||
{
|
||||
Vocabulary.Content.Id, Vocabulary.Content.Code, Vocabulary.Content.TakenAt, Vocabulary.Content.Caption, Vocabulary.Content.Images,
|
||||
Vocabulary.Content.Videos, Vocabulary.Content.Children, Vocabulary.Content.ChildCount, Vocabulary.Content.Owner, Vocabulary.Content.Pinned,
|
||||
Vocabulary.Content.ExpiresAt, Vocabulary.Content.Duration, Vocabulary.Version.Url, Vocabulary.Version.Width, Vocabulary.Version.Height,
|
||||
Vocabulary.Version.HasAudio, Vocabulary.Profile.Id, Vocabulary.Profile.Username, Vocabulary.Profile.DisplayName, Vocabulary.Profile.IsPrivate,
|
||||
Vocabulary.Profile.IsFollowed, Vocabulary.Profile.PostCount, Vocabulary.Profile.Picture, Vocabulary.Profile.LatestStoryAt,
|
||||
Vocabulary.Highlight.Id, Vocabulary.Highlight.Title, Vocabulary.Highlight.Owner, Vocabulary.Highlight.Items,
|
||||
Vocabulary.Page.HasMore, Vocabulary.Page.Cursor, Vocabulary.Viewer,
|
||||
};
|
||||
foreach (var path in concepts.SelectMany(c => c.Paths))
|
||||
{
|
||||
Assert.IsTrue(paths.Contains(path), $"«{path}» non compare in nessun campione ripulito di Instagram.");
|
||||
}
|
||||
|
||||
foreach (var key in Vocabulary.Relevance)
|
||||
{
|
||||
Assert.IsTrue(names.Contains(key), $"«{key}» non compare in nessun campione ripulito di Instagram.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GraphQlAnswersComeAsJavaScriptAndAreReadAsData()
|
||||
{
|
||||
// Why the capture reads «text/javascript»: the stories and highlights data of the samples was served that way.
|
||||
Assert.AreEqual("text/javascript", MimeOf("raccolta-in-evidenza"));
|
||||
Assert.AreEqual("application/json", MimeOf("post-video"));
|
||||
Assert.IsTrue(DataResponses.IsData("text/javascript", "XHR"));
|
||||
Assert.IsTrue(DataResponses.IsData("text/javascript", "Fetch"));
|
||||
Assert.IsTrue(DataResponses.IsData("application/x-javascript", "XHR"));
|
||||
Assert.IsTrue(DataResponses.IsData("application/json", "Fetch"));
|
||||
Assert.IsTrue(DataResponses.IsData("application/json", null));
|
||||
Assert.IsFalse(DataResponses.IsData("text/javascript", "Script"), "Script files are never parsed.");
|
||||
Assert.IsFalse(DataResponses.IsData("text/javascript", null));
|
||||
Assert.IsFalse(DataResponses.IsData("text/html", "Document"));
|
||||
Assert.IsFalse(DataResponses.IsData("video/mp4", "Fetch"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AHighlightPageGivesTheCollectionsTheirStoriesAndTheirOwner()
|
||||
{
|
||||
var result = ReadSample("raccolta-in-evidenza");
|
||||
Assert.AreEqual(ReadShape.Recognized, result.Shape);
|
||||
Assert.AreEqual(2, result.Highlights.Count);
|
||||
foreach (var highlight in result.Highlights)
|
||||
{
|
||||
// «highlight:<17 digits>» in the data, «/stories/highlights/<17 digits>/» in the address: the reader keeps
|
||||
// the address form (the cleaned samples fake the letters of the prefix, not its shape).
|
||||
StringAssert.Matches(highlight.Id, new System.Text.RegularExpressions.Regex("^[0-9]{17}$"));
|
||||
Assert.AreEqual(4, highlight.Items.Count);
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(highlight.Title));
|
||||
Assert.IsNotNull(highlight.Owner);
|
||||
Assert.IsTrue(highlight.Items.All(i => i.HighlightId == highlight.Id));
|
||||
|
||||
// The «user» of each item has only an identifier: the author is the owner of the collection.
|
||||
Assert.IsTrue(highlight.Items.All(i => i.Owner?.Id == highlight.Owner.Id && i.Owner.Username == highlight.Owner.Username));
|
||||
Assert.IsTrue(highlight.Items.All(i => i.ExpiresAt > i.TakenAt), "Highlight items keep the expiry they had as stories.");
|
||||
Assert.IsTrue(highlight.Items.All(i => i.Code is { Length: 11 }));
|
||||
Assert.IsTrue(highlight.Items.All(i => i.IsComplete && i.Files.Count == 1));
|
||||
}
|
||||
|
||||
Assert.AreEqual(result.Highlights.Sum(h => h.Items.Count), result.Contents.Count);
|
||||
Assert.IsFalse(result.Contents.Any(c => c.ExpiresAt is null && c.HighlightId is null), "Nothing here looks like a post.");
|
||||
Assert.AreEqual(true, result.Page?.HasMore);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(result.Page?.Cursor));
|
||||
Assert.IsTrue(result.Profiles.Any(p => p.Id == result.Highlights[0].Owner!.Id && p.IsPrivate == false));
|
||||
Assert.IsNull(result.Viewer, "xdt_viewer.user has no user name: the connected account is not recognized from it alone (H10).");
|
||||
Assert.IsNotNull(result.ViewerId, "Its identifier is kept, to recognize its profile in other answers.");
|
||||
Assert.IsFalse(result.Profiles.Any(p => p.Id == result.ViewerId), "In this answer the connected account has no profile.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void StoryFilesTakeTheLargestImageAndTheFirstVideoVersion()
|
||||
{
|
||||
var items = ReadSample("raccolta-in-evidenza").Contents;
|
||||
var photos = items.Where(i => i.Files[0].Kind == MediaKind.Photo).ToList();
|
||||
var videos = items.Where(i => i.Files[0].Kind == MediaKind.Video).ToList();
|
||||
Assert.IsTrue(photos.Count > 0 && videos.Count > 0);
|
||||
|
||||
// The largest of the 10–14 candidates: 1206×2144 or 640×1136 in the samples.
|
||||
Assert.IsTrue(items.All(i => i.Files[0].Kind == MediaKind.Video || i.Files[0].Best.Area >= 640 * 1136));
|
||||
Assert.IsTrue(photos.All(p => p.Files[0].Best.Url.EndsWith(".jpg", StringComparison.Ordinal)));
|
||||
|
||||
// Story video versions (type 101, 102, 103) carry no size: the first one is taken, with the cover image.
|
||||
foreach (var video in videos.Select(v => v.Files[0]))
|
||||
{
|
||||
Assert.IsTrue(video.Best.Url.EndsWith(".mp4", StringComparison.Ordinal));
|
||||
Assert.IsNull(video.Best.Width);
|
||||
Assert.IsNotNull(video.Cover);
|
||||
Assert.IsTrue(video.Duration > TimeSpan.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheNextPageOfHighlightsIsReadLikeTheFirst()
|
||||
{
|
||||
var result = ReadSample("raccolta-pagina-successiva");
|
||||
var highlight = result.Highlights.Single();
|
||||
Assert.AreEqual(3, highlight.Items.Count);
|
||||
Assert.IsNotNull(highlight.Owner);
|
||||
Assert.IsNotNull(result.Page);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void APostPageGivesTheVideoItsCoverTheCaptionAndTheAuthor()
|
||||
{
|
||||
var result = ReadSample("post-video");
|
||||
Assert.AreEqual(ReadShape.Recognized, result.Shape);
|
||||
var post = result.Contents.Single();
|
||||
Assert.AreEqual(11, post.Code?.Length);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(post.Caption), "The caption is an object: its text is in caption.text.");
|
||||
Assert.IsNull(post.ExpiresAt);
|
||||
Assert.IsNull(post.HighlightId);
|
||||
Assert.IsTrue(post.IsComplete);
|
||||
Assert.IsNotNull(post.Owner);
|
||||
Assert.AreEqual(false, post.Owner.IsFollowed, "friendship_status.following of the author.");
|
||||
Assert.AreEqual(false, post.Owner.IsPrivate);
|
||||
Assert.IsNotNull(post.Owner.Picture);
|
||||
Assert.AreEqual(960, post.Owner.Picture.Width, "hd_profile_pic_url_info, the largest picture.");
|
||||
Assert.IsNotNull(post.Owner.LatestStoryAt);
|
||||
|
||||
var video = post.Files.Single();
|
||||
Assert.AreEqual(MediaKind.Video, video.Kind);
|
||||
Assert.AreEqual((720, 1280), (video.Best.Width, video.Best.Height));
|
||||
Assert.IsTrue(video.Best.Url.EndsWith(".mp4", StringComparison.Ordinal));
|
||||
Assert.AreEqual((720, 1280), (video.Cover?.Width, video.Cover?.Height), "The largest of the 12 candidates.");
|
||||
Assert.AreEqual(5.919, video.Duration!.Value.TotalSeconds, 0.001);
|
||||
Assert.AreEqual(false, result.Page?.HasMore, "more_available of the REST answer.");
|
||||
|
||||
var now = new DateTimeOffset(2026, 10, 25, 12, 0, 0, TimeSpan.Zero);
|
||||
var media = ReadMapping.ToMedia(post, now).Single();
|
||||
Assert.AreEqual(MediaKind.Video, media.Kind);
|
||||
Assert.AreEqual(video.Best.Url, media.SourceUrl);
|
||||
Assert.AreEqual(video.Cover!.Url, media.CoverUrl);
|
||||
Assert.AreEqual(post.TakenAt, ReadMapping.ToEntry(post, 1, EntryKind.Post, now).PublishedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheProfilesOfSearchSuggestionsAndCommentsAreProfilesOnly()
|
||||
{
|
||||
var search = ReadSample("ricerca-profili");
|
||||
Assert.AreEqual(ReadShape.Recognized, search.Shape);
|
||||
Assert.AreEqual(5, search.Profiles.Count);
|
||||
Assert.AreEqual(0, search.Contents.Count);
|
||||
|
||||
var suggested = ReadSample("profili-suggeriti");
|
||||
Assert.AreEqual(3, suggested.Profiles.Count);
|
||||
Assert.IsTrue(suggested.Profiles.All(p => p.IsFollowed == false), "Suggested profiles are not followed.");
|
||||
Assert.AreEqual(0, suggested.Contents.Count);
|
||||
|
||||
var comments = ReadSample("commenti");
|
||||
Assert.AreEqual(0, comments.Contents.Count);
|
||||
Assert.IsTrue(comments.Profiles.Count > 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AnswersAboutOtherThingsAreUnrelatedNotAnUnknownFormat()
|
||||
{
|
||||
foreach (var name in new[] { "promozioni", "storia-vista" })
|
||||
{
|
||||
var result = ReadSample(name);
|
||||
Assert.AreEqual(ReadShape.Unrelated, result.Shape, name);
|
||||
Assert.IsNull(result.KeyStructure, name);
|
||||
}
|
||||
|
||||
// A response that speaks of contents but in keys nobody knows is still an unknown format (spec §6.4).
|
||||
var changed = Reader.Read("""{"data":{"feed":{"items":[{"pk":"1","taken_at":1777663535,"image_versions3":{"candidates":[]}}]}}}""");
|
||||
Assert.AreEqual(ReadShape.Unrecognized, changed.Shape);
|
||||
Assert.IsNotNull(changed.KeyStructure);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheCollectorKeepsNothingOfUnrelatedAnswers()
|
||||
{
|
||||
var clock = new Febe.Tests.Browser.TestSupport.VirtualClock();
|
||||
var collector = new CaptureCollector(Reader, clock);
|
||||
var observer = (IResponseObserver)collector;
|
||||
var descriptor = new ResponseDescriptor("r1", HostKind.Site, "https://www.instagram.com/api/graphql", "www.instagram.com", "/api/graphql", 200, "text/javascript", "XHR", false, clock.Now);
|
||||
observer.OnResponse(descriptor);
|
||||
Assert.AreEqual(1, collector.Pending, "A JavaScript data answer is awaited like a JSON one.");
|
||||
var mark = collector.Mark();
|
||||
using (var promo = JsonDocument.Parse(File.ReadAllText(SampleFile("promozioni"))))
|
||||
{
|
||||
Assert.IsNull(collector.Accept(descriptor, promo.RootElement.GetProperty("corpo")));
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, collector.Pending);
|
||||
Assert.AreEqual(mark, collector.Mark(), "An unrelated answer is not «something new arrived».");
|
||||
using var highlights = JsonDocument.Parse(File.ReadAllText(SampleFile("raccolta-in-evidenza")));
|
||||
Assert.IsNotNull(collector.Accept(descriptor with { RequestId = "r2" }, highlights.RootElement.GetProperty("corpo")));
|
||||
Assert.AreEqual(ReadShape.Recognized, collector.Since(mark).Single().Result.Shape);
|
||||
|
||||
observer.OnResponse(descriptor with { RequestId = "r3", ResourceType = "Script" });
|
||||
Assert.AreEqual(0, collector.Pending, "A script file is not data.");
|
||||
|
||||
// The connected account's identifier is remembered even from an answer that is otherwise not kept.
|
||||
using var unrelated = JsonDocument.Parse("""{"data":{"xdt_viewer":{"user":{"id":"5512345","pk":"5512345"}},"segni":[1]}}""");
|
||||
var before = collector.Mark();
|
||||
Assert.IsNull(collector.Accept(descriptor with { RequestId = "r4" }, unrelated.RootElement));
|
||||
Assert.AreEqual(before, collector.Mark());
|
||||
Assert.AreEqual("5512345", collector.ViewerId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheDataEmbeddedInAPageDocumentIsReadLikeAnAnswer()
|
||||
{
|
||||
// Each valid block is an answer of its own, as the capture hands it to the readers: the collections (which say
|
||||
// «has_next_page: true» of themselves) and the post (which says «more_available: false» of itself) keep each
|
||||
// their own pagination, whatever their order in the document.
|
||||
var head = $$"""
|
||||
<!DOCTYPE html><html><head>
|
||||
<script type="application/json" data-sjs>{"require":[["Bootloader","handle",null,[{"x":1}]]]}</script>
|
||||
<script>var notData = {"a":1};</script>
|
||||
<script type="application/json">{ not json </script>
|
||||
<script type="application/json">{{SampleBody("raccolta-in-evidenza")}}</script>
|
||||
</head><body>
|
||||
<script type="application/json" data-content-len="9" data-sjs>{"require":[["ScheduledServerJS","handle",null,[{"__bbox":{"result":{"data":
|
||||
""";
|
||||
var html = head + SampleBody("post-video") + """}}}]]]}</script></body></html>""";
|
||||
var reads = new List<ReadResult>();
|
||||
foreach (var block in DataResponses.EmbeddedJsonBlocks(html))
|
||||
{
|
||||
using (block)
|
||||
{
|
||||
reads.Add(Reader.Read(block.RootElement));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.AreEqual(3, reads.Count, "Only the valid application/json blocks, in order.");
|
||||
Assert.AreEqual(ReadShape.Unrelated, reads[0].Shape, "The loader's block is not about contents.");
|
||||
Assert.AreEqual(2, reads[1].Highlights.Count);
|
||||
Assert.AreEqual(true, reads[1].Page?.HasMore);
|
||||
Assert.AreEqual(ReadShape.Recognized, reads[2].Shape);
|
||||
Assert.AreEqual(1, reads[2].Contents.Count);
|
||||
Assert.AreEqual(0, reads[2].Highlights.Count);
|
||||
Assert.AreEqual(false, reads[2].Page?.HasMore, "The post's own pagination, not the collections'.");
|
||||
|
||||
Assert.IsFalse(DataResponses.EmbeddedJsonBlocks("<html><script>var a = 1;</script></html>").Any());
|
||||
Assert.IsTrue(DataResponses.IsPageDocument("text/html", isMainFrameDocument: true));
|
||||
Assert.IsFalse(DataResponses.IsPageDocument("text/html", isMainFrameDocument: false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ABadBlockOfAPageDocumentIsLeftOutAndTheNextOnesAreStillRead()
|
||||
{
|
||||
// Text that is not valid UTF-16 (a lone surrogate: JsonDocument throws ArgumentException, not JsonException),
|
||||
// a block nested deeper than any body may be, a blank one: none of them stops the reading of the document.
|
||||
const string Open = """<script type="application/json">""";
|
||||
var html = Open + "{\"a\":\"\ud800\"}</script>" + Open + new string('[', 300) + new string(']', 300) + "</script>"
|
||||
+ Open + " </script>" + Open + """{"b":[2]}</script>""";
|
||||
var blocks = new List<string>();
|
||||
foreach (var block in DataResponses.EmbeddedJsonBlocks(html))
|
||||
{
|
||||
using (block)
|
||||
{
|
||||
blocks.Add(block.RootElement.GetRawText());
|
||||
}
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { """{"b":[2]}""" }, blocks);
|
||||
}
|
||||
|
||||
private static void Collect(JsonElement element, HashSet<string> paths, HashSet<string> names)
|
||||
{
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
names.Add(property.Name);
|
||||
paths.Add(property.Name);
|
||||
foreach (var below in NestedPaths(property.Value))
|
||||
{
|
||||
paths.Add(property.Name + "." + below);
|
||||
}
|
||||
|
||||
Collect(property.Value, paths, names);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
Collect(item, paths, names);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Dotted paths of object keys directly below <paramref name="element"/> (two levels are enough here).</summary>
|
||||
private static IEnumerable<string> NestedPaths(JsonElement element)
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
yield return property.Name;
|
||||
if (property.Value.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var deeper in property.Value.EnumerateObject())
|
||||
{
|
||||
yield return property.Name + "." + deeper.Name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,820 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Tests.Collection.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The recipes of the profile, the history, the sweep and the following list over answers shaped like Instagram's,
|
||||
/// without a browser: the cleaned real samples of <c>tests/campioni/instagram</c> (HAR of 21 October 2026), and
|
||||
/// variants built here from them where Instagram's answer is not in the samples (the profile, the grid, the feed, the
|
||||
/// stories bar, the following list: REPERTI «Not in the sample»). The variants use only keys of the samples and move
|
||||
/// their parts around; they say nothing new about Instagram's format. Unlike the test site, the page receives what it
|
||||
/// shows in several answers, one after the other, and answers about something else in between.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class InstagramRecipeTests
|
||||
{
|
||||
private const string AlbertoId = "1000";
|
||||
|
||||
[TestMethod]
|
||||
public void TheNotFoundMarkerIsOptionalAndTheTabsStillNeedTheirTargets()
|
||||
{
|
||||
foreach (var kind in new[] { RecipeKind.ProfileCheck, RecipeKind.Backfill })
|
||||
{
|
||||
Assert.AreEqual(0, RecipeRunner.Requirements(kind).Targets.Count, kind.ToString());
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { SiteTargets.ProfileTabTagged }, RecipeRunner.Requirements(RecipeKind.Tagged).Targets.ToArray());
|
||||
CollectionAssert.AreEqual(new[] { SiteTargets.ProfileTabReels }, RecipeRunner.Requirements(RecipeKind.Reels).Targets.ToArray());
|
||||
|
||||
var map = InstagramBed.Map();
|
||||
var (pages, targets) = RecipeRunner.Requirements(RecipeKind.ProfileCheck);
|
||||
Assert.AreEqual(0, map.Missing(pages, targets).Count, "The profile page is enough for the check.");
|
||||
var tagged = RecipeRunner.Requirements(RecipeKind.Tagged);
|
||||
CollectionAssert.AreEqual(new[] { $"bersaglio «{SiteTargets.ProfileTabTagged}» (vuoto)" }, map.Missing(tagged.Pages, tagged.Targets).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheProfileCheckKeepsTheGridAndTheCollectionsThatComeAfterTheProfile()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2002", "marta.prova");
|
||||
var marta = Author("2002", "marta.prova");
|
||||
|
||||
// The profile first; the grid asked for only after the page has settled on it; then the collections and a
|
||||
// post of another account, both saying there is nothing more of themselves.
|
||||
bed.Page.OnOpen["/marta.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(marta), TimeSpan.Zero, TimeSpan.FromMilliseconds(300)),
|
||||
new(Grid(Posts(marta, 0, 12, bed.Clock.Now.AddDays(-1)), "griglia-12", hasNext: true), TimeSpan.FromSeconds(1.5), TimeSpan.FromSeconds(1.9)),
|
||||
new(Highlights("2002", "marta.prova", hasNext: false), TimeSpan.FromSeconds(1.9), TimeSpan.FromSeconds(2.3)),
|
||||
new(Sample("post-video"), TimeSpan.FromSeconds(2.0), TimeSpan.FromSeconds(2.5)),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual(12, (await bed.PostIdsAsync(account.Id)).Count, "The grid came after the profile and was read.");
|
||||
Assert.AreEqual(2, (await bed.Db.Highlights.ListAsync(account.Id)).Count, "So were the collections, after the grid.");
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual("griglia-12", stored!.BackfillCursor, "The history goes on from the grid's own page.");
|
||||
Assert.IsNull(stored.BackfillCompletedAt, "Neither «more_available: false» of the post nor «has_next_page: false» of the collections ends it.");
|
||||
Assert.IsFalse(bed.Page.Looked.Contains(SiteTargets.ProfileNotFound), "The marker is not in the map: it is not looked for.");
|
||||
Assert.IsFalse((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code is "mappa-incompleta" or "formato-non-riconosciuto"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheMarkerAMissingProfileIsAnEmptyPageAndWithItTheAccountIsUnreachable()
|
||||
{
|
||||
await using (var bed = await InstagramBed.CreateAsync())
|
||||
{
|
||||
var account = await bed.AddAccountAsync("2004", "sparito.prova");
|
||||
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual("La pagina è arrivata vuota: nessun dato da leggere.", outcome.Message);
|
||||
Assert.AreNotEqual(AccountState.Unreachable, (await bed.Db.Accounts.GetAsync(account.Id))!.State, "Nothing says the profile is gone.");
|
||||
Assert.IsFalse(bed.Page.Looked.Contains(SiteTargets.ProfileNotFound));
|
||||
}
|
||||
|
||||
await using (var bed = await InstagramBed.CreateAsync(InstagramBed.Map(SiteTargets.ProfileNotFound)))
|
||||
{
|
||||
var account = await bed.AddAccountAsync("2004", "sparito.prova");
|
||||
bed.Page.Present.Add(SiteTargets.ProfileNotFound);
|
||||
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.AccountUnreachable, outcome.Status, outcome.Message);
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual(AccountState.Unreachable, stored!.State);
|
||||
Assert.AreEqual(UnreachableReason.NotFound, stored.UnreachableReason);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnAnswerWithoutMorePagesOfSomethingElseDoesNotEndTheHistory()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2001", "luca.prova");
|
||||
var luca = Author("2001", "luca.prova");
|
||||
var newest = bed.Clock.Now.AddDays(-2);
|
||||
bed.Page.OnOpen["/luca.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(luca), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(Grid(Posts(luca, 0, 12, newest), "griglia-12", hasNext: true), TimeSpan.Zero, TimeSpan.Zero),
|
||||
];
|
||||
|
||||
// The first burst brings only answers about something else, each saying it has no more: a post of another
|
||||
// account and the collections. The next page of the grid comes with the second burst.
|
||||
bed.Page.OnScroll["/luca.prova/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[Sample("post-video"), Highlights("2001", "luca.prova", hasNext: false)],
|
||||
[Grid(Posts(luca, 12, 24, newest), "griglia-24", hasNext: true)],
|
||||
[Grid(Posts(luca, 24, 30, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 5);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, "The end of the grid, not of the post.");
|
||||
Assert.AreEqual(30, (await bed.PostIdsAsync(account.Id)).Count);
|
||||
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCompletedAt);
|
||||
Assert.AreEqual(2, bed.Governor.Granted(ActionKind.BackfillPage), "The answers about something else did not count as a page.");
|
||||
Assert.AreEqual(3, bed.Page.Scrolls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThePageOfAPostOfTheAccountNeitherEndsTheHistoryNorCountsAsItsNextPage()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2001", "luca.prova");
|
||||
var luca = Author("2001", "luca.prova");
|
||||
var newest = bed.Clock.Now.AddDays(-2);
|
||||
|
||||
// After the grid, the page of one of its posts: the REST answer of the samples, «more_available: false».
|
||||
bed.Page.OnOpen["/luca.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(luca), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(Grid(Posts(luca, 0, 12, newest), "griglia-12", hasNext: true), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(PostPage(Posts(luca, 3, 4, newest)[0]), TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(400)),
|
||||
];
|
||||
|
||||
var check = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual("griglia-12", stored!.BackfillCursor, "The history goes on from the grid's own page.");
|
||||
Assert.IsNull(stored.BackfillCompletedAt, "«more_available: false» of the page of one of its posts does not complete it.");
|
||||
|
||||
// The first burst brings only the page of another post already read; the next page of the grid comes with the second.
|
||||
bed.Page.OnScroll["/luca.prova/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[PostPage(Posts(luca, 5, 6, newest)[0])],
|
||||
[Grid(Posts(luca, 12, 24, newest), "griglia-24", hasNext: true)],
|
||||
[Grid(Posts(luca, 24, 30, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 5);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, "The end of the grid, not of the post.");
|
||||
Assert.AreEqual(30, (await bed.PostIdsAsync(account.Id)).Count);
|
||||
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCompletedAt);
|
||||
Assert.AreEqual(2, bed.Governor.Granted(ActionKind.BackfillPage), "The page of a post already read did not count as a page.");
|
||||
Assert.AreEqual(3, bed.Page.Scrolls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OnTheTaggedTabThePageOfAPostAlreadyReadDoesNotEndTheWalk()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync(InstagramBed.Map(SiteTargets.ProfileTabTagged));
|
||||
bed.Page.Present.Add(SiteTargets.ProfileTabTagged);
|
||||
var account = await bed.AddAccountAsync("2001", "luca.prova", change: a => a with { ContentTypes = a.ContentTypes | ContentTypes.Tagged });
|
||||
var luca = Author("2001", "luca.prova");
|
||||
var other = Author("2005", "altro.prova");
|
||||
var newest = bed.Clock.Now.AddDays(-3);
|
||||
|
||||
// On the tab every post of another account is an item of the walk, the page of one of them too.
|
||||
bed.Page.OnOpen["/luca.prova/"] = [new(ProfileAnswer(luca), TimeSpan.Zero, TimeSpan.Zero)];
|
||||
bed.Page.OnClick[SiteTargets.ProfileTabTagged] =
|
||||
[
|
||||
new(Grid(Posts(other, 0, 12, newest), "taggati-12", hasNext: true), TimeSpan.Zero, TimeSpan.FromMilliseconds(200)),
|
||||
new(PostPage(Posts(other, 4, 5, newest)[0]), TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(600)),
|
||||
];
|
||||
bed.Page.OnScroll["/luca.prova/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[PostPage(Posts(other, 7, 8, newest)[0])],
|
||||
[Grid(Posts(other, 12, 20, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.Tagged, account.Id, maxPages: 5);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, "The end of the tab, not of the post.");
|
||||
Assert.AreEqual(20, (await bed.PostIdsAsync(account.Id, EntryKind.Tagged)).Count);
|
||||
Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.taggati.{account.Id.ToString(CultureInfo.InvariantCulture)}.completo"));
|
||||
Assert.AreEqual(2, bed.Governor.Granted(ActionKind.BackfillPage), "The tab and its second page; the page of a post is not one.");
|
||||
Assert.AreEqual(2, bed.Page.Scrolls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThePageOfAPostAlreadyInTheFeedDoesNotEndTheSweep()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2003", "nadia.prova");
|
||||
var nadia = Author("2003", "nadia.prova");
|
||||
var newest = bed.Clock.Now.AddHours(-1);
|
||||
bed.Page.OnOpen["/"] = [new(Grid(Posts(nadia, 0, 6, newest), "feed-6", hasNext: true), TimeSpan.Zero, TimeSpan.Zero)];
|
||||
bed.Page.OnScroll["/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[PostPage(Posts(nadia, 2, 3, newest)[0])],
|
||||
[Grid(Posts(nadia, 6, 12, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingSweep);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual(12, (await bed.PostIdsAsync(account.Id)).Count, "«more_available: false» of the page of a post read already is not the end of the feed.");
|
||||
Assert.AreEqual(2, bed.Page.Scrolls, "The feed's own end stops the sweep.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheEmptyCollectionsOfAnAccountWithoutAnyAreNotAnEmptyGrid()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2002", "marta.prova");
|
||||
var marta = Author("2002", "marta.prova");
|
||||
|
||||
// No collections: their answer, an empty connection saying there are no more, comes before the grid, which
|
||||
// the page asks for only after it has settled on the profile.
|
||||
bed.Page.OnOpen["/marta.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(marta), TimeSpan.Zero, TimeSpan.FromMilliseconds(300)),
|
||||
new(NoHighlights(), TimeSpan.FromMilliseconds(400), TimeSpan.FromMilliseconds(800)),
|
||||
new(Grid(Posts(marta, 0, 12, bed.Clock.Now.AddDays(-1)), "griglia-12", hasNext: true), TimeSpan.FromSeconds(1.6), TimeSpan.FromSeconds(2.0)),
|
||||
];
|
||||
|
||||
var check = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
|
||||
Assert.AreEqual(12, (await bed.PostIdsAsync(account.Id)).Count, "The grid was still waited for.");
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual("griglia-12", stored!.BackfillCursor);
|
||||
Assert.IsNull(stored.BackfillCompletedAt, "«has_next_page: false» of the empty collections does not complete the history.");
|
||||
|
||||
// When the grid does not come, the empty collections do not stand for it either.
|
||||
var other = await bed.AddAccountAsync("2003", "nadia.prova");
|
||||
bed.Page.OnOpen["/nadia.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(Author("2003", "nadia.prova")), TimeSpan.Zero, TimeSpan.FromMilliseconds(300)),
|
||||
new(NoHighlights(), TimeSpan.FromMilliseconds(400), TimeSpan.FromMilliseconds(800)),
|
||||
];
|
||||
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.ProfileCheck, other.Id)).Status);
|
||||
stored = await bed.Db.Accounts.GetAsync(other.Id);
|
||||
Assert.IsNull(stored!.BackfillCompletedAt, "Nothing said the grid is empty.");
|
||||
Assert.IsNull(stored.BackfillCursor);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SuggestedProfilesAreNeverSavedAsFollowed()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
await bed.AddMineAsync();
|
||||
|
||||
// A profile Febe keeps that Alberto does not follow, among the suggestions of the sample.
|
||||
var suggestions = Sample("profili-suggeriti");
|
||||
var suggested = suggestions["data"]!["xdt_api__v1__discover__chaining"]!["users"]!.AsArray().Select(u => u!["username"]!.GetValue<string>()).ToList();
|
||||
var kept = await bed.AddAccountAsync(suggestions["data"]!["xdt_api__v1__discover__chaining"]!["users"]![0]!["pk"]!.GetValue<string>(), suggested[0], followed: false);
|
||||
|
||||
var followed = Enumerable.Range(0, 4).Select(i => Author((3000 + i).ToString(CultureInfo.InvariantCulture), $"seguito{i}.prova")).ToList();
|
||||
bed.Page.OnOpen["/alberto.prova/seguiti-di-prova/"] =
|
||||
[
|
||||
new(suggestions, TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(ProfileAnswer(Author(AlbertoId, "alberto.prova", following: null)), TimeSpan.Zero, TimeSpan.FromMilliseconds(200)),
|
||||
new(FollowingList(followed), TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(700)),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingList);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, outcome.Message);
|
||||
var list = (await bed.Db.Following.ListAsync()).Select(f => f.Username).ToList();
|
||||
CollectionAssert.AreEquivalent(new[] { "seguito0.prova", "seguito1.prova", "seguito2.prova", "seguito3.prova" }, list, "Neither the suggestions nor Alberto himself.");
|
||||
Assert.IsFalse((await bed.Db.Accounts.GetAsync(kept.Id))!.IsFollowed, "A suggested profile is not followed.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SuggestionsAndAlbertoAloneAreNotTheFollowingList()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
await bed.AddMineAsync();
|
||||
bed.Page.OnOpen["/alberto.prova/seguiti-di-prova/"] =
|
||||
[
|
||||
new(Sample("profili-suggeriti"), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(ProfileAnswer(Author(AlbertoId, "alberto.prova", following: null)), TimeSpan.Zero, TimeSpan.Zero),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingList);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual("La pagina è arrivata vuota: nessun dato da leggere.", outcome.Message);
|
||||
Assert.AreEqual(0, await bed.Db.Following.CountAsync());
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(RecipeRunner.FollowingKeys.Cursor));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheConnectedAccountIsRecognizedFromItsIdentifierAndItsEntryInTheStoriesBar()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2003", "nadia.prova");
|
||||
var nadia = Author("2003", "nadia.prova", latestStoryAt: bed.Clock.Now.AddHours(-2));
|
||||
|
||||
// The feed says who the connected account is by its identifier only (xdt_viewer.user, as in the samples);
|
||||
// its name comes later, with its own entry in the stories bar.
|
||||
bed.Page.OnOpen["/"] =
|
||||
[
|
||||
new(Grid(Posts(nadia, 0, 2, bed.Clock.Now.AddHours(-5)), "feed-2", hasNext: false, viewerId: AlbertoId), TimeSpan.Zero, TimeSpan.FromMilliseconds(200)),
|
||||
new(StoriesBar(Author(AlbertoId, "alberto.prova", following: null, latestStoryAt: bed.Clock.Now.AddHours(-1)), nadia), TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(900)),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingSweep);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
var mine = await bed.Db.Accounts.GetMineAsync();
|
||||
Assert.IsNotNull(mine, "«Tu» from the identifier of one answer and the profile of another.");
|
||||
Assert.AreEqual("alberto.prova", mine.Username);
|
||||
Assert.AreEqual(AlbertoId, mine.InstagramId);
|
||||
Assert.AreEqual(2, (await bed.PostIdsAsync(account.Id)).Count);
|
||||
Assert.IsTrue(outcome.AccountsWithStories.Contains(account.Id), "The stories bar came after the feed and was read.");
|
||||
Assert.IsTrue((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "account-collegato"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SuggestedProfilesAloneAreNotTheHome()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
bed.Page.OnOpen["/"] = [new(Sample("profili-suggeriti"), TimeSpan.Zero, TimeSpan.Zero)];
|
||||
|
||||
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.FollowingSweep)).Status);
|
||||
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.FollowingSweep)).Status);
|
||||
Assert.AreEqual(0, bed.Breaker.Signals.Count);
|
||||
var third = await bed.RunAsync(RecipeKind.FollowingSweep);
|
||||
Assert.AreEqual(RecipeStatus.StoppedBySignal, third.Status, "Three homes with nothing but suggestions are three empty pages: " + third.Message);
|
||||
Assert.AreEqual("empty-pages", bed.Breaker.Signals.Single().Code);
|
||||
Assert.IsNull(await bed.Db.Accounts.GetMineAsync());
|
||||
}
|
||||
|
||||
// ----- Answers: the cleaned samples, and variants built from them -----
|
||||
|
||||
private static string SampleFile(string name) =>
|
||||
Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), $"*-{name}.json").Single();
|
||||
|
||||
/// <summary>The body of a cleaned sample, as the page received it.</summary>
|
||||
private static JsonObject Sample(string name) =>
|
||||
JsonNode.Parse(File.ReadAllText(SampleFile(name)))!["corpo"]!.DeepClone().AsObject();
|
||||
|
||||
/// <summary>
|
||||
/// A profile as the post of the samples describes its author (pk, username, friendship_status, latest_reel_media,
|
||||
/// the pictures), with another identity. <paramref name="following"/> null: without friendship_status.
|
||||
/// </summary>
|
||||
private static JsonObject Author(string pk, string username, bool? following = true, DateTimeOffset? latestStoryAt = null)
|
||||
{
|
||||
var user = Sample("post-video")["items"]![0]!["user"]!.DeepClone().AsObject();
|
||||
user["pk"] = pk;
|
||||
user["pk_id"] = pk;
|
||||
user["id"] = pk;
|
||||
user["strong_id__"] = pk;
|
||||
user["username"] = username;
|
||||
user["full_name"] = username;
|
||||
if (following is { } value)
|
||||
{
|
||||
user["friendship_status"]!["following"] = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
user.Remove("friendship_status");
|
||||
}
|
||||
|
||||
if (latestStoryAt is { } latest)
|
||||
{
|
||||
user["latest_reel_media"] = latest.ToUnixTimeSeconds();
|
||||
}
|
||||
else
|
||||
{
|
||||
user.Remove("latest_reel_media");
|
||||
}
|
||||
|
||||
Retag(user, "a" + pk);
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>Posts of <paramref name="author"/>, one hour apart going back from <paramref name="newest"/>: the post of the samples, renumbered.</summary>
|
||||
private static List<JsonObject> Posts(JsonObject author, int from, int to, DateTimeOffset newest)
|
||||
{
|
||||
var template = Sample("post-video")["items"]![0]!;
|
||||
var authorPk = author["pk"]!.GetValue<string>();
|
||||
var posts = new List<JsonObject>();
|
||||
for (var i = from; i < to; i++)
|
||||
{
|
||||
var pk = authorPk + "9" + i.ToString("D4", CultureInfo.InvariantCulture);
|
||||
var post = template.DeepClone().AsObject();
|
||||
post["pk"] = pk;
|
||||
post["id"] = $"{pk}_{authorPk}";
|
||||
post["code"] = ("C" + pk).PadRight(11, 'x')[..11];
|
||||
post["taken_at"] = newest.AddHours(-i).ToUnixTimeSeconds();
|
||||
Retag(post, "p" + pk);
|
||||
post["user"] = author.DeepClone();
|
||||
post["owner"] = author.DeepClone();
|
||||
posts.Add(post);
|
||||
}
|
||||
|
||||
return posts;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A page of posts: Instagram's grid and feed are not in the samples, so the posts go into the GraphQL connection
|
||||
/// the samples show (data.…connection.edges[].node, page_info), with xdt_viewer.user when given.
|
||||
/// </summary>
|
||||
private static JsonObject Grid(IEnumerable<JsonObject> posts, string? cursor, bool hasNext, string? viewerId = null)
|
||||
{
|
||||
var body = Sample("raccolta-in-evidenza");
|
||||
var data = body["data"]!.AsObject();
|
||||
var connection = data["xdt_api__v1__feed__reels_media__connection"]!.AsObject();
|
||||
connection["edges"] = new JsonArray([.. posts.Select(p => (JsonNode)new JsonObject { ["node"] = p, ["cursor"] = null })]);
|
||||
connection["page_info"]!["end_cursor"] = cursor;
|
||||
connection["page_info"]!["has_next_page"] = hasNext;
|
||||
if (viewerId is null)
|
||||
{
|
||||
data.Remove("xdt_viewer");
|
||||
}
|
||||
else
|
||||
{
|
||||
var user = data["xdt_viewer"]!["user"]!;
|
||||
user["pk"] = viewerId;
|
||||
user["id"] = viewerId;
|
||||
user["user_id"] = viewerId;
|
||||
}
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The collections of the samples, as if of another account, saying whether there are more of them.</summary>
|
||||
private static JsonObject Highlights(string pk, string username, bool hasNext)
|
||||
{
|
||||
var body = Sample("raccolta-in-evidenza");
|
||||
var connection = body["data"]!["xdt_api__v1__feed__reels_media__connection"]!;
|
||||
foreach (var node in connection["edges"]!.AsArray().Select(e => e!["node"]!))
|
||||
{
|
||||
var owner = node["user"]!;
|
||||
owner["pk"] = pk;
|
||||
owner["id"] = pk;
|
||||
owner["user_id"] = pk;
|
||||
owner["username"] = username;
|
||||
foreach (var item in node["items"]!.AsArray())
|
||||
{
|
||||
item!["user"]!["pk"] = pk;
|
||||
item["user"]!["id"] = pk;
|
||||
item["user"]!["instagram_pk"] = pk;
|
||||
}
|
||||
}
|
||||
|
||||
connection["page_info"]!["has_next_page"] = hasNext;
|
||||
body["data"]!.AsObject().Remove("xdt_viewer");
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The collections of an account that has none: the connection of the samples without edges, saying there are no more.</summary>
|
||||
private static JsonObject NoHighlights()
|
||||
{
|
||||
var body = Highlights("0", "nessuno.prova", hasNext: false);
|
||||
body["data"]!["xdt_api__v1__feed__reels_media__connection"]!["edges"] = new JsonArray();
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The page of one post: the REST answer of the samples («more_available: false») with <paramref name="post"/> as its item.</summary>
|
||||
private static JsonObject PostPage(JsonObject post)
|
||||
{
|
||||
var body = Sample("post-video");
|
||||
body["items"] = new JsonArray(post);
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>A profile on its own (data.user): Instagram's profile answer is not in the samples.</summary>
|
||||
private static JsonObject ProfileAnswer(JsonObject profile) => new() { ["data"] = new JsonObject { ["user"] = profile.DeepClone() } };
|
||||
|
||||
/// <summary>
|
||||
/// The stories bar of the home, not in the samples: the reels of the samples (XDTReelDict) without what makes them a
|
||||
/// collection (title, items), one per account, its author in «user».
|
||||
/// </summary>
|
||||
private static JsonObject StoriesBar(params JsonObject[] authors)
|
||||
{
|
||||
var body = Sample("raccolta-in-evidenza");
|
||||
var data = body["data"]!.AsObject();
|
||||
var connection = data["xdt_api__v1__feed__reels_media__connection"]!.AsObject();
|
||||
var template = connection["edges"]![0]!["node"]!;
|
||||
connection["edges"] = new JsonArray([.. authors.Select(author =>
|
||||
{
|
||||
var reel = template.DeepClone().AsObject();
|
||||
reel.Remove("title");
|
||||
reel.Remove("items");
|
||||
reel.Remove("cover_media");
|
||||
reel["id"] = author["pk"]!.GetValue<string>();
|
||||
reel["user"] = author.DeepClone();
|
||||
reel["latest_reel_media"] = author["latest_reel_media"]?.DeepClone();
|
||||
return (JsonNode)new JsonObject { ["node"] = reel, ["cursor"] = null };
|
||||
})]);
|
||||
connection.Remove("page_info");
|
||||
data.Remove("xdt_viewer");
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The following list, not in the samples: its profiles in «users», as the suggestions of the samples have them, and «more_available».</summary>
|
||||
private static JsonObject FollowingList(IEnumerable<JsonObject> profiles) => new()
|
||||
{
|
||||
["users"] = new JsonArray([.. profiles.Select(p => (JsonNode)p.DeepClone())]),
|
||||
["more_available"] = false,
|
||||
};
|
||||
|
||||
/// <summary>Gives the file addresses of a copied part their own name, so that copies are different files.</summary>
|
||||
private static void Retag(JsonNode node, string tag)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case JsonObject obj:
|
||||
foreach (var (key, value) in obj.ToList())
|
||||
{
|
||||
if (value is JsonValue v && v.TryGetValue<string>(out var text) && text.StartsWith("https://cdn.esempio/", StringComparison.Ordinal))
|
||||
{
|
||||
obj[key] = "https://cdn.esempio/" + tag + "-" + text["https://cdn.esempio/".Length..];
|
||||
}
|
||||
else if (value is not null)
|
||||
{
|
||||
Retag(value, tag);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonArray array:
|
||||
foreach (var item in array.Where(i => i is not null))
|
||||
{
|
||||
Retag(item!, tag);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ----- The bed: a page driver that hands the capture Instagram-shaped answers over time -----
|
||||
|
||||
/// <summary>An answer of a page: its response seen at <paramref name="Announced"/>, its body read at <paramref name="Delivered"/>.</summary>
|
||||
private sealed record Answer(JsonNode Body, TimeSpan Announced, TimeSpan Delivered);
|
||||
|
||||
/// <summary>A virtual clock that also runs what is due when time passes: bodies arrive while the recipe waits.</summary>
|
||||
private sealed class StepClock(DateTimeOffset start) : IClock
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<(DateTimeOffset At, long Order, Action Action)> _due = [];
|
||||
private DateTimeOffset _now = start;
|
||||
private long _order;
|
||||
|
||||
public DateTimeOffset Now
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public TimeZoneInfo LocalZone => TimeZoneInfo.Utc;
|
||||
|
||||
public void After(TimeSpan delay, Action action)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_due.Add((_now + delay, _order++, action));
|
||||
}
|
||||
}
|
||||
|
||||
public Task Delay(TimeSpan time, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
List<Action> due;
|
||||
lock (_gate)
|
||||
{
|
||||
if (time > TimeSpan.Zero)
|
||||
{
|
||||
_now += time;
|
||||
}
|
||||
|
||||
due = [.. _due.Where(d => d.At <= _now).OrderBy(d => d.At).ThenBy(d => d.Order).Select(d => d.Action)];
|
||||
_due.RemoveAll(d => d.At <= _now);
|
||||
}
|
||||
|
||||
foreach (var action in due)
|
||||
{
|
||||
action();
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page: opening a path hands the capture its answers (each seen as a response first, its body read later, as
|
||||
/// the browser does), and so does a click on a target; a burst hands it the next answers queued for the path.
|
||||
/// Targets are found only when present.
|
||||
/// </summary>
|
||||
private sealed class InstagramPage(CaptureCollector capture, StepClock clock) : IPageDriver
|
||||
{
|
||||
private int _requests;
|
||||
|
||||
public Dictionary<string, List<Answer>> OnOpen { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public Dictionary<string, List<Answer>> OnClick { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public Dictionary<string, Queue<IReadOnlyList<JsonNode>>> OnScroll { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public HashSet<string> Present { get; } = [];
|
||||
|
||||
public List<string> Looked { get; } = [];
|
||||
|
||||
public int Scrolls { get; private set; }
|
||||
|
||||
public string CurrentPath { get; private set; } = "about:blank";
|
||||
|
||||
public double WaitMultiplier => 1;
|
||||
|
||||
public void BeginSession(double mood)
|
||||
{
|
||||
}
|
||||
|
||||
public Task<PageLoad> OpenAsync(string path, CancellationToken ct)
|
||||
{
|
||||
CurrentPath = path;
|
||||
foreach (var answer in OnOpen.GetValueOrDefault(path) ?? [])
|
||||
{
|
||||
Send(answer.Body, answer.Announced, answer.Delivered);
|
||||
}
|
||||
|
||||
return Task.FromResult(new PageLoad(true, path, null));
|
||||
}
|
||||
|
||||
public Task<string> CurrentPathAsync(CancellationToken ct) => Task.FromResult(CurrentPath);
|
||||
|
||||
public Task<bool> IsOnSiteAsync(CancellationToken ct) => Task.FromResult(true);
|
||||
|
||||
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
|
||||
{
|
||||
Looked.Add(target);
|
||||
return Task.FromResult(Present.Contains(target)
|
||||
? new TargetCheck(target, TargetCheckStatus.Found, 1, "Trovato.")
|
||||
: new TargetCheck(target, TargetCheckStatus.NotFound, 0, $"Bersaglio «{target}» non trovato."));
|
||||
}
|
||||
|
||||
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
|
||||
{
|
||||
if (!Present.Contains(target))
|
||||
{
|
||||
return Task.FromResult(new TargetCheck(target, TargetCheckStatus.NotFound, 0, $"Bersaglio «{target}» non trovato."));
|
||||
}
|
||||
|
||||
foreach (var answer in OnClick.GetValueOrDefault(target) ?? [])
|
||||
{
|
||||
Send(answer.Body, answer.Announced, answer.Delivered);
|
||||
}
|
||||
|
||||
return Task.FromResult(new TargetCheck(target, TargetCheckStatus.Clicked, 1, "Cliccato."));
|
||||
}
|
||||
|
||||
public Task ScrollBurstAsync(CancellationToken ct)
|
||||
{
|
||||
Scrolls++;
|
||||
if (OnScroll.TryGetValue(CurrentPath, out var queue) && queue.Count > 0)
|
||||
{
|
||||
foreach (var body in queue.Dequeue())
|
||||
{
|
||||
Send(body, TimeSpan.Zero, TimeSpan.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task WaitAfterLoadAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Task.FromResult<bool?>(true);
|
||||
|
||||
public Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
CurrentPath = "about:blank";
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void Send(JsonNode body, TimeSpan announced, TimeSpan delivered)
|
||||
{
|
||||
var id = "r" + Interlocked.Increment(ref _requests).ToString(CultureInfo.InvariantCulture);
|
||||
var descriptor = new ResponseDescriptor(id, HostKind.Site, "https://sito.esempio/graphql/query", "sito.esempio", "/graphql/query", 200, "text/javascript", "XHR", false, clock.Now);
|
||||
var text = body.ToJsonString();
|
||||
void Announce() => ((IResponseObserver)capture).OnResponse(descriptor);
|
||||
void Deliver()
|
||||
{
|
||||
using var document = JsonDocument.Parse(text);
|
||||
capture.Accept(descriptor, document.RootElement);
|
||||
}
|
||||
|
||||
if (delivered <= TimeSpan.Zero)
|
||||
{
|
||||
Announce();
|
||||
Deliver();
|
||||
return;
|
||||
}
|
||||
|
||||
clock.After(announced, Announce);
|
||||
clock.After(delivered, Deliver);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Database, clock, Governor, signals and runner over <see cref="InstagramPage"/> and the Instagram vocabulary.</summary>
|
||||
private sealed class InstagramBed : IAsyncDisposable
|
||||
{
|
||||
private InstagramBed(TempFolder temp, FebeDatabase db, StepClock clock, InstagramPage page, RecipeRunner runner, TestSession session)
|
||||
{
|
||||
Temp = temp;
|
||||
Db = db;
|
||||
Clock = clock;
|
||||
Page = page;
|
||||
Runner = runner;
|
||||
Session = session;
|
||||
}
|
||||
|
||||
public TempFolder Temp { get; }
|
||||
|
||||
public FebeDatabase Db { get; }
|
||||
|
||||
public StepClock Clock { get; }
|
||||
|
||||
public InstagramPage Page { get; }
|
||||
|
||||
public RecipeRunner Runner { get; }
|
||||
|
||||
public TestSession Session { get; }
|
||||
|
||||
public PermissiveGovernor Governor => (PermissiveGovernor)Runner.Env.Governor;
|
||||
|
||||
public RecordingBreaker Breaker => (RecordingBreaker)Runner.Env.Breaker!;
|
||||
|
||||
/// <summary>
|
||||
/// Pages with Instagram's addresses where the samples show them (home, profile, post: route definitions of the
|
||||
/// HAR); the following list has an address of the test, Instagram's is not in the samples. Targets: only
|
||||
/// <paramref name="configured"/>.
|
||||
/// </summary>
|
||||
public static SiteMap Map(params string[] configured) => new(
|
||||
"instagram",
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
[SitePages.Home] = "/",
|
||||
[SitePages.Profile] = "/{username}/",
|
||||
[SitePages.Post] = "/p/{code}/",
|
||||
[SitePages.Following] = "/{username}/seguiti-di-prova/",
|
||||
},
|
||||
configured,
|
||||
SiteTargets.All);
|
||||
|
||||
public static async Task<InstagramBed> CreateAsync(SiteMap? map = null)
|
||||
{
|
||||
var temp = new TempFolder("ricette-instagram");
|
||||
var db = await TestDatabase.OpenAsync(temp);
|
||||
var clock = new StepClock(new DateTimeOffset(2026, 10, 25, 9, 0, 0, TimeSpan.Zero));
|
||||
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadInstagram()), clock);
|
||||
var page = new InstagramPage(capture, clock);
|
||||
var breaker = new RecordingBreaker();
|
||||
var governor = new PermissiveGovernor();
|
||||
var runner = new RecipeRunner(new RecipeEnvironment
|
||||
{
|
||||
Driver = page,
|
||||
Capture = capture,
|
||||
Governor = governor,
|
||||
Budget = governor,
|
||||
Signals = new SignalDetector(SignalRules.LoadDefault(), breaker, clock),
|
||||
Storage = db,
|
||||
SiteMap = map ?? Map(),
|
||||
Clock = clock,
|
||||
Random = new SeededRandom(7),
|
||||
Breaker = breaker,
|
||||
});
|
||||
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
|
||||
return new InstagramBed(temp, db, clock, page, runner, session);
|
||||
}
|
||||
|
||||
public Task<Account> AddAccountAsync(string instagramId, string username, bool followed = true, Func<Account, Account>? change = null)
|
||||
{
|
||||
var account = Account.Create(username, StartingPoint.EverythingAndKeepUpdated, Clock.Now, TestZones.Rome) with
|
||||
{
|
||||
InstagramId = instagramId,
|
||||
IsFollowed = followed,
|
||||
};
|
||||
return Db.Accounts.AddAsync(change is null ? account : change(account));
|
||||
}
|
||||
|
||||
public Task<Account> AddMineAsync() =>
|
||||
Db.Accounts.AddAsync(Account.Create("alberto.prova", StartingPoint.EverythingAndKeepUpdated, Clock.Now, TestZones.Rome, isMine: true) with { InstagramId = AlbertoId });
|
||||
|
||||
public Task<RecipeOutcome> RunAsync(RecipeKind kind, long? accountId = null, int? maxPages = null) =>
|
||||
Runner.RunAsync(new RecipeRequest(kind, accountId, MaxPages: maxPages), Session, CancellationToken.None);
|
||||
|
||||
public async Task<IReadOnlyList<string>> PostIdsAsync(long accountId, EntryKind kind = EntryKind.Post) =>
|
||||
[.. (await Db.Entries.ListByAccountAsync(accountId, new EntryListOptions { Kind = kind, Limit = 1000 })).Select(e => e.InstagramId!)];
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Db.DisposeAsync();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The generic reader (spec §6.4) on the cleaned samples of <c>tests/campioni/prova</c>: captured from the test site,
|
||||
/// cleaned with «febe-sonda ripulisci» and checked with «febe-sonda verifica». Never real Instagram samples: there
|
||||
/// are none yet (rule 10).
|
||||
/// cleaned with «febe-sonda ripulisci» and checked with «febe-sonda verifica». The real Instagram samples have their
|
||||
/// own tests (<see cref="InstagramReaderTests"/>).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ReaderTests
|
||||
@@ -199,31 +199,16 @@ public sealed class ReaderTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheShippedVocabulariesLoadAndInstagramsIsOnlyAHypothesis()
|
||||
public void TheShippedVocabulariesLoad()
|
||||
{
|
||||
var test = ReaderVocabulary.LoadTestSite();
|
||||
Assert.IsTrue(test.IsUsable, test.UnusableReason);
|
||||
Assert.AreEqual(0, test.Relevance.Count, "On the test site every unknown answer is a format change.");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "lettori.prova.json")), "Editable without recompiling.");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "lettori.instagram.json")));
|
||||
|
||||
var instagram = ReaderVocabulary.LoadInstagram();
|
||||
Assert.AreEqual(VocabularyStatus.Hypothesis, instagram.Status);
|
||||
Assert.IsFalse(instagram.IsUsable);
|
||||
StringAssert.Contains(instagram.UnusableReason, "ipotesi");
|
||||
StringAssert.Contains(instagram.Note, "IPOTESI, DA CONFERMARE CON I CAMPIONI DI M0");
|
||||
|
||||
// Only the hint keys of spec §6.4: nothing invented (rule 10).
|
||||
var keys = new[]
|
||||
{
|
||||
instagram.Content.Id, instagram.Content.Code, instagram.Content.TakenAt, instagram.Content.Caption, instagram.Content.Images,
|
||||
instagram.Content.Videos, instagram.Content.Children, instagram.Content.ChildCount, instagram.Content.Owner, instagram.Content.Pinned,
|
||||
instagram.Content.ExpiresAt, instagram.Content.Duration, instagram.Version.Url, instagram.Version.Width, instagram.Version.Height,
|
||||
instagram.Version.HasAudio, instagram.Profile.Id, instagram.Profile.Username, instagram.Profile.DisplayName, instagram.Profile.IsPrivate,
|
||||
instagram.Profile.IsFollowed, instagram.Profile.PostCount, instagram.Profile.Picture, instagram.Profile.LatestStoryAt,
|
||||
instagram.Highlight.Id, instagram.Highlight.Title, instagram.Highlight.Owner, instagram.Highlight.Items,
|
||||
instagram.Page.HasMore, instagram.Page.Cursor, instagram.Viewer,
|
||||
}.SelectMany(k => k.Paths).Order().ToArray();
|
||||
CollectionAssert.AreEqual(new[] { "carousel_media", "code", "image_versions2.candidates", "pk", "taken_at", "video_versions" }, keys);
|
||||
// Instagram's vocabulary has its own tests on the real cleaned samples (InstagramReaderTests).
|
||||
Assert.IsTrue(ReaderVocabulary.LoadInstagram().IsUsable);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -134,6 +134,39 @@ public sealed class RecipeRuleTests
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync($"raccolta.lacuna.{account.Id}.cursore"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AProfileWithCollectionsAndNoPostsHasItsWholeHistoryInTheFirstAnswer()
|
||||
{
|
||||
// The test site sends the collections with the first page of the grid, here empty: the profile in the same
|
||||
// answer says there are no posts.
|
||||
await using var bed = await ScriptedBed.CreateAsync();
|
||||
var timeout = new RecipeOptions().DataTimeout;
|
||||
var vera = bed.Site.Add(new ScriptedAccount("2006", "vera.prova"));
|
||||
vera.HighlightsWithItems.Add(("h1", "Estate", []));
|
||||
var account = await bed.AddAccountAsync(vera, a => a with { State = AccountState.Backfilling });
|
||||
|
||||
var start = bed.Clock.Now;
|
||||
var check = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
|
||||
Assert.IsTrue(bed.Clock.Now - start < timeout, "The empty grid came with the profile: no wait for another one.");
|
||||
Assert.AreEqual(1, (await bed.Db.Highlights.ListAsync(account.Id)).Count);
|
||||
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCompletedAt);
|
||||
Assert.IsTrue(check.BackfillFinished, "Its history is complete, with nothing in it.");
|
||||
|
||||
// The history of an account like it, not marked complete yet, ends at the profile without a page of its own.
|
||||
var lia = bed.Site.Add(new ScriptedAccount("2007", "lia.prova"));
|
||||
lia.HighlightsWithItems.Add(("h2", "Inverno", []));
|
||||
var other = await bed.AddAccountAsync(lia, a => a with { State = AccountState.Backfilling });
|
||||
start = bed.Clock.Now;
|
||||
var backfill = await bed.RunAsync(RecipeKind.Backfill, other.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, backfill.Status, backfill.Message);
|
||||
Assert.IsTrue(backfill.BackfillFinished, backfill.Message);
|
||||
Assert.IsTrue(bed.Clock.Now - start < timeout);
|
||||
Assert.AreEqual(0, bed.Governor.Granted(ActionKind.BackfillPage), "No page asked for after the profile.");
|
||||
Assert.AreEqual(0, bed.Site.Scrolls);
|
||||
Assert.AreEqual(0, bed.Breaker.Signals.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AResponseUnrelatedToThePageNeitherEndsTheWalkNorStopsTheRecipe()
|
||||
{
|
||||
|
||||
@@ -193,6 +193,24 @@ public sealed class SanitizerTests
|
||||
StringAssert.EndsWith(node["c"]!.GetValue<string>(), ".webp");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ValuesUnderSecretLikeKeysBecomeANeutralFillerOfTheSameShape()
|
||||
{
|
||||
// A fake drawn letter by letter from a long token still looks like a token to a secret scanner (gitleaks).
|
||||
var sanitizer = new SampleSanitizer(key: new byte[32]);
|
||||
// Built at run time, so the source itself holds no token-like literal next to a token-like key (gitleaks).
|
||||
var tracked = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("""{"version":5,"payload":{"is_analytics_tracked":true"""));
|
||||
var ranked = new Guid(0x18f2c1b0, 0xaa77, 0x4c2e, 0x9e, 0x1d, 0x0c, 0x6a, 0x1b, 0x2c, 0x3d, 0x4e).ToString();
|
||||
var node = sanitizer.Sanitize(JsonNode.Parse(new JsonObject { ["organic_tracking_token"] = tracked, ["rank_token"] = ranked, ["nome"] = "Lucia" }.ToJsonString()))!;
|
||||
Assert.AreEqual("xxx7xxxx", node["organic_tracking_token"]!.GetValue<string>()[..8]);
|
||||
Assert.IsTrue(node["organic_tracking_token"]!.GetValue<string>().All(c => c is 'x' or '7'));
|
||||
Assert.AreEqual("77x7x7x7-xx77-7x7x-7x7x-7x7x7x7x7x7x", node["rank_token"]!.GetValue<string>());
|
||||
Assert.AreNotEqual("Lucia", node["nome"]!.GetValue<string>());
|
||||
Assert.IsFalse(node["nome"]!.GetValue<string>().All(c => c == 'x'), "Ordinary values keep their varied fakes.");
|
||||
Assert.IsTrue(SampleSanitizer.LooksLikeSecretKey("client_cache_key"));
|
||||
Assert.IsFalse(SampleSanitizer.LooksLikeSecretKey("username"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheProbeReadsOnlyThroughAReadOnlyScript() =>
|
||||
Febe.Browser.Cdp.ReadOnlyScriptGuard.EnsureReadOnly(ProbeRecorder.InteractionScript);
|
||||
@@ -209,5 +227,31 @@ public sealed class SanitizerTests
|
||||
using var document = JsonDocument.Parse(text);
|
||||
Assert.IsTrue(document.RootElement.TryGetProperty("corpo", out _));
|
||||
}
|
||||
|
||||
// The same for tests/campioni/instagram: no address of Instagram or of its CDN, every address a fake one.
|
||||
foreach (var file in Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), "*.json"))
|
||||
{
|
||||
var text = File.ReadAllText(file);
|
||||
foreach (var host in new[] { "instagram.com", "cdninstagram", "fbcdn" })
|
||||
{
|
||||
Assert.IsFalse(text.Contains(host, StringComparison.OrdinalIgnoreCase), $"{file}: {host}");
|
||||
}
|
||||
|
||||
using var document = JsonDocument.Parse(text);
|
||||
Assert.IsTrue(document.RootElement.TryGetProperty("descrittore", out _), file);
|
||||
Assert.IsTrue(document.RootElement.TryGetProperty("corpo", out _), file);
|
||||
foreach (var address in Strings(document.RootElement).Where(v => v.StartsWith("http", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
Assert.IsTrue(System.Text.RegularExpressions.Regex.IsMatch(address, @"^https://(sito|cdn|altro)\.esempio/"), $"{file}: indirizzo non ripulito");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<string> Strings(JsonElement element) => element.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => [element.GetString()!],
|
||||
JsonValueKind.Object => element.EnumerateObject().SelectMany(p => Strings(p.Value)),
|
||||
JsonValueKind.Array => element.EnumerateArray().SelectMany(Strings),
|
||||
_ => [],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,732 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Tests.Collection.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The story and highlight viewers on the scripted site, with and without the item shown in the address. Instagram's
|
||||
/// highlight viewer stays on «/stories/highlights/{id}/» from one item to the next (HAR of 21/10/2026): the recipe
|
||||
/// counts the items against the list the page received. The test site writes the item in the address
|
||||
/// («/storie/{username}/{id}/»): the recipe keeps reading it from there.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ViewerAddressTests
|
||||
{
|
||||
private const string SummerId = "17900000000000001";
|
||||
private const string TravelId = "17900000000000002";
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(SummerId)]
|
||||
[DataRow("highlight:" + SummerId)]
|
||||
public async Task AHighlightViewerWithoutTheItemInTheAddressSavesTheItemsShownAndClosesAfterTheLast(string requested)
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false);
|
||||
var (_, account) = await bed.AddCollectionsAsync();
|
||||
|
||||
var outcome = await bed.RunHighlightAsync(account, requested);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual(4, outcome.NewEntries);
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2", "e3" }, bed.Viewer.Seen, "Closed after the last item: never on to the next collection.");
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2", "e3" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "Every item shown, in order.");
|
||||
Assert.AreEqual(0, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Highlight })).Count(e => e.InstagramId!.StartsWith('v')), "The other collection received with it is not saved.");
|
||||
Assert.AreEqual(3, bed.Viewer.NextClicks);
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
Assert.AreEqual(4, bed.Bed.Governor.Granted(ActionKind.StoryView), "One permit per item shown.");
|
||||
bed.AssertNoItemCameOnScreenBeforeItsPermit();
|
||||
Assert.AreEqual("/profilo/nadia.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None), "Back on the profile.");
|
||||
Assert.AreEqual("/evidenza/" + SummerId + "/", bed.Viewer.OpenedAt, "The collection is clicked by the identifier of its address.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheItemInTheAddressAVideoIsLeftBeforeItEndsAlsoWhenTheWatchWouldLastLonger()
|
||||
{
|
||||
// Mood × pace 1.2 and a draw near the top: the watch of a ten-second video would last 11.3 s, past its end but
|
||||
// short of the old three-second margin. Clicked then, «next» would have skipped «p1».
|
||||
var random = new FixedRandom(0.9);
|
||||
var watch = StoryTimings.Watch(random, TimeSpan.FromSeconds(10), 1.2);
|
||||
Assert.IsTrue(watch > TimeSpan.FromSeconds(10) && watch < TimeSpan.FromSeconds(13), $"Watch of {watch}.");
|
||||
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false, waitMultiplier: 1.2, random: random);
|
||||
var (_, account) = await bed.AddCollectionsAsync([new("v0", Video: TimeSpan.FromSeconds(10)), new("p1"), new("p2")]);
|
||||
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "v0", "p1", "p2" }, bed.Viewer.Seen, "Never on to the next collection.");
|
||||
CollectionAssert.AreEqual(new[] { "v0", "p1", "p2" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "Every item shown, in order.");
|
||||
Assert.AreEqual(2, bed.Viewer.NextClicks, "«next» on the video before it ended, then on «p1».");
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
bed.AssertNoItemCameOnScreenBeforeItsPermit();
|
||||
Assert.IsFalse((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "visualizzatore-altro-account"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public async Task AnUnexpectedErrorInTheViewerClosesItAndKeepsWhatWasShown(bool itemInAddress)
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress);
|
||||
var (_, account) = await bed.AddCollectionsAsync();
|
||||
bed.Viewer.FailAtNextClick = 2;
|
||||
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.Failed, outcome.Status, outcome.Message);
|
||||
StringAssert.Contains(outcome.Message, "Errore imprevisto");
|
||||
StringAssert.Contains(outcome.Message, nameof(InvalidOperationException));
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks, "The viewer is closed: left open it would move on by itself.");
|
||||
Assert.AreEqual("/profilo/nadia.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "The two items shown before the error are saved.");
|
||||
Assert.IsTrue((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "ricetta-fallita"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(2, DisplayName = "The video ended: the viewer moved on by itself")]
|
||||
[DataRow(30, DisplayName = "The video stalled: the viewer is still on it")]
|
||||
public async Task WithoutTheItemInTheAddressAVideoThatMayHaveEndedIsNeverClickedPastNorCountedAsOver(int onScreenSeconds)
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false, spacing: TimeSpan.FromSeconds(6));
|
||||
var nadia = bed.Bed.Site.Add(new ScriptedAccount("2003", "nadia.prova"));
|
||||
var account = await bed.Bed.AddAccountAsync(nadia);
|
||||
nadia.HighlightsWithItems.Add(("highlight:" + SummerId, "Estate", []));
|
||||
var video = new ViewerItem("v0", TimeSpan.FromSeconds(onScreenSeconds), Video: TimeSpan.FromSeconds(2));
|
||||
bed.Viewer.Add(ViewerAnswers.Highlight(nadia, SummerId, "Estate", [video, new ViewerItem("p1"), new ViewerItem("p2")]));
|
||||
|
||||
// The Governor makes the permit for «p1» wait 6 s: the two-second video may be over by then, with the viewer on
|
||||
// «p1» by itself, or it may have stalled. The address does not say which: closed, without clicking «next».
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
var saved = (await bed.ItemsOfAsync(account, SummerId)).ToArray();
|
||||
CollectionAssert.AreEqual(new[] { "v0" }, saved, "Only what was surely shown under its permit.");
|
||||
CollectionAssert.IsSubsetOf(saved, bed.Viewer.Seen, "Nothing saved that was not on screen.");
|
||||
Assert.AreEqual(0, bed.Viewer.NextClicks, "No click on a video that may have ended: it would have skipped «p1».");
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
Assert.AreEqual(2, bed.Bed.Governor.Granted(ActionKind.StoryView), "For «v0», and for «p1» before it could come on screen.");
|
||||
Assert.IsTrue((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "visualizzatore-chiuso-prima"), "The early close is recorded.");
|
||||
Assert.AreEqual("/profilo/nadia.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheItemInTheAddressOnlyStoriesAreCountedAsStories()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
|
||||
// A post of the account arrives with the stories, ahead of them: counted by position it would take the place of «s0».
|
||||
var post = ScriptedSite.Post(marta, new ScriptedPost("post1", bed.Bed.Clock.Now.AddDays(-1)));
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1")], post));
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "s0", "s1" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray());
|
||||
Assert.AreEqual(0, (await bed.Bed.PostIdsAsync(account.Id)).Count, "The post received with the viewer is not saved by it.");
|
||||
Assert.AreEqual(1, bed.Viewer.NextClicks);
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
Assert.AreEqual("/profilo/marta.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithTheItemInTheAddressStoriesAreFollowedByTheAddressAsBefore()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
await bed.Bed.AddAccountAsync(bed.Bed.Site.Add(new ScriptedAccount("2001", "luca.prova")));
|
||||
|
||||
// «s1» stays on screen half a second: the viewer moves on to «s2» by itself while the recipe watches.
|
||||
var stories = ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1", TimeSpan.FromMilliseconds(500)), new ViewerItem("s2")]);
|
||||
bed.Viewer.Add(stories with { Next = "luca.prova" });
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(bed.Bed.Site.Accounts["luca.prova"], [new ViewerItem("l0")]));
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual(3, outcome.NewEntries);
|
||||
CollectionAssert.AreEqual(new[] { "s0", "s1", "s2" }, bed.Viewer.Seen, "Closed after the last story, before the next account.");
|
||||
Assert.AreEqual(1, bed.Viewer.NextClicks, "From «s0» to «s1»; «s2» came by itself, and the address said so.");
|
||||
Assert.AreEqual(3, bed.Bed.Governor.Granted(ActionKind.StoryView), "One permit per story shown.");
|
||||
bed.AssertNoItemCameOnScreenBeforeItsPermit(); // «s2» too, that came by itself: its permit was asked on «s1»
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
Assert.AreEqual("/profilo/marta.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithTheItemInTheAddressAPostArrivingAfterTheStoriesDoesNotHideTheLastOne()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
await bed.Bed.AddAccountAsync(bed.Bed.Site.Add(new ScriptedAccount("2001", "luca.prova")));
|
||||
|
||||
// The grid of the profile comes in an answer of its own, after the viewer opened: a post of the account.
|
||||
var post = ScriptedSite.Post(marta, new ScriptedPost("post1", bed.Bed.Clock.Now.AddDays(-1)));
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1"), new ViewerItem("s2")]) with
|
||||
{
|
||||
Next = "luca.prova",
|
||||
Then = new JsonObject { ["contenuti"] = new JsonArray(post) },
|
||||
});
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(bed.Bed.Site.Accounts["luca.prova"], [new ViewerItem("l0")]));
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "s0", "s1", "s2" }, bed.Viewer.Seen, "Closed after «s2», the last story: never on to the next account.");
|
||||
Assert.AreEqual(2, bed.Viewer.NextClicks);
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
Assert.AreEqual(3, bed.Bed.Governor.Granted(ActionKind.StoryView), "No permit for a story after the last one.");
|
||||
Assert.IsFalse((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "visualizzatore-altro-account"));
|
||||
CollectionAssert.AreEqual(new[] { "s0", "s1", "s2" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public async Task AViewerThatDoesNotCloseStopsTheRunAsATargetNotFoundAndKeepsWhatWasShown(bool itemInAddress)
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress);
|
||||
var (_, account) = await bed.AddCollectionsAsync();
|
||||
bed.Viewer.IgnoresClose = true; // «viewer-close» is found, and the viewer stays open
|
||||
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.TargetNotFound, outcome.Status, outcome.Message);
|
||||
StringAssert.Contains(outcome.Message, SiteTargets.ViewerClose);
|
||||
Assert.AreEqual(2, bed.Viewer.CloseClicks, "One more try on the way out.");
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2", "e3" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "What was shown is saved all the same.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARefusedPermitWithAViewerThatDoesNotCloseStopsAsATargetNotFound()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false, storyGrants: 2);
|
||||
var (_, account) = await bed.AddCollectionsAsync();
|
||||
bed.Viewer.IgnoresClose = true;
|
||||
|
||||
// Refused on «e1», the viewer is closed at once, but it stays open: the run says so, as a target not found
|
||||
// (the session stops and puts the page at rest), not as a refusal (it would go on with the viewer open).
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.TargetNotFound, outcome.Status, outcome.Message);
|
||||
StringAssert.Contains(outcome.Message, "Tetto delle storie raggiunto (prova).");
|
||||
StringAssert.Contains(outcome.Message, SiteTargets.ViewerClose);
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public async Task ACancellationWhileWatchingKeepsWhatWasShownAndThenGoesOn(bool itemInAddress)
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress);
|
||||
var (_, account) = await bed.AddCollectionsAsync();
|
||||
using var cancel = new CancellationTokenSource();
|
||||
bed.Viewer.CancelAtWait = (3, cancel); // while watching «e2», as a pause or a signal that closes the session would
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.Highlight, account.Id, HighlightId: SummerId), cancel.Token);
|
||||
Assert.AreEqual(RecipeStatus.Cancelled, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "The three items shown are saved.");
|
||||
Assert.AreEqual(0, bed.Viewer.CloseClicks, "A cancelled run leaves the page as it is.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ACancellationWhileWatchingStoriesKeepsTheStoriesShown()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1"), new ViewerItem("s2")]));
|
||||
using var cancel = new CancellationTokenSource();
|
||||
bed.Viewer.CancelAtWait = (2, cancel); // while watching «s1»
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id), cancel.Token);
|
||||
Assert.AreEqual(RecipeStatus.Cancelled, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "s0", "s1" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray());
|
||||
Assert.AreEqual(0, bed.Viewer.CloseClicks);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(true)]
|
||||
[DataRow(false)]
|
||||
public async Task AClickThatOpensAnAddressTheMapDoesNotTakeForTheViewerIsClosedBeforeTheRecipeStops(bool closes)
|
||||
{
|
||||
// The map wants the story in the address; the site opens the viewer without it.
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true, siteWritesItem: false);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1")]));
|
||||
bed.Viewer.IgnoresClose = !closes;
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
|
||||
Assert.AreEqual(closes ? RecipeStatus.Failed : RecipeStatus.TargetNotFound, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "s0" }, bed.Viewer.Seen, "No second click on what opened.");
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks, "What opened is closed like a viewer.");
|
||||
Assert.AreEqual(closes ? "/profilo/marta.prova/" : "/storie/marta.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
|
||||
Assert.AreEqual(0, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithTheItemInTheAddressTheViewerIsFollowedFromTheItemItOpensOn()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1"), new ViewerItem("s2")]));
|
||||
bed.Viewer.StartAt = 1; // a site that opens on the first story not seen yet
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "s1", "s2" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray(), "«s0» was received, never shown.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ProfilesSuggestedBesideTheProfileAreNotItsPage()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false);
|
||||
var account = await bed.Bed.AddAccountAsync(new ScriptedAccount("2003", "nadia.prova")); // its profile never arrives
|
||||
bed.Viewer.AlongsideEveryPage = new JsonObject
|
||||
{
|
||||
["suggeriti"] = new JsonArray(ScriptedSite.Profile(new ScriptedAccount("4001", "altro.prova")), ScriptedSite.Profile(new ScriptedAccount("4002", "ancora.prova"))),
|
||||
};
|
||||
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual("La pagina è arrivata vuota: nessun dato da leggere.", outcome.Message, "An empty page, not «the collection is not on the profile».");
|
||||
Assert.AreEqual(0, bed.Bed.Governor.Granted(ActionKind.StoryView));
|
||||
Assert.IsNull(bed.Viewer.OpenedAt);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the viewer of the scripted site receives, in the format of the test site (<c>lettori.prova.json</c>).</summary>
|
||||
internal static class ViewerAnswers
|
||||
{
|
||||
/// <summary>A collection of <paramref name="owner"/> as the viewer receives it: «highlight:» before the identifier, as Instagram writes it.</summary>
|
||||
public static Viewable Highlight(ScriptedAccount owner, string id, string title, IReadOnlyList<ViewerItem> items, params Viewable[] alsoReceived)
|
||||
{
|
||||
var node = HighlightNode(owner, id, title, items);
|
||||
var all = new JsonArray(node);
|
||||
foreach (var other in alsoReceived)
|
||||
{
|
||||
all.Add(HighlightNode(owner, other.Key, other.Title, other.Items));
|
||||
}
|
||||
|
||||
return new Viewable("evidenza", id, title, items, new JsonObject { ["raccolte"] = all });
|
||||
}
|
||||
|
||||
private static JsonObject HighlightNode(ScriptedAccount owner, string id, string title, IReadOnlyList<ViewerItem> items) => new()
|
||||
{
|
||||
["numero"] = "highlight:" + id,
|
||||
["titolo"] = title,
|
||||
["autore"] = ScriptedSite.Lite(owner),
|
||||
["contenuti"] = new JsonArray([.. items.Select(i => (JsonNode)Item(owner, i, expires: false))]),
|
||||
};
|
||||
|
||||
/// <summary>The stories of <paramref name="owner"/> as the viewer receives them, after <paramref name="before"/> when given.</summary>
|
||||
public static Viewable Stories(ScriptedAccount owner, IReadOnlyList<ViewerItem> items, JsonObject? before = null)
|
||||
{
|
||||
var body = new JsonObject();
|
||||
if (before is not null)
|
||||
{
|
||||
body["contenuti"] = new JsonArray(before);
|
||||
}
|
||||
|
||||
body["storie"] = new JsonArray([.. items.Select(i => (JsonNode)Item(owner, i, expires: true))]);
|
||||
body["autore"] = ScriptedSite.Lite(owner);
|
||||
return new Viewable("storie", owner.Username, owner.Username, items, body);
|
||||
}
|
||||
|
||||
private static JsonObject Item(ScriptedAccount owner, ViewerItem item, bool expires)
|
||||
{
|
||||
var takenAt = new DateTimeOffset(2026, 10, 13, 6, 0, 0, TimeSpan.Zero);
|
||||
var node = ScriptedSite.Post(owner, new ScriptedPost(item.Id, takenAt)
|
||||
{
|
||||
ExpiresAt = expires ? takenAt.AddHours(24) : null,
|
||||
Url = $"https://cdn.prova/m/{item.Id}.jpg",
|
||||
});
|
||||
if (item.Video is { } duration)
|
||||
{
|
||||
node["filmati"] = new JsonArray(new JsonObject { ["indirizzo"] = $"https://cdn.prova/m/{item.Id}.mp4", ["larghezza"] = 720, ["altezza"] = 1280, ["audio"] = true });
|
||||
node["durata"] = duration.TotalSeconds;
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An item of a viewer: how long it stays on screen before the viewer moves on by itself, and its video length.</summary>
|
||||
internal sealed record ViewerItem(string Id, TimeSpan? OnScreen = null, TimeSpan? Video = null);
|
||||
|
||||
/// <summary>What a viewer shows for one owner (an account, or a collection), and what the page receives when it opens.</summary>
|
||||
/// <param name="Kind">«storie» or «evidenza», the first segment of its address.</param>
|
||||
/// <param name="Key">The owner in the address: user name, or identifier of the collection.</param>
|
||||
internal sealed record Viewable(string Kind, string Key, string Title, IReadOnlyList<ViewerItem> Items, JsonObject Body)
|
||||
{
|
||||
/// <summary>The owner the viewer moves on to by itself after the last item (another account, another collection).</summary>
|
||||
public string? Next { get; init; }
|
||||
|
||||
/// <summary>An answer of its own the page receives right after <see cref="Body"/> (the grid of the profile, say).</summary>
|
||||
public JsonObject? Then { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The scripted site with a viewer, as a decorator: clicking a story ring or a collection opens its viewer on the first
|
||||
/// item (or on <see cref="StartAt"/>) and hands the capture what the page receives; «viewer-next» moves one item on; an
|
||||
/// item moves on by itself after its time on screen (time is the virtual clock, which the waits move on); after the last
|
||||
/// item the viewer goes on to <see cref="Viewable.Next"/> or closes; «viewer-close» goes back to the page it was opened
|
||||
/// from. The address carries the item shown only with <see cref="AddressWithItem"/>.
|
||||
/// </summary>
|
||||
internal sealed class ViewerSite(ScriptedSite site, CaptureCollector capture, VirtualClock clock) : IPageDriver
|
||||
{
|
||||
private static readonly TimeSpan PhotoOnScreen = TimeSpan.FromMinutes(1); // long: only clicks move a photo on, unless a test says so
|
||||
|
||||
private readonly Dictionary<string, Viewable> _viewables = new(StringComparer.OrdinalIgnoreCase);
|
||||
private Viewable? _open;
|
||||
private int _index;
|
||||
private DateTimeOffset _since;
|
||||
private int _responses;
|
||||
private int _waits;
|
||||
|
||||
public bool AddressWithItem { get; init; }
|
||||
|
||||
/// <summary>The item the viewer opens on (a site that resumes from the first item not seen).</summary>
|
||||
public int StartAt { get; set; }
|
||||
|
||||
/// <summary>The click on «next» (from 1) that throws, as a broken connection with the browser would.</summary>
|
||||
public int? FailAtNextClick { get; set; }
|
||||
|
||||
/// <summary>«viewer-close» is found, but the viewer stays open (a click that lands on the wrong element).</summary>
|
||||
public bool IgnoresClose { get; set; }
|
||||
|
||||
/// <summary>The wait (from 1) during which the source is cancelled: the wait then throws, as <see cref="Task.Delay(TimeSpan, CancellationToken)"/> would.</summary>
|
||||
public (int Wait, CancellationTokenSource Source)? CancelAtWait { get; set; }
|
||||
|
||||
/// <summary>An answer unrelated to the account (suggested profiles) that arrives with every page opened.</summary>
|
||||
public JsonObject? AlongsideEveryPage { get; set; }
|
||||
|
||||
/// <summary>The items that came on screen, in order.</summary>
|
||||
public List<string> Seen { get; } = [];
|
||||
|
||||
public int NextClicks { get; private set; }
|
||||
|
||||
public int CloseClicks { get; private set; }
|
||||
|
||||
/// <summary>The address of the first viewer opened.</summary>
|
||||
public string? OpenedAt { get; private set; }
|
||||
|
||||
public double WaitMultiplier { get; init; } = 1;
|
||||
|
||||
public void Add(Viewable viewable) => _viewables[viewable.Kind + "/" + viewable.Key] = viewable;
|
||||
|
||||
/// <summary>How many items have come on screen until now.</summary>
|
||||
public int OnScreenSoFar()
|
||||
{
|
||||
Tick();
|
||||
return Seen.Count;
|
||||
}
|
||||
|
||||
public void BeginSession(double mood) => site.BeginSession(mood);
|
||||
|
||||
public async Task<PageLoad> OpenAsync(string path, CancellationToken ct)
|
||||
{
|
||||
_open = null;
|
||||
var load = await site.OpenAsync(path, ct);
|
||||
if (AlongsideEveryPage is { } other)
|
||||
{
|
||||
Deliver(other);
|
||||
}
|
||||
|
||||
return load;
|
||||
}
|
||||
|
||||
public Task<string> CurrentPathAsync(CancellationToken ct)
|
||||
{
|
||||
Tick();
|
||||
if (_open is not { } open)
|
||||
{
|
||||
return Task.FromResult(site.CurrentPath);
|
||||
}
|
||||
|
||||
var path = "/" + open.Kind + "/" + Uri.EscapeDataString(open.Key) + "/";
|
||||
return Task.FromResult(AddressWithItem ? path + Uri.EscapeDataString(open.Items[_index].Id) + "/" : path);
|
||||
}
|
||||
|
||||
public Task<bool> IsOnSiteAsync(CancellationToken ct) => Task.FromResult(true);
|
||||
|
||||
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => site.FindAsync(target, parameters, ct);
|
||||
|
||||
public async Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
|
||||
{
|
||||
Tick();
|
||||
var check = await site.FindAsync(target, parameters, ct);
|
||||
if (!check.Found)
|
||||
{
|
||||
return check;
|
||||
}
|
||||
|
||||
var clicked = new TargetCheck(target, TargetCheckStatus.Clicked, 1, "Cliccato.");
|
||||
switch (target)
|
||||
{
|
||||
case SiteTargets.ProfileHighlight:
|
||||
return Show("evidenza/" + parameters!["id"]) ? clicked : NotFound(target);
|
||||
case SiteTargets.ProfileStoryRing or SiteTargets.HomeStory:
|
||||
return Show("storie/" + parameters!["username"]) ? clicked : NotFound(target);
|
||||
case SiteTargets.ViewerNext when _open is not null:
|
||||
if (++NextClicks == FailAtNextClick)
|
||||
{
|
||||
throw new InvalidOperationException("Il collegamento con il navigatore si è interrotto (prova).");
|
||||
}
|
||||
|
||||
MoveOn(clock.Now);
|
||||
return clicked;
|
||||
case SiteTargets.ViewerClose when _open is not null:
|
||||
CloseClicks++;
|
||||
if (!IgnoresClose)
|
||||
{
|
||||
_open = null;
|
||||
}
|
||||
|
||||
return clicked;
|
||||
default:
|
||||
return clicked;
|
||||
}
|
||||
}
|
||||
|
||||
public Task ScrollBurstAsync(CancellationToken ct) => site.ScrollBurstAsync(ct);
|
||||
|
||||
public Task WaitAfterLoadAsync(CancellationToken ct) => site.WaitAfterLoadAsync(ct);
|
||||
|
||||
public Task WaitAsync(TimeSpan duration, CancellationToken ct)
|
||||
{
|
||||
clock.Advance(duration);
|
||||
if (CancelAtWait is { } cancel && ++_waits == cancel.Wait)
|
||||
{
|
||||
cancel.Source.Cancel();
|
||||
}
|
||||
|
||||
return ct.IsCancellationRequested ? Task.FromCanceled(ct) : Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Task.FromResult<bool?>(true);
|
||||
|
||||
public Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
_open = null;
|
||||
return site.RestAsync(ct);
|
||||
}
|
||||
|
||||
private static TargetCheck NotFound(string target) => new(target, TargetCheckStatus.NotFound, 0, $"Bersaglio «{target}» non trovato.");
|
||||
|
||||
private static TimeSpan OnScreen(ViewerItem item) => item.OnScreen ?? item.Video ?? PhotoOnScreen;
|
||||
|
||||
private bool Show(string key)
|
||||
{
|
||||
if (!_viewables.TryGetValue(key, out var viewable))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Open(viewable, StartAt, clock.Now);
|
||||
OpenedAt ??= "/" + viewable.Kind + "/" + viewable.Key + "/";
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Open(Viewable viewable, int index, DateTimeOffset since)
|
||||
{
|
||||
_open = viewable;
|
||||
_index = index;
|
||||
_since = since;
|
||||
Seen.Add(viewable.Items[index].Id);
|
||||
Deliver(viewable.Body);
|
||||
if (viewable.Then is { } then)
|
||||
{
|
||||
Deliver(then);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The viewer moves on by itself when an item has been on screen for its time.</summary>
|
||||
private void Tick()
|
||||
{
|
||||
while (_open is { } open && clock.Now - _since >= OnScreen(open.Items[_index]))
|
||||
{
|
||||
MoveOn(_since + OnScreen(open.Items[_index]));
|
||||
}
|
||||
}
|
||||
|
||||
private void MoveOn(DateTimeOffset at)
|
||||
{
|
||||
var open = _open!;
|
||||
if (_index + 1 < open.Items.Count)
|
||||
{
|
||||
_index++;
|
||||
_since = at;
|
||||
Seen.Add(open.Items[_index].Id);
|
||||
return;
|
||||
}
|
||||
|
||||
if (open.Next is { } next && _viewables.TryGetValue(open.Kind + "/" + next, out var following))
|
||||
{
|
||||
Open(following, 0, at);
|
||||
return;
|
||||
}
|
||||
|
||||
_open = null; // after the last item, with nothing after it, the viewer closes by itself
|
||||
}
|
||||
|
||||
private void Deliver(JsonObject body)
|
||||
{
|
||||
var id = "v" + Interlocked.Increment(ref _responses).ToString(CultureInfo.InvariantCulture);
|
||||
using var document = JsonDocument.Parse(body.ToJsonString());
|
||||
capture.Accept(new ResponseDescriptor(id, HostKind.Site, "http://prova.local/dati", "prova.local", "/dati", 200, "application/json", "Fetch", false, clock.Now), document.RootElement);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A scripted bed whose page has a viewer; the Governor can make every story permit wait, like its minimum spacing.</summary>
|
||||
internal sealed class ViewerBed : IAsyncDisposable
|
||||
{
|
||||
private ViewerBed(ScriptedBed bed, ViewerSite viewer, PermitWatcher permits, RecipeRunner runner)
|
||||
{
|
||||
Bed = bed;
|
||||
Viewer = viewer;
|
||||
Permits = permits;
|
||||
Runner = runner;
|
||||
}
|
||||
|
||||
public ScriptedBed Bed { get; }
|
||||
|
||||
public ViewerSite Viewer { get; }
|
||||
|
||||
/// <summary>What was on screen at each story permit granted.</summary>
|
||||
public PermitWatcher Permits { get; }
|
||||
|
||||
public RecipeRunner Runner { get; }
|
||||
|
||||
/// <param name="itemInAddress">Whether the map's viewer addresses carry the item shown.</param>
|
||||
/// <param name="spacing">Every story permit first waits this long (the Governor's minimum spacing).</param>
|
||||
/// <param name="waitMultiplier">Mood × pace of the page driver.</param>
|
||||
/// <param name="random">The random source of the recipes (a seeded one by default).</param>
|
||||
/// <param name="siteWritesItem">Whether the site writes the item in the address (as the map says, by default).</param>
|
||||
/// <param name="storyGrants">After this many story permits the Governor refuses, while the budget says there is room.</param>
|
||||
public static async Task<ViewerBed> CreateAsync(bool itemInAddress, TimeSpan? spacing = null, double waitMultiplier = 1, IRandomSource? random = null, bool? siteWritesItem = null, int? storyGrants = null)
|
||||
{
|
||||
var pages = ScriptedBed.TestSitePages.ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal);
|
||||
if (!itemInAddress)
|
||||
{
|
||||
pages[SitePages.StoryViewer] = "/storie/{username}/";
|
||||
pages[SitePages.HighlightViewer] = "/evidenza/{highlight}/";
|
||||
}
|
||||
|
||||
var bed = await ScriptedBed.CreateAsync(new SiteMap("prova", pages, SiteTargets.All, SiteTargets.All));
|
||||
var viewer = new ViewerSite(bed.Site, bed.Runner.Env.Capture, bed.Clock) { AddressWithItem = siteWritesItem ?? itemInAddress, WaitMultiplier = waitMultiplier };
|
||||
IGovernor governor = storyGrants is { } grants ? new StoryGrantsGovernor(bed.Governor, grants) : bed.Governor;
|
||||
governor = spacing is { } wait ? new SpacedGovernor(governor, bed.Clock, wait) : governor;
|
||||
var permits = new PermitWatcher(governor, viewer);
|
||||
return new ViewerBed(bed, viewer, permits, new RecipeRunner(bed.Runner.Env with { Driver = viewer, Governor = permits, Random = random ?? bed.Runner.Env.Random }));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «nadia.prova» with two collections on her profile, «Estate» (e0–e3, or <paramref name="summer"/>) and «Viaggi»
|
||||
/// (v0–v1): the viewer of «Estate» receives both, as Instagram's did, and goes on to «Viaggi» by itself after the last item.
|
||||
/// </summary>
|
||||
public async Task<(ScriptedAccount Scripted, Account Account)> AddCollectionsAsync(IReadOnlyList<ViewerItem>? summer = null)
|
||||
{
|
||||
var nadia = Bed.Site.Add(new ScriptedAccount("2003", "nadia.prova"));
|
||||
var account = await Bed.AddAccountAsync(nadia);
|
||||
nadia.HighlightsWithItems.Add(("highlight:17900000000000001", "Estate", []));
|
||||
nadia.HighlightsWithItems.Add(("highlight:17900000000000002", "Viaggi", []));
|
||||
summer ??= [new("e0"), new("e1"), new("e2"), new("e3")];
|
||||
IReadOnlyList<ViewerItem> travel = [new("v0"), new("v1")];
|
||||
var travelView = ViewerAnswers.Highlight(nadia, "17900000000000002", "Viaggi", travel);
|
||||
Viewer.Add(ViewerAnswers.Highlight(nadia, "17900000000000001", "Estate", summer, travelView) with { Next = "17900000000000002" });
|
||||
Viewer.Add(travelView);
|
||||
return (nadia, account);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every item that came on screen had its story permit before (rule 7, §6.3): the n-th permit was granted before
|
||||
/// the n-th item came, and no item came without one.
|
||||
/// </summary>
|
||||
public void AssertNoItemCameOnScreenBeforeItsPermit()
|
||||
{
|
||||
var atPermit = Permits.OnScreenAtStoryPermit;
|
||||
for (var i = 0; i < atPermit.Count; i++)
|
||||
{
|
||||
Assert.IsTrue(atPermit[i] <= i, $"Story permit {i + 1} granted when {atPermit[i]} items had already come on screen ({string.Join(", ", Viewer.Seen)}).");
|
||||
}
|
||||
|
||||
Assert.IsTrue(Viewer.Seen.Count <= atPermit.Count, $"{Viewer.Seen.Count} items came on screen ({string.Join(", ", Viewer.Seen)}) with {atPermit.Count} story permits.");
|
||||
}
|
||||
|
||||
public Task<RecipeOutcome> RunAsync(RecipeRequest request, CancellationToken ct = default) => Runner.RunAsync(request, Bed.Session, ct);
|
||||
|
||||
public Task<RecipeOutcome> RunHighlightAsync(Account account, string highlightId) =>
|
||||
RunAsync(new RecipeRequest(RecipeKind.Highlight, account.Id, HighlightId: highlightId));
|
||||
|
||||
/// <summary>Instagram identifiers of the items of a collection, in their order.</summary>
|
||||
public async Task<IReadOnlyList<string>> ItemsOfAsync(Account account, string highlightId)
|
||||
{
|
||||
var highlight = await Bed.Db.Highlights.FindAsync(account.Id, highlightId) ?? throw new AssertFailedException($"Raccolta {highlightId} non salvata.");
|
||||
var ids = new List<string>();
|
||||
foreach (var item in (await Bed.Db.Highlights.ListItemsAsync(highlight.Id)).OrderBy(i => i.Position))
|
||||
{
|
||||
ids.Add((await Bed.Db.Entries.GetAsync(item.EntryId))!.InstagramId!);
|
||||
}
|
||||
|
||||
return ids;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync() => Bed.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Grants what the inner Governor grants, but every story permit first waits <paramref name="spacing"/> (its minimum spacing).</summary>
|
||||
internal sealed class SpacedGovernor(IGovernor inner, VirtualClock clock, TimeSpan spacing) : IGovernor
|
||||
{
|
||||
public Task<Permit> RequestAsync(ActionKind kind, long? accountId, CancellationToken ct)
|
||||
{
|
||||
if (kind == ActionKind.StoryView)
|
||||
{
|
||||
clock.Advance(spacing);
|
||||
}
|
||||
|
||||
return inner.RequestAsync(kind, accountId, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Grants what the inner Governor grants, but refuses story permits after <paramref name="grants"/> (the budget view still says there is room).</summary>
|
||||
internal sealed class StoryGrantsGovernor(IGovernor inner, int grants) : IGovernor
|
||||
{
|
||||
private int _granted;
|
||||
|
||||
public Task<Permit> RequestAsync(ActionKind kind, long? accountId, CancellationToken ct) =>
|
||||
kind == ActionKind.StoryView && Interlocked.Increment(ref _granted) > grants
|
||||
? Task.FromResult(Permit.Deny(kind, accountId, DenialReason.HourlyBudgetReached, "Tetto delle storie raggiunto (prova)."))
|
||||
: inner.RequestAsync(kind, accountId, ct);
|
||||
}
|
||||
|
||||
/// <summary>Passes every request on and records, at each story permit granted, how many items had come on screen.</summary>
|
||||
internal sealed class PermitWatcher(IGovernor inner, ViewerSite viewer) : IGovernor
|
||||
{
|
||||
public List<int> OnScreenAtStoryPermit { get; } = [];
|
||||
|
||||
public async Task<Permit> RequestAsync(ActionKind kind, long? accountId, CancellationToken ct)
|
||||
{
|
||||
var permit = await inner.RequestAsync(kind, accountId, ct);
|
||||
if (kind == ActionKind.StoryView && permit.Granted)
|
||||
{
|
||||
OnScreenAtStoryPermit.Add(viewer.OnScreenSoFar());
|
||||
}
|
||||
|
||||
return permit;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A degenerate random source: always the same value (the draws of §7.2 come out the same every time).</summary>
|
||||
internal sealed class FixedRandom(double value) : IRandomSource
|
||||
{
|
||||
public double NextDouble() => value;
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Engine.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// The collection configuration in use (reader vocabulary and target map of the site, as loaded): what the log says of
|
||||
/// it, the copies in the Data folder that hide newer embedded files, and the suspensions counted against other files,
|
||||
/// cleared once when it changes.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class CollectionConfigurationTests
|
||||
{
|
||||
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
|
||||
|
||||
[TestMethod]
|
||||
public async Task AChangedCollectionConfigurationLiftsTheSuspensionsOfTheOldFilesOnce()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
await bed.AddAccountAsync("strano.demo", followed: false, Frequency.High);
|
||||
|
||||
// What the first Instagram files left in Alberto's database: suspended recipes and failures counted.
|
||||
var since = Morning.AddDays(-3).ToUnixTimeMilliseconds();
|
||||
await bed.Db.Settings.SetAsync(EngineSettingKeys.SuspendedRecipes, $"AccountStories={since};ProfileCheck={since}");
|
||||
await bed.Db.Settings.SetAsync(EngineSettingKeys.RecipeFailures, "AccountStories=3;Backfill=2;ProfileCheck=3");
|
||||
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
|
||||
var changed = false;
|
||||
var host = await bed.StartAsync(runner, async h => changed = await h.ApplyCollectionConfigurationAsync("impronta-1"));
|
||||
Assert.IsTrue(changed, "The first start that knows the configuration counts as a change.");
|
||||
Assert.IsEmpty(host.SuspendedRecipes);
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.SuspendedRecipes));
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures));
|
||||
Assert.AreEqual("impronta-1", await bed.Db.Settings.GetAsync(EngineSettingKeys.CollectionConfiguration));
|
||||
|
||||
var line = (await bed.Db.Events.ListAsync(new EventQuery())).Single(e => e.Code == EngineEventCodes.CollectionConfigurationChanged);
|
||||
Assert.AreEqual("La configurazione della raccolta è cambiata: le ricette sospese ripartono («Le storie», «Il controllo del profilo»).", line.Message);
|
||||
Assert.AreEqual(EventSeverity.Info, line.Severity);
|
||||
|
||||
await bed.RunUntilAsync(Morning.AddDays(1));
|
||||
Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck && r.Status == RecipeStatus.Completed), "The recipe runs again.");
|
||||
Assert.IsFalse(await host.ApplyCollectionConfigurationAsync("impronta-1"), "Same files: nothing to do.");
|
||||
|
||||
// A restart with the same files changes nothing; new files with nothing to clear say nothing.
|
||||
await bed.ReopenAsync(8);
|
||||
var again = true;
|
||||
var reopened = await bed.StartAsync(new ScriptedRunner(bed.Governor, bed.Clock), async h => again = await h.ApplyCollectionConfigurationAsync("impronta-1"));
|
||||
Assert.IsFalse(again);
|
||||
Assert.IsTrue(await reopened.ApplyCollectionConfigurationAsync("impronta-2"));
|
||||
Assert.AreEqual("impronta-2", await bed.Db.Settings.GetAsync(EngineSettingKeys.CollectionConfiguration));
|
||||
Assert.AreEqual(1, (await bed.Db.Events.ListAsync(new EventQuery())).Count(e => e.Code == EngineEventCodes.CollectionConfigurationChanged));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task FailuresAloneAreClearedWithTheirOwnLine()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
await bed.Db.Settings.SetAsync(EngineSettingKeys.RecipeFailures, "ProfileCheck=2");
|
||||
var host = new EngineHost(bed.Services, new ScriptedRunner(bed.Governor, bed.Clock));
|
||||
await using (host)
|
||||
{
|
||||
Assert.IsTrue(await host.ApplyCollectionConfigurationAsync("impronta"));
|
||||
}
|
||||
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures));
|
||||
var line = (await bed.Db.Events.ListAsync(new EventQuery())).Single(e => e.Code == EngineEventCodes.CollectionConfigurationChanged);
|
||||
Assert.AreEqual("La configurazione della raccolta è cambiata: i problemi delle ricette contati finora non valgono più.", line.Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheEmbeddedFilesAreDescribedWithoutTheirContentAndFingerprinted()
|
||||
{
|
||||
var configuration = CollectionConfiguration.Describe("prova", ReaderVocabulary.LoadTestSite(), SiteMap.LoadTestSite());
|
||||
Assert.IsFalse(configuration.VocabularyFile.IsOverride);
|
||||
Assert.IsFalse(configuration.MapFile.IsOverride);
|
||||
Assert.IsEmpty(configuration.Blocked);
|
||||
Assert.IsEmpty(configuration.Warnings);
|
||||
CollectionAssert.AreEqual(
|
||||
new[]
|
||||
{
|
||||
"Vocabolario dei lettori per «prova»: il file incorporato in Febe (lettori.prova.json), confermato.",
|
||||
"Mappa dei bersagli per «prova»: il file incorporato in Febe (bersagli.prova.json), tutte le voci compilate.",
|
||||
"Con questa configurazione tutte le ricette possono girare.",
|
||||
},
|
||||
configuration.Lines.ToArray());
|
||||
Assert.MatchesRegex("^[0-9a-f]{64}$", configuration.Fingerprint);
|
||||
Assert.AreEqual(configuration.Fingerprint, CollectionConfiguration.Describe("prova", ReaderVocabulary.LoadTestSite(), SiteMap.LoadTestSite()).Fingerprint);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ACopyInTheDataFolderIsNamedAndOneThatHidesABetterEmbeddedFileIsAWarning()
|
||||
{
|
||||
using var folder = new TempFolder("configurazione");
|
||||
var vocabularyText = SiteMap.ReadEmbeddedText("lettori.prova.json");
|
||||
var mapText = SiteMap.ReadEmbeddedText("bersagli.prova.json");
|
||||
var embedded = CollectionConfiguration.Describe("prova", ReaderVocabulary.LoadTestSite(), SiteMap.LoadTestSite());
|
||||
|
||||
// The same map with other line endings is the same configuration.
|
||||
var mapPath = folder.Combine("bersagli.prova.json");
|
||||
File.WriteAllText(mapPath, mapText.Contains("\r\n", StringComparison.Ordinal) ? mapText.Replace("\r\n", "\n", StringComparison.Ordinal) : mapText.Replace("\n", "\r\n", StringComparison.Ordinal));
|
||||
var sameMap = Loaded(folder, "prova");
|
||||
Assert.IsTrue(sameMap.MapFile.IsOverride);
|
||||
Assert.AreEqual(mapPath, sameMap.MapFile.OverridePath);
|
||||
Assert.AreEqual(embedded.Fingerprint, sameMap.Fingerprint);
|
||||
Assert.IsEmpty(sameMap.Warnings);
|
||||
StringAssert.Contains(sameMap.Lines[1], $"la copia nella cartella dei dati ({mapPath})");
|
||||
|
||||
// A stale vocabulary, still a hypothesis, hides the confirmed embedded one: every recipe would be refused.
|
||||
var vocabularyPath = folder.Combine("lettori.prova.json");
|
||||
File.WriteAllText(vocabularyPath, vocabularyText.Replace("\"confermato\"", "\"ipotesi\"", StringComparison.Ordinal));
|
||||
var stale = Loaded(folder, "prova");
|
||||
Assert.AreNotEqual(embedded.Fingerprint, stale.Fingerprint);
|
||||
CollectionAssert.AreEqual(Enum.GetValues<RecipeKind>(), stale.Blocked.ToArray());
|
||||
Assert.HasCount(1, stale.Warnings);
|
||||
StringAssert.Contains(stale.Warnings[0], vocabularyPath);
|
||||
StringAssert.Contains(stale.Warnings[0], "è ancora un'ipotesi, mentre quello incorporato in Febe è confermato");
|
||||
StringAssert.EndsWith(stale.Lines[0], ", ipotesi.");
|
||||
StringAssert.StartsWith(stale.Lines[2], "Con questa configurazione non possono girare 9 ricette su 9: Giro dei seguiti, ");
|
||||
|
||||
// A map that lacks what the embedded one has leaves recipes still that could run.
|
||||
File.Delete(vocabularyPath);
|
||||
File.WriteAllText(mapPath, """{ "site": "prova", "pages": { "home": "/" } }""");
|
||||
var poor = Loaded(folder, "prova");
|
||||
CollectionAssert.Contains(poor.Blocked.ToArray(), RecipeKind.ProfileCheck);
|
||||
CollectionAssert.DoesNotContain(poor.Blocked.ToArray(), RecipeKind.FollowingSweep);
|
||||
Assert.HasCount(1, poor.Warnings);
|
||||
StringAssert.Contains(poor.Warnings[0], $"La mappa dei bersagli in {mapPath} lascia ferme ricette che con quella incorporata in Febe potrebbero girare (");
|
||||
StringAssert.Contains(poor.Warnings[0], "Controllo del profilo");
|
||||
|
||||
// Never what is in the files.
|
||||
var note = ReaderVocabulary.LoadTestSite().Note!;
|
||||
foreach (var text in stale.Lines.Concat(stale.Warnings).Concat(poor.Lines).Concat(poor.Warnings))
|
||||
{
|
||||
Assert.IsFalse(text.Contains(note, StringComparison.Ordinal), text);
|
||||
Assert.IsFalse(text.Contains("/profilo/", StringComparison.Ordinal), text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The files loaded as the collection pipeline loads them: the Data-folder copy when it exists.</summary>
|
||||
private static CollectionConfiguration Loaded(TempFolder folder, string site)
|
||||
{
|
||||
var vocabulary = ReaderVocabulary.LoadOrEmbedded(folder.Combine($"lettori.{site}.json"), $"lettori.{site}.json");
|
||||
var map = SiteMap.LoadOrEmbedded(folder.Combine($"bersagli.{site}.json"), $"bersagli.{site}.json");
|
||||
return CollectionConfiguration.Describe(site, vocabulary, map);
|
||||
}
|
||||
}
|
||||
@@ -607,4 +607,28 @@ public sealed class EngineHostTests
|
||||
Assert.HasCount(foodLooks, Looks("17900000002"));
|
||||
Assert.IsTrue(Looks("17900000001").Count > travelLooks);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ASinglePostQueuedByTheCollectionRunsInsteadOfBeingCancelledByTheQueue()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
var account = await bed.AddAccountAsync("uno.demo", followed: true);
|
||||
var paused = await bed.AddAccountAsync("due.demo", followed: true, state: AccountState.Paused);
|
||||
|
||||
// As CollectionWriter.QueueSinglePostAsync queues it for an address that expired (spec §6.5 point 5).
|
||||
EngineTask SinglePost(Account a, string entryId) =>
|
||||
new() { Kind = EngineTaskKind.SinglePost, AccountId = a.Id, Payload = entryId, DueAt = Morning, CreatedAt = Morning };
|
||||
var refresh = await bed.Db.Tasks.EnqueueAsync(SinglePost(account, "41"));
|
||||
var held = await bed.Db.Tasks.EnqueueAsync(SinglePost(paused, "42"));
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
|
||||
bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(1));
|
||||
|
||||
var runs = runner.Runs.Where(r => r.Request.Kind == RecipeKind.SinglePost).ToList();
|
||||
Assert.HasCount(1, runs, "The expired address is refreshed once, on the account that may be contacted.");
|
||||
Assert.AreEqual(41L, runs[0].Request.EntryId);
|
||||
Assert.AreEqual(account.Id, runs[0].Request.AccountId);
|
||||
Assert.AreEqual(EngineTaskState.Done, (await bed.Db.Tasks.GetAsync(refresh.Id))!.State);
|
||||
Assert.AreEqual(EngineTaskState.Cancelled, (await bed.Db.Tasks.GetAsync(held.Id))!.State, "«In pausa»: not contacted.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Tests.Collection.Support;
|
||||
using Febe.Tests.Engine.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// A recipe the files of the site do not let run (target map or reader vocabulary incomplete) is a state of the
|
||||
/// configuration, not a failure (spec §6.4): never counted towards suspension, not planned, said once per process.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class NotConfiguredRecipeTests
|
||||
{
|
||||
private const string ProfileReason = "«Controllo del profilo» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano pagina «profile»).";
|
||||
private const string SweepReason = "«Giro dei seguiti» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano pagina «home»).";
|
||||
private const string ListReason = "«Elenco dei seguiti» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano pagina «following»).";
|
||||
private const string StoriesReason = "«Storie di un account» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano bersaglio «profile-story-ring»).";
|
||||
|
||||
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARecipeTheConfigurationDoesNotLetRunIsNotPlannedNotCountedAndSaidOnce()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
var account = await bed.AddAccountAsync("lontano.demo", followed: false, Frequency.High);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock) { NotConfigured = k => k == RecipeKind.ProfileCheck ? ProfileReason : null };
|
||||
var host = bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(2));
|
||||
|
||||
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck), "Never run: it would only be refused.");
|
||||
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.ProfileCheck), "Nor planned.");
|
||||
Assert.IsEmpty(host.SuspendedRecipes);
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures), "No failure counted.");
|
||||
|
||||
var events = await bed.Db.Events.ListAsync(new EventQuery());
|
||||
var said = events.Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).ToList();
|
||||
Assert.HasCount(1, said, "Once per recipe and process, not at every session.");
|
||||
Assert.AreEqual(ProfileReason + SessionComposer.NotConfiguredTail, said[0].Message);
|
||||
Assert.AreEqual(EventSeverity.Warning, said[0].Severity);
|
||||
Assert.IsFalse(events.Any(e => e.Code is EngineEventCodes.RecipeSuspended or EngineEventCodes.TargetNotFound or EngineEventCodes.FormatUnrecognized));
|
||||
Assert.IsGreaterThan(1, events.Count(e => e.Code == EngineEventCodes.SessionEnded), "Several sessions went by.");
|
||||
|
||||
// «Controlla ora» says why at once instead of queueing a check that cannot run.
|
||||
var check = await host.CheckNowAsync(account.Id);
|
||||
Assert.AreEqual(CheckNowStatus.Refused, check.Status);
|
||||
Assert.AreEqual(ProfileReason + " Il controllo non parte.", check.Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheSweepFollowedStoriesAreCheckedOneByOneAndACommandThatCannotRunIsDropped()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
await bed.AddAccountAsync("vicina.demo", followed: true);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
|
||||
{
|
||||
NotConfigured = k => k switch
|
||||
{
|
||||
RecipeKind.FollowingSweep => SweepReason,
|
||||
RecipeKind.FollowingList => ListReason,
|
||||
_ => null,
|
||||
},
|
||||
};
|
||||
var host = bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(1));
|
||||
|
||||
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.FollowingSweep));
|
||||
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.FollowingSweep), "The sweep is not shown in the queue.");
|
||||
Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.AccountStories), "No sweep covers the stories bar: they are checked explicitly.");
|
||||
|
||||
await host.RequestFollowingListAsync();
|
||||
await bed.RunForAsync(TimeSpan.FromHours(8));
|
||||
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.FollowingList));
|
||||
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.FollowingList), "Alberto's command is dropped, not left waiting for ever.");
|
||||
|
||||
var said = (await bed.Db.Events.ListAsync(new EventQuery())).Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).Select(e => e.Message).ToList();
|
||||
Assert.AreEqual(1, said.Count(m => m.StartsWith(SweepReason, StringComparison.Ordinal)));
|
||||
Assert.AreEqual(1, said.Count(m => m.StartsWith(ListReason, StringComparison.Ordinal)));
|
||||
Assert.AreEqual(1, said.Count(m => m == $"La tua richiesta (l'elenco dei profili che segui) è annullata: {ListReason}"));
|
||||
Assert.IsEmpty(host.SuspendedRecipes);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WhileTheStoriesCannotRunAProfileNotFollowedIsVisitedOnlyForItsPosts()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
var account = await bed.AddAccountAsync("lontana.demo", followed: false, Frequency.Low);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock) { NotConfigured = k => k == RecipeKind.AccountStories ? StoriesReason : null };
|
||||
bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(4));
|
||||
|
||||
// «Bassa»: the profile every 12 hours or so, never sooner than 0.6 × 12 h. A visit that also served the stories
|
||||
// would come at the story interval instead (a third of the window, about 5 hours), and collect nothing more.
|
||||
var visits = runner.Runs.Where(r => r.Request.Kind == RecipeKind.ProfileCheck && r.Status == RecipeStatus.Completed).Select(r => r.At).ToList();
|
||||
Assert.IsGreaterThan(2, visits.Count, "The profile is still checked for its posts.");
|
||||
for (var i = 1; i < visits.Count; i++)
|
||||
{
|
||||
Assert.IsTrue(visits[i] - visits[i - 1] >= TimeSpan.FromHours(7), $"Visit after {visits[i] - visits[i - 1]}.");
|
||||
}
|
||||
|
||||
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.AccountStories));
|
||||
Assert.IsNull((await bed.Db.Accounts.GetAsync(account.Id))!.NextStoriesCheckAt, "Story times stay as they are, for when the stories can run.");
|
||||
var said = (await bed.Db.Events.ListAsync(new EventQuery())).Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).ToList();
|
||||
Assert.HasCount(1, said);
|
||||
Assert.AreEqual(StoriesReason + SessionComposer.NotConfiguredTail, said[0].Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheStoriesBarQueuesNoStoryCheckTheConfigurationDoesNotLetRun()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
var account = await bed.AddAccountAsync("vicina.demo", followed: true);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
|
||||
{
|
||||
FlaggedStories = [account.Id],
|
||||
NotConfigured = k => k == RecipeKind.AccountStories ? StoriesReason : null,
|
||||
};
|
||||
bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(1));
|
||||
|
||||
Assert.IsGreaterThan(1, runner.Runs.Count(r => r.Request.Kind == RecipeKind.FollowingSweep && r.Status == RecipeStatus.Completed), "Several sweeps flagged the account.");
|
||||
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.AccountStories));
|
||||
Assert.AreEqual(0L, await TasksAsync(bed, EngineTaskKind.AccountStories), "No story check queued: none waits in the Coda, none is cancelled at the next session.");
|
||||
var said = (await bed.Db.Events.ListAsync(new EventQuery())).Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).ToList();
|
||||
Assert.HasCount(1, said, "Said once, not at every sweep.");
|
||||
Assert.AreEqual(StoriesReason + SessionComposer.NotConfiguredTail, said[0].Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARefusalOfTheRunnerIsNotAFailureAndIsNotTriedAgainInTheProcess()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
await bed.AddAccountAsync("strano.demo", followed: false, Frequency.High);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
|
||||
{
|
||||
Script = r => r.Kind == RecipeKind.ProfileCheck ? new RecipeOutcome(RecipeStatus.NotConfigured, 0, 0, ProfileReason) : null,
|
||||
};
|
||||
var host = bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(3));
|
||||
|
||||
// Three unrecognized formats suspend the recipe in two days (EngineHostTests); a refusal never does.
|
||||
Assert.AreEqual(1, runner.Runs.Count(r => r.Request.Kind == RecipeKind.ProfileCheck));
|
||||
Assert.IsEmpty(host.SuspendedRecipes);
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures));
|
||||
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.ProfileCheck));
|
||||
|
||||
var events = await bed.Db.Events.ListAsync(new EventQuery());
|
||||
Assert.IsFalse(events.Any(e => e.Code is EngineEventCodes.RecipeSuspended or EngineEventCodes.FormatUnrecognized or EngineEventCodes.TargetNotFound or EngineEventCodes.RecipeFailed));
|
||||
Assert.AreEqual(0, events.Count(e => e.Code == EngineEventCodes.RecipeNotConfigured), "The runner said it; the engine does not say it again.");
|
||||
var line = events.Single(e => e.Code == EngineEventCodes.RecipePrefix + RecipeKind.ProfileCheck);
|
||||
StringAssert.EndsWith(line.Message, "Configurazione della raccolta incompleta");
|
||||
var snapshot = await host.Monitor.GetSnapshotAsync();
|
||||
Assert.IsTrue(snapshot.RecentActions.Any(a => a.Badge == "Da configurare"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheRunnerRefusesBeforeDoingAnythingAndSaysItOncePerRecipe()
|
||||
{
|
||||
using var temp = new TempFolder("non-configurata");
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var clock = new VirtualClock();
|
||||
var governor = new PermissiveGovernor();
|
||||
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
|
||||
RecipeEnvironment Environment(SiteMap map, ReaderVocabulary vocabulary) => new()
|
||||
{
|
||||
Driver = new UntouchedDriver(),
|
||||
Capture = new CaptureCollector(new ShapeReader(vocabulary), clock),
|
||||
Governor = governor,
|
||||
Signals = new SignalDetector(SignalRules.LoadDefault(), new RecordingBreaker(), clock),
|
||||
Storage = db,
|
||||
SiteMap = map,
|
||||
Clock = clock,
|
||||
Random = new SeededRandom(1),
|
||||
};
|
||||
|
||||
var empty = SiteMap.Parse("""{ "site": "vuoto", "pages": { "home": "" } }""", "bersagli.vuoto.json");
|
||||
var runner = new RecipeRunner(Environment(empty, ReaderVocabulary.LoadTestSite()));
|
||||
StringAssert.Contains(runner.NotConfiguredReason(RecipeKind.FollowingSweep), "pagina «home»");
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
var sweep = await runner.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, sweep.Status);
|
||||
Assert.AreEqual(runner.NotConfiguredReason(RecipeKind.FollowingSweep), sweep.Message);
|
||||
Assert.AreEqual(0, sweep.CountedActions);
|
||||
}
|
||||
|
||||
var profile = await runner.RunAsync(new RecipeRequest(RecipeKind.ProfileCheck, 1), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, profile.Status);
|
||||
StringAssert.Contains(profile.Message, "la mappa dei bersagli non è ancora compilata");
|
||||
|
||||
var lines = (await db.Events.ListAsync(new EventQuery())).Where(e => e.Code == "mappa-incompleta").ToList();
|
||||
Assert.HasCount(2, lines, "One line per recipe, not one per run.");
|
||||
Assert.IsTrue(lines.All(e => e.Severity == EventSeverity.Warning && e.Message.EndsWith(SessionComposer.NotConfiguredTail, StringComparison.Ordinal)));
|
||||
|
||||
// A vocabulary that is only a hypothesis refuses every recipe the same way.
|
||||
var hypothesis = new RecipeRunner(Environment(SiteMap.LoadTestSite(), ReaderVocabulary.LoadTestSite() with { Status = VocabularyStatus.Hypothesis }));
|
||||
var readers = await hypothesis.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, readers.Status);
|
||||
Assert.IsTrue((await db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "lettori-incompleti"));
|
||||
Assert.AreEqual(0, governor.Requests.Count, "No permit asked, no gesture, no page.");
|
||||
|
||||
// The test site's own files let every recipe run.
|
||||
var full = new RecipeRunner(Environment(SiteMap.LoadTestSite(), ReaderVocabulary.LoadTestSite()));
|
||||
foreach (var kind in Enum.GetValues<RecipeKind>())
|
||||
{
|
||||
Assert.IsNull(full.NotConfiguredReason(kind), kind.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tasks of a kind in the queue, whatever their state (cancelled ones included).</summary>
|
||||
private static Task<long> TasksAsync(EngineTestBed bed, EngineTaskKind kind) =>
|
||||
bed.Db.ReadAsync(c => c.Command("SELECT COUNT(*) FROM task WHERE kind = @k").With("@k", kind.ToString()).ScalarInt64(), default);
|
||||
|
||||
/// <summary>A driver that fails the test if a refused recipe touches it.</summary>
|
||||
private sealed class UntouchedDriver : IPageDriver
|
||||
{
|
||||
public double WaitMultiplier => 1;
|
||||
|
||||
public void BeginSession(double mood) => throw Touched();
|
||||
|
||||
public Task<PageLoad> OpenAsync(string path, CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<string> CurrentPathAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<bool> IsOnSiteAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task ScrollBurstAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task WaitAfterLoadAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task RestAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
private static AssertFailedException Touched() => new("Una ricetta rifiutata ha toccato la pagina.");
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,19 @@ internal sealed class EngineTestBed : IAsyncDisposable
|
||||
return _host;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Like <see cref="Start"/>, with <paramref name="beforeLoop"/> run on the host before its loop, as the composition
|
||||
/// does at start-up (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>).
|
||||
/// </summary>
|
||||
public async Task<EngineHost> StartAsync(IRecipeRunner runner, Func<EngineHost, Task> beforeLoop)
|
||||
{
|
||||
_host = new EngineHost(Services, runner);
|
||||
await beforeLoop(_host);
|
||||
_loopCts = new CancellationTokenSource();
|
||||
_loop = _host.RunAsync(_loopCts.Token);
|
||||
return _host;
|
||||
}
|
||||
|
||||
public EngineHost Host => _host ?? throw new InvalidOperationException("Engine not started.");
|
||||
|
||||
/// <summary>Advances virtual time to <paramref name="target"/>, letting the engine run.</summary>
|
||||
|
||||
@@ -31,6 +31,9 @@ internal sealed class ScriptedRunner(IGovernor governor, IClock clock) : IRecipe
|
||||
/// <summary>Accounts the stories bar flags in every sweep.</summary>
|
||||
public IReadOnlyList<long> FlaggedStories { get; set; } = [];
|
||||
|
||||
/// <summary>What the runner says of the configuration of the site (null: every recipe can run).</summary>
|
||||
public Func<RecipeKind, string?>? NotConfigured { get; set; }
|
||||
|
||||
public int Rests { get; private set; }
|
||||
|
||||
public IReadOnlyList<RunRecord> Runs
|
||||
@@ -74,6 +77,8 @@ internal sealed class ScriptedRunner(IGovernor governor, IClock clock) : IRecipe
|
||||
return outcome;
|
||||
}
|
||||
|
||||
public string? NotConfiguredReason(RecipeKind kind) => NotConfigured?.Invoke(kind);
|
||||
|
||||
public Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
Rests++;
|
||||
|
||||
@@ -0,0 +1,977 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Packaging;
|
||||
|
||||
/// <summary>
|
||||
/// The cleanup of the CI: .gitea/scripts/pulizia-docker.sh, its choice of registry tags (versioni-registro.js) and the
|
||||
/// steps that run it. The Docker daemon is shared with Alberto's other projects, very likely with his Unraid apps, and
|
||||
/// may run a real Febe. Since 21 October 2026 the cleanup removes what the CI of Febe made and what nothing uses any
|
||||
/// more, of any project; never a container, a volume or a network that is not the CI's, never main, latest or a
|
||||
/// release on the registry, never the token in the log; with --prova it removes nothing at all. The script runs against
|
||||
/// a fake docker client (fake-docker.sh) and a fake curl (fake-curl.sh): no daemon, no network.
|
||||
/// </summary>
|
||||
public sealed partial class PipelineTests
|
||||
{
|
||||
private const string RegistryApi = "http://gitea.invalid/api/v1";
|
||||
|
||||
private const string WeeklyStep = "Pulizia completa del demone Docker e del registro";
|
||||
|
||||
// Low entropy on purpose: gitleaks reads every commit, and a fake value shaped like a token would look like one.
|
||||
private const string RegistryToken = "gettone-finto-gettone-finto";
|
||||
|
||||
/// <summary>The tags versioni-registro.json leaves to the cleanup once the ten newest sha- are kept, oldest first.</summary>
|
||||
private static readonly string[] OldShaTags = ["sha-0a1b2c3", "sha-1b2c3d4", "sha-2c3d4e5", "sha-4e5f6a7"];
|
||||
|
||||
/// <summary>The untagged versions of the container febe in versioni-registro.json (manifests of an index), oldest first.</summary>
|
||||
private static readonly string[] UntaggedDigests =
|
||||
[
|
||||
"sha256:4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b",
|
||||
"sha256:7c39e42c6e919ae17c7dfa17bd5fcf8cd38fa29c02be97e2b0134947b4674f3c",
|
||||
"sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647",
|
||||
];
|
||||
|
||||
[TestMethod]
|
||||
public void TheCleanupNeverPrunesBlindlyAndChoosesOnlyByTheMarksOfTheCiOrByUse()
|
||||
{
|
||||
var cleanup = Code(Script("pulizia-docker.sh"));
|
||||
foreach (var forbidden in new[] { "system prune", "container prune", "volume prune", "network prune", "prune --all", "image prune -f -a", "builder prune -f -a" })
|
||||
{
|
||||
Assert.DoesNotContain(forbidden, cleanup, "the daemon is shared with Alberto's other projects and his Unraid apps");
|
||||
}
|
||||
|
||||
// Only these prunes: what nothing uses after every run, the narrow weekly of before, and in the complete
|
||||
// cleanup every unused image and all the cache. The cache always with the filter of 24 hours, after every run
|
||||
// too: other projects build with the daemon's builder, and what they used today stays.
|
||||
string[] allowed =
|
||||
[
|
||||
"image prune -f",
|
||||
"image prune -f --filter \"until=72h\"",
|
||||
"image prune -a -f --filter \"until=24h\"",
|
||||
"builder prune -f --filter \"until=24h\"",
|
||||
"builder prune -a -f --filter \"until=24h\"",
|
||||
];
|
||||
CollectionAssert.AreEquivalent(allowed, Prune().Matches(cleanup).Select(m => $"{m.Groups["what"].Value} prune{m.Groups["args"].Value.TrimEnd()}").Distinct().ToList());
|
||||
StringAssert.Contains(cleanup, "export BUILDX_BUILDER=default", "the cache pruned is the daemon's, not the builder of the run, which is gone by then");
|
||||
|
||||
// The febe.ci.* labels of the image are in every container made from a published image, a real Febe too: they
|
||||
// never choose what goes. Containers are listed for removal only by a mark of the CI (the label of the tried
|
||||
// containers with their exact name, the name of Febe's builders, the name act_runner gives its jobs); who uses
|
||||
// an image, a volume or a network is asked only to keep it; the one listing of every container reads.
|
||||
Assert.IsFalse(ProvenanceLabelFilter().IsMatch(cleanup), "the cleanup filters on febe.ci.prova only");
|
||||
var readsOnly = Function(cleanup, "immagini_in_uso");
|
||||
Assert.IsFalse(Removal().IsMatch(readsOnly), "immagini_in_uso only reads");
|
||||
foreach (var line in cleanup.Split('\n').Where(l => l.Contains("docker ps", StringComparison.Ordinal)))
|
||||
{
|
||||
var marked = new[] { "--filter \"label=febe.ci.prova", "--filter \"name=buildx_buildkit_febe-ci-\"", "--filter \"name=GITEA-ACTIONS-TASK-\"", "--filter \"ancestor=", "--filter \"volume=", "--filter \"network=" }
|
||||
.Any(filter => line.Contains(filter, StringComparison.Ordinal));
|
||||
Assert.IsTrue(marked || readsOnly.Contains(line, StringComparison.Ordinal), $"«{line.Trim()}» lists containers without a mark of the CI");
|
||||
}
|
||||
|
||||
StringAssert.Contains(cleanup, "\"febe-prova-$valore\"", "the name must match the mark");
|
||||
StringAssert.Contains(cleanup, "contenitori_di_prova \"\" exited created dead", "the sweeps take only stopped tried containers");
|
||||
StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$");
|
||||
StringAssert.Contains(cleanup, "nome_act='^GITEA-ACTIONS-TASK-[0-9]+[-_]'", "act_runner's objects start with the task");
|
||||
StringAssert.Contains(cleanup, "togli_contenitore \"$id\" \"$nome\" && conta \"contenitori fermi di act_runner\"", "act_runner's containers go without -f: Docker keeps a running one");
|
||||
StringAssert.Contains(cleanup, "docker volume rm \"$nome\"", "act_runner's volumes go without -f");
|
||||
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
|
||||
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
|
||||
|
||||
// On the registry only the shape of a sha- tag of the verification, checked again before every DELETE.
|
||||
StringAssert.Contains(cleanup, "[[ ! \"$versione\" =~ ^sha-[0-9a-f]{7,40}$ ]]");
|
||||
StringAssert.Contains(Script("versioni-registro.js"), "/^sha-[0-9a-f]{7,40}$/");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryImageJobEndsByPruningWhatNobodyUsesAndThatNeverFailsTheJob()
|
||||
{
|
||||
foreach (var name in new[] { "verifica.yml", "rilascio.yml" })
|
||||
{
|
||||
var cleanup = Step(Job(Workflow(name), "immagine"), "Pulizia (sempre)");
|
||||
StringAssert.Contains(cleanup, "if: always()", name);
|
||||
var own = cleanup.IndexOf("bash .gitea/scripts/pulizia-docker.sh esecuzione \"$ESECUZIONE\"", StringComparison.Ordinal);
|
||||
var everyone = cleanup.IndexOf("bash .gitea/scripts/pulizia-docker.sh penzolanti || echo \"::warning::", StringComparison.Ordinal);
|
||||
Assert.IsTrue(own >= 0 && everyone > own, $"{name}: after the cleanup of the run, and a failure is only a warning");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheWeeklyCleanupIsCompleteAndCanBeTriedFirstWithoutRemovingAnything()
|
||||
{
|
||||
var weekly = Workflow("pulizia.yml");
|
||||
StringAssert.Contains(weekly, "schedule:\n - cron: \"17 4 * * 1\"");
|
||||
StringAssert.Contains(weekly, " workflow_dispatch:\n inputs:\n prova:\n");
|
||||
var input = weekly[weekly.IndexOf(" prova:\n", StringComparison.Ordinal)..weekly.IndexOf("\npermissions:", StringComparison.Ordinal)];
|
||||
StringAssert.Contains(input, "type: boolean", "Gitea 28 shows a checkbox and puts \"true\" or \"false\" in the event");
|
||||
StringAssert.Contains(input, "default: false", "by hand the cleanup is real unless the box is ticked");
|
||||
|
||||
var step = Step(Job(weekly, "docker"), WeeklyStep);
|
||||
StringAssert.Contains(step, "PROVA: ${{ gitea.event.inputs.prova }}");
|
||||
StringAssert.Contains(step, "REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}");
|
||||
StringAssert.Contains(step, "GITEA_API: ${{ gitea.server_url }}/api/v1");
|
||||
StringAssert.Contains(step, "PROPRIETARIO: ${{ gitea.repository_owner }}");
|
||||
Assert.DoesNotContain("settimanale", Code(weekly), "the weekly cleanup is the complete one");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TheWeeklyStepTriesOnlyForTrueCleansForFalseOrNothingAndStopsOnAnyOtherValue()
|
||||
{
|
||||
// The run block of the step, as the runner executes it, with a cleanup script that only records how it is
|
||||
// called. The box of the form gives "true" or "false" and Monday no value at all; a dispatch through the API
|
||||
// passes any text as it is, and anything else must not become the real cleanup.
|
||||
var bash = RequireBash();
|
||||
var block = RunBlock(Step(Job(Workflow("pulizia.yml"), "docker"), WeeklyStep));
|
||||
using var folder = new TempFolder("febe-passo-pulizia");
|
||||
Directory.CreateDirectory(folder.Combine(".gitea", "scripts"));
|
||||
await File.WriteAllTextAsync(folder.Combine(".gitea", "scripts", "pulizia-docker.sh"), "printf '%s\\n' \"$*\" >> chiamate\n", TestContext.CancellationToken);
|
||||
await File.WriteAllTextAsync(folder.Combine("passo.sh"), block, TestContext.CancellationToken);
|
||||
(string? Value, string? Called)[] cases =
|
||||
[
|
||||
("true", "completa --prova"),
|
||||
("false", "completa"),
|
||||
(string.Empty, "completa"),
|
||||
(null, "completa"),
|
||||
("True", null),
|
||||
("1", null),
|
||||
("yes", null),
|
||||
("true ", null),
|
||||
("x\n::add-mask::y", null),
|
||||
];
|
||||
foreach (var (value, called) in cases)
|
||||
{
|
||||
File.Delete(folder.Combine("chiamate"));
|
||||
var step = await RunProcessAsync(bash, ["--noprofile", "--norc", "-eo", "pipefail", "passo.sh"], start =>
|
||||
{
|
||||
start.WorkingDirectory = folder.Path;
|
||||
start.Environment.Remove("PROVA");
|
||||
if (value is not null)
|
||||
{
|
||||
start.Environment["PROVA"] = value;
|
||||
}
|
||||
});
|
||||
var calls = await ReadLinesAsync(folder.Combine("chiamate"));
|
||||
var report = $"PROVA=«{value}»: codice {step.Code}\n{step.Output}\n{step.Errors}";
|
||||
if (called is not null)
|
||||
{
|
||||
Assert.AreEqual(0, step.Code, report);
|
||||
CollectionAssert.AreEqual(new[] { called }, calls, report);
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.AreEqual(2, step.Code, report);
|
||||
Assert.IsEmpty(calls, report);
|
||||
StringAssert.StartsWith(step.Output, "::error::", report);
|
||||
Assert.HasCount(1, Lines(step.Output), "a value cannot add a workflow command of its own");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task AWrongOptionOrAWordTooManyStopsTheCleanupBeforeItTouchesDocker()
|
||||
{
|
||||
// By hand on the server a dry run spelt another way must not become the real cleanup.
|
||||
var bash = RequireBash();
|
||||
string[][] wrong =
|
||||
[
|
||||
["completa", "--dry-run"],
|
||||
["completa", "--Prova"],
|
||||
["completa", "-n"],
|
||||
["completa", "prova"],
|
||||
["--prova"],
|
||||
[],
|
||||
["penzolanti", "--forza"],
|
||||
["settimanale", "-f"],
|
||||
["esecuzione", "777", "778"],
|
||||
["residui", "90", "10"],
|
||||
];
|
||||
foreach (var arguments in wrong)
|
||||
{
|
||||
var run = await RunCleanupAsync(bash, SharedDaemon.World, touchesDocker: false, arguments);
|
||||
var report = $"«{string.Join(' ', arguments)}»\n{run.Report}";
|
||||
Assert.AreEqual(2, run.Code, report);
|
||||
Assert.IsEmpty(run.Calls, report);
|
||||
StringAssert.Contains(run.Errors, "Uso: ", report);
|
||||
Assert.IsEmpty(run.Output, report);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade()
|
||||
{
|
||||
var bash = RequireBash();
|
||||
|
||||
// At the start or the end of a run (a release run again keeps its id, so the published image has the same
|
||||
// febe.ci.run as the run): only the tried container, the local name and the builder of that run.
|
||||
var run = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "esecuzione", "777");
|
||||
Assert.AreEqual(0, run.Code, run.Report);
|
||||
Assert.DoesNotContain("::warning::", run.Output, run.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-777", "b-777"]).ToList(), run.Containers, run.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777(), run.Images, run.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-7770_state"]).ToList(), run.Volumes, run.Report);
|
||||
|
||||
// Leftovers of interrupted runs: stopped tried containers, febe-ci images and builders older than 90 minutes.
|
||||
var leftovers = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "residui", "90");
|
||||
Assert.AreEqual(0, leftovers.Code, leftovers.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-555", "b-vecchio"]).ToList(), leftovers.Containers, leftovers.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555"), leftovers.Images, leftovers.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-4560_state"]).ToList(), leftovers.Volumes, leftovers.Report);
|
||||
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore di prova febe-prova-556 è acceso", "a running tried container is reported, not removed");
|
||||
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore buildx_buildkit_febe-ci-4570 non è un builder buildx", leftovers.Report);
|
||||
|
||||
// The narrow weekly cleanup of before, on a daemon without anything odd: the same, the old febe:ci and the
|
||||
// dangling images older than 72 hours that no container uses. Green.
|
||||
var weekly = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Clean), "settimanale");
|
||||
Assert.AreEqual(0, weekly.Code, weekly.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Clean).Except(["c-prova-555", "b-vecchio"]).ToList(), weekly.Containers, weekly.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555", "img-ci556", "img-legacy", "img-penzolante-vecchia"), weekly.Images, weekly.Report);
|
||||
|
||||
// With something left for a person to look at, the weekly cleanup goes red.
|
||||
var noticed = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "settimanale");
|
||||
Assert.AreEqual(1, noticed.Code, noticed.Report);
|
||||
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
|
||||
CollectionAssert.Contains(noticed.Containers, "c-febe-vero");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task AfterEveryRunOnlyWhatNobodyUsesGoesAndADaemonThatRefusesIsOnlyAWarning()
|
||||
{
|
||||
var bash = RequireBash();
|
||||
var run = await RunCleanupAsync(bash, SharedDaemon.World, "penzolanti");
|
||||
Assert.AreEqual(0, run.Code, run.Report);
|
||||
Assert.DoesNotContain("::warning::", run.Output, run.Report);
|
||||
|
||||
// Images without a name that no container uses, of any age; never one with a name, never one a stopped
|
||||
// container uses. Containers, volumes and networks stay as they are.
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds.Except(["img-plex-precedente", "img-penzolante-giovane"]).ToList(), run.ImageIds, run.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(SharedDaemon.Containers), run.Containers, run.Report);
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.VolumeNames, run.Volumes, run.Report);
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.NetworkNames, run.Networks, run.Report);
|
||||
CollectionAssert.Contains(run.Calls, "BUILDX_BUILDER=default docker image prune -f");
|
||||
CollectionAssert.Contains(run.Calls, "BUILDX_BUILDER=default docker builder prune -f --filter until=24h", "the dangling cache of the daemon's builder, without -a, unused for a day");
|
||||
|
||||
// A daemon that refuses: two warnings, and the job of the run stays green.
|
||||
var refused = await RunCleanupAsync(bash, SharedDaemon.World with { Broken = ["image prune", "builder prune"] }, "penzolanti");
|
||||
Assert.AreEqual(0, refused.Code, refused.Report);
|
||||
Assert.HasCount(2, WarningLine().Matches(refused.Output), refused.Report);
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds, refused.ImageIds, refused.Report);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task TheCompleteCleanupTakesWhatNobodyUsesAndNeverAContainerVolumeOrNetworkOfAnotherProject()
|
||||
{
|
||||
var bash = RequireBash();
|
||||
var run = await RunCleanupAsync(bash, SharedDaemon.World, "completa");
|
||||
Assert.AreEqual(0, run.Code, run.Report);
|
||||
Assert.DoesNotContain("::warning::", run.Output, run.Report);
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.ContainersLeft, run.Containers, run.Report);
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.ImagesLeft, run.ImageIds, run.Report);
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.VolumesLeft, run.Volumes, run.Report);
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.NetworksLeft, run.Networks, run.Report);
|
||||
|
||||
// An image a container uses stays, but «image prune -a» takes its extra names: with the classic store all but
|
||||
// the last in the order of their full names, even the one the container was made from (Jellyfin, from :10.9).
|
||||
// The log says so, name by name.
|
||||
StringAssert.Contains(run.Output, "== Store delle immagini del demone: classico", run.Report);
|
||||
CollectionAssert.Contains(run.Images, "img-rilascio|192.168.30.23:3000/alby96/febe:latest", run.Report);
|
||||
CollectionAssert.Contains(run.Images, "img-jellyfin|jellyfin/jellyfin:latest", run.Report);
|
||||
StringAssert.Contains(run.Output, " tolto il nome jellyfin/jellyfin:10.9; l'immagine img-jellyfin resta\n", run.Report);
|
||||
StringAssert.Contains(run.Output, " tolto il nome 192.168.30.23:3000/alby96/febe:0.1.0; l'immagine img-rilascio resta\n", run.Report);
|
||||
Assert.AreEqual("2", SummaryCount(run.Output, "nomi tolti a immagini che restano"), run.Report);
|
||||
|
||||
// Not even an attempt on what is not the CI's (Docker would refuse some of it: the script must not ask), and
|
||||
// the prunes of everyone only with their filter, once.
|
||||
foreach (var call in run.Calls)
|
||||
{
|
||||
var target = RemovalTarget().Match(call);
|
||||
if (target.Success)
|
||||
{
|
||||
CollectionAssert.Contains(SharedDaemon.Removed, target.Groups["target"].Value, call);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.HasCount(1, run.Calls.Where(c => c == "BUILDX_BUILDER=default docker image prune -a -f --filter until=24h"), run.Report);
|
||||
Assert.HasCount(1, run.Calls.Where(c => c == "BUILDX_BUILDER=default docker builder prune -a -f --filter until=24h"), run.Report);
|
||||
Assert.HasCount(2, run.Calls.Where(c => c.EndsWith("docker system df", StringComparison.Ordinal)), "before and after");
|
||||
|
||||
// Without the secret the registry is not touched, and the summary says what went.
|
||||
StringAssert.Contains(run.Output, " Manca il segreto REGISTRY_TOKEN: il registro non si tocca.");
|
||||
Assert.IsEmpty(run.RegistryCalls, run.Report);
|
||||
StringAssert.Contains(run.Output, "== Riepilogo\n");
|
||||
Assert.AreEqual("2", SummaryCount(run.Output, "contenitori fermi di act_runner"), run.Report);
|
||||
Assert.AreEqual("4", SummaryCount(run.Output, "volumi di act_runner"), run.Report);
|
||||
Assert.AreEqual("2", SummaryCount(run.Output, "reti di act_runner"), run.Report);
|
||||
Assert.AreEqual("4", SummaryCount(run.Output, "immagini che nessun contenitore usa"), run.Report);
|
||||
|
||||
// Something left for a person to look at (a tried container still running) turns it red, as before.
|
||||
var noticed = await RunCleanupAsync(bash, SharedDaemon.World with { Containers = [.. SharedDaemon.Containers, "c-prova-556|febe-prova-556|running|300|febe-ci:556|img-rilascio|febe.ci.prova=556"] }, "completa");
|
||||
Assert.AreEqual(1, noticed.Code, noticed.Report);
|
||||
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task TheDryRunListsWhatTheCleanupWouldTakeAndTouchesNothing()
|
||||
{
|
||||
var bash = RequireBash();
|
||||
RequireNode();
|
||||
var world = SharedDaemon.World with { Registry = new FakeRegistry(RegistryToken) };
|
||||
var tried = await RunCleanupAsync(bash, world, "completa", "--prova");
|
||||
Assert.AreEqual(0, tried.Code, tried.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(SharedDaemon.Containers), tried.Containers, tried.Report);
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds, tried.ImageIds, tried.Report);
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.VolumeNames, tried.Volumes, tried.Report);
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.NetworkNames, tried.Networks, tried.Report);
|
||||
foreach (var call in tried.Calls)
|
||||
{
|
||||
Assert.IsFalse(Destructive().IsMatch(call), $"the dry run called «{call}»");
|
||||
}
|
||||
|
||||
Assert.IsTrue(tried.RegistryCalls.Count > 0 && tried.RegistryCalls.All(c => c.StartsWith("GET ", StringComparison.Ordinal)), tried.Report);
|
||||
Assert.IsEmpty(tried.Deleted, tried.Report);
|
||||
Assert.DoesNotContain(RegistryToken, tried.Output + tried.Errors, "the token never reaches the log");
|
||||
|
||||
// What it lists, with size and age: also what becomes unused once the leftovers it lists are gone.
|
||||
Assert.DoesNotContain("solo indicativo", tried.Output, "with the classic store the ages are those «until» uses");
|
||||
foreach (var expected in new[]
|
||||
{
|
||||
"Prova: elenco che cosa toglierei, senza togliere nulla.",
|
||||
"== Store delle immagini del demone: classico (le 24 ore contano dalla costruzione dell'immagine)\n",
|
||||
" toglierei il contenitore febe-prova-555\n",
|
||||
" toglierei il contenitore GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove\n",
|
||||
" toglierei il volume GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove-env\n",
|
||||
" toglierei la rete GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove-prove-network\n",
|
||||
" toglierei 192.168.30.23:3000/alby96/febe:0.0.9 (img-febe-vec) · 400MB · creata 34 giorni fa\n",
|
||||
" toglierei node:24-trixie (img-node) · 410MB · creata 13 giorni fa\n",
|
||||
" toglierei un'immagine senza nome (img-plex-pre) · 300MB · creata 69 giorni fa\n",
|
||||
" toglierei il nome 192.168.30.23:3000/alby96/febe:0.1.0; l'immagine img-rilascio resta, perché la usa un contenitore\n",
|
||||
" toglierei il nome jellyfin/jellyfin:10.9; l'immagine img-jellyfin resta, perché la usa un contenitore\n",
|
||||
"la cache di costruzione del demone occupa 5.3GB",
|
||||
" toglierei sha-4e5f6a7 (pubblicata il 2026-10-05T01:00:00+02:00)\n",
|
||||
$" {UntaggedDigests.Length} versioni senza etichetta (sha256:…",
|
||||
"== Riepilogo della prova",
|
||||
})
|
||||
{
|
||||
StringAssert.Contains(tried.Output, expected, tried.Report);
|
||||
}
|
||||
|
||||
foreach (var kept in new[] { "plexinc/pms-docker", "encelado:latest", "mimante:latest", "runner-images", "moby/buildkit", "act-toolcache", "encelado-dati", "febe:latest", "jellyfin/jellyfin:latest", "toglierei main", "toglierei latest", "toglierei 0.1.", "GITEA-ACTIONS-TASK-90", "GITEA-ACTIONS-TASK-60", "GITEA-ACTIONS-TASK-88", "GITEA-ACTIONS-TASK-89", "GITEA-ACTIONS-TASK-77" })
|
||||
{
|
||||
Assert.DoesNotContain(kept, tried.Output, tried.Report);
|
||||
}
|
||||
|
||||
// And it counts what the real cleanup then takes.
|
||||
var real = await RunCleanupAsync(bash, world, "completa");
|
||||
Assert.AreEqual(0, real.Code, real.Report);
|
||||
foreach (var kind in new[] { "contenitori di prova della CI di Febe", "immagini febe-ci", "builder buildx della CI di Febe", "contenitori fermi di act_runner", "volumi di act_runner", "reti di act_runner", "immagini che nessun contenitore usa", "nomi tolti a immagini che restano", "etichette sha- sul registro" })
|
||||
{
|
||||
Assert.AreEqual(SummaryCount(real.Output, kind), SummaryCount(tried.Output, kind), $"{kind}\n{tried.Report}\n{real.Report}");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task OnTheContainerdStoreTheCleanupSaysSoAndTheAgesOfTheDryRunAreOnlyIndicative()
|
||||
{
|
||||
// With the containerd image store «until» counts from when a name reached the daemon, which no command shows;
|
||||
// the dry run can only give the age of the image and must say so.
|
||||
var bash = RequireBash();
|
||||
var world = SharedDaemon.World with { Store = "containerd" };
|
||||
var tried = await RunCleanupAsync(bash, world, "completa", "--prova");
|
||||
Assert.AreEqual(0, tried.Code, tried.Report);
|
||||
StringAssert.Contains(tried.Output, "== Store delle immagini del demone: containerd (le 24 ore contano da quando un nome è arrivato sul demone)\n", tried.Report);
|
||||
StringAssert.Contains(tried.Output, "l'elenco è solo indicativo)", tried.Report);
|
||||
CollectionAssert.Contains(tried.Calls, "BUILDX_BUILDER=default docker info --format {{json .DriverStatus}}", "the store is read, never changed");
|
||||
|
||||
// Of an image a container uses, containerd keeps the names the containers were made from and takes the others:
|
||||
// Jellyfin keeps :10.9 and loses :latest, the other way round from the classic store. The dry run says so, and
|
||||
// the real cleanup does it.
|
||||
StringAssert.Contains(tried.Output, " toglierei il nome jellyfin/jellyfin:latest; l'immagine img-jellyfin resta, perché la usa un contenitore\n", tried.Report);
|
||||
StringAssert.Contains(tried.Output, " toglierei il nome 192.168.30.23:3000/alby96/febe:0.1.0; l'immagine img-rilascio resta, perché la usa un contenitore\n", tried.Report);
|
||||
Assert.DoesNotContain("jellyfin/jellyfin:10.9", tried.Output, tried.Report);
|
||||
var real = await RunCleanupAsync(bash, world, "completa");
|
||||
Assert.AreEqual(0, real.Code, real.Report);
|
||||
CollectionAssert.AreEquivalent(SharedDaemon.ImagesLeft, real.ImageIds, real.Report);
|
||||
CollectionAssert.Contains(real.Images, "img-jellyfin|jellyfin/jellyfin:10.9", real.Report);
|
||||
CollectionAssert.Contains(real.Images, "img-rilascio|192.168.30.23:3000/alby96/febe:latest", real.Report);
|
||||
foreach (var kind in new[] { "immagini che nessun contenitore usa", "nomi tolti a immagini che restano" })
|
||||
{
|
||||
Assert.AreEqual(SummaryCount(real.Output, kind), SummaryCount(tried.Output, kind), $"{kind}\n{tried.Report}\n{real.Report}");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheImageIsAPlainManifestSoRemovingATagFromTheRegistryFreesItsLayers()
|
||||
{
|
||||
// With attestations, which buildx adds by itself, the image is an index: Gitea keeps each child manifest as an
|
||||
// untagged sha256: version holding the configuration and the layers, and deleting the tag deletes only the
|
||||
// index. Both builds (the tried archive and the push) share these arguments, so they stay the same image.
|
||||
var build = Code(Script("costruisci-immagine.sh"));
|
||||
var start = build.IndexOf("comuni=(", StringComparison.Ordinal);
|
||||
Assert.IsGreaterThanOrEqualTo(0, start, "costruisci-immagine.sh has no common arguments");
|
||||
var common = build[start..build.IndexOf(')', start)];
|
||||
StringAssert.Contains(common, "--provenance=false");
|
||||
StringAssert.Contains(common, "--sbom=false");
|
||||
Assert.AreEqual(2, Regex.Count(build, @"docker buildx build ""\$\{comuni\[@\]\}"""), "every build uses the common arguments");
|
||||
Assert.DoesNotContain("--platform", build, "more platforms would make an index again");
|
||||
Assert.DoesNotContain("--attest", build);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task TheRegistryKeepsMainLatestTheReleasesAndTheTenNewestShaTags()
|
||||
{
|
||||
var node = RequireNode();
|
||||
var script = CiPath("scripts", "versioni-registro.js");
|
||||
using var folder = new TempFolder("febe-registro");
|
||||
var pages = await WriteRegistryPagesAsync(folder.Path);
|
||||
|
||||
// Of fourteen sha- tags the four oldest go. sha-3d4e5f6 (23:30 UTC) is newer than sha-4e5f6a7 (01:00 in Italy,
|
||||
// 23:00 UTC): dates, not text. main, latest, the releases, digests, malformed sha- tags, one without a date and
|
||||
// other packages stay, though they are older; a tag in two pages counts once.
|
||||
var chosen = await RunProcessAsync(node, [script, "10", .. pages]);
|
||||
Assert.AreEqual(0, chosen.Code, chosen.Errors);
|
||||
CollectionAssert.AreEqual(OldShaTags, Lines(chosen.Output).Select(l => l.Split('\t')[0]).ToList(), chosen.Output);
|
||||
StringAssert.Contains(chosen.Output, "sha-2c3d4e5\t2026-10-03T07:00:00Z\n");
|
||||
|
||||
// Keeping none: every well formed sha- tag of the container febe, and nothing else.
|
||||
var all = await RunProcessAsync(node, [script, "0", .. pages]);
|
||||
Assert.HasCount(14, Lines(all.Output), all.Output);
|
||||
foreach (var line in Lines(all.Output))
|
||||
{
|
||||
Assert.IsTrue(ShaTagLine().IsMatch(line), line);
|
||||
}
|
||||
|
||||
// The untagged versions, the manifests of an index with their layers: listed only to be counted, oldest first,
|
||||
// those of the container febe and no other package.
|
||||
var untagged = await RunProcessAsync(node, [script, "senza-etichetta", .. pages]);
|
||||
Assert.AreEqual(0, untagged.Code, untagged.Errors);
|
||||
CollectionAssert.AreEqual(UntaggedDigests, Lines(untagged.Output).Select(l => l.Split('\t')[0]).ToList(), untagged.Output);
|
||||
|
||||
// Keeping more than there are: nothing. An empty page of Gitea is fine; a page that is not a list stops
|
||||
// everything, so in doubt nothing goes.
|
||||
var empty = Path.Combine(folder.Path, "vuota.json");
|
||||
await File.WriteAllTextAsync(empty, "null", TestContext.CancellationToken);
|
||||
Assert.IsEmpty((await RunProcessAsync(node, [script, "20", .. pages, empty])).Output);
|
||||
var broken = Path.Combine(folder.Path, "rotta.json");
|
||||
await File.WriteAllTextAsync(broken, "{\"message\":\"internal error\"}", TestContext.CancellationToken);
|
||||
var refused = await RunProcessAsync(node, [script, "10", .. pages, broken]);
|
||||
Assert.AreEqual(2, refused.Code, refused.Errors);
|
||||
Assert.IsEmpty(refused.Output);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task TheRegistryCleanupDeletesOnlyTheChosenTagsNeverPrintsTheTokenAndARefusalIsOnlyAWarning()
|
||||
{
|
||||
var bash = RequireBash();
|
||||
RequireNode();
|
||||
|
||||
// A daemon with almost nothing on it: here only the registry counts.
|
||||
var quiet = new World(["c-encelado|encelado|exited|5000|encelado:latest|img-encelado|"], ["img-encelado|encelado:latest|5000||250MB"], [], []);
|
||||
var run = await RunCleanupAsync(bash, quiet with { Registry = new FakeRegistry(RegistryToken) }, "completa");
|
||||
Assert.AreEqual(0, run.Code, run.Report);
|
||||
CollectionAssert.AreEqual(OldShaTags, run.Deleted, run.Report);
|
||||
var package = $"{RegistryApi}/packages/Alby96/container/febe";
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { $"GET {package}?page=1&limit=50", $"GET {package}?page=2&limit=50", $"GET {package}?page=3&limit=50" }
|
||||
.Concat(OldShaTags.Select(tag => $"DELETE {package}/{tag}")).ToList(),
|
||||
run.RegistryCalls,
|
||||
run.Report);
|
||||
Assert.DoesNotContain(RegistryToken, run.Output + run.Errors, "the token never reaches the log");
|
||||
Assert.AreEqual("4", SummaryCount(run.Output, "etichette sha- sul registro"), run.Report);
|
||||
|
||||
// The untagged versions stay, and the log says how many there are: their layers are freed only by a cleanup
|
||||
// rule of Gitea, which knows whether a tag still uses them.
|
||||
Assert.IsFalse(run.RegistryCalls.Any(c => c.Contains("sha256:", StringComparison.Ordinal)), run.Report);
|
||||
StringAssert.Contains(run.Output, $" {UntaggedDigests.Length} versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano", run.Report);
|
||||
|
||||
// The API refuses (a token without the permission) or does not know the token: a warning, nothing deleted,
|
||||
// and the weekly job stays green.
|
||||
foreach (var registry in new[] { new FakeRegistry(RegistryToken, Refuse: true), new FakeRegistry(RegistryToken, Sent: "un-altro-gettone-finto") })
|
||||
{
|
||||
var refused = await RunCleanupAsync(bash, quiet with { Registry = registry }, "completa");
|
||||
Assert.AreEqual(0, refused.Code, refused.Report);
|
||||
StringAssert.Contains(refused.Output, "::warning::L'API dei pacchetti di Gitea risponde 40", refused.Report);
|
||||
Assert.IsEmpty(refused.Deleted, refused.Report);
|
||||
Assert.HasCount(1, refused.RegistryCalls, refused.Report);
|
||||
Assert.DoesNotContain(RegistryToken, refused.Output + refused.Errors);
|
||||
Assert.DoesNotContain("un-altro-gettone-finto", refused.Output + refused.Errors);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The daemon of <see cref="OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade"/> (format in
|
||||
/// fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of their images,
|
||||
/// as Docker gives them; the image of the release also has the local name of run 777.
|
||||
/// </summary>
|
||||
private static class FakeDaemon
|
||||
{
|
||||
public static readonly string[] Full =
|
||||
[
|
||||
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0",
|
||||
"c-febe-fermo|febe-main|exited|43200|192.168.30.23:3000/alby96/febe:main|img-main|febe.ci.workflow=verifica,febe.ci.run=888",
|
||||
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
|
||||
"c-prova-777|febe-prova-777|running|5|febe-ci:777|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.prova=777",
|
||||
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
|
||||
"c-prova-556|febe-prova-556|running|300|febe-ci:556|img-ci556|febe.ci.run=556,febe.ci.prova=556",
|
||||
"c-prova-557|febe-prova-557|exited|10|febe-ci:557|img-ci557|febe.ci.run=557,febe.ci.prova=557",
|
||||
"c-nome-strano|febe-prova-558-bis|exited|300|encelado:latest|img-encelado|febe.ci.prova=558",
|
||||
"c-segno-diverso|febe-prova-559|exited|300|encelado:latest|img-encelado|febe.ci.prova=560",
|
||||
"c-senza-segno|febe-prova-561|exited|300|encelado:latest|img-encelado|",
|
||||
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|",
|
||||
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-4560_state",
|
||||
"b-finto|buildx_buildkit_febe-ci-4570|running|300|encelado:latest|img-encelado||buildx_buildkit_febe-ci-4570_state",
|
||||
"b-giovane|buildx_buildkit_febe-ci-7890|running|10|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-7890_state",
|
||||
"b-altro|altro_buildx_buildkit_febe-ci-10|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
|
||||
"b-777|buildx_buildkit_febe-ci-7770|running|20|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-7770_state",
|
||||
];
|
||||
|
||||
/// <summary>The same daemon without the running tried container and the builder that is not one.</summary>
|
||||
public static readonly string[] Clean = [.. Full.Where(c => !c.StartsWith("c-prova-556|", StringComparison.Ordinal) && !c.StartsWith("b-finto|", StringComparison.Ordinal))];
|
||||
|
||||
public static readonly string[] Images =
|
||||
[
|
||||
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0,febe-ci:777|43200|febe.ci.run=777",
|
||||
"img-main|192.168.30.23:3000/alby96/febe:main|43200|febe.ci.run=888",
|
||||
"img-ci555|febe-ci:555|300|febe.ci.run=555",
|
||||
"img-ci556|febe-ci:556|300|febe.ci.run=556",
|
||||
"img-ci557|febe-ci:557|10|febe.ci.run=557",
|
||||
"img-penzolante-febe||300|febe.ci.run=999",
|
||||
"img-penzolante-vecchia||6000|",
|
||||
"img-penzolante-in-uso||20000|febe.ci.run=111",
|
||||
"img-encelado|encelado:latest|5000|",
|
||||
"img-buildkit|moby/buildkit:buildx-stable-1|50000|",
|
||||
"img-legacy|febe:ci|6000|",
|
||||
];
|
||||
|
||||
public static readonly string[] Volumes =
|
||||
[
|
||||
"buildx_buildkit_febe-ci-4560_state",
|
||||
"buildx_buildkit_febe-ci-4570_state",
|
||||
"buildx_buildkit_febe-ci-7890_state",
|
||||
"buildx_buildkit_febe-ci-7770_state",
|
||||
"encelado-dati",
|
||||
];
|
||||
|
||||
public static World WorldOf(string[] containers) => new(containers, Images, Volumes, []);
|
||||
|
||||
public static List<string> ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])];
|
||||
|
||||
/// <summary>
|
||||
/// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without
|
||||
/// the images given.
|
||||
/// </summary>
|
||||
public static List<string> ImagesWithout777(params string[] gone) =>
|
||||
[
|
||||
.. Images
|
||||
.Select(i => string.Join('|', i.Split('|')[..2]).Replace(",febe-ci:777", string.Empty, StringComparison.Ordinal))
|
||||
.Where(i => !gone.Contains(i[..i.IndexOf('|', StringComparison.Ordinal)])),
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A daemon as the runner's is likely to be (format in fake-docker.sh): a real Febe and Unraid apps, running and
|
||||
/// stopped; the job container of the cleanup itself; leftovers of act_runner, with the names of today's act_runner
|
||||
/// («_WORKFLOW-…») and of older ones («-WORKFLOW-…» with a hash), and look-alikes; leftovers of the CI of Febe;
|
||||
/// images used and unused, named and dangling, old and young; volumes and networks of every kind. The images of the
|
||||
/// real Febe and of Jellyfin have two names each, and Jellyfin was created from the one that is not the last.
|
||||
/// </summary>
|
||||
private static class SharedDaemon
|
||||
{
|
||||
private const string Job53 = "GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove";
|
||||
private const string Job41 = "GITEA-ACTIONS-TASK-41-WORKFLOW-verifica-JOB-prove-9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
|
||||
private const string Job90 = "GITEA-ACTIONS-TASK-90_WORKFLOW-pulizia_JOB-docker";
|
||||
|
||||
public static readonly string[] Containers =
|
||||
[
|
||||
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0|febe-dati|bridge",
|
||||
"c-plex|plex|exited|90000|plexinc/pms-docker:latest|img-plex||plex-config|br0",
|
||||
"c-jellyfin|jellyfin|running|90000|jellyfin/jellyfin:10.9|img-jellyfin||",
|
||||
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|||encelado_default",
|
||||
$"c-lavoro|{Job90}|running|5|docker.gitea.com/runner-images:ubuntu-latest|img-runner||{Job90},{Job90}-env,act-toolcache|{Job90}-docker-network",
|
||||
$"c-act-fermo|{Job53}|exited|3000|node:24-trixie|img-node||{Job53},{Job53}-env,act-toolcache|{Job53}-prove-network",
|
||||
$"c-act-antico|{Job41}|dead|20000|node:24-trixie|img-node||{Job41}-env|",
|
||||
"c-act-giovane|GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|exited|30|docker.gitea.com/runner-images:ubuntu-latest|img-runner||GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|",
|
||||
"c-act-acceso|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|running|3000|docker.gitea.com/runner-images:ubuntu-latest|img-runner||GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build-build-network",
|
||||
"c-quasi-act|mio-GITEA-ACTIONS-TASK-7_WORKFLOW-x|exited|3000|encelado:latest|img-encelado||GITEA-ACTIONS-TASK-77_WORKFLOW-y_JOB-z|",
|
||||
"c-senza-numero|GITEA-ACTIONS-TASK-x_WORKFLOW-y|exited|3000|encelado:latest|img-encelado|",
|
||||
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
|
||||
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
|
||||
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-4560_state|",
|
||||
"b-altro|buildx_buildkit_encelado0|running|3000|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_encelado0_state|",
|
||||
];
|
||||
|
||||
public static readonly string[] Images =
|
||||
[
|
||||
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0|43200|febe.ci.run=777|412MB",
|
||||
"img-febe-vecchia|192.168.30.23:3000/alby96/febe:0.0.9|50000||400MB",
|
||||
"img-plex|plexinc/pms-docker:latest|100000||300MB",
|
||||
"img-plex-precedente||100000||300MB",
|
||||
"img-jellyfin|jellyfin/jellyfin:10.9,jellyfin/jellyfin:latest|100000||900MB",
|
||||
"img-encelado|encelado:latest|5000||250MB",
|
||||
"img-encelado-dev|encelado:dev|3000||250MB",
|
||||
"img-mimante-nuova|mimante:latest|60||180MB",
|
||||
"img-runner|docker.gitea.com/runner-images:ubuntu-latest|20000||1.2GB",
|
||||
"img-node|node:24-trixie|20000||410MB",
|
||||
"img-buildkit|moby/buildkit:buildx-stable-1|50000||210MB",
|
||||
"img-penzolante-giovane||30||40MB",
|
||||
"img-penzolante-in-uso||20000|febe.ci.run=111|400MB",
|
||||
"img-ci555|febe-ci:555|300|febe.ci.run=555|412MB",
|
||||
"img-legacy|febe:ci|6000||400MB",
|
||||
];
|
||||
|
||||
public static readonly string[] Volumes =
|
||||
[
|
||||
$"{Job53}|3000",
|
||||
$"{Job53}-env|3000",
|
||||
$"{Job41}-env|20000",
|
||||
$"{Job90}|5",
|
||||
$"{Job90}-env|5",
|
||||
"GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|30",
|
||||
"GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|3000",
|
||||
"GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x|50000",
|
||||
"GITEA-ACTIONS-TASK-88_WORKFLOW-nuovo_JOB-y|30",
|
||||
"GITEA-ACTIONS-TASK-77_WORKFLOW-y_JOB-z|50000",
|
||||
"act-toolcache|50000",
|
||||
"encelado-dati|50000",
|
||||
"febe-dati|43200",
|
||||
"plex-config|100000",
|
||||
"3f9a2b7c1d0e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a|50000",
|
||||
"mio-GITEA-ACTIONS-TASK-3_WORKFLOW-x|50000",
|
||||
"buildx_buildkit_febe-ci-4560_state",
|
||||
"buildx_buildkit_encelado0_state",
|
||||
];
|
||||
|
||||
public static readonly string[] Networks =
|
||||
[
|
||||
"net-bridge|bridge|100000",
|
||||
"net-host|host|100000",
|
||||
"net-none|none|100000",
|
||||
"net-br0|br0|100000",
|
||||
"net-encelado|encelado_default|5000",
|
||||
$"net-act-53|{Job53}-prove-network|3000",
|
||||
$"net-act-90|{Job90}-docker-network|5",
|
||||
"net-act-60|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build-build-network|3000",
|
||||
"net-act-12|GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x-x-network|50000",
|
||||
"net-act-88|GITEA-ACTIONS-TASK-88_WORKFLOW-nuovo_JOB-y-y-network|30",
|
||||
"net-quasi|altro-GITEA-ACTIONS-TASK-5_WORKFLOW-x-network|50000",
|
||||
];
|
||||
|
||||
public static readonly World World = new(Containers, Images, Volumes, Networks);
|
||||
|
||||
public static readonly List<string> ImageIds = [.. Images.Select(First)];
|
||||
|
||||
public static readonly List<string> VolumeNames = [.. Volumes.Select(First)];
|
||||
|
||||
public static readonly List<string> NetworkNames = [.. Networks.Select(n => n.Split('|')[1])];
|
||||
|
||||
/// <summary>
|
||||
/// What the complete cleanup takes: stopped act_runner containers older than 90 minutes, a stopped tried
|
||||
/// container and a builder of Febe; the volumes and networks of act_runner nothing else uses; the images no
|
||||
/// container uses created more than a day ago (node:24-trixie only once its stopped containers are gone).
|
||||
/// </summary>
|
||||
public static readonly string[] Removed =
|
||||
[
|
||||
"c-act-fermo", "c-act-antico", "c-prova-555", "b-vecchio",
|
||||
"img-febe-vecchia", "img-plex-precedente", "img-encelado-dev", "img-node", "img-ci555", "img-legacy",
|
||||
$"{Job53}", $"{Job53}-env", $"{Job41}-env", "GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x", "buildx_buildkit_febe-ci-4560_state",
|
||||
"net-act-53", "net-act-12",
|
||||
|
||||
// How the cleanup names what it removes: by id or by name, and the local names of the images.
|
||||
"buildx_buildkit_febe-ci-4560", "febe-ci:555", "febe:ci", "febe-ci-4560",
|
||||
];
|
||||
|
||||
public static readonly List<string> ContainersLeft = [.. FakeDaemon.ContainersOf(Containers).Except(Removed)];
|
||||
|
||||
public static readonly List<string> ImagesLeft = [.. ImageIds.Except(Removed)];
|
||||
|
||||
public static readonly List<string> VolumesLeft = [.. VolumeNames.Except(Removed)];
|
||||
|
||||
public static readonly List<string> NetworksLeft = [.. Networks.Where(n => !Removed.Contains(First(n))).Select(n => n.Split('|')[1])];
|
||||
|
||||
private static string First(string line) => line.Split('|')[0];
|
||||
}
|
||||
|
||||
/// <summary>A fake daemon (format in fake-docker.sh) and, for the registry, a fake Gitea (fake-curl.sh).</summary>
|
||||
private sealed record World(string[] Containers, string[] Images, string[] Volumes, string[] Networks)
|
||||
{
|
||||
/// <summary>Docker commands that fail as if the daemon refused them («image prune», «builder prune»).</summary>
|
||||
public string[] Broken { get; init; } = [];
|
||||
|
||||
/// <summary>The registry; without it the cleanup runs with no REGISTRY_TOKEN.</summary>
|
||||
public FakeRegistry? Registry { get; init; }
|
||||
|
||||
/// <summary>«containerd» for the containerd image store; null for the classic one.</summary>
|
||||
public string? Store { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The packages API of Gitea with the pages of versioni-registro.json, for the token given. Sent is the token the
|
||||
/// cleanup gets (the same, if null); Refuse answers 403 to everything.
|
||||
/// </summary>
|
||||
private sealed record FakeRegistry(string Token, bool Refuse = false, string? Sent = null);
|
||||
|
||||
private sealed record CleanupRun(int Code, string Output, string Errors)
|
||||
{
|
||||
/// <summary>The ids of the containers left.</summary>
|
||||
public List<string> Containers { get; init; } = [];
|
||||
|
||||
/// <summary>«id|names» of the images left.</summary>
|
||||
public List<string> Images { get; init; } = [];
|
||||
|
||||
public List<string> Volumes { get; init; } = [];
|
||||
|
||||
public List<string> Networks { get; init; } = [];
|
||||
|
||||
/// <summary>Every docker call, as fake-docker.sh writes it.</summary>
|
||||
public List<string> Calls { get; init; } = [];
|
||||
|
||||
/// <summary>Every call to the API of the registry, «METHOD URL».</summary>
|
||||
public List<string> RegistryCalls { get; init; } = [];
|
||||
|
||||
/// <summary>The versions deleted from the registry.</summary>
|
||||
public List<string> Deleted { get; init; } = [];
|
||||
|
||||
public List<string> ImageIds => [.. Images.Select(i => i.Split('|')[0])];
|
||||
|
||||
public string Report => $"codice {Code}\n{Output}\n{Errors}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// pulizia-docker.sh against the fake daemon and, with a registry, the fake curl. DOCKER_HOST points nowhere and the
|
||||
/// API is on a domain that cannot exist (.invalid): even if a real docker or curl came first on the PATH they could
|
||||
/// reach nothing, and the test fails because the fakes recorded no call or curl complained on stderr.
|
||||
/// </summary>
|
||||
private Task<CleanupRun> RunCleanupAsync(string bash, World world, params string[] arguments) =>
|
||||
RunCleanupAsync(bash, world, touchesDocker: true, arguments);
|
||||
|
||||
/// <summary>
|
||||
/// As <see cref="RunCleanupAsync(string, World, string[])"/>; with <paramref name="touchesDocker"/> false the run
|
||||
/// may call no docker at all (wrong arguments stop before it).
|
||||
/// </summary>
|
||||
private async Task<CleanupRun> RunCleanupAsync(string bash, World world, bool touchesDocker, string[] arguments)
|
||||
{
|
||||
using var folder = new TempFolder("febe-pulizia");
|
||||
var bin = folder.Combine("bin");
|
||||
var registry = folder.Combine("registro");
|
||||
var temporary = folder.Combine("tmp");
|
||||
foreach (var directory in new[] { bin, registry, temporary })
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
InstallFake("fake-docker.sh", Path.Combine(bin, "docker"));
|
||||
await WriteLinesAsync(folder.Combine("containers"), world.Containers);
|
||||
await WriteLinesAsync(folder.Combine("images"), world.Images);
|
||||
await WriteLinesAsync(folder.Combine("volumes"), world.Volumes);
|
||||
await WriteLinesAsync(folder.Combine("networks"), world.Networks);
|
||||
if (world.Broken.Length > 0)
|
||||
{
|
||||
await WriteLinesAsync(folder.Combine("broken"), world.Broken);
|
||||
}
|
||||
|
||||
if (world.Store is { } store)
|
||||
{
|
||||
await WriteLinesAsync(folder.Combine("store"), [store]);
|
||||
}
|
||||
|
||||
if (world.Registry is { } fake)
|
||||
{
|
||||
InstallFake("fake-curl.sh", Path.Combine(bin, "curl"));
|
||||
await File.WriteAllTextAsync(Path.Combine(registry, "token"), fake.Token, TestContext.CancellationToken);
|
||||
await File.WriteAllTextAsync(Path.Combine(registry, "base"), $"{RegistryApi}/packages/Alby96/container/febe", TestContext.CancellationToken);
|
||||
if (fake.Refuse)
|
||||
{
|
||||
await File.WriteAllTextAsync(Path.Combine(registry, "refuse"), string.Empty, TestContext.CancellationToken);
|
||||
}
|
||||
|
||||
await WriteRegistryPagesAsync(registry);
|
||||
}
|
||||
|
||||
// The fakes go first on the PATH from inside bash: Git Bash puts its own folders (with a real curl) before the
|
||||
// PATH it is given.
|
||||
string[] script = ["-c", "bin=\"$FAKE_BIN\"; if command -v cygpath > /dev/null; then bin=\"$(cygpath -u \"$bin\")\"; fi; PATH=\"$bin:$PATH\"; exec bash \"$@\"", "bash", ".gitea/scripts/pulizia-docker.sh"];
|
||||
var result = await RunProcessAsync(bash, [.. script, .. arguments], start =>
|
||||
{
|
||||
start.Environment["FAKE_BIN"] = bin;
|
||||
start.Environment["FAKE_DOCKER_WORLD"] = folder.Path.Replace('\\', '/');
|
||||
start.Environment["FAKE_CURL_WORLD"] = registry.Replace('\\', '/');
|
||||
start.Environment["TMPDIR"] = temporary.Replace('\\', '/');
|
||||
start.Environment["DOCKER_HOST"] = OperatingSystem.IsWindows() ? "npipe:////./pipe/febe-nessun-demone" : "unix:///nonexistent/febe-nessun-demone.sock";
|
||||
start.Environment.Remove("DOCKER_CONTEXT");
|
||||
start.Environment.Remove("BUILDX_BUILDER");
|
||||
start.Environment.Remove("REGISTRY_TOKEN");
|
||||
start.Environment["GITEA_API"] = RegistryApi;
|
||||
start.Environment["PROPRIETARIO"] = "Alby96";
|
||||
if (world.Registry is { } sent)
|
||||
{
|
||||
start.Environment["REGISTRY_TOKEN"] = sent.Sent ?? sent.Token;
|
||||
}
|
||||
});
|
||||
|
||||
var run = new CleanupRun(result.Code, result.Output, result.Errors)
|
||||
{
|
||||
Containers = FakeDaemon.ContainersOf([.. await ReadLinesAsync(folder.Combine("containers"))]),
|
||||
Images = [.. (await ReadLinesAsync(folder.Combine("images"))).Select(i => string.Join('|', i.Split('|')[..2]))],
|
||||
Volumes = [.. (await ReadLinesAsync(folder.Combine("volumes"))).Select(v => v.Split('|')[0])],
|
||||
Networks = [.. (await ReadLinesAsync(folder.Combine("networks"))).Select(n => n.Split('|')[1])],
|
||||
Calls = await ReadLinesAsync(folder.Combine("calls")),
|
||||
RegistryCalls = await ReadLinesAsync(Path.Combine(registry, "calls")),
|
||||
Deleted = await ReadLinesAsync(Path.Combine(registry, "deleted")),
|
||||
};
|
||||
if (touchesDocker)
|
||||
{
|
||||
Assert.IsNotEmpty(run.Calls, $"the fake docker client was not the one called\n{run.Report}");
|
||||
}
|
||||
|
||||
Assert.DoesNotContain("unexpected call", run.Errors, run.Report);
|
||||
Assert.DoesNotContain("fake curl:", run.Errors, run.Report);
|
||||
Assert.DoesNotContain("curl: (", run.Errors, $"a real curl was called\n{run.Report}");
|
||||
Assert.IsEmpty(Directory.EnumerateFileSystemEntries(temporary), $"the cleanup leaves no temporary files\n{run.Report}");
|
||||
return run;
|
||||
}
|
||||
|
||||
/// <summary>A program with its arguments, from the root of the repository; its output with Unix lines.</summary>
|
||||
private async Task<(int Code, string Output, string Errors)> RunProcessAsync(string program, IEnumerable<string> arguments, Action<ProcessStartInfo>? configure = null)
|
||||
{
|
||||
var start = new ProcessStartInfo(program)
|
||||
{
|
||||
WorkingDirectory = Repository.Root()!,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
StandardOutputEncoding = System.Text.Encoding.UTF8,
|
||||
StandardErrorEncoding = System.Text.Encoding.UTF8,
|
||||
};
|
||||
foreach (var argument in arguments)
|
||||
{
|
||||
start.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
configure?.Invoke(start);
|
||||
using var process = Process.Start(start)!;
|
||||
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
|
||||
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
|
||||
await process.WaitForExitAsync(TestContext.CancellationToken);
|
||||
return (process.ExitCode, (await output).Replace("\r\n", "\n", StringComparison.Ordinal), (await errors).Replace("\r\n", "\n", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>The pages of versioni-registro.json as Gitea would answer them, one file each.</summary>
|
||||
private async Task<List<string>> WriteRegistryPagesAsync(string folder)
|
||||
{
|
||||
var fixture = await File.ReadAllTextAsync(Repository.PathOf("tests", "Febe.Tests", "Packaging", "versioni-registro.json"), TestContext.CancellationToken);
|
||||
using var pages = JsonDocument.Parse(fixture);
|
||||
var files = new List<string>();
|
||||
foreach (var page in pages.RootElement.EnumerateArray())
|
||||
{
|
||||
var file = Path.Combine(folder, $"page-{files.Count + 1}.json");
|
||||
await File.WriteAllTextAsync(file, page.GetRawText(), TestContext.CancellationToken);
|
||||
files.Add(file);
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
private static void InstallFake(string name, string path)
|
||||
{
|
||||
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", name), path);
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task WriteLinesAsync(string path, IEnumerable<string> lines) =>
|
||||
await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken);
|
||||
|
||||
private async Task<List<string>> ReadLinesAsync(string path) =>
|
||||
File.Exists(path) ? Lines(await File.ReadAllTextAsync(path, TestContext.CancellationToken)) : [];
|
||||
|
||||
private static List<string> Lines(string text) => [.. text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n', StringSplitOptions.RemoveEmptyEntries)];
|
||||
|
||||
/// <summary>The number the summary of the cleanup gives for a kind of object, or null when it does not list it.</summary>
|
||||
private static string? SummaryCount(string output, string kind)
|
||||
{
|
||||
var match = Regex.Match(output, $@"^ {Regex.Escape(kind)}: (?<count>[0-9]+)", RegexOptions.Multiline);
|
||||
return match.Success ? match.Groups["count"].Value : null;
|
||||
}
|
||||
|
||||
/// <summary>The «run: |» block of a step without its indentation, as the runner writes it to a script.</summary>
|
||||
private static string RunBlock(string step)
|
||||
{
|
||||
const string start = "run: |\n";
|
||||
var at = step.IndexOf(start, StringComparison.Ordinal);
|
||||
Assert.IsGreaterThanOrEqualTo(0, at, $"the step has no «{start.Trim()}» block");
|
||||
var lines = step[(at + start.Length)..].Split('\n');
|
||||
var indent = new string(' ', lines.First(l => l.Trim().Length > 0).TakeWhile(c => c == ' ').Count());
|
||||
var body = lines.TakeWhile(l => l.Trim().Length == 0 || l.StartsWith(indent, StringComparison.Ordinal));
|
||||
return string.Concat(body.Select(l => (l.Length >= indent.Length ? l[indent.Length..] : string.Empty) + "\n"));
|
||||
}
|
||||
|
||||
/// <summary>The body of a shell function of a script, from «name() {» to the closing brace at the start of a line.</summary>
|
||||
private static string Function(string script, string name)
|
||||
{
|
||||
var match = Regex.Match(script, $@"^{Regex.Escape(name)}\(\) \{{\n(?<body>.*?)^\}}", RegexOptions.Multiline | RegexOptions.Singleline);
|
||||
Assert.IsTrue(match.Success, $"manca la funzione {name}");
|
||||
return match.Groups["body"].Value;
|
||||
}
|
||||
|
||||
private static string RequireBash()
|
||||
{
|
||||
var bash = BashForScripts();
|
||||
if (bash is null)
|
||||
{
|
||||
Assert.Inconclusive("Manca bash (su Windows serve Git Bash): la prova della pulizia su un demone finto si salta.");
|
||||
}
|
||||
|
||||
Assert.IsTrue(File.Exists(CiPath("scripts", "pulizia-docker.sh")));
|
||||
return bash;
|
||||
}
|
||||
|
||||
/// <summary>node from the PATH: the registry part of the cleanup reads JSON with it, in the CI as here.</summary>
|
||||
private static string RequireNode()
|
||||
{
|
||||
var names = OperatingSystem.IsWindows() ? new[] { "node.exe" } : ["node"];
|
||||
var node = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty)
|
||||
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)
|
||||
.SelectMany(folder => names.Select(name => Path.Combine(folder.Trim('"'), name)))
|
||||
.FirstOrDefault(File.Exists);
|
||||
if (node is null)
|
||||
{
|
||||
Assert.Inconclusive("Manca node: la prova della scelta delle versioni del registro si salta.");
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"docker (?<what>[a-z]+) prune(?<args>[^\n]*)")]
|
||||
private static partial Regex Prune();
|
||||
|
||||
[GeneratedRegex(@"label=febe\.ci\.(?!prova\b)")]
|
||||
private static partial Regex ProvenanceLabelFilter();
|
||||
|
||||
[GeneratedRegex(@"docker (?:image rm|rmi)\s+(?:-\w+\s+)*-\w*f")]
|
||||
private static partial Regex ForcedImageRemoval();
|
||||
|
||||
[GeneratedRegex(@"docker (?:rm|image rm|volume rm|network rm|buildx rm)\b|prune")]
|
||||
private static partial Regex Removal();
|
||||
|
||||
[GeneratedRegex(@"docker (?:rm|image rm|volume rm|network rm)(?: -[a-z]+)* (?<target>\S+)$")]
|
||||
private static partial Regex RemovalTarget();
|
||||
|
||||
[GeneratedRegex(@"docker (?:rm|kill|stop|image rm|rmi|image prune|builder prune|buildx rm|buildx prune|volume rm|volume prune|network rm|network prune|container prune|system prune)\b")]
|
||||
private static partial Regex Destructive();
|
||||
|
||||
[GeneratedRegex(@"^::warning::", RegexOptions.Multiline)]
|
||||
private static partial Regex WarningLine();
|
||||
|
||||
[GeneratedRegex(@"^sha-[0-9a-f]{7,40}\t")]
|
||||
private static partial Regex ShaTagLine();
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
@@ -10,8 +9,8 @@ namespace Febe.Tests.Packaging;
|
||||
/// text: the rules that must survive later edits. Every push of every branch is verified and nothing else triggers
|
||||
/// it twice; the tests run only through tests/Febe.Tests, with the browser, and again with the seed of the run; the
|
||||
/// image is published only from main and never as :latest; credentials are never printed; the external tools are
|
||||
/// pinned and checked; the cleanup touches only what the CI of Febe made, never a real Febe on the same daemon; the
|
||||
/// tried container never has a network.
|
||||
/// pinned and checked; the tried container never has a network. The cleanup, which runs against fake docker and curl
|
||||
/// clients, is in PipelineTests.Pulizia.cs.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed partial class PipelineTests
|
||||
@@ -163,41 +162,6 @@ public sealed partial class PipelineTests
|
||||
StringAssert.Contains(scan, "--exit-code 1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheCleanupTouchesOnlyWhatTheCiOfFebeMade()
|
||||
{
|
||||
var cleanup = Code(Script("pulizia-docker.sh"));
|
||||
foreach (var forbidden in new[] { "system prune", "builder prune", "volume prune", "container prune", "image prune -a", "prune --all", "image prune -f -a" })
|
||||
{
|
||||
Assert.DoesNotContain(forbidden, cleanup, "the daemon is shared with Alberto's other projects");
|
||||
}
|
||||
|
||||
Assert.HasCount(1, ImagePrune().Matches(cleanup), "only dangling images, older than three days");
|
||||
StringAssert.Contains(cleanup, "docker image prune -f --filter \"until=72h\"");
|
||||
StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$");
|
||||
|
||||
// The febe.ci.* labels of the image are in every container made from a published image, a real Febe too: they
|
||||
// never choose what goes. Containers are chosen by febe.ci.prova (and their exact name), the builders by name,
|
||||
// and an image only by its local name febe-ci:<run>, never by id and never forced.
|
||||
Assert.IsFalse(ProvenanceLabelFilter().IsMatch(cleanup), "the cleanup filters on febe.ci.prova only");
|
||||
foreach (var line in cleanup.Split('\n').Where(l => l.Contains("docker ps", StringComparison.Ordinal)))
|
||||
{
|
||||
Assert.IsTrue(
|
||||
line.Contains("--filter \"label=febe.ci.prova", StringComparison.Ordinal) || line.Contains("--filter \"name=buildx_buildkit_febe-ci-\"", StringComparison.Ordinal) || line.Contains("--filter \"ancestor=", StringComparison.Ordinal),
|
||||
$"«{line.Trim()}» lists containers without the mark of the tried container");
|
||||
}
|
||||
|
||||
StringAssert.Contains(cleanup, "\"febe-prova-$valore\"", "the name must match the mark");
|
||||
StringAssert.Contains(cleanup, "contenitori_di_prova \"\" exited created dead", "the sweeps take only stopped tried containers");
|
||||
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
|
||||
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
|
||||
|
||||
var weekly = Workflow("pulizia.yml");
|
||||
StringAssert.Contains(weekly, "schedule:");
|
||||
StringAssert.Contains(weekly, "workflow_dispatch:");
|
||||
StringAssert.Contains(weekly, "bash .gitea/scripts/pulizia-docker.sh settimanale");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheTriedContainerNeverHasANetworkAndAlwaysCarriesTheMarkNoImageHas()
|
||||
{
|
||||
@@ -218,186 +182,6 @@ public sealed partial class PipelineTests
|
||||
Assert.DoesNotContain("febe.ci.prova", Code(Read(Repository.PathOf("docker", "Dockerfile"))));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade()
|
||||
{
|
||||
var script = CiPath("scripts", "pulizia-docker.sh");
|
||||
var bash = BashForScripts();
|
||||
if (bash is null)
|
||||
{
|
||||
Assert.Inconclusive("Manca bash (su Windows serve Git Bash): la prova della pulizia su un demone finto si salta.");
|
||||
}
|
||||
|
||||
Assert.IsTrue(File.Exists(script));
|
||||
|
||||
// At the start or the end of a run (a release run again keeps its id, so the published image has the same
|
||||
// febe.ci.run as the run): only the tried container, the local name and the builder of that run.
|
||||
var run = await RunCleanupAsync(bash, FakeDaemon.Full, "esecuzione", "777");
|
||||
Assert.AreEqual(0, run.Code, run.Report);
|
||||
Assert.DoesNotContain("::warning::", run.Output, run.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-777", "b-777"]).ToList(), run.Containers, run.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777(), run.Images, run.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-7770_state"]).ToList(), run.Volumes, run.Report);
|
||||
|
||||
// Leftovers of interrupted runs: stopped tried containers, febe-ci images and builders older than 90 minutes.
|
||||
var leftovers = await RunCleanupAsync(bash, FakeDaemon.Full, "residui", "90");
|
||||
Assert.AreEqual(0, leftovers.Code, leftovers.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-555", "b-vecchio"]).ToList(), leftovers.Containers, leftovers.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555"), leftovers.Images, leftovers.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-4560_state"]).ToList(), leftovers.Volumes, leftovers.Report);
|
||||
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore di prova febe-prova-556 è acceso", "a running tried container is reported, not removed");
|
||||
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore buildx_buildkit_febe-ci-4570 non è un builder buildx", leftovers.Report);
|
||||
|
||||
// Every week, on a daemon without anything odd: the same, the old febe:ci and the dangling images older than
|
||||
// 72 hours that no container uses. Green.
|
||||
var weekly = await RunCleanupAsync(bash, FakeDaemon.Clean, "settimanale");
|
||||
Assert.AreEqual(0, weekly.Code, weekly.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Clean).Except(["c-prova-555", "b-vecchio"]).ToList(), weekly.Containers, weekly.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555", "img-ci556", "img-legacy", "img-penzolante-vecchia"), weekly.Images, weekly.Report);
|
||||
|
||||
// With something left for a person to look at, the weekly cleanup goes red.
|
||||
var noticed = await RunCleanupAsync(bash, FakeDaemon.Full, "settimanale");
|
||||
Assert.AreEqual(1, noticed.Code, noticed.Report);
|
||||
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
|
||||
CollectionAssert.Contains(noticed.Containers, "c-febe-vero");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The daemon the cleanup runs against in <see cref="OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade"/>
|
||||
/// (format in fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of
|
||||
/// their images, as Docker gives them; the image of the release also has the local name of run 777.
|
||||
/// </summary>
|
||||
private static class FakeDaemon
|
||||
{
|
||||
public static readonly string[] Full =
|
||||
[
|
||||
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0",
|
||||
"c-febe-fermo|febe-main|exited|43200|192.168.30.23:3000/alby96/febe:main|img-main|febe.ci.workflow=verifica,febe.ci.run=888",
|
||||
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
|
||||
"c-prova-777|febe-prova-777|running|5|febe-ci:777|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.prova=777",
|
||||
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
|
||||
"c-prova-556|febe-prova-556|running|300|febe-ci:556|img-ci556|febe.ci.run=556,febe.ci.prova=556",
|
||||
"c-prova-557|febe-prova-557|exited|10|febe-ci:557|img-ci557|febe.ci.run=557,febe.ci.prova=557",
|
||||
"c-nome-strano|febe-prova-558-bis|exited|300|encelado:latest|img-encelado|febe.ci.prova=558",
|
||||
"c-segno-diverso|febe-prova-559|exited|300|encelado:latest|img-encelado|febe.ci.prova=560",
|
||||
"c-senza-segno|febe-prova-561|exited|300|encelado:latest|img-encelado|",
|
||||
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|",
|
||||
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
|
||||
"b-finto|buildx_buildkit_febe-ci-4570|running|300|encelado:latest|img-encelado|",
|
||||
"b-giovane|buildx_buildkit_febe-ci-7890|running|10|moby/buildkit:buildx-stable-1|img-buildkit|",
|
||||
"b-altro|altro_buildx_buildkit_febe-ci-10|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
|
||||
"b-777|buildx_buildkit_febe-ci-7770|running|20|moby/buildkit:buildx-stable-1|img-buildkit|",
|
||||
];
|
||||
|
||||
/// <summary>The same daemon without the running tried container and the builder that is not one.</summary>
|
||||
public static readonly string[] Clean = [.. Full.Where(c => !c.StartsWith("c-prova-556|", StringComparison.Ordinal) && !c.StartsWith("b-finto|", StringComparison.Ordinal))];
|
||||
|
||||
public static readonly string[] Images =
|
||||
[
|
||||
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0,febe-ci:777|43200|febe.ci.run=777",
|
||||
"img-main|192.168.30.23:3000/alby96/febe:main|43200|febe.ci.run=888",
|
||||
"img-ci555|febe-ci:555|300|febe.ci.run=555",
|
||||
"img-ci556|febe-ci:556|300|febe.ci.run=556",
|
||||
"img-ci557|febe-ci:557|10|febe.ci.run=557",
|
||||
"img-penzolante-febe||300|febe.ci.run=999",
|
||||
"img-penzolante-vecchia||6000|",
|
||||
"img-penzolante-in-uso||20000|febe.ci.run=111",
|
||||
"img-encelado|encelado:latest|5000|",
|
||||
"img-buildkit|moby/buildkit:buildx-stable-1|50000|",
|
||||
"img-legacy|febe:ci|6000|",
|
||||
];
|
||||
|
||||
public static readonly string[] Volumes =
|
||||
[
|
||||
"buildx_buildkit_febe-ci-4560_state",
|
||||
"buildx_buildkit_febe-ci-4570_state",
|
||||
"buildx_buildkit_febe-ci-7890_state",
|
||||
"buildx_buildkit_febe-ci-7770_state",
|
||||
"encelado-dati",
|
||||
];
|
||||
|
||||
public static List<string> ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])];
|
||||
|
||||
/// <summary>
|
||||
/// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without
|
||||
/// the images given.
|
||||
/// </summary>
|
||||
public static List<string> ImagesWithout777(params string[] gone) =>
|
||||
[
|
||||
.. Images
|
||||
.Select(i => string.Join('|', i.Split('|')[..2]).Replace(",febe-ci:777", string.Empty, StringComparison.Ordinal))
|
||||
.Where(i => !gone.Contains(i[..i.IndexOf('|', StringComparison.Ordinal)])),
|
||||
];
|
||||
}
|
||||
|
||||
private sealed record CleanupRun(int Code, string Output, string Errors, List<string> Containers, List<string> Images, List<string> Volumes)
|
||||
{
|
||||
public string Report => $"codice {Code}\n{Output}\n{Errors}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// pulizia-docker.sh against the fake daemon. DOCKER_HOST points nowhere: even if a real docker client came first on
|
||||
/// the PATH it could not reach a daemon, and the test fails because the fake recorded no call.
|
||||
/// </summary>
|
||||
private async Task<CleanupRun> RunCleanupAsync(string bash, string[] containers, params string[] arguments)
|
||||
{
|
||||
using var world = new TempFolder("febe-pulizia");
|
||||
var bin = world.Combine("bin");
|
||||
Directory.CreateDirectory(bin);
|
||||
var docker = Path.Combine(bin, "docker");
|
||||
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", "fake-docker.sh"), docker);
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
File.SetUnixFileMode(docker, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
|
||||
await WriteLinesAsync(world.Combine("containers"), containers);
|
||||
await WriteLinesAsync(world.Combine("images"), FakeDaemon.Images);
|
||||
await WriteLinesAsync(world.Combine("volumes"), FakeDaemon.Volumes);
|
||||
|
||||
var start = new ProcessStartInfo(bash)
|
||||
{
|
||||
WorkingDirectory = Repository.Root()!,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
StandardOutputEncoding = System.Text.Encoding.UTF8,
|
||||
StandardErrorEncoding = System.Text.Encoding.UTF8,
|
||||
};
|
||||
start.ArgumentList.Add(".gitea/scripts/pulizia-docker.sh");
|
||||
foreach (var argument in arguments)
|
||||
{
|
||||
start.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
start.Environment["PATH"] = bin + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH");
|
||||
start.Environment["FAKE_DOCKER_WORLD"] = world.Path.Replace('\\', '/');
|
||||
start.Environment["DOCKER_HOST"] = OperatingSystem.IsWindows() ? "npipe:////./pipe/febe-nessun-demone" : "unix:///nonexistent/febe-nessun-demone.sock";
|
||||
start.Environment.Remove("DOCKER_CONTEXT");
|
||||
using var process = Process.Start(start)!;
|
||||
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
|
||||
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
|
||||
await process.WaitForExitAsync(TestContext.CancellationToken);
|
||||
|
||||
var result = new CleanupRun(
|
||||
process.ExitCode,
|
||||
(await output).Replace("\r\n", "\n", StringComparison.Ordinal),
|
||||
await errors,
|
||||
FakeDaemon.ContainersOf([.. await ReadLinesAsync(world.Combine("containers"))]),
|
||||
[.. (await ReadLinesAsync(world.Combine("images"))).Select(i => string.Join('|', i.Split('|')[..2]))],
|
||||
await ReadLinesAsync(world.Combine("volumes")));
|
||||
var calls = world.Combine("calls");
|
||||
Assert.IsTrue(File.Exists(calls) && (await File.ReadAllTextAsync(calls, TestContext.CancellationToken)).Contains("docker ps", StringComparison.Ordinal), $"the fake docker client was not the one called\n{result.Report}");
|
||||
Assert.DoesNotContain("unexpected call", result.Errors, result.Report);
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task WriteLinesAsync(string path, IEnumerable<string> lines) =>
|
||||
await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken);
|
||||
|
||||
private async Task<List<string>> ReadLinesAsync(string path) =>
|
||||
[.. (await File.ReadAllTextAsync(path, TestContext.CancellationToken)).Split('\n', StringSplitOptions.RemoveEmptyEntries)];
|
||||
|
||||
/// <summary>bash for the scripts of the CI: the system one on Linux, Git Bash on Windows (not the one of WSL).</summary>
|
||||
private static string? BashForScripts()
|
||||
{
|
||||
@@ -473,15 +257,6 @@ public sealed partial class PipelineTests
|
||||
[GeneratedRegex(@"\b[0-9a-f]{64}\b")]
|
||||
private static partial Regex Sha256();
|
||||
|
||||
[GeneratedRegex(@"docker (?:image|container|volume|builder|system) prune")]
|
||||
private static partial Regex ImagePrune();
|
||||
|
||||
[GeneratedRegex(@"docker run\b(?:[^\n]*\\\n)*[^\n]*")]
|
||||
private static partial Regex DockerRun();
|
||||
|
||||
[GeneratedRegex(@"label=febe\.ci\.(?!prova\b)")]
|
||||
private static partial Regex ProvenanceLabelFilter();
|
||||
|
||||
[GeneratedRegex(@"docker (?:image rm|rmi)\s+(?:-\w+\s+)*-\w*f")]
|
||||
private static partial Regex ForcedImageRemoval();
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env bash
|
||||
# A fake curl for PipelineTests: the registry part of .gitea/scripts/pulizia-docker.sh talks to the packages API of
|
||||
# Gitea 28 through it. No network. It knows only the options the cleanup uses and answers like Gitea:
|
||||
# GET <base>?page=<n>&limit=50 the page $FAKE_CURL_WORLD/page-<n>.json, or [] after the last one (200)
|
||||
# DELETE <base>/<version> 204, and the version is written to $FAKE_CURL_WORLD/deleted
|
||||
# where <base> is the content of $FAKE_CURL_WORLD/base (…/api/v1/packages/<owner>/container/febe). Without the header
|
||||
# «Authorization: token <content of $FAKE_CURL_WORLD/token>» it answers 401; with $FAKE_CURL_WORLD/refuse it answers
|
||||
# 403 to every call; any other address is 404. Every call goes to $FAKE_CURL_WORLD/calls as «METHOD URL», never with
|
||||
# its headers. Any other option is an error (exit 3).
|
||||
set -uo pipefail
|
||||
|
||||
world="${FAKE_CURL_WORLD:?}"
|
||||
token="$(cat "$world/token" 2> /dev/null)"
|
||||
method=GET output="" write="" url="" authorized=0
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
-s | -S | -sS) ;;
|
||||
--max-time) shift ;;
|
||||
-X) method="$2"; shift ;;
|
||||
-H) [[ -n "$token" && "$2" == "Authorization: token $token" ]] && authorized=1; shift ;;
|
||||
-o) output="$2"; shift ;;
|
||||
-w) write="$2"; shift ;;
|
||||
-*) echo "fake curl: unexpected option $1" >&2; exit 3 ;;
|
||||
*)
|
||||
[[ -z "$url" ]] || { echo "fake curl: a second address $1" >&2; exit 3; }
|
||||
url="$1"
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
printf '%s %s\n' "$method" "$url" >> "$world/calls"
|
||||
[[ -z "$write" || "$write" == '%{http_code}' ]] || { echo "fake curl: unexpected -w $write" >&2; exit 3; }
|
||||
|
||||
answer() {
|
||||
local code="$1" body="${2:-}"
|
||||
if [[ -n "$output" ]]; then
|
||||
printf '%s' "$body" > "$output"
|
||||
else
|
||||
printf '%s' "$body"
|
||||
fi
|
||||
[[ -z "$write" ]] || printf '%s' "$code"
|
||||
exit 0
|
||||
}
|
||||
|
||||
[[ -f "$world/refuse" ]] && answer 403 '{"message":"token does not have at least one of required scope(s): [write:package]"}'
|
||||
((authorized)) || answer 401 '{"message":"token is required"}'
|
||||
|
||||
base="$(cat "$world/base")"
|
||||
case "$method $url" in
|
||||
"GET $base?page="*"&limit=50")
|
||||
page="${url#"$base?page="}"
|
||||
page="${page%%&*}"
|
||||
if [[ -f "$world/page-$page.json" ]]; then
|
||||
answer 200 "$(cat "$world/page-$page.json")"
|
||||
fi
|
||||
answer 200 "[]"
|
||||
;;
|
||||
"DELETE $base/"*)
|
||||
echo "${url#"$base/"}" >> "$world/deleted"
|
||||
answer 204
|
||||
;;
|
||||
*) answer 404 '{"message":"The target couldn'"'"'t be found."}' ;;
|
||||
esac
|
||||
@@ -3,32 +3,53 @@
|
||||
# files, and the test reads what is left. No daemon, no network. It models only what the cleanup relies on, the way
|
||||
# Docker does it:
|
||||
# - filters of «ps»: label filters must all match, the values of any other key are alternatives (status, name as a
|
||||
# regular expression, ancestor by name or id);
|
||||
# regular expression, ancestor by name or id, volume and network by name; stopped containers too);
|
||||
# - «rm» refuses a running container without -f;
|
||||
# - «image rm <name>» only untags when the image has other names, and refuses an image a container uses (always if the
|
||||
# container runs, without -f if it is stopped);
|
||||
# - «image prune --filter until=72h» takes only images without a name, older than 72 hours, used by no container.
|
||||
# Any other call is an error (exit 3), so the test sees every command the cleanup starts to use.
|
||||
# - «image prune» takes only images no container uses, running or stopped: without -a only those without a name, with
|
||||
# -a any; «until» keeps those created in the last 72 or 24 hours. With -a an image a container uses stays but loses
|
||||
# its extra names, as moby does it with the classic store or, with $FAKE_DOCKER_WORLD/store, with containerd;
|
||||
# - «builder prune» only answers (the cache is not modelled);
|
||||
# - «volume rm» refuses a volume a container mounts, running or stopped, even with -f;
|
||||
# - «network rm» refuses the predefined networks and a network a running container is attached to;
|
||||
# - creation times: containers and images in UTC with nanoseconds, volumes and networks two hours ahead with the
|
||||
# offset (+02:00), as a daemon in Italy writes them; the Created of a network is a time of Go, which the template
|
||||
# prints as «2026-10-21 06:17:03.123456789 +0200 CEST» and {{json .Created}} as RFC 3339 between quotes.
|
||||
# Any other call is an error (exit 3), so the test sees every command the cleanup starts to use. That includes any prune
|
||||
# other than those the cleanup may run: image prune -f [--filter until=72h], image prune -a -f --filter until=24h,
|
||||
# builder prune [-a] -f --filter until=24h.
|
||||
#
|
||||
# $FAKE_DOCKER_WORLD/containers id|name|state|minutes ago|image as given to «docker run»|image id|labels
|
||||
# (labels as Docker gives them to the container: those of the image plus those of «run»)
|
||||
# $FAKE_DOCKER_WORLD/images id|names (comma separated; empty: dangling)|minutes ago|labels
|
||||
# $FAKE_DOCKER_WORLD/volumes one name per line
|
||||
# $FAKE_DOCKER_WORLD/calls every call, one per line (written here)
|
||||
# $FAKE_DOCKER_WORLD/containers id|name|state|minutes ago|image as given to «docker run»|image id|labels|volumes|networks
|
||||
# (labels as Docker gives them to the container: those of the image plus those of «run»;
|
||||
# volumes and networks by name, comma separated; the last fields may be missing)
|
||||
# $FAKE_DOCKER_WORLD/images id|names (comma separated; empty: dangling)|minutes ago|labels|size
|
||||
# $FAKE_DOCKER_WORLD/volumes name|minutes ago (missing: just created)
|
||||
# $FAKE_DOCKER_WORLD/networks id|name|minutes ago
|
||||
# $FAKE_DOCKER_WORLD/store optional: «containerd» for the containerd image store (what «docker info» says);
|
||||
# otherwise the classic store of overlay2
|
||||
# $FAKE_DOCKER_WORLD/broken optional: commands («image prune», «builder prune») that fail as if the daemon refused
|
||||
# $FAKE_DOCKER_WORLD/calls every call, one per line (written here), after BUILDX_BUILDER=<value> when it is set
|
||||
set -uo pipefail
|
||||
|
||||
world="${FAKE_DOCKER_WORLD:?}"
|
||||
printf 'docker %s\n' "$*" >> "$world/calls"
|
||||
printf '%sdocker %s\n' "${BUILDX_BUILDER:+BUILDX_BUILDER=$BUILDX_BUILDER }" "$*" >> "$world/calls"
|
||||
now=$(date -u +%s)
|
||||
touch "$world/containers" "$world/images" "$world/volumes"
|
||||
touch "$world/containers" "$world/images" "$world/volumes" "$world/networks"
|
||||
|
||||
unexpected() {
|
||||
echo "fake docker: unexpected call: $*" >&2
|
||||
exit 3
|
||||
}
|
||||
|
||||
broken() {
|
||||
[[ -f "$world/broken" ]] && grep -qxF -- "$1" "$world/broken"
|
||||
}
|
||||
|
||||
created() { date -u -d "@$((now - $1 * 60))" +%Y-%m-%dT%H:%M:%S.123456789Z; }
|
||||
|
||||
created_in_italy() { date -u -d "@$((now - ${1:-0} * 60 + 7200))" "+%Y-%m-%dT%H:%M:%S${2:-}+02:00"; }
|
||||
|
||||
# The value of a label, or $3 when it is missing («docker ps» prints nothing, «inspect» prints <no value>).
|
||||
label_value() {
|
||||
local labels=",$1," key="$2" rest
|
||||
@@ -48,8 +69,8 @@ has_label() {
|
||||
|
||||
# Image id for a name or an id; empty when there is none.
|
||||
resolve_image() {
|
||||
local ref="$1" id names age labels
|
||||
while IFS='|' read -r id names age labels; do
|
||||
local ref="$1" id names rest
|
||||
while IFS='|' read -r id names rest; do
|
||||
[[ -n "$id" ]] || continue
|
||||
if [[ "$id" == "$ref" || ",$names," == *",$ref,"* ]]; then
|
||||
echo "$id"
|
||||
@@ -58,26 +79,29 @@ resolve_image() {
|
||||
done < "$world/images"
|
||||
}
|
||||
|
||||
# The image line for an id; empty when there is none.
|
||||
image_line() {
|
||||
local line
|
||||
# The line of a world file whose first field (or, with $3, whose field number $3) is $2; empty when there is none.
|
||||
line_of() {
|
||||
local file="$1" wanted="$2" field="${3:-1}" line fields
|
||||
while IFS= read -r line; do
|
||||
[[ -n "$line" && "${line%%|*}" == "$1" ]] && { echo "$line"; return; }
|
||||
done < "$world/images"
|
||||
}
|
||||
|
||||
# The container line for an id or a name; empty when there is none.
|
||||
find_container() {
|
||||
local ref="$1" line id name rest
|
||||
while IFS= read -r line; do
|
||||
IFS='|' read -r id name rest <<< "$line"
|
||||
if [[ -n "$id" && ("$id" == "$ref" || "$name" == "$ref") ]]; then
|
||||
[[ -n "$line" ]] || continue
|
||||
IFS='|' read -r -a fields <<< "$line"
|
||||
if [[ "${fields[0]}" == "$wanted" || "${fields[field - 1]:-}" == "$wanted" ]]; then
|
||||
echo "$line"
|
||||
return
|
||||
fi
|
||||
done < "$world/containers"
|
||||
done < "$file"
|
||||
}
|
||||
|
||||
image_line() { line_of "$world/images" "$1"; }
|
||||
|
||||
# The container line for an id or a name; empty when there is none.
|
||||
find_container() { line_of "$world/containers" "$1" 2; }
|
||||
|
||||
volume_line() { line_of "$world/volumes" "$1"; }
|
||||
|
||||
# The network line for an id or a name; empty when there is none.
|
||||
network_line() { line_of "$world/networks" "$1" 2; }
|
||||
|
||||
# Rewrites a world file without the lines whose first field is $2.
|
||||
drop() {
|
||||
local file="$1" id="$2" line
|
||||
@@ -88,18 +112,31 @@ drop() {
|
||||
mv "$file.new" "$file"
|
||||
}
|
||||
|
||||
# True when a container uses the image (any: in any state; running: only a running one).
|
||||
used_by() {
|
||||
local image="$1" want="$2" id name state age config image_id labels
|
||||
while IFS='|' read -r id name state age config image_id labels; do
|
||||
local image="$1" want="$2" id name state age config image_id labels volumes networks
|
||||
while IFS='|' read -r id name state age config image_id labels volumes networks; do
|
||||
[[ -n "$id" && "$image_id" == "$image" ]] || continue
|
||||
[[ "$want" == any || "$state" == running ]] && return 0
|
||||
done < "$world/containers"
|
||||
return 1
|
||||
}
|
||||
|
||||
# True when a container (any: in any state; running: only a running one) has the volume or the network.
|
||||
uses() {
|
||||
local field="$1" wanted="$2" want="$3" id name state age config image_id labels volumes networks list
|
||||
while IFS='|' read -r id name state age config image_id labels volumes networks; do
|
||||
[[ -n "$id" ]] || continue
|
||||
if [[ "$field" == volume ]]; then list="$volumes"; else list="$networks"; fi
|
||||
[[ ",$list," == *",$wanted,"* ]] || continue
|
||||
[[ "$want" == any || "$state" == running ]] && return 0
|
||||
done < "$world/containers"
|
||||
return 1
|
||||
}
|
||||
|
||||
matches() {
|
||||
local name="$1" state="$2" image_id="$3" labels="$4"
|
||||
shift 4
|
||||
local name="$1" state="$2" image_id="$3" labels="$4" volumes="$5" networks="$6"
|
||||
shift 6
|
||||
local -A seen=() ok=()
|
||||
local filter key value
|
||||
for filter in "$@"; do
|
||||
@@ -110,6 +147,8 @@ matches() {
|
||||
status) seen[$key]=1; [[ "$state" == "$value" ]] && ok[$key]=1 ;;
|
||||
name) seen[$key]=1; [[ "$name" =~ $value ]] && ok[$key]=1 ;;
|
||||
ancestor) seen[$key]=1; [[ -n "$image_id" && "$(resolve_image "$value")" == "$image_id" ]] && ok[$key]=1 ;;
|
||||
volume) seen[$key]=1; [[ ",$volumes," == *",$value,"* ]] && ok[$key]=1 ;;
|
||||
network) seen[$key]=1; [[ ",$networks," == *",$value,"* ]] && ok[$key]=1 ;;
|
||||
*) unexpected "filter $filter" ;;
|
||||
esac
|
||||
done
|
||||
@@ -131,10 +170,10 @@ ps_command() {
|
||||
esac
|
||||
shift
|
||||
done
|
||||
local id name state age config image_id labels out key
|
||||
while IFS='|' read -r id name state age config image_id labels; do
|
||||
local id name state age config image_id labels volumes networks out key
|
||||
while IFS='|' read -r id name state age config image_id labels volumes networks; do
|
||||
[[ -n "$id" ]] || continue
|
||||
matches "$name" "$state" "$image_id" "$labels" "${filters[@]}" || continue
|
||||
matches "$name" "$state" "$image_id" "$labels" "$volumes" "$networks" "${filters[@]}" || continue
|
||||
if ((quiet)); then
|
||||
echo "$id"
|
||||
continue
|
||||
@@ -145,6 +184,7 @@ ps_command() {
|
||||
key="${BASH_REMATCH[1]}"
|
||||
out="${out/"${BASH_REMATCH[0]}"/$(label_value "$labels" "$key" "")}"
|
||||
done
|
||||
[[ "$out" == *"{{"* ]] && unexpected "ps --format $format"
|
||||
printf '%s\n' "$out"
|
||||
done < "$world/containers"
|
||||
return 0
|
||||
@@ -153,18 +193,28 @@ ps_command() {
|
||||
container_inspect() {
|
||||
local format=""
|
||||
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
|
||||
local line id name state age config image_id labels
|
||||
line=$(find_container "${1:?}")
|
||||
[[ -n "$line" ]] || { echo "Error: No such container: $1" >&2; exit 1; }
|
||||
IFS='|' read -r id name state age config image_id labels <<< "$line"
|
||||
case "$format" in
|
||||
"") echo "[{\"Id\": \"$id\"}]" ;;
|
||||
"{{.Created}}") created "$age" ;;
|
||||
"{{.Config.Image}}") echo "$config" ;;
|
||||
"{{.Name}}") echo "/$name" ;;
|
||||
'{{index .Config.Labels "febe.ci.prova"}}') label_value "$labels" febe.ci.prova "<no value>" ;;
|
||||
*) unexpected "container inspect -f $format" ;;
|
||||
esac
|
||||
(($#)) || unexpected "container inspect without a container"
|
||||
local ref line id name state age config image_id labels volumes networks status=0
|
||||
for ref in "$@"; do
|
||||
line=$(find_container "$ref")
|
||||
if [[ -z "$line" ]]; then
|
||||
echo "Error: No such container: $ref" >&2
|
||||
status=1
|
||||
continue
|
||||
fi
|
||||
IFS='|' read -r id name state age config image_id labels volumes networks <<< "$line"
|
||||
case "$format" in
|
||||
"") echo "[{\"Id\": \"$id\"}]" ;;
|
||||
"{{.Created}}") created "$age" ;;
|
||||
"{{.Config.Image}}") echo "$config" ;;
|
||||
"{{.Image}}") echo "$image_id" ;;
|
||||
"{{.Image}} {{.Config.Image}}") echo "$image_id $config" ;;
|
||||
"{{.Name}}") echo "/$name" ;;
|
||||
'{{index .Config.Labels "febe.ci.prova"}}') label_value "$labels" febe.ci.prova "<no value>" ;;
|
||||
*) unexpected "container inspect -f $format" ;;
|
||||
esac
|
||||
done
|
||||
return "$status"
|
||||
}
|
||||
|
||||
rm_command() {
|
||||
@@ -192,19 +242,31 @@ image_ls() {
|
||||
local format="" reference=""
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--no-trunc) ;;
|
||||
--filter) [[ "$2" == reference=* ]] || unexpected "image ls --filter $2"; reference="${2#reference=}"; shift ;;
|
||||
--format) format="$2"; shift ;;
|
||||
*) unexpected "image ls $1" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
[[ "$format" == "{{.Repository}}:{{.Tag}}" ]] || unexpected "image ls --format $format"
|
||||
local id names age labels tag
|
||||
while IFS='|' read -r id names age labels; do
|
||||
[[ -n "$format" ]] || unexpected "image ls without --format"
|
||||
local id names age labels size tag out
|
||||
while IFS='|' read -r id names age labels size; do
|
||||
[[ -n "$id" ]] || continue
|
||||
IFS=',' read -r -a tags <<< "$names"
|
||||
tags=()
|
||||
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
|
||||
if ((${#tags[@]} == 0)); then
|
||||
[[ -z "$reference" ]] || continue
|
||||
tags=("<none>:<none>")
|
||||
fi
|
||||
for tag in "${tags[@]}"; do
|
||||
[[ -z "$reference" || "${tag%:*}" == "$reference" || "$tag" == "$reference" ]] && echo "$tag"
|
||||
[[ -z "$reference" || "${tag%:*}" == "$reference" || "$tag" == "$reference" ]] || continue
|
||||
out="${format//"{{.ID}}"/$id}"
|
||||
out="${out//"{{.Repository}}"/${tag%:*}}"
|
||||
out="${out//"{{.Tag}}"/${tag##*:}}"
|
||||
out="${out//"{{.Size}}"/${size:-100MB}}"
|
||||
[[ "$out" == *"{{"* ]] && unexpected "image ls --format $format"
|
||||
printf '%s\n' "$out"
|
||||
done
|
||||
done < "$world/images"
|
||||
return 0
|
||||
@@ -213,34 +275,31 @@ image_ls() {
|
||||
image_inspect() {
|
||||
local format=""
|
||||
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
|
||||
local wanted id names age labels
|
||||
local wanted id names age labels size
|
||||
wanted=$(resolve_image "${1:?}")
|
||||
[[ -n "$wanted" ]] || { echo "Error: No such image: $1" >&2; exit 1; }
|
||||
while IFS='|' read -r id names age labels; do
|
||||
[[ "$id" == "$wanted" ]] || continue
|
||||
case "$format" in
|
||||
"") echo "[{\"Id\": \"$id\"}]" ;;
|
||||
"{{.Created}}") created "$age" ;;
|
||||
"{{len .RepoTags}}") if [[ -z "$names" ]]; then echo 0; else IFS=',' read -r -a tags <<< "$names"; echo "${#tags[@]}"; fi ;;
|
||||
*) unexpected "image inspect -f $format" ;;
|
||||
esac
|
||||
done < "$world/images"
|
||||
IFS='|' read -r id names age labels size <<< "$(image_line "$wanted")"
|
||||
case "$format" in
|
||||
"") echo "[{\"Id\": \"$id\"}]" ;;
|
||||
"{{.Created}}") created "$age" ;;
|
||||
"{{len .RepoTags}}") if [[ -z "$names" ]]; then echo 0; else IFS=',' read -r -a tags <<< "$names"; echo "${#tags[@]}"; fi ;;
|
||||
*) unexpected "image inspect -f $format" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
image_rm() {
|
||||
local force=0
|
||||
[[ "${1:-}" == -f ]] && { force=1; shift; }
|
||||
local ref="${1:?}" wanted id names age labels left="" tag
|
||||
local ref="${1:?}" wanted id names age labels size left="" tag
|
||||
wanted=$(resolve_image "$ref")
|
||||
[[ -n "$wanted" ]] || { echo "Error: No such image: $ref" >&2; exit 1; }
|
||||
IFS='|' read -r id names age labels <<< "$(image_line "$wanted")"
|
||||
IFS='|' read -r id names age labels size <<< "$(image_line "$wanted")"
|
||||
tags=()
|
||||
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
|
||||
if [[ "$ref" != "$id" && ${#tags[@]} -gt 1 ]]; then
|
||||
for tag in "${tags[@]}"; do [[ "$tag" == "$ref" ]] || left="${left:+$left,}$tag"; done
|
||||
drop "$world/images" "$id"
|
||||
printf '%s|%s|%s|%s
|
||||
' "$id" "$left" "$age" "$labels" >> "$world/images"
|
||||
printf '%s|%s|%s|%s|%s\n' "$id" "$left" "$age" "$labels" "$size" >> "$world/images"
|
||||
echo "Untagged: $ref"
|
||||
return 0
|
||||
fi
|
||||
@@ -256,18 +315,232 @@ image_rm() {
|
||||
echo "Deleted: $id"
|
||||
}
|
||||
|
||||
# The full name of an image name, the way Docker sorts references: docker.io/library/ or docker.io/ before the names
|
||||
# of Docker Hub written without a domain, :latest when the tag is missing.
|
||||
full_name() {
|
||||
local name="$1" first
|
||||
[[ "${name##*/}" == *:* ]] || name="$name:latest"
|
||||
if [[ "$name" != */* ]]; then
|
||||
echo "docker.io/library/$name"
|
||||
return
|
||||
fi
|
||||
first="${name%%/*}"
|
||||
if [[ "$first" == *.* || "$first" == *:* || "$first" == localhost ]]; then echo "$name"; else echo "docker.io/$name"; fi
|
||||
}
|
||||
|
||||
# The names «image prune -a» leaves to an image a container uses, comma separated, the way moby does it. With the
|
||||
# classic store it removes the references in lexical order of their full names and only the last one is refused
|
||||
# (ImageDelete keeps the single reference of an image in use); with containerd it keeps the names the containers were
|
||||
# created from and, when a container uses the image by id and no name would be left, the last one in lexical order.
|
||||
names_kept() {
|
||||
local image="$1" names="$2" sorted name full cid cname state age config image_id rest by_id=0
|
||||
local -A from=()
|
||||
local kept=()
|
||||
sorted=$(IFS=','; for name in $names; do printf '%s %s\n' "$(full_name "$name")" "$name"; done | LC_ALL=C sort)
|
||||
if [[ "$(store)" == classic ]]; then
|
||||
tail -n 1 <<< "$sorted" | cut -d' ' -f2-
|
||||
return
|
||||
fi
|
||||
while IFS='|' read -r cid cname state age config image_id rest; do
|
||||
[[ -n "$cid" && "$image_id" == "$image" ]] || continue
|
||||
if [[ "$config" == "$image" ]]; then by_id=1; else from[$(full_name "$config")]=1; fi
|
||||
done < "$world/containers"
|
||||
while read -r full name; do
|
||||
[[ -n "${from[$full]:-}" ]] && kept+=("$name")
|
||||
done <<< "$sorted"
|
||||
((${#kept[@]} > 0 || !by_id)) || kept=("$(tail -n 1 <<< "$sorted" | cut -d' ' -f2-)")
|
||||
(IFS=','; echo "${kept[*]}")
|
||||
}
|
||||
|
||||
image_prune() {
|
||||
[[ "$*" == "-f --filter until=72h" ]] || unexpected "image prune $*"
|
||||
local id names age labels gone=()
|
||||
while IFS='|' read -r id names age labels; do
|
||||
[[ -n "$id" && -z "$names" && "$age" -ge $((72 * 60)) ]] || continue
|
||||
used_by "$id" any || gone+=("$id")
|
||||
local all=0 hours=0
|
||||
case "$*" in
|
||||
"-f") ;;
|
||||
"-f --filter until=72h") hours=72 ;;
|
||||
"-a -f --filter until=24h") all=1; hours=24 ;;
|
||||
*) unexpected "image prune $*" ;;
|
||||
esac
|
||||
broken "image prune" && { echo "Error response from daemon: a prune operation is already running" >&2; exit 1; }
|
||||
local id names age labels size gone=() untag=() tag left
|
||||
while IFS='|' read -r id names age labels size; do
|
||||
[[ -n "$id" ]] || continue
|
||||
((all)) || [[ -z "$names" ]] || continue
|
||||
((age >= hours * 60)) || continue
|
||||
if used_by "$id" any; then
|
||||
[[ "$names" == *,* ]] && untag+=("$id")
|
||||
else
|
||||
gone+=("$id")
|
||||
fi
|
||||
done < "$world/images"
|
||||
for id in "${gone[@]}"; do
|
||||
((${#gone[@]} + ${#untag[@]} == 0)) || echo "Deleted Images:"
|
||||
for id in "${untag[@]}"; do
|
||||
IFS='|' read -r id names age labels size <<< "$(image_line "$id")"
|
||||
left=$(names_kept "$id" "$names")
|
||||
IFS=',' read -r -a tags <<< "$names"
|
||||
for tag in "${tags[@]}"; do
|
||||
[[ ",$left," == *",$tag,"* ]] || echo "untagged: $tag"
|
||||
done
|
||||
drop "$world/images" "$id"
|
||||
echo "deleted: $id"
|
||||
printf '%s|%s|%s|%s|%s\n' "$id" "$left" "$age" "$labels" "$size" >> "$world/images"
|
||||
done
|
||||
echo "Total reclaimed space: 0B"
|
||||
for id in "${gone[@]}"; do
|
||||
IFS='|' read -r id names age labels size <<< "$(image_line "$id")"
|
||||
tags=()
|
||||
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
|
||||
for tag in "${tags[@]}"; do
|
||||
echo "untagged: $tag"
|
||||
echo "untagged: ${tag%:*}@sha256:0123456789abcdef"
|
||||
done
|
||||
drop "$world/images" "$id"
|
||||
echo "deleted: sha256:$id"
|
||||
done
|
||||
echo
|
||||
if ((${#gone[@]} > 0)); then
|
||||
echo "Total reclaimed space: ${#gone[@]}00MB"
|
||||
else
|
||||
echo "Total reclaimed space: 0B"
|
||||
fi
|
||||
}
|
||||
|
||||
builder_prune() {
|
||||
case "$*" in
|
||||
"-f --filter until=24h" | "-a -f --filter until=24h") ;;
|
||||
*) unexpected "builder prune $*" ;;
|
||||
esac
|
||||
broken "builder prune" && { echo "ERROR: failed to prune build cache: a prune operation is already running" >&2; exit 1; }
|
||||
printf 'Total:\t1.5GB\n'
|
||||
}
|
||||
|
||||
volume_ls() {
|
||||
local filters=() format='{{.Name}}' filter name age
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
-q) ;;
|
||||
--filter) filters+=("$2"); shift ;;
|
||||
--format) format="$2"; shift ;;
|
||||
*) unexpected "volume ls $1" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
[[ "$format" == '{{.Name}}' ]] || unexpected "volume ls --format $format"
|
||||
while IFS='|' read -r name age; do
|
||||
[[ -n "$name" ]] || continue
|
||||
for filter in "${filters[@]}"; do
|
||||
case "$filter" in
|
||||
name=*) [[ "$name" =~ ${filter#name=} ]] || continue 2 ;;
|
||||
dangling=true) uses volume "$name" any && continue 2 ;;
|
||||
*) unexpected "volume ls --filter $filter" ;;
|
||||
esac
|
||||
done
|
||||
echo "$name"
|
||||
done < "$world/volumes"
|
||||
return 0
|
||||
}
|
||||
|
||||
volume_inspect() {
|
||||
local format=""
|
||||
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
|
||||
local line name age
|
||||
line=$(volume_line "${1:?}")
|
||||
[[ -n "$line" ]] || { echo "Error response from daemon: get $1: no such volume" >&2; exit 1; }
|
||||
IFS='|' read -r name age <<< "$line"
|
||||
case "$format" in
|
||||
"") echo "[{\"Name\": \"$name\"}]" ;;
|
||||
"{{.CreatedAt}}") created_in_italy "$age" ;;
|
||||
*) unexpected "volume inspect -f $format" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
volume_rm() {
|
||||
[[ "${1:-}" == -f ]] && shift
|
||||
local name="${1:?}"
|
||||
[[ -n "$(volume_line "$name")" ]] || { echo "Error response from daemon: get $name: no such volume" >&2; exit 1; }
|
||||
if uses volume "$name" any; then
|
||||
echo "Error response from daemon: remove $name: volume is in use" >&2
|
||||
exit 1
|
||||
fi
|
||||
drop "$world/volumes" "$name"
|
||||
}
|
||||
|
||||
network_ls() {
|
||||
local filters=() format='{{.ID}} {{.Name}}' filter id name age
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--no-trunc) ;;
|
||||
--filter) filters+=("$2"); shift ;;
|
||||
--format) format="$2"; shift ;;
|
||||
*) unexpected "network ls $1" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
[[ "$format" == '{{.ID}} {{.Name}}' ]] || unexpected "network ls --format $format"
|
||||
while IFS='|' read -r id name age; do
|
||||
[[ -n "$id" ]] || continue
|
||||
for filter in "${filters[@]}"; do
|
||||
case "$filter" in
|
||||
name=*) [[ "$name" =~ ${filter#name=} ]] || continue 2 ;;
|
||||
*) unexpected "network ls --filter $filter" ;;
|
||||
esac
|
||||
done
|
||||
echo "$id $name"
|
||||
done < "$world/networks"
|
||||
return 0
|
||||
}
|
||||
|
||||
network_inspect() {
|
||||
local format=""
|
||||
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
|
||||
local line id name age
|
||||
line=$(network_line "${1:?}")
|
||||
[[ -n "$line" ]] || { echo "Error response from daemon: network $1 not found" >&2; exit 1; }
|
||||
IFS='|' read -r id name age <<< "$line"
|
||||
case "$format" in
|
||||
"") echo "[{\"Id\": \"$id\", \"Name\": \"$name\"}]" ;;
|
||||
"{{json .Created}}") echo "\"$(created_in_italy "$age" .123456789)\"" ;;
|
||||
# Created of a network is a time.Time: the template prints it the way Go does, not as RFC 3339.
|
||||
"{{.Created}}") date -u -d "@$((now - ${age:-0} * 60 + 7200))" "+%Y-%m-%d %H:%M:%S.123456789 +0200 CEST" ;;
|
||||
*) unexpected "network inspect -f $format" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
network_rm() {
|
||||
local line id name age
|
||||
line=$(network_line "${1:?}")
|
||||
[[ -n "$line" ]] || { echo "Error response from daemon: network $1 not found" >&2; exit 1; }
|
||||
IFS='|' read -r id name age <<< "$line"
|
||||
case "$name" in
|
||||
bridge | host | none) echo "Error response from daemon: $name is a pre-defined network and cannot be removed" >&2; exit 1 ;;
|
||||
esac
|
||||
if uses network "$name" running; then
|
||||
echo "Error response from daemon: error while removing network: network $name id $id has active endpoints" >&2
|
||||
exit 1
|
||||
fi
|
||||
drop "$world/networks" "$id"
|
||||
}
|
||||
|
||||
store() {
|
||||
if [[ "$(cat "$world/store" 2> /dev/null)" == containerd ]]; then echo containerd; else echo classic; fi
|
||||
}
|
||||
|
||||
# The DriverStatus of «docker info» as Docker prints it: with the containerd image store the snapshotter, with the
|
||||
# classic one the details of overlay2.
|
||||
info_command() {
|
||||
[[ "$*" == "--format {{json .DriverStatus}}" ]] || unexpected "info $*"
|
||||
if [[ "$(store)" == containerd ]]; then
|
||||
echo '[["driver-type","io.containerd.snapshotter.v1"]]'
|
||||
else
|
||||
echo '[["Backing Filesystem","extfs"],["Supports d_type","true"],["Using metacopy","false"],["Native Overlay Diff","true"],["userxattr","false"]]'
|
||||
fi
|
||||
}
|
||||
|
||||
system_df() {
|
||||
case "$*" in
|
||||
"") echo "TYPE TOTAL ACTIVE SIZE RECLAIMABLE" ;;
|
||||
"--format {{.Type}}|{{.Size}}|{{.Reclaimable}}")
|
||||
printf '%s\n' "Images|9.1GB|6.2GB (68%)" "Containers|120MB|80MB (66%)" "Local Volumes|3.4GB|1.1GB (32%)" "Build Cache|5.3GB|4.8GB"
|
||||
;;
|
||||
*) unexpected "system df $*" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
@@ -285,18 +558,29 @@ case "${1:-}" in
|
||||
*) unexpected "image $sub" ;;
|
||||
esac
|
||||
;;
|
||||
builder) [[ "${2:-}" == prune ]] || unexpected "$*"; shift 2; builder_prune "$@" ;;
|
||||
buildx) [[ "${2:-}" == rm ]] || unexpected "$*"; echo "ERROR: no builder \"${4:-}\" found" >&2; exit 1 ;;
|
||||
volume)
|
||||
case "${2:-}" in
|
||||
inspect) grep -qxF -- "${3:?}" "$world/volumes" || { echo "Error: no such volume: $3" >&2; exit 1; } ;;
|
||||
rm)
|
||||
[[ "${3:-}" == -f ]] || unexpected "$*"
|
||||
grep -vxF -- "${4:?}" "$world/volumes" > "$world/volumes.new"
|
||||
mv "$world/volumes.new" "$world/volumes"
|
||||
;;
|
||||
*) unexpected "$*" ;;
|
||||
sub="${2:-}"
|
||||
shift 2
|
||||
case "$sub" in
|
||||
ls) volume_ls "$@" ;;
|
||||
inspect) volume_inspect "$@" ;;
|
||||
rm) volume_rm "$@" ;;
|
||||
*) unexpected "volume $sub" ;;
|
||||
esac
|
||||
;;
|
||||
system) [[ "${2:-}" == df ]] || unexpected "$*"; echo "TYPE TOTAL ACTIVE SIZE RECLAIMABLE" ;;
|
||||
network)
|
||||
sub="${2:-}"
|
||||
shift 2
|
||||
case "$sub" in
|
||||
ls) network_ls "$@" ;;
|
||||
inspect) network_inspect "$@" ;;
|
||||
rm) network_rm "$@" ;;
|
||||
*) unexpected "network $sub" ;;
|
||||
esac
|
||||
;;
|
||||
system) [[ "${2:-}" == df ]] || unexpected "$*"; shift 2; system_df "$@" ;;
|
||||
info) shift; info_command "$@" ;;
|
||||
*) unexpected "$*" ;;
|
||||
esac
|
||||
@@ -0,0 +1,36 @@
|
||||
[
|
||||
[
|
||||
{"id": 140, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "main", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/main", "created_at": "2026-10-20T19:42:15+02:00"},
|
||||
{"id": 142, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647", "created_at": "2026-10-20T19:42:09+02:00"},
|
||||
{"id": 141, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:7c39e42c6e919ae17c7dfa17bd5fcf8cd38fa29c02be97e2b0134947b4674f3c", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:7c39e42c6e919ae17c7dfa17bd5fcf8cd38fa29c02be97e2b0134947b4674f3c", "created_at": "2026-10-20T19:42:09+02:00"},
|
||||
{"id": 139, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-d0a3b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-d0a3b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1", "created_at": "2026-10-20T19:42:11+02:00"},
|
||||
{"id": 138, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.1.1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.1.1", "created_at": "2026-10-20T18:05:00+02:00"},
|
||||
{"id": 137, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "latest", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/latest", "created_at": "2026-10-14T10:00:00+02:00"},
|
||||
{"id": 136, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.1.0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.1.0", "created_at": "2026-10-14T10:00:00+02:00"},
|
||||
{"id": 113, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-cf2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-cf2a3b4", "created_at": "2026-10-13T09:00:00+02:00"},
|
||||
{"id": 101, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-0a1b2c3", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-0a1b2c3", "created_at": "2026-10-01T09:00:00+02:00"},
|
||||
{"id": 112, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-be1f2a3", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-be1f2a3", "created_at": "2026-10-12T09:00:00+02:00"},
|
||||
{"id": 111, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-ad0e1f2", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-ad0e1f2", "created_at": "2026-10-11T09:00:00+02:00"},
|
||||
{"id": 110, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-9d0e1f2", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-9d0e1f2", "created_at": "2026-10-10T09:00:00+02:00"},
|
||||
{"id": 99, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b", "created_at": "2026-09-20T09:00:00+02:00"},
|
||||
{"id": 109, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-8c9d0e1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-8c9d0e1", "created_at": "2026-10-09T09:00:00+02:00"}
|
||||
],
|
||||
[
|
||||
{"id": 113, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-cf2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-cf2a3b4", "created_at": "2026-10-13T09:00:00+02:00"},
|
||||
{"id": 108, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-7b8c9d0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-7b8c9d0", "created_at": "2026-10-08T09:00:00+02:00"},
|
||||
{"id": 107, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-6a7b8c9", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-6a7b8c9", "created_at": "2026-10-07T09:00:00+02:00"},
|
||||
{"id": 106, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-5f6a7b8", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-5f6a7b8", "created_at": "2026-10-06T09:00:00+02:00"},
|
||||
{"id": 105, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-4e5f6a7", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-4e5f6a7", "created_at": "2026-10-05T01:00:00+02:00"},
|
||||
{"id": 104, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-3d4e5f6", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-3d4e5f6", "created_at": "2026-10-04T23:30:00Z"},
|
||||
{"id": 103, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-2c3d4e5", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-2c3d4e5", "created_at": "2026-10-03T07:00:00Z"},
|
||||
{"id": 102, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-1b2c3d4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-1b2c3d4", "created_at": "2026-10-02T09:00:00+02:00"},
|
||||
{"id": 100, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.2.0-rc.1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.2.0-rc.1", "created_at": "2026-09-01T09:00:00+02:00"},
|
||||
{"id": 97, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-zzzzzzz", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-zzzzzzz", "created_at": "2026-09-01T09:00:00+02:00"},
|
||||
{"id": 96, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-1a2b3c", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-1a2b3c", "created_at": "2026-09-01T09:00:00+02:00"},
|
||||
{"id": 95, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-ABCDEF0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-ABCDEF0", "created_at": "2026-09-01T09:00:00+02:00"},
|
||||
{"id": 94, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-e1f2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-e1f2a3b4"},
|
||||
{"id": 93, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe-strumenti", "version": "sha-0000000", "html_url": "https://gitea.example/Alby96/-/packages/container/febe-strumenti/sha-0000000", "created_at": "2026-08-01T09:00:00+02:00"},
|
||||
{"id": 91, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe-strumenti", "version": "sha256:48f76e113cd23ae3e60a2657cf0f84618fce331ef675e8ea39527ba0937b34d0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe-strumenti/sha256:48f76e113cd23ae3e60a2657cf0f84618fce331ef675e8ea39527ba0937b34d0", "created_at": "2026-08-01T09:00:00+02:00"},
|
||||
{"id": 92, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe", "version": "sha-1111111", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe/sha-1111111", "created_at": "2026-08-01T09:00:00+02:00"}
|
||||
]
|
||||
]
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Tests.Web.Part2Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>
|
||||
/// The link to Instagram in the sidebar (<c>/api/engine</c>, «connection»): it comes from the session cookie, as the
|
||||
/// engine's mode or the connection says, never from whether the account «Tu» is already known (H10: its name may come
|
||||
/// much later, and meanwhile the sidebar says «Collegato» with «Nome non ancora noto»).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class EngineConnectionStateTests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task TheSidebarSaysConnectedFromTheSessionCookieEvenBeforeTuIsKnown()
|
||||
{
|
||||
var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.Connected, null, null, false, null) };
|
||||
await using var server = await Part2.StartAsync(services: s =>
|
||||
{
|
||||
s.AddSingleton<IEngineMonitor>(sp => new FixedModeMonitor(sp.GetRequiredService<IClock>()));
|
||||
s.AddSingleton<IConnectionService>(connection);
|
||||
});
|
||||
var monitor = (FixedModeMonitor)server.App.Services.GetRequiredService<IEngineMonitor>();
|
||||
async Task<JsonElement> LinkAsync(EngineMode mode)
|
||||
{
|
||||
monitor.Mode = mode;
|
||||
return (await server.GetJsonAsync("/api/engine")).GetProperty("connection");
|
||||
}
|
||||
|
||||
// Collecting (or about to), with the cookie and without «Tu»: connected, no name yet.
|
||||
foreach (var mode in new[] { EngineMode.Starting, EngineMode.InSession, EngineMode.Resting, EngineMode.OutsideWindow, EngineMode.Paused, EngineMode.Throttled, EngineMode.UserDriving })
|
||||
{
|
||||
var link = await LinkAsync(mode);
|
||||
Assert.AreEqual("connected", link.Str("state"), mode.ToString());
|
||||
Assert.AreEqual(JsonValueKind.Null, link.GetProperty("username").ValueKind, mode.ToString());
|
||||
}
|
||||
|
||||
Assert.AreEqual("notConnected", (await LinkAsync(EngineMode.NotConnected)).Str("state"));
|
||||
Assert.AreEqual("disconnected", (await LinkAsync(EngineMode.Disconnected)).Str("state"));
|
||||
Assert.AreEqual("verification", (await LinkAsync(EngineMode.StoppedForVerification)).Str("state"));
|
||||
|
||||
// The engine loop does not run: the connection itself is asked.
|
||||
Assert.AreEqual("connected", (await LinkAsync(EngineMode.Off)).Str("state"));
|
||||
connection.Status = new ConnectionStatus(ConnectionState.NotConnected, null, null, false, null);
|
||||
Assert.AreEqual("notConnected", (await LinkAsync(EngineMode.Off)).Str("state"));
|
||||
|
||||
// Once «Tu» is known, its name comes along.
|
||||
await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
|
||||
var named = await LinkAsync(EngineMode.Resting);
|
||||
Assert.AreEqual("connected", named.Str("state"));
|
||||
Assert.AreEqual("tuo.profilo", named.Str("username"));
|
||||
Assert.AreEqual(JsonValueKind.Null, (await LinkAsync(EngineMode.NotConnected)).GetProperty("username").ValueKind, "Not connected: no name.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutEngineAndBrowserTheSidebarSaysNotConnectedEvenIfTuIsKnown()
|
||||
{
|
||||
await using var server = await Part2.StartAsync();
|
||||
await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
|
||||
var engine = await server.GetJsonAsync("/api/engine");
|
||||
Assert.AreEqual("Off", engine.GetProperty("snapshot").Str("mode"));
|
||||
Assert.AreEqual("notConnected", engine.GetProperty("connection").Str("state"), "No engine has looked at the cookie and the browser is not there.");
|
||||
}
|
||||
|
||||
/// <summary>An engine that reports the mode the test sets.</summary>
|
||||
private sealed class FixedModeMonitor(IClock clock) : IEngineMonitor
|
||||
{
|
||||
public EngineMode Mode { get; set; } = EngineMode.Resting;
|
||||
|
||||
public Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default) =>
|
||||
Task.FromResult(SnapshotParts.Build(clock, Mode, "Prova", [], "Prova", CautionProfile.Prudent));
|
||||
|
||||
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,33 @@ public sealed class InterfaceTests
|
||||
})();
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// Installed before the page scripts: <c>window.__timers()</c> lists the timeouts of the page still pending and
|
||||
/// <c>window.__timersOver(ids)</c> says whether those have all run or been cleared. A test waits for the timers that
|
||||
/// were pending at a given moment (a debounced redraw, say) to be over, instead of a pause that may be too short.
|
||||
/// </summary>
|
||||
private const string PageTimers = """
|
||||
(() => {
|
||||
const set = window.setTimeout.bind(window);
|
||||
const clear = window.clearTimeout.bind(window);
|
||||
const pending = new Set();
|
||||
window.setTimeout = (fn, ms, ...rest) => {
|
||||
const id = set((...args) => {
|
||||
pending.delete(id);
|
||||
fn(...args);
|
||||
}, ms, ...rest);
|
||||
pending.add(id);
|
||||
return id;
|
||||
};
|
||||
window.clearTimeout = (id) => {
|
||||
pending.delete(id);
|
||||
clear(id);
|
||||
};
|
||||
window.__timers = () => [...pending];
|
||||
window.__timersOver = (ids) => ids.every((id) => !pending.has(id));
|
||||
})();
|
||||
""";
|
||||
|
||||
// ------------------------------------------------------------------------------------------ the driving lease
|
||||
|
||||
[TestMethod]
|
||||
@@ -94,22 +121,23 @@ public sealed class InterfaceTests
|
||||
var view = new FakeRemoteViewHost();
|
||||
await using var server = await DockerAsync(connection, view);
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.FetchDelays);
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
|
||||
|
||||
// The status of the connection answers late; Alberto is already elsewhere.
|
||||
await ui.EvalAsync("""
|
||||
import('/js/core/shell.js').then((m) => {
|
||||
window.__delays.push({ match: '/api/connection', ms: 600 });
|
||||
m.navigate('/browser');
|
||||
setTimeout(() => m.navigate('/libreria'), 150);
|
||||
return true;
|
||||
})
|
||||
""");
|
||||
// The status of the connection answers late: the Browser page asks for it, Alberto goes elsewhere, then it
|
||||
// comes. In this order on any machine (issue #8: a page left after a fixed delay may not have asked yet).
|
||||
await ui.EvalAsync("window.__hold('/api/connection')");
|
||||
await ui.NavigateAsync("/browser");
|
||||
await ui.WaitAsync("window.__started['/api/connection'] >= 1", "pagina Browser in attesa dello stato del collegamento");
|
||||
await ui.NavigateAsync("/libreria");
|
||||
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
|
||||
await ui.EvalAsync("window.__release('/api/connection')");
|
||||
await ui.WaitAsync("window.__done['/api/connection'] >= 1", "risposta in ritardo arrivata");
|
||||
await Task.Delay(300);
|
||||
Assert.IsEmpty(connection.Snapshot(), "nothing taken by a page that is gone");
|
||||
|
||||
// What the page did with the late answer is done: whatever it asked then is in the list.
|
||||
CollectionAssert.AreEqual(new[] { "GET /api/connection" }, await ui.AskedAsync("/api/connection"), "nothing taken by a page that is gone");
|
||||
Assert.IsEmpty(await ui.AskedAsync("/api/vista"), "no remote view for a page that is gone");
|
||||
Assert.IsEmpty(connection.Snapshot());
|
||||
Assert.IsEmpty(view.Opened);
|
||||
}
|
||||
|
||||
@@ -120,6 +148,7 @@ public sealed class InterfaceTests
|
||||
var view = new FakeRemoteViewHost();
|
||||
await using var server = await DockerAsync(connection, view);
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
|
||||
await ui.OpenAsync(new Uri(server.Address, "/browser"));
|
||||
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "il browser in uso");
|
||||
@@ -128,8 +157,12 @@ public sealed class InterfaceTests
|
||||
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
|
||||
await ui.NavigateAsync("/libreria");
|
||||
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
|
||||
await Task.Delay(500);
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "«Ho finito» already gave the browser back");
|
||||
|
||||
// A page gives the browser back as it is left (PageFrame.onLeave): a «cancel» would be asked by now, and once
|
||||
// the page is quiet every command it asked has reached the server.
|
||||
await ui.WaitForQuietAsync("richieste della pagina finite");
|
||||
CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "«Ho finito» already gave the browser back");
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -154,6 +187,7 @@ public sealed class InterfaceTests
|
||||
var view = new FakeRemoteViewHost();
|
||||
await using var server = await DockerAsync(connection, view);
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
|
||||
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
|
||||
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:True") && view.Opened.Count == 1, "pagina di accesso nella vista remota");
|
||||
@@ -164,7 +198,9 @@ public sealed class InterfaceTests
|
||||
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa dopo «Ho finito»");
|
||||
await ui.NavigateAsync("/libreria");
|
||||
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
|
||||
await Task.Delay(500);
|
||||
await ui.WaitForQuietAsync("richieste della pagina finite");
|
||||
CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "«Ho finito» already gave the browser back");
|
||||
CollectionAssert.AreEqual(new[] { "WS /api/vista" }, await ui.AskedAsync("WS "), "no view opened again");
|
||||
CollectionAssert.AreEqual(new[] { "begin:True", "finish" }, connection.Snapshot());
|
||||
Assert.HasCount(1, view.Opened);
|
||||
}
|
||||
@@ -176,23 +212,28 @@ public sealed class InterfaceTests
|
||||
var view = new FakeRemoteViewHost();
|
||||
await using var server = await DockerAsync(connection, view, new FixedMonitor(EngineMode.StoppedForVerification));
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
|
||||
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
|
||||
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False") && view.Opened.Count == 1, "verifica nella vista remota");
|
||||
await ui.EvalAsync("document.querySelector('.bottoni-collegamento .btn.primo').click()");
|
||||
await ui.WaitAsync("document.querySelector('.riapri-browser') !== null", "«Ho finito» fatto, in attesa di «Riprendi»");
|
||||
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa dopo «Ho finito»");
|
||||
await Task.Delay(500);
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "no new lease after «Ho finito»");
|
||||
Assert.HasCount(1, view.Opened, "no new view after «Ho finito»");
|
||||
|
||||
// «Ho finito» also asks for the engine: what its answer brings has been drawn once the page is quiet.
|
||||
await ui.WaitForQuietAsync("richieste di «Ho finito» finite");
|
||||
CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "no new lease after «Ho finito»");
|
||||
CollectionAssert.AreEqual(new[] { "WS /api/vista" }, await ui.AskedAsync("WS "), "no new view after «Ho finito»");
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot());
|
||||
Assert.HasCount(1, view.Opened);
|
||||
|
||||
// «Riapri il browser» takes it again; leaving the page then gives it back.
|
||||
await ui.EvalAsync("document.querySelector('.riapri-browser').click()");
|
||||
await ui.WaitForAsync(() => connection.Snapshot().Length == 3 && view.Opened.Count == 2, "browser riaperto");
|
||||
await ui.NavigateAsync("/libreria");
|
||||
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
|
||||
await ui.WaitForAsync(() => connection.Snapshot().Length == 4, "il browser restituito lasciando la pagina");
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot());
|
||||
await ui.WaitForQuietAsync("richieste della pagina finite");
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot(), "leaving the page gives the browser back");
|
||||
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
|
||||
}
|
||||
|
||||
@@ -204,6 +245,7 @@ public sealed class InterfaceTests
|
||||
var engine = new FixedMonitor(EngineMode.StoppedForVerification);
|
||||
await using var server = await DockerAsync(connection, view, engine);
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
|
||||
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
|
||||
await ui.WaitAsync("document.querySelector('.arresto') !== null", "striscia rossa della verifica");
|
||||
@@ -216,9 +258,11 @@ public sealed class InterfaceTests
|
||||
connection.Status = Connected;
|
||||
await ui.EvalAsync("import('/js/core/engine.js').then((m) => m.refreshEngine()).then(() => true)");
|
||||
await ui.WaitAsync("document.querySelector('.pannello.collegato') !== null", "collegato dopo «Riprendi»");
|
||||
await Task.Delay(300);
|
||||
await ui.WaitForQuietAsync("richieste dopo «Riprendi» finite");
|
||||
CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "the browser is not taken again");
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot());
|
||||
Assert.IsTrue(view.Opened.All(v => v.Disposed));
|
||||
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
|
||||
Assert.HasCount(1, view.Opened);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------ remote view input
|
||||
@@ -230,10 +274,13 @@ public sealed class InterfaceTests
|
||||
var view = new FakeRemoteViewHost();
|
||||
await using var server = await DockerAsync(connection, view);
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
await ui.OpenAsync(new Uri(server.Address, "/browser"));
|
||||
await ui.WaitForAsync(() => view.Opened.Count == 1, "vista aperta");
|
||||
await ui.WaitAsync("document.querySelector('canvas.vista-schermo') !== null", "schermo della vista");
|
||||
await Task.Delay(300);
|
||||
|
||||
// The view sends keys only once its socket is open (the server opens the view before it answers the socket).
|
||||
await ui.WaitAsync("window.__sockets.some((s) => s.url.endsWith('/api/vista') && s.readyState === WebSocket.OPEN)", "vista collegata");
|
||||
|
||||
// Italian layout on Windows: AltGr+ò is «@», reported as Ctrl+Alt with the AltGraph modifier.
|
||||
Assert.IsTrue((await ui.EvalAsync("new KeyboardEvent('keydown', { key: '@', modifierAltGraph: true }).getModifierState('AltGraph')")).GetBoolean());
|
||||
@@ -270,7 +317,9 @@ public sealed class InterfaceTests
|
||||
await ui.OpenAsync(new Uri(server.Address, "/browser"));
|
||||
await ui.WaitForAsync(() => view.Opened.Count == 1, "vista aperta");
|
||||
var remote = view.Opened.Single();
|
||||
await Task.Delay(300);
|
||||
|
||||
// What the view writes waits in it until the socket is open, and the page listens from the start; the first
|
||||
// frame on the screen says that the socket is open, so the buttons can go.
|
||||
remote.Write(new RemoteViewMeta(320, 225, "https://www.instagram.com/"));
|
||||
remote.Write(new RemoteViewFrame(TestFile.PhotoBytes(3, 320, 225)));
|
||||
await ui.WaitAsync("!document.querySelector('canvas.vista-schermo').hidden", "primo fotogramma");
|
||||
@@ -302,31 +351,64 @@ public sealed class InterfaceTests
|
||||
}
|
||||
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.FetchDelays);
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
await ui.AddInitScriptAsync(PageTimers);
|
||||
await ui.OpenAsync(new Uri(server.Address, $"/account/{account.Id}?tipo=evidenza"));
|
||||
await ui.WaitAsync("document.querySelector('main .raccolta-titolo') !== null", "raccolte in evidenza");
|
||||
|
||||
// «Post» after «In evidenza»: the posts stay, also when the area changes size.
|
||||
await ui.EvalAsync("document.querySelectorAll('.strumenti .filtri button')[0].click()");
|
||||
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post");
|
||||
await Task.Delay(500);
|
||||
await ui.SendAsync("Emulation.setDeviceMetricsOverride", new JsonObject { ["width"] = 1100, ["height"] = 900, ["deviceScaleFactor"] = 1, ["mobile"] = false });
|
||||
await Task.Delay(600);
|
||||
await AssertPostsShownAsync(ui);
|
||||
|
||||
// «In evidenza» and at once «Post», while the tiles of the collections are still loading.
|
||||
// «Post» after «In evidenza»: the posts stay, also once what «In evidenza» left pending has run (it redraws
|
||||
// itself 150 ms after a change of size, and it has just been drawn).
|
||||
await ui.EvalAsync("""
|
||||
(() => {
|
||||
window.__delays.push({ match: '/api/library/tiles', ms: 600 });
|
||||
window.__pendingAtSwitch = window.__timers();
|
||||
document.querySelectorAll('.strumenti .filtri button')[0].click();
|
||||
return true;
|
||||
})()
|
||||
""");
|
||||
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post");
|
||||
await ui.WaitAsync("window.__timersOver(window.__pendingAtSwitch)", "attese di «In evidenza» finite");
|
||||
await AssertPostsShownAsync(ui);
|
||||
|
||||
// The area changes size. The page's own observers see it before this one, which came last: what they left
|
||||
// pending then (a redraw, a frame) runs, and the posts are still there.
|
||||
await ui.EvalAsync("""
|
||||
(() => {
|
||||
let before = null;
|
||||
window.__afterResize = null;
|
||||
new ResizeObserver((entries, observer) => {
|
||||
const width = entries[0].contentRect.width;
|
||||
if (before === null) {
|
||||
before = width;
|
||||
return;
|
||||
}
|
||||
if (Math.abs(width - before) < 1) return;
|
||||
observer.disconnect();
|
||||
const pending = window.__timers();
|
||||
requestAnimationFrame(() => { window.__afterResize = pending; });
|
||||
}).observe(document.querySelector('main .corpo > div'));
|
||||
window.__resizeWatched = () => before !== null;
|
||||
return true;
|
||||
})()
|
||||
""");
|
||||
await ui.WaitAsync("window.__resizeWatched()", "dimensione dei contenuti osservata");
|
||||
await ui.SendAsync("Emulation.setDeviceMetricsOverride", new JsonObject { ["width"] = 1100, ["height"] = 900, ["deviceScaleFactor"] = 1, ["mobile"] = false });
|
||||
await ui.WaitAsync("window.__afterResize !== null && window.__timersOver(window.__afterResize)", "contenuti ridisegnati alla nuova larghezza");
|
||||
await AssertPostsShownAsync(ui);
|
||||
|
||||
// «In evidenza» and at once «Post», while the tiles of the collections are still loading: they come after the
|
||||
// posts are drawn.
|
||||
await ui.EvalAsync("""
|
||||
(() => {
|
||||
window.__hold('/api/library/tiles');
|
||||
const chips = document.querySelectorAll('.strumenti .filtri button');
|
||||
chips[2].click();
|
||||
chips[0].click();
|
||||
return true;
|
||||
})()
|
||||
""");
|
||||
await ui.WaitAsync("window.__started['/api/library/tiles'] >= 1 && document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post");
|
||||
await ui.EvalAsync("window.__release('/api/library/tiles')");
|
||||
await ui.WaitAsync("window.__done['/api/library/tiles'] >= 1", "tessere delle raccolte arrivate in ritardo");
|
||||
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post");
|
||||
await Task.Delay(400);
|
||||
await AssertPostsShownAsync(ui);
|
||||
}
|
||||
|
||||
@@ -336,23 +418,23 @@ public sealed class InterfaceTests
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
await server.AddAccountWithEntriesAsync("anna.prova", 5, Make.T0, TimeSpan.FromHours(30));
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.FetchDelays);
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
|
||||
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "mosaico");
|
||||
|
||||
// «Storie» (nothing: an empty answer, late) and at once «Foto».
|
||||
// «Storie» (nothing: an empty answer, late) and at once «Foto»: the stories answer after the photos are drawn.
|
||||
await ui.EvalAsync("""
|
||||
(() => {
|
||||
window.__delays.push({ match: 'kind=stories', ms: 700 });
|
||||
window.__hold('kind=stories');
|
||||
const chips = document.querySelectorAll('.strumenti .filtri button');
|
||||
chips[3].click();
|
||||
chips[1].click();
|
||||
return true;
|
||||
})()
|
||||
""");
|
||||
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "foto");
|
||||
await ui.WaitAsync("window.__started['kind=stories'] >= 1 && document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "foto");
|
||||
await ui.EvalAsync("window.__release('kind=stories')");
|
||||
await ui.WaitAsync("window.__done['kind=stories'] >= 1", "risposta delle storie arrivata in ritardo");
|
||||
await Task.Delay(300);
|
||||
Assert.IsTrue((await ui.EvalAsync("location.search.includes('tipo=foto')")).GetBoolean());
|
||||
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null")).GetBoolean(), "the photos are shown " + ui.Report());
|
||||
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina') === null")).GetBoolean(), "no empty state over the results");
|
||||
@@ -385,7 +467,9 @@ public sealed class InterfaceTests
|
||||
[TestMethod]
|
||||
public async Task TheEmptyLibraryFollowsTheConnectionAlsoWhenTheEngineAnswersLate()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
// No engine loop here (mode Off): the link in /api/engine is the connection's, from the session cookie.
|
||||
var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.NotConnected, null, null, false, null) };
|
||||
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IConnectionService>(connection));
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(HoldEngine);
|
||||
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
|
||||
@@ -397,12 +481,12 @@ public sealed class InterfaceTests
|
||||
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina, main .benvenuto, main .mosaico') === null")).GetBoolean(), "no empty state is guessed " + ui.Report());
|
||||
StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.testa .quanti').textContent")).GetString(), "0 ");
|
||||
|
||||
// Not connected (no own account): the first start with its two ways to begin (spec §10.3).
|
||||
// Not connected (no session cookie): the first start with its two ways to begin (spec §10.3).
|
||||
await ui.EvalAsync("window.__releaseEngine()");
|
||||
await ui.WaitAsync("document.querySelector('main .benvenuto') !== null && document.querySelector('main [aria-busy=true]') === null", "primo avvio dopo la risposta del motore");
|
||||
|
||||
// Connected now (the own account is known): the welcome gives way to the empty library.
|
||||
await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
|
||||
// Connected now (the session cookie is there; «Tu» is not known yet, H10): the welcome gives way to the empty library.
|
||||
connection.Status = new ConnectionStatus(ConnectionState.Connected, null, null, false, null);
|
||||
await ui.EvalAsync("import('/js/core/engine.js').then((m) => m.refreshEngine()).then(() => true)");
|
||||
await ui.WaitAsync("document.querySelector('main .benvenuto') === null && document.querySelector('main .vuoto-pagina h2') !== null", "libreria vuota da collegato");
|
||||
Assert.AreEqual("La libreria è ancora vuota", (await ui.EvalAsync("document.querySelector('main .vuoto-pagina h2').textContent")).GetString());
|
||||
@@ -441,7 +525,6 @@ public sealed class InterfaceTests
|
||||
})()
|
||||
""",
|
||||
$"intestazione aggiornata dopo «{choice}»");
|
||||
await Task.Delay(200);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -480,7 +563,7 @@ public sealed class InterfaceTests
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.FetchDelays);
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
await ui.AddInitScriptAsync("""
|
||||
(() => {
|
||||
const live = new Map();
|
||||
@@ -489,25 +572,62 @@ public sealed class InterfaceTests
|
||||
window.setInterval = (fn, ms, ...rest) => { const id = set(fn, ms, ...rest); live.set(id, ms); return id; };
|
||||
window.clearInterval = (id) => { live.delete(id); clear(id); };
|
||||
window.__intervals = (ms) => [...live.values()].filter((v) => v === ms).length;
|
||||
// Every short notice shown, also one already gone again.
|
||||
window.__notices = [];
|
||||
new MutationObserver((records) => {
|
||||
for (const record of records) {
|
||||
for (const node of record.addedNodes) {
|
||||
if (node.nodeType === 1 && node.matches('.brevi > *')) window.__notices.push(node.textContent);
|
||||
}
|
||||
}
|
||||
}).observe(document, { childList: true, subtree: true });
|
||||
// A change of the library as the event stream brings it: every page that listens is called before this
|
||||
// returns (the number of streams).
|
||||
const NativeSource = window.EventSource;
|
||||
const streams = [];
|
||||
window.EventSource = class extends NativeSource {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
streams.push(this);
|
||||
}
|
||||
};
|
||||
window.__libraryChanged = () => {
|
||||
for (const stream of streams) stream.dispatchEvent(new MessageEvent('libreria', { data: '{}' }));
|
||||
return streams.length;
|
||||
};
|
||||
})();
|
||||
""");
|
||||
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
|
||||
await ui.EvalAsync("""
|
||||
import('/js/core/shell.js').then((m) => {
|
||||
window.__delays.push({ match: '/api/alerts', ms: 600 });
|
||||
m.navigate('/attivita');
|
||||
setTimeout(() => m.navigate('/libreria'), 200);
|
||||
return true;
|
||||
})
|
||||
""");
|
||||
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
|
||||
|
||||
// Attività waits for its alerts and Alberto goes back to the Libreria before they come. Issue #8: going back
|
||||
// after a fixed 200 ms, a slow machine had not even loaded the page yet, and the alerts were never asked.
|
||||
await ui.EvalAsync("window.__hold('/api/alerts')");
|
||||
await ui.NavigateAsync("/attivita");
|
||||
await ui.WaitAsync("window.__started['/api/alerts'] >= 1", "Attività in attesa dei suoi avvisi");
|
||||
await ui.NavigateAsync("/libreria");
|
||||
await ui.WaitAsync("location.pathname === '/libreria' && document.querySelector('main .benvenuto') !== null", "Libreria (primo avvio)");
|
||||
await ui.EvalAsync("window.__release('/api/alerts')");
|
||||
await ui.WaitAsync("window.__done['/api/alerts'] >= 1", "risposta in ritardo arrivata");
|
||||
await Task.Delay(300);
|
||||
Assert.AreEqual(0, (await ui.EvalAsync("window.__intervals(60000)")).GetInt32(), "the minute timer of Attività is gone with its page");
|
||||
|
||||
// The page that stays open still works as usual.
|
||||
// Nothing of it is shown over the Libreria: what it draws went with its frame, so only a short notice, or a
|
||||
// node put straight into the page area, could show.
|
||||
var notices = await ui.EvalAsync<string[]>("window.__notices");
|
||||
Assert.IsEmpty(notices, "no notice of Attività over the Libreria: " + string.Join(" | ", notices));
|
||||
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .attivita') === null && document.querySelector('main .benvenuto') !== null")).GetBoolean(), "nothing of Attività in the page area " + ui.Report());
|
||||
|
||||
// Nor does it still listen to the library: a change reaches the Libreria, which asks for its days again, and
|
||||
// Attività asks for nothing more than when it was opened.
|
||||
var days = (await ui.AskedAsync("GET /api/library/days")).Length;
|
||||
Assert.AreEqual(1, (await ui.EvalAsync("window.__libraryChanged()")).GetInt32(), "the event stream of the interface");
|
||||
await ui.WaitAsync($"window.__asked.filter((r) => r.includes('GET /api/library/days')).length > {days}", "Libreria aggiornata dopo la modifica");
|
||||
CollectionAssert.AreEqual(new[] { "GET /api/alerts" }, await ui.AskedAsync("/api/alerts"), "Attività, left, no longer listens to the library");
|
||||
|
||||
// The page that stays open still works as usual: its minute timer runs, and a change of the library reloads it.
|
||||
await ui.NavigateAsync("/attivita");
|
||||
await ui.WaitAsync("window.__intervals(60000) === 1", "Attività aperta");
|
||||
await ui.EvalAsync("window.__libraryChanged()");
|
||||
await ui.WaitAsync("window.__asked.filter((r) => r.includes('/api/alerts')).length >= 3", "Attività aggiornata dopo la modifica");
|
||||
await ui.NavigateAsync("/libreria");
|
||||
await ui.WaitAsync("window.__intervals(60000) === 0", "Attività lasciata");
|
||||
}
|
||||
@@ -524,19 +644,27 @@ public sealed class InterfaceTests
|
||||
var handle = await ui.EvalAsync("(() => { const r = document.querySelector('.fascia-barra .maniglia').getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; })()");
|
||||
var (handleX, handleY) = (handle[0].GetDouble(), handle[1].GetDouble());
|
||||
var left = barX - (barWidth / 2);
|
||||
string TimeAt(double at)
|
||||
{
|
||||
var minutes = (int)(Math.Round((at - left) / barWidth * 1440 / 15) * 15);
|
||||
return $"{minutes / 60:00}:{minutes % 60:00}";
|
||||
}
|
||||
|
||||
await ui.MouseAsync("mouseMoved", handleX, handleY);
|
||||
await ui.MouseAsync("mousePressed", handleX, handleY, buttons: 1);
|
||||
var x = handleX;
|
||||
foreach (var ratio in new[] { 0.30, 0.34, 0.38, 0.42, 0.46 })
|
||||
{
|
||||
// Each step is followed before the next one moves: a handle drawn again would lose the drag after the
|
||||
// first step, and steps sent together may reach the page as one move.
|
||||
x = left + (barWidth * ratio);
|
||||
await ui.MouseAsync("mouseMoved", x, barY, buttons: 1);
|
||||
await Task.Delay(60);
|
||||
var step = TimeAt(x);
|
||||
await ui.WaitAsync($"document.querySelector('#fascia-inizio').value === '{step}'", $"inizio della fascia a {step} durante il trascinamento");
|
||||
}
|
||||
|
||||
await ui.MouseAsync("mouseReleased", x, barY);
|
||||
var minutes = (int)(Math.Round((x - left) / barWidth * 1440 / 15) * 15);
|
||||
var expected = $"{minutes / 60:00}:{minutes % 60:00}";
|
||||
var expected = TimeAt(x);
|
||||
await ui.WaitAsync($"document.querySelector('#fascia-inizio').value === '{expected}'", $"inizio della fascia a {expected}");
|
||||
}
|
||||
|
||||
|
||||
@@ -16,25 +16,93 @@ namespace Febe.Tests.Web.Support;
|
||||
internal sealed class UiBrowser : IAsyncDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Installed before the page scripts: <c>window.__delays</c> holds { match, ms } rules that hold back a matching
|
||||
/// fetch, so that a test can make one answer arrive late (stale answers, slow pages); <c>window.__done[match]</c>
|
||||
/// counts the held-back requests that are over (answered, failed or aborted).
|
||||
/// Installed before the page scripts: what the page asks of the server, and answers that come when the test says.
|
||||
/// <list type="bullet">
|
||||
/// <item><c>window.__asked</c>: every request the page started, in order («GET /api/connection», «POST
|
||||
/// /api/connection/begin», «WS /api/vista»); <c>window.__sockets</c>: its WebSockets.</item>
|
||||
/// <item><c>window.__busy()</c>: the requests not over yet. A fetch is over once the page's own continuation of
|
||||
/// its answer has run, and the body it reads there (as api.js does) has arrived; a WebSocket once it is open or
|
||||
/// closed. See <see cref="WaitForQuietAsync"/>.</item>
|
||||
/// <item><c>window.__hold(match)</c> holds back every fetch whose address contains match, from then until
|
||||
/// <c>window.__release(match)</c>, also one the page aborts meanwhile. The release lets them go and ends the hold:
|
||||
/// later requests pass at once, and the address can be held again (twice at the same time is an error).
|
||||
/// <c>window.__started[match]</c> counts the held-back requests that started and <c>window.__done[match]</c>
|
||||
/// those that are over, adding up all the holds of that address.</item>
|
||||
/// </list>
|
||||
/// An answer is late because the test holds it, never because of a delay the page might outlast on a slow machine:
|
||||
/// the test waits until the page has asked (<c>__started</c>), does what has to come first, releases it, and
|
||||
/// checks once the page is done with it (<c>__done</c>).
|
||||
/// </summary>
|
||||
public const string FetchDelays = """
|
||||
public const string Requests = """
|
||||
(() => {
|
||||
const original = window.fetch.bind(window);
|
||||
window.__delays = [];
|
||||
const fetchNow = window.fetch.bind(window);
|
||||
const later = window.setTimeout.bind(window);
|
||||
const NativeSocket = window.WebSocket;
|
||||
const holds = [];
|
||||
let busy = 0;
|
||||
const count = (counts, key) => { counts[key] = (counts[key] || 0) + 1; };
|
||||
const pathOf = (url) => { const u = new URL(url, location.href); return u.pathname + u.search; };
|
||||
window.__asked = [];
|
||||
window.__sockets = [];
|
||||
window.__started = {};
|
||||
window.__done = {};
|
||||
window.__busy = () => busy;
|
||||
window.__hold = (match) => {
|
||||
if (holds.some((h) => h.match === match)) throw new Error(`richieste già trattenute per ${match}`);
|
||||
let release;
|
||||
holds.push({ match, gate: new Promise((resolve) => { release = resolve; }), release: () => release() });
|
||||
return true;
|
||||
};
|
||||
// The requests held so far keep their hold and count as over under its match; the next ones pass.
|
||||
window.__release = (match) => {
|
||||
const index = holds.findIndex((h) => h.match === match);
|
||||
if (index < 0) throw new Error(`nessuna richiesta trattenuta per ${match}`);
|
||||
holds.splice(index, 1)[0].release();
|
||||
return true;
|
||||
};
|
||||
window.fetch = async (input, init) => {
|
||||
const url = typeof input === 'string' ? input : input.url;
|
||||
const rule = window.__delays.find((d) => url.includes(d.match));
|
||||
if (!rule) return original(input, init);
|
||||
const url = input instanceof Request ? input.url : String(input);
|
||||
const method = ((init && init.method) || (input instanceof Request ? input.method : 'GET')).toUpperCase();
|
||||
const hold = holds.find((h) => url.includes(h.match));
|
||||
window.__asked.push(`${method} ${pathOf(url)}`);
|
||||
if (hold) count(window.__started, hold.match);
|
||||
busy += 1;
|
||||
let read = Promise.resolve();
|
||||
try {
|
||||
await new Promise((resolve) => setTimeout(resolve, rule.ms));
|
||||
return await original(input, init);
|
||||
if (hold) await hold.gate;
|
||||
const response = await fetchNow(input, init);
|
||||
for (const name of ['json', 'text', 'blob', 'arrayBuffer']) {
|
||||
const body = response[name].bind(response);
|
||||
response[name] = () => {
|
||||
const reading = body();
|
||||
read = reading.then(() => {}, () => {});
|
||||
return reading;
|
||||
};
|
||||
}
|
||||
return response;
|
||||
} finally {
|
||||
// After the page's own continuation of this answer has run.
|
||||
setTimeout(() => { window.__done[rule.match] = (window.__done[rule.match] || 0) + 1; }, 50);
|
||||
// The page's continuation of this answer runs before the first timer and, if it reads the body, the
|
||||
// continuation of that read runs before the second.
|
||||
later(() => read.then(() => later(() => {
|
||||
busy -= 1;
|
||||
if (hold) count(window.__done, hold.match);
|
||||
})));
|
||||
}
|
||||
};
|
||||
window.WebSocket = class extends NativeSocket {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
window.__asked.push(`WS ${pathOf(this.url)}`);
|
||||
window.__sockets.push(this);
|
||||
busy += 1;
|
||||
let connecting = true;
|
||||
const over = () => {
|
||||
if (!connecting) return;
|
||||
connecting = false;
|
||||
busy -= 1;
|
||||
};
|
||||
this.addEventListener('open', over);
|
||||
this.addEventListener('close', over);
|
||||
}
|
||||
};
|
||||
})();
|
||||
@@ -247,6 +315,21 @@ internal sealed class UiBrowser : IAsyncDisposable
|
||||
public Task AddInitScriptAsync(string source) =>
|
||||
SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = source });
|
||||
|
||||
/// <summary>
|
||||
/// Waits until no request of the page is in flight (<see cref="Requests"/>): every request it started has reached
|
||||
/// the server and been answered, and the page's continuation of each answer has run, a request it started there
|
||||
/// included (that one starts before the answer it follows is over). What the page leaves for later is not waited
|
||||
/// for: a request started by an observer, an animation frame, a timer, a message of the event stream or a module
|
||||
/// still loading may come after (the mosaic asks for its rows from an observer, once it has drawn its days). The
|
||||
/// moment to check that a command the page would send as it is left, or in the continuation of an answer, was not
|
||||
/// sent, instead of a pause a slow machine may not wait out; for one started later, wait for that request itself.
|
||||
/// </summary>
|
||||
public Task WaitForQuietAsync(string what) => WaitAsync("window.__busy() === 0", what);
|
||||
|
||||
/// <summary>The requests the page started so far (<see cref="Requests"/>) whose «METHOD path» contains the text.</summary>
|
||||
public Task<string[]> AskedAsync(string match) =>
|
||||
EvalAsync<string[]>($"window.__asked.filter((r) => r.includes({JsonSerializer.Serialize(match)}))");
|
||||
|
||||
/// <summary>Loads an address of the interface and waits until the frame and the first page are drawn.</summary>
|
||||
public async Task OpenAsync(Uri address)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/vgw3tpjgl1868811",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "text/javascript",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:35:04Z"
|
||||
},
|
||||
"corpo": {
|
||||
"data": {
|
||||
"ig_quick_promotion_batch_fetch_root": [
|
||||
{
|
||||
"surface_nux_id": "TRZWJXPWP_SCR_STFPZDBBB",
|
||||
"eligible_promotions": {
|
||||
"edges": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"surface_nux_id": "FZGHXFCSS_KHW_RJF_RWSQVJQZKMRP_ND",
|
||||
"eligible_promotions": {
|
||||
"edges": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"surface_nux_id": "QQJKWMDPD_MGG_LDB_PRRTGPN_JR",
|
||||
"eligible_promotions": {
|
||||
"edges": []
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"extensions": {
|
||||
"server_metadata": {
|
||||
"request_start_time_ms": 6491170198676,
|
||||
"time_at_flush_ms": 6962160759946
|
||||
},
|
||||
"is_final": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/vgw3tpjgl1868811",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "text/javascript",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:35:57Z"
|
||||
},
|
||||
"corpo": {
|
||||
"data": {
|
||||
"xdt_api__v1__fbsearch__topsearch_connection": {
|
||||
"see_more": null,
|
||||
"inform_module": null,
|
||||
"hashtags": [],
|
||||
"places": [],
|
||||
"users": [
|
||||
{
|
||||
"position": 0,
|
||||
"user": {
|
||||
"username": "dwvqbrgcjf",
|
||||
"is_verified": false,
|
||||
"ai_agent_owner_username": null,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_enabled": false
|
||||
},
|
||||
"full_name": "Gqqdcr Vkrmp",
|
||||
"search_social_context": "Dddfhhp fp mgfkpgntpndkm \u00B7 hvsfq 5",
|
||||
"search_social_context_snippet_type": "typeahead_mutual_followers",
|
||||
"unseen_count": 0,
|
||||
"pk": "215081405",
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"profile_pic_url": "https://cdn.esempio/07030bdh2v0xr6k5.jpg",
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/647n30r26f451997.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "215081405"
|
||||
}
|
||||
},
|
||||
{
|
||||
"position": 1,
|
||||
"user": {
|
||||
"username": "_knkrcbq",
|
||||
"is_verified": false,
|
||||
"ai_agent_owner_username": null,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_enabled": false
|
||||
},
|
||||
"full_name": "\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7",
|
||||
"search_social_context": null,
|
||||
"search_social_context_snippet_type": null,
|
||||
"unseen_count": 0,
|
||||
"pk": "51077241323",
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"profile_pic_url": "https://cdn.esempio/52323983k4g85lf2.jpg",
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/0r67762f9b08cs29.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "51077241323"
|
||||
}
|
||||
},
|
||||
{
|
||||
"position": 2,
|
||||
"user": {
|
||||
"username": "tpmzvqmgq",
|
||||
"is_verified": false,
|
||||
"ai_agent_owner_username": null,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_enabled": false
|
||||
},
|
||||
"full_name": "Gfvfds Cvwlsxb\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7",
|
||||
"search_social_context": null,
|
||||
"search_social_context_snippet_type": null,
|
||||
"unseen_count": 0,
|
||||
"pk": "1878810562",
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"profile_pic_url": "https://cdn.esempio/50q0271sh117xmkh.jpg",
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/95424rmcv4b31999.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "1878810562"
|
||||
}
|
||||
},
|
||||
{
|
||||
"position": 3,
|
||||
"user": {
|
||||
"username": "ldrcdvnhrhzz",
|
||||
"is_verified": false,
|
||||
"ai_agent_owner_username": null,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_enabled": false
|
||||
},
|
||||
"full_name": "Xpdcsvzwfqvm Qkvnk-gftsqrqmpk",
|
||||
"search_social_context": null,
|
||||
"search_social_context_snippet_type": null,
|
||||
"unseen_count": 0,
|
||||
"pk": "3162721231",
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"profile_pic_url": "https://cdn.esempio/305401nc89mc40qs.jpg",
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/5256037mb91hp50k.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "3162721231"
|
||||
}
|
||||
},
|
||||
{
|
||||
"position": 4,
|
||||
"user": {
|
||||
"username": "hkngtchnglsv",
|
||||
"is_verified": false,
|
||||
"ai_agent_owner_username": null,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_enabled": false
|
||||
},
|
||||
"full_name": "Wmjqb",
|
||||
"search_social_context": null,
|
||||
"search_social_context_snippet_type": null,
|
||||
"unseen_count": 0,
|
||||
"pk": "0388923287",
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"profile_pic_url": "https://cdn.esempio/514p2980v17438q8.jpg",
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/72zh4k37vr72lr9f.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "0388923287"
|
||||
}
|
||||
}
|
||||
],
|
||||
"rank_token": "7777777777777\u00B7xx77777xxx7x7x7x7x777xx7777x77777777777x7x777xx7x7x77777xxxx7x77"
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"server_metadata": {
|
||||
"request_start_time_ms": 5319299593604,
|
||||
"time_at_flush_ms": 7904759334510
|
||||
},
|
||||
"is_final": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/vgw3tpjgl1868811",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "text/javascript",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:36:00Z"
|
||||
},
|
||||
"corpo": {
|
||||
"data": {
|
||||
"xdt_api__v1__discover__chaining": {
|
||||
"users": [
|
||||
{
|
||||
"friendship_status": {
|
||||
"following": false,
|
||||
"blocking": false,
|
||||
"is_feed_favorite": false,
|
||||
"outgoing_request": false,
|
||||
"followed_by": false,
|
||||
"incoming_request": false,
|
||||
"is_restricted": false,
|
||||
"is_bestie": false
|
||||
},
|
||||
"full_name": "sgdcmwkjqgwmhg",
|
||||
"is_verified": false,
|
||||
"pk": "1575951745",
|
||||
"profile_pic_url": "https://cdn.esempio/1981r1hc98hsp8b6.jpg",
|
||||
"username": "vxpclbv_bkvgmvq",
|
||||
"is_private": false,
|
||||
"supervision_info": null,
|
||||
"social_context": null,
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/2v973665034n8123.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "1575951745"
|
||||
},
|
||||
{
|
||||
"friendship_status": {
|
||||
"following": false,
|
||||
"blocking": false,
|
||||
"is_feed_favorite": false,
|
||||
"outgoing_request": false,
|
||||
"followed_by": false,
|
||||
"incoming_request": false,
|
||||
"is_restricted": false,
|
||||
"is_bestie": false
|
||||
},
|
||||
"full_name": "KZ6Q - Tpkqftnb Dlhlc 3Qjwm",
|
||||
"is_verified": false,
|
||||
"pk": "6092958043",
|
||||
"profile_pic_url": "https://cdn.esempio/s62m19s6181q16rm.jpg",
|
||||
"username": "hndphqqhdvktn6dnpj",
|
||||
"is_private": false,
|
||||
"supervision_info": null,
|
||||
"social_context": null,
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/9zh0q9f43861n513.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "6092958043"
|
||||
},
|
||||
{
|
||||
"friendship_status": {
|
||||
"following": false,
|
||||
"blocking": false,
|
||||
"is_feed_favorite": false,
|
||||
"outgoing_request": false,
|
||||
"followed_by": false,
|
||||
"incoming_request": false,
|
||||
"is_restricted": false,
|
||||
"is_bestie": false
|
||||
},
|
||||
"full_name": "PNQHC HXGBF VTMHJTV",
|
||||
"is_verified": false,
|
||||
"pk": "24973134344",
|
||||
"profile_pic_url": "https://cdn.esempio/f092k9mj8664rdc9.jpg",
|
||||
"username": "hwjfbsgqhdqhmkcgs_",
|
||||
"is_private": false,
|
||||
"supervision_info": null,
|
||||
"social_context": null,
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/j7c0c9m17ztg64xg.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "24973134344"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"server_metadata": {
|
||||
"request_start_time_ms": 4070744587334,
|
||||
"time_at_flush_ms": 7911613436243
|
||||
},
|
||||
"is_final": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/tb3199751p061262",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "application/json",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:38:56Z"
|
||||
},
|
||||
"corpo": {
|
||||
"can_view_more_preview_comments": false,
|
||||
"caption": {
|
||||
"bit_flags": 0,
|
||||
"content_type": "comment",
|
||||
"created_at": 1788817267,
|
||||
"created_at_for_fb_app": 7133613899,
|
||||
"created_at_utc": 7133613899,
|
||||
"did_report_as_spam": false,
|
||||
"is_covered": false,
|
||||
"is_created_by_media_owner": true,
|
||||
"is_ranked_comment": false,
|
||||
"media_id": "9222129690324603277",
|
||||
"pk": "40021847552872166",
|
||||
"private_reply_status": 0,
|
||||
"share_enabled": true,
|
||||
"status": "Active",
|
||||
"strong_id__": "40021847552872166",
|
||||
"text": "Qwqwpb \u00B7\u00B7",
|
||||
"type": 1,
|
||||
"user": {
|
||||
"fbid_v2": "55370645405178029",
|
||||
"full_name": "Gqqdcr Vkrmp",
|
||||
"id": "215081405",
|
||||
"is_private": false,
|
||||
"is_unpublished": false,
|
||||
"is_verified": false,
|
||||
"pk": 681057818,
|
||||
"pk_id": "215081405",
|
||||
"profile_pic_id": "6460827721051748069_181896617",
|
||||
"profile_pic_url": "https://cdn.esempio/07030bdh2v0xr6k5.jpg",
|
||||
"strong_id__": "215081405",
|
||||
"username": "dwvqbrgcjf"
|
||||
},
|
||||
"user_id": 681057818
|
||||
},
|
||||
"caption_is_edited": false,
|
||||
"comment_count": 2,
|
||||
"comment_cover_pos": "nrfkbf",
|
||||
"comment_filter_param": "pv_mbxxnt",
|
||||
"comment_likes_enabled": true,
|
||||
"comments": [],
|
||||
"has_more_comments": false,
|
||||
"has_more_headload_comments": false,
|
||||
"initiate_at_top": true,
|
||||
"insert_new_comment_to_top": true,
|
||||
"liked_by_media_owner_badge_enabled": true,
|
||||
"media_header_display": "lwrc",
|
||||
"quick_response_emojis": [
|
||||
{
|
||||
"unicode": "\u00B7\uFE0F"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
}
|
||||
],
|
||||
"scroll_behavior": 1,
|
||||
"threading_enabled": true,
|
||||
"filter_options": [],
|
||||
"sort_options": [],
|
||||
"should_render_upsell": false,
|
||||
"foundation_improvements_enabled": true,
|
||||
"geoblocked_comment_notices": [],
|
||||
"has_more_headload_fb_comments": false,
|
||||
"fb_comments": [],
|
||||
"ai_topic_filters": [],
|
||||
"status": "ok"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,699 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/81jg128fq9rkr95q",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "application/json",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:38:56Z"
|
||||
},
|
||||
"corpo": {
|
||||
"num_results": 1,
|
||||
"more_available": false,
|
||||
"items": [
|
||||
{
|
||||
"strong_id__": "7909533858063387797_250912751",
|
||||
"id": "7909533858063387797_250912751",
|
||||
"disable_caption_and_comment": false,
|
||||
"fbid": "16246906758569910",
|
||||
"deleted_reason": 0,
|
||||
"client_cache_key": "xxx7xxxxxxx7xxx7xxxxxxx7xx\u00B7\u00B7.7",
|
||||
"integrity_review_decision": "xnmfgvb",
|
||||
"is_awaiting_distribution": false,
|
||||
"has_delayed_metadata": false,
|
||||
"mezql_token": "",
|
||||
"should_request_ads": false,
|
||||
"has_privately_liked": false,
|
||||
"share_count_disabled": false,
|
||||
"is_reshare_of_text_post_app_media_in_ig": false,
|
||||
"is_visual_reply_commenter_notice_enabled": true,
|
||||
"subtype_name_for_REST__": "RZJRtmmpMsqnt",
|
||||
"is_quiet_post": false,
|
||||
"is_third_party_downloads_eligible": true,
|
||||
"is_short_drama": false,
|
||||
"media_type": 2,
|
||||
"organic_tracking_token": "xxx7xxxxxx7xxxx7xxxxxxxxx7xxxxx7xxxxx7xxxxx7xxxxx777xxxxx7xxxxx7xxxxxxx7xxxxxxxxxxxxxxx7xxx7xxx7xxxxxxx7xxxxxxx7xxx7xxxxxxxxxxxxxxx7xxx7xxxxxxx7xxxxxxxxx7xxxxxxx7xxx7xxxxxxxxx7xxxxxxxxxxxxxxxxxxxxxxx7xxx7xxxxxxx7xxxxxxx7xxx7xxx7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx7xxxxxxx7xxxxxxxxxxxxxxxxxxx7xxx7xxx7xxxxxxxxxxxxxx7xxxxxx77xxxxxxxx7xxx7",
|
||||
"music_metadata": null,
|
||||
"clips_tab_pinned_user_ids": [],
|
||||
"is_open_to_public_submission": false,
|
||||
"is_social_ufi_disabled": false,
|
||||
"timeline_pinned_user_ids": [],
|
||||
"taken_at": 1788817278,
|
||||
"pk": "9222129690324603277",
|
||||
"can_see_insights_as_brand": false,
|
||||
"is_affiliate_commission_eligible": false,
|
||||
"is_in_profile_grid": false,
|
||||
"profile_grid_control_enabled": false,
|
||||
"product_type": "clips",
|
||||
"subscribe_cta_visible": false,
|
||||
"is_cutout_sticker_allowed": true,
|
||||
"cutout_sticker_info": [],
|
||||
"should_show_author_pog_for_tagged_media_shared_to_profile_grid": false,
|
||||
"is_eligible_content_for_post_roll_ad": false,
|
||||
"related_ads_pivots_media_info": "LRNPHZQ_DT_GZRCR_LCH_LQSPKFSMNZM",
|
||||
"eligible_insights_entrypoints": "XJMH",
|
||||
"basel_encoding_timeout": 60,
|
||||
"media_attributions_data": [],
|
||||
"media_ui_attributions_data": [],
|
||||
"media_ui_attributions_data_v2": [],
|
||||
"is_eligible_for_poe": false,
|
||||
"is_eligible_for_organic_eager_refresh": true,
|
||||
"commerce_integrity_review_decision": "",
|
||||
"boost_unavailable_identifier": null,
|
||||
"boost_unavailable_reason": null,
|
||||
"boost_unavailable_reason_v2": null,
|
||||
"coauthor_producers": [],
|
||||
"coauthor_producer_can_see_organic_insights": false,
|
||||
"invited_coauthor_producers": [],
|
||||
"is_paid_partnership": false,
|
||||
"ig_media_sharing_disabled": false,
|
||||
"comment_inform_treatment": {
|
||||
"action_type": null,
|
||||
"should_have_inform_treatment": false,
|
||||
"text": "",
|
||||
"url": null
|
||||
},
|
||||
"is_photo_comments_composer_enabled_for_author": true,
|
||||
"fb_comment_count": 2,
|
||||
"hide_view_all_comment_entrypoint": true,
|
||||
"locations": [],
|
||||
"are_remixes_crosspostable": true,
|
||||
"crosspost_metadata": {
|
||||
"is_feedback_aggregated": true,
|
||||
"unified_feedback_enabled": true,
|
||||
"fb_downstream_use_xpost_metadata": {
|
||||
"downstream_use_xpost_deny_reason": "XJMH"
|
||||
}
|
||||
},
|
||||
"is_eligible_for_autodub": false,
|
||||
"is_eligible_for_autodub_upsell": false,
|
||||
"video_sticker_locales": [],
|
||||
"has_audio": true,
|
||||
"video_versions": [
|
||||
{
|
||||
"bandwidth": 7488206,
|
||||
"height": 1280,
|
||||
"id": "6329013574175521c",
|
||||
"progressive_identifier": "FL\u00B7\u00B7",
|
||||
"type": 101,
|
||||
"url": "https://cdn.esempio/09m2z2jjrhj04846.mp4",
|
||||
"url_expiration_timestamp_us": null,
|
||||
"width": 720,
|
||||
"fallback": null
|
||||
},
|
||||
{
|
||||
"bandwidth": 7488206,
|
||||
"height": 1280,
|
||||
"id": "6329013574175521c",
|
||||
"progressive_identifier": "FL\u00B7\u00B7",
|
||||
"type": 102,
|
||||
"url": "https://cdn.esempio/09m2z2jjrhj04846.mp4",
|
||||
"url_expiration_timestamp_us": null,
|
||||
"width": 720,
|
||||
"fallback": null
|
||||
},
|
||||
{
|
||||
"bandwidth": 7488206,
|
||||
"height": 1280,
|
||||
"id": "6329013574175521c",
|
||||
"progressive_identifier": "FL\u00B7\u00B7",
|
||||
"type": 103,
|
||||
"url": "https://cdn.esempio/09m2z2jjrhj04846.mp4",
|
||||
"url_expiration_timestamp_us": null,
|
||||
"width": 720,
|
||||
"fallback": null
|
||||
}
|
||||
],
|
||||
"number_of_qualities": 5,
|
||||
"sharing_friction_info": {
|
||||
"should_have_sharing_friction": false,
|
||||
"bloks_app_url": null,
|
||||
"sharing_friction_payload": null
|
||||
},
|
||||
"gen_ai_detection_method": {
|
||||
"detection_method": "XJMH"
|
||||
},
|
||||
"tappable_elements": [],
|
||||
"premium_reaction_count": 0,
|
||||
"viewer_premium_reaction_asset_id": null,
|
||||
"creator_is_in_premium_reactions_alpha": false,
|
||||
"image_versions2": {
|
||||
"additional_candidates": {
|
||||
"first_frame": {
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 1136,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/34217235931q327b.jpg",
|
||||
"width": 640,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
"igtv_first_frame": {
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 1136,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/34217235931q327b.jpg",
|
||||
"width": 640,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
"smart_frame": null
|
||||
},
|
||||
"candidates": [
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 1280,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/kx13rmfs3p38w278.jpg",
|
||||
"width": 720,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 1138,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/33m7013129286664.jpg",
|
||||
"width": 640,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 853,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/vkzpk03019d4p6l9.jpg",
|
||||
"width": 480,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 569,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/h459gzh05hqwdp7q.jpg",
|
||||
"width": 320,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 427,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/4p4s1v897755d261.jpg",
|
||||
"width": 240,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 720,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/w2sq4q2jmczmk8rv.jpg",
|
||||
"width": 720,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 720,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/w2sq4q2jmczmk8rv.jpg",
|
||||
"width": 720,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 640,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/7794f286mv847mpk.jpg",
|
||||
"width": 640,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 480,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/6cbl44591025c4gt.jpg",
|
||||
"width": 480,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 320,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/20zvr63s211lt69k.jpg",
|
||||
"width": 320,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 240,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/l4xq85tt02lk907c.jpg",
|
||||
"width": 240,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 150,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/9fpxtl37s22c73v1.jpg",
|
||||
"width": 150,
|
||||
"is_spatial_image": false
|
||||
}
|
||||
],
|
||||
"scrubber_spritesheet_info_candidates": {
|
||||
"default": {
|
||||
"file_size_kb": 681,
|
||||
"max_thumbnails_per_sprite": 105,
|
||||
"rendered_width": 96,
|
||||
"sprite_height": 1232,
|
||||
"sprite_urls": [
|
||||
"https://cdn.esempio/b9h31456q6z1k694.jpg"
|
||||
],
|
||||
"sprite_width": 1500,
|
||||
"thumbnail_duration": 0.05619047619047619,
|
||||
"thumbnail_height": 176,
|
||||
"thumbnail_width": 100,
|
||||
"thumbnails_per_row": 15,
|
||||
"total_thumbnail_num_per_sprite": 105,
|
||||
"video_length": 5.9
|
||||
}
|
||||
}
|
||||
},
|
||||
"original_width": 1440,
|
||||
"original_height": 2560,
|
||||
"has_tagged_users": false,
|
||||
"fb_user_tags": {
|
||||
"in": []
|
||||
},
|
||||
"media_overlay_info": null,
|
||||
"media_notes": {
|
||||
"items": []
|
||||
},
|
||||
"social_context": [],
|
||||
"creative_config": {
|
||||
"capture_type": "clips_v2",
|
||||
"face_effect_id": null,
|
||||
"failure_reason": null,
|
||||
"attribution_user": null,
|
||||
"creation_tool_info": [
|
||||
{
|
||||
"camera_tool": 434,
|
||||
"duration_selector_seconds": 0.0,
|
||||
"speed_selector": 0.0,
|
||||
"color_filters": "",
|
||||
"appearance_effect": 0,
|
||||
"timer_selector_seconds": 0.0,
|
||||
"magic_cut_start_time": 0.0,
|
||||
"magic_cut_end_time": 0.0,
|
||||
"effect_filter_name": ""
|
||||
}
|
||||
],
|
||||
"effect_configs": null,
|
||||
"effect_preview": null,
|
||||
"gen_ai_tool_info": null
|
||||
},
|
||||
"floating_context_items": [],
|
||||
"is_reuse_allowed": true,
|
||||
"igbio_product": null,
|
||||
"clips_metadata": {
|
||||
"clips_creation_entry_point": "gmzkv",
|
||||
"featured_label": null,
|
||||
"is_public_chat_welcome_video": false,
|
||||
"professional_clips_upsell_type": 0,
|
||||
"show_tips": null,
|
||||
"achievements_info": {
|
||||
"num_earned_achievements": null,
|
||||
"show_achievements": false
|
||||
},
|
||||
"additional_audio_info": {
|
||||
"additional_audio_username": null,
|
||||
"audio_reattribution_info": {
|
||||
"should_allow_restore": false
|
||||
}
|
||||
},
|
||||
"asset_recommendation_info": null,
|
||||
"audio_ranking_info": {
|
||||
"best_audio_cluster_id": "887740111386887"
|
||||
},
|
||||
"audio_type": "original_sounds",
|
||||
"branded_content_tag_info": {
|
||||
"can_add_tag": false
|
||||
},
|
||||
"breaking_content_info": null,
|
||||
"breaking_creator_info": null,
|
||||
"challenge_info": null,
|
||||
"content_appreciation_info": {
|
||||
"enabled": false,
|
||||
"entry_point_container": null
|
||||
},
|
||||
"contextual_highlight_info": null,
|
||||
"cutout_sticker_info": [],
|
||||
"disable_use_in_clips_client_cache": false,
|
||||
"external_media_info": null,
|
||||
"is_fan_club_promo_video": false,
|
||||
"is_shared_to_fb": false,
|
||||
"mashup_info": {
|
||||
"can_toggle_mashups_allowed": false,
|
||||
"formatted_mashups_count": null,
|
||||
"has_been_mashed_up": false,
|
||||
"has_nonmimicable_additional_audio": false,
|
||||
"is_creator_requesting_mashup": false,
|
||||
"is_light_weight_check": true,
|
||||
"is_light_weight_reuse_allowed_check": false,
|
||||
"is_pivot_page_available": false,
|
||||
"is_reuse_allowed": true,
|
||||
"mashup_type": null,
|
||||
"mashups_allowed": true,
|
||||
"mashups_allowed_for_carousel": false,
|
||||
"non_privacy_filtered_mashups_media_count": 0,
|
||||
"privacy_filtered_mashups_media_count": null,
|
||||
"original_media": null
|
||||
},
|
||||
"merchandising_pill_info": null,
|
||||
"music_canonical_id": "91113504822483696",
|
||||
"music_info": null,
|
||||
"nux_info": null,
|
||||
"original_sound_info": {
|
||||
"allow_creator_to_rename": true,
|
||||
"audio_asset_id": "12471162636763090",
|
||||
"attributed_custom_audio_asset_id": null,
|
||||
"can_remix_be_shared_to_fb": true,
|
||||
"can_remix_be_shared_to_fb_expansion": true,
|
||||
"dash_manifest": "\u00B7?fgw hcmrvts\u00B7\u00227.5\u0022 czvtdjch\u00B7\u0022JWZ-0\u0022?\u00B7\n\u00B7KKJ dsqwq\u00B7\u0022rsh:hrqr:dfxm:sndnsc:ctw:3176\u0022 sgggq:mkf\u00B7\u0022dbgs://dmh.q5.gvj/0496/QXXJhftxf-mfjjjlmb\u0022 lck:dznkzgWmtbzbdc\u00B7\u0022pxb:rttk:pptt:ksrnzr:twz:1853 CLQN-MJT.mhg\u0022 hdpgpbvz\u00B7\u0022qkh:ppvf:ncwf:kdspllk:qmfbk-jn-kdxszp:3300\u0022 llvNzcbcdCnrg\u00B7\u0022TR0F\u0022 vxpv\u00B7\u0022xjvrrh\u0022 klmhnDhkggrvgzmjrKwkknxlg\u00B7\u0022ZM2.541945N\u0022 RXNnkhcsrmLbwlwcmmk\u00B7\u00222221857858\u0022 JWWhsmmtksVvtfdvvgbr\u00B7\u0022DtVcj16XPDtZ//LtsdWsGzPCFKM2TDlxZ3KbK19rbz66TpTdNPLR\u0022\u00B7\u00B7Zmqtcs zv\u00B7\u00220\u0022 xrxlkzmg\u00B7\u0022PS7.526638D\u0022\u00B7\u00B7SmhvzlzspnHpr gl\u00B7\u00221\u0022 qzllhrxTzfb\u00B7\u0022bdqdh\u0022 dhzccrszrlNqptxbHbvgZPR\u00B7\u00221\u0022 qqhgzppzjdLlqlrjlqk\u00B7\u0022mvcp\u0022\u00B7\u00B7Gsppwhdkqwzfwg gd\u00B7\u00223454055608463982k\u0022 rtqfglzdz\u00B7\u002214114\u0022 rcvhdj\u00B7\u0022pn8d.44.9\u0022 pcfkPdmb\u00B7\u0022gzjgv/xg2\u0022 MCQgcLfqqmnp\u00B7\u002256757\u0022 cpthjDkfxrxndZqjs\u00B7\u002293511\u0022\u00B7\u00B7RbvvvBlvwvwkPtqfsgvsvwwzx krtcgmFhQjz\u00B7\u0022zsb:gtwm:crjv:19112:3:swpbc_sdnlcnw_spzcltkfmkvzp:5596\u0022 lnmgs\u00B7\u00221\u0022/\u00B7\u00B7JlwjHRG\u00B7pqqqk://zhphpxdp-zdw7-1.whkmjdjxmdsh.vcd/b6/w/m6/s0/c96/ZKVd5xnMnvrpG8sJGFCH486Z1ljbM1N2gCmhgFNS8pHTbSSHTG95C7KhKsLMrxQLz7nzVCB441PWTHqjzgLdCKsDt7FWkCWChScQPkx.lb0?_hj_wzg\u00B75\u0026thc;_rr_sbm\u00B78qr563\u0026jnh;_vb_dv\u00B7sxjnwqrf-rsf1-2.wdqwxrwjxlpp.zjx\u0026rzg;_np_dfm\u00B7FBcvc9cBtPMM1wHdqHnjqlf\u0026gwk;kwc\u00B7jzR6DX4bl0VcK9PgJpK6LrMhz6tlwJ9ljCGwNLXnlhLtR99qhQTdxdBpNrDmBBGhM2hhCgdstFmsCDGppRzgvNMsJ7FvK3XbkD0cNLF1ZfW9XxlrXPHgNHQ0QZHmxDgkczFnlqZvLQK0VzPxj21hm42hCPW2hLFnJPSrJVBkdKFcGcDsSGt8JMLbLkS5JDf1WHGnZmJpr6V5T8GzRN7zLMpdVxzmVSCxJzShQ2ZbXGPwd9TxbCGrGgPkZCz3FKMbpVLxnZkvzt6nQgh0CDWclWDfRHLkSbk4WkN9PPzzvXFhL4GgM8CczLLcDFB8Bgh6wbL5\u0026mcw;hwt\u00B746-2\u0026mnq;_bd_wgc\u00B7xNZ-cG63JpqFxw2L3j3ZxN\u0026wqj;_jk_rz\u00B75k86f\u0026fvx;_mv_sf\u00B745\u0026rqg;nr\u00B790_VNFj_ZnbnTk9sL-MsGWng01vWhN_pkB6KvDhmbTrVfWKgQ\u0026dvd;fr\u00B79CSWT4Z9\u00B7/QdqlGTS\u00B7\u00B7CzqgsvzRmpm hdddqKknjd\u00B7\u0022700-263\u0022 bpqxltqtq\u00B7\u002255460\u0022\u00B7\u00B7Vgmznbtxjpxskh xrmhv\u00B7\u00221-933\u0022/\u00B7\u00B7/LpvglhtZzsn\u00B7\u00B7/Lfbjfktxgrbgdf\u00B7\u00B7/VbgtkkljtpVxx\u00B7\u00B7/Tbdrnw\u00B7\u00B7/RPJ\u00B7\n",
|
||||
"duration_in_ms": 5900,
|
||||
"formatted_clips_media_count": null,
|
||||
"hide_remixing": false,
|
||||
"is_audio_automatically_attributed": false,
|
||||
"is_eligible_for_audio_effects": false,
|
||||
"is_eligible_for_vinyl_sticker": true,
|
||||
"is_explicit": false,
|
||||
"is_original_audio_download_eligible": false,
|
||||
"is_reuse_disabled": false,
|
||||
"is_xpost_from_fb": false,
|
||||
"music_canonical_id": null,
|
||||
"oa_owner_is_music_artist": false,
|
||||
"original_audio_subtype": "spvmmvm",
|
||||
"original_audio_title": "Nvskk dtcpxknbk",
|
||||
"original_media_id": "7211154431180240139",
|
||||
"progressive_download_url": "https://cdn.esempio/kk33cnh1t9rwwd57.mp4",
|
||||
"should_mute_audio": false,
|
||||
"time_created": 2618720927,
|
||||
"trend_rank": null,
|
||||
"previous_trend_rank": null,
|
||||
"overlap_duration_in_ms": 5900,
|
||||
"audio_asset_start_time_in_ms": 0,
|
||||
"derived_content_start_time_in_composition_in_ms": 0,
|
||||
"should_allow_audio_editing": false,
|
||||
"ig_artist": {
|
||||
"strong_id__": "3615921134",
|
||||
"pk": "3615921134",
|
||||
"pk_id": "3615921134",
|
||||
"id": "3615921134",
|
||||
"username": "zhlnznghsvglgmmh",
|
||||
"full_name": "Xrrwgthgj Gpfprwb",
|
||||
"is_private": false,
|
||||
"is_verified": true,
|
||||
"profile_pic_id": "4387790421367093288_3487371757",
|
||||
"profile_pic_url": "https://cdn.esempio/f728qmjp637n0647.jpg"
|
||||
},
|
||||
"audio_filter_infos": null,
|
||||
"audio_parts": [],
|
||||
"audio_parts_by_filter": [],
|
||||
"consumption_info": {
|
||||
"display_media_id": null,
|
||||
"is_bookmarked": false,
|
||||
"is_trending_in_clips": false,
|
||||
"should_mute_audio_reason": "",
|
||||
"should_mute_audio_reason_type": null,
|
||||
"inline_audio_label": null,
|
||||
"display_labels": null,
|
||||
"display_labels_with_translations": null,
|
||||
"user_notes": null
|
||||
},
|
||||
"xpost_fb_creator_info": null,
|
||||
"fb_downstream_use_xpost_metadata": {
|
||||
"downstream_use_xpost_deny_reason": "XJMH"
|
||||
}
|
||||
},
|
||||
"originality_info": null,
|
||||
"reels_on_the_rise_info": null,
|
||||
"reusable_text_attribute_string": null,
|
||||
"reusable_text_info": null,
|
||||
"show_achievements": false,
|
||||
"may_have_template_info": null,
|
||||
"viewer_interaction_settings": null,
|
||||
"shopping_info": null,
|
||||
"template_info": null
|
||||
},
|
||||
"hide_stickers_for_original_language": false,
|
||||
"like_count": 64,
|
||||
"fb_like_count": 13,
|
||||
"has_liked": false,
|
||||
"top_likers": [
|
||||
"dvtgnfcmcjq"
|
||||
],
|
||||
"facepile_top_likers": [
|
||||
{
|
||||
"strong_id__": "3851043056",
|
||||
"pk": "3851043056",
|
||||
"pk_id": "3851043056",
|
||||
"id": "3851043056",
|
||||
"username": "dvtgnfcmcjq",
|
||||
"full_name": "Jtfgfd Bkkmw",
|
||||
"is_private": false,
|
||||
"is_verified": false,
|
||||
"profile_pic_id": "6174566419957196250_8710701751",
|
||||
"profile_pic_url": "https://cdn.esempio/57n1d16w4k1j353f.jpg"
|
||||
}
|
||||
],
|
||||
"hidden_likes_string_variant": -1,
|
||||
"caption": {
|
||||
"strong_id__": "40021847552872166",
|
||||
"bit_flags": 0,
|
||||
"created_at": 1788817267,
|
||||
"created_at_utc": 7133613899,
|
||||
"did_report_as_spam": false,
|
||||
"is_ranked_comment": false,
|
||||
"pk": "40021847552872166",
|
||||
"share_enabled": false,
|
||||
"content_type": "comment",
|
||||
"media_id": "9222129690324603277",
|
||||
"status": "Active",
|
||||
"type": 1,
|
||||
"user_id": "215081405",
|
||||
"text": "Qwqwpb \u00B7\u00B7",
|
||||
"user": {
|
||||
"strong_id__": "215081405",
|
||||
"pk": "215081405",
|
||||
"pk_id": "215081405",
|
||||
"id": "215081405",
|
||||
"is_unpublished": false,
|
||||
"fbid_v2": "55370645405178029",
|
||||
"username": "dwvqbrgcjf",
|
||||
"full_name": "Gqqdcr Vkrmp",
|
||||
"is_private": false,
|
||||
"is_verified": false,
|
||||
"profile_pic_id": "6460827721051748069_181896617",
|
||||
"profile_pic_url": "https://cdn.esempio/l77dd7l0fd384l17.jpg"
|
||||
},
|
||||
"is_covered": false,
|
||||
"private_reply_status": 0
|
||||
},
|
||||
"comment_count": 2,
|
||||
"can_view_more_preview_comments": false,
|
||||
"preview_comments": [],
|
||||
"comment_likes_enabled": true,
|
||||
"play_count": 1547,
|
||||
"ig_play_count": 929,
|
||||
"fb_play_count": 618,
|
||||
"shop_routing_user_id": null,
|
||||
"featured_products": [],
|
||||
"video_duration": 5.919000148773193,
|
||||
"is_dash_eligible": 1,
|
||||
"video_dash_manifest": "\u00B7?bxp fgdhnhx\u00B7\u00223.2\u0022 nqvdpphx\u00B7\u0022RCW-4\u0022?\u00B7\n\u00B7JRP kcldb\u00B7\u0022mnl:tkbn:slxv:dzzklk:xsp:5071\u0022 xhjbh:mrc\u00B7\u0022pfgz://gbl.w1.nbs/9401/DRCHjbsnh-rljkspqs\u0022 hnc:fcsswcVctjvxbk\u00B7\u0022qgc:zhwc:vggr:wbxfkx:srh:0506 BNZH-KFR.rvb\u0022 tzthfssh\u00B7\u0022mpx:chqr:zrfv:nwrbzpp:znrtp-mv-bhnngp:4898\u0022 jkbLhwxjkDsdz\u00B7\u0022QC7Q\u0022 mwqj\u00B7\u0022wrtpmp\u0022 zlcntXtlvfwkrfjwvHnchpssp\u00B7\u0022PR2.066339S\u0022 PWGdmhbgbsVkgjkqnks\u00B7\u00222790501876\u0022 PTXtlphwmvGgbjsjmffb\u00B7\u0022TlSvf25KMHFvV02kPXTmK1Bps0khP3QlJGrm2p2M9hzb1bV3t3xVxX7qB\u00B7ZN2KbzgbRWmGbZcXkg1xXw5PHFlZ3jM2vXb3lrqrWZVfnSFGMjmH5pjq4qJMWqF068ZfJvJ1Z9VQmwXhpSQZnnmFVmDW8hzDqmqGBBBmQJRsRVFT\u00B7\u00B7\u0022\u00B7\u00B7Kxnftp dd\u00B7\u00225\u0022 fpkcvxsb\u00B7\u0022XT6.568319G\u0022\u00B7\u00B7FfwzgmjljtQrd nw\u00B7\u00226\u0022 xdvwwqjVjsc\u00B7\u0022cznms\u0022 jcqgwgflhmNxgzgrnmx\u00B7\u0022rqrb\u0022 mfh\u00B7\u00223:32\u0022 QFCwccmvpGljvcpDplrjnmbzwHqn\u00B7\u0022391:23.1\u0022\u00B7\u00B7Lgmxfmdblgtsxz mg\u00B7\u00222072495724225125w\u0022 wwbqvpfbf\u00B7\u0022068578\u0022 dcddzm\u00B7\u0022sr39.23.94.78.63.68.85.94.54\u0022 rgffJclm\u00B7\u0022jxxdr/ws3\u0022 qgr\u00B7\u00228:7\u0022 RJGlfjwmfcFfs\u00B7\u0022qgtd_lm4-tndjk-vxl2_338j\u0022 QDBbpkdjzPnfjtw\u00B7\u0022388834\u0022 HFRbprjjznNppvhwtgzdVvc\u00B7\u00227:899,087:77.8,698:08.6,509:11.8,0173:52.3,2389:62.2\u0022 XTNnnpbcgvRpbdnrflmlWlrFkdrlmpqgkPwrrq\u00B7\u0022dfjd\u0022 FHBzwwbdtgQzmsqghhtxQjzrm\u00B7\u00227:037,999:82.3,127:93.1,733:56.5,4575:00.3,6844:12.9\u0022 RKLfnTjrsqsHlbn\u00B7\u0022\u0022 vkzcw\u00B7\u0022116\u0022 rjbjmg\u00B7\u0022378\u0022 xrnbxLwtl\u00B7\u002200691/004\u0022 BZQrpvgwcHjlms\u00B7\u0022rk\u0022 QCBvjljlsHwlzm\u00B7\u0022105p\u0022\u00B7\u00B7LqfhTHL\u00B7wmkjc://nxnfbkvk-xfr1-6.bfrgzgmjcfms.fhz/h8/j/x7/m2/q467/QNFSlPCwVmr3t5q_NjwjGLFzkwcKNC6CBz2X6b-gfc1dmzVdcLL17N8Qz0MfP2wGqscPNBMVmst5XDzV6QGxGm1QkPtMwMbJzXMJjzdfpH7D7s.xb9?_xl_wqh\u00B7579\u0026vlt;_ln_jqm\u00B75ld419\u0026wcr;_cj_wn\u00B7hbtqmtbb-fbz5-0.cgsglvthksxb.xpz\u0026fbt;_pd_zvs\u00B7TldglJzWhxNF8lTtnMXgJ4v\u0026bwr;lgl\u00B7cgT5MH3wh9HjT9SxNrG0FvjnTWrdvtKnBdPbrRJfGdNtFPGcKqBtw0zsjdR4QKSlk1klVRfmrqPzKgGltLQxJpBvBBZlL1kfTzvldShsSVCkrBkghGZdJ6NnS9TmxV8gSWP8LCQ7HqS6SrLrLgqsSKZ8NLXlhTqqxhNcbtFqPZD9ZzvpFvgprLJ6N2Pqx8H4S5zdFgxwTJr8DmHfDVp0DSP6JpS7VLVvx0KkfP4pM3TsCNK8tlV5XSVbCbKmD3BdNWBqw0QlhHGfJgQsBWM8LFWgmXMrxZnwhf8bRzw4DLFbzPDqGJMhWzs3TvQ5HLKsXnRshSmzmv7ht3QqR4PsQsQ7n4ndpH%3W%5D\u0026fpv;knf\u00B719-5\u0026qlt;_pk_vjf\u00B7vRZ-xW72WhlFrx7N9c3LxH\u0026ppg;_fx_jj\u00B71b38z\u0026nzd;_mz_qs\u00B735\u0026vmg;hs\u00B770_GKXfPFBBzvNRBKkhVn2-wbGF0wnQ8fwdQVBtqlVsNHDVDN\u0026fch;hj\u00B72KBMHS36\u00B7/ZcxpXGN\u00B7\u00B7ZjcrvsjRvjr xqptjPtttr\u00B7\u0022579-154\u0022 gfjzjbkvj\u00B7\u002296708\u0022 ZHBdqstjlZbxpnbsdZtxjj\u00B7\u0022712-44180\u0022 LVPrzlrxnKbvzcgdqFghclhfn\u00B7\u00220076\u0022 ZKCfwmmdbHrsnqnkfNgsxx\u00B7\u0022317-065318\u0022 QTJrjkpDsnlnmgThcmd\u00B7\u0022553-680009\u0022 TPGxgnxHgjzswxSppwfpmn\u00B7\u00223152\u0022 SFZnnhqbLzccqxlFqqzn\u00B7\u0022303182-344504\u0022 GKTljbfxhgDgqjpwfGlqnk\u00B7\u0022118-472377\u0022 ZPVtsbhdzxGcfbwjbNvjbvnpk\u00B7\u00227004\u0022\u00B7\u00B7Nxvkfqvhjmqwzw mcxsl\u00B7\u00227-580\u0022/\u00B7\u00B7/DxzggthWvpr\u00B7\u00B7/Cwkgtrwwtwfrrx\u00B7\u00B7Djzcbnsxxpbscf wp\u00B7\u00224559668956075875r\u0022 lfkdlrspk\u00B7\u00224840764\u0022 cqbhnv\u00B7\u0022rc95.04.95.89.72.91.09.82.99\u0022 pztxTvjz\u00B7\u0022dtstp/jp3\u0022 nqq\u00B7\u00227:9\u0022 MHWstfgbxrZcr\u00B7\u0022qxpp_qv6-zgzmj-gtq6_932c\u0022 VHSzcsrgfNpgqwm\u00B7\u00221305635\u0022 ZLNczfntftJwpxzflrdxPmk\u00B7\u00225:496,146:11,187:35.5,716:49.8,5177:64.4,6062:57.6\u0022 WFHcmqqdqkBxrpnhbkrtLjbKwhqvdqmcfZbktf\u00B7\u0022jcjj\u0022 GTStrpmxbkKxlcwsmccnSnzfz\u00B7\u00222:328,067:94,839:60.4,071:34.8,7745:31.1,6322:63.8\u0022 WZQzcQgsxwqSplx\u00B7\u0022\u0022 xxlws\u00B7\u0022783\u0022 fwfkvh\u00B7\u0022380\u0022 hdvkwTsmh\u00B7\u002245054/163\u0022 XHCxzjwxkQnxzf\u00B7\u0022mf\u0022 PKNtcgnndBhzxd\u00B7\u0022471j\u0022\u00B7\u00B7XctbPMS\u00B7psskz://snjmzxxw-fkm7-7.drtbrbzrfrxs.hjh/q2/x/b9/d6/b419/RGC5Zbt9NPsrz9Gt2FggsDmPdw78stTMzkRTNkb6V4mNGkhmG53Zd2JPfhg8vlvB5RVwLTSdSSHhBlCVwNP3840vTzp8ZkZHDNTncrHBSddrSf.vp3?_xs_kmd\u00B7672\u0026pfj;_dk_nws\u00B72qm860\u0026wsp;_vx_cr\u00B7bwsjvsvv-bjj8-2.zgvpmlwzmxqk.cgb\u0026jdq;_gk_ngh\u00B7BS5zmjwbmcRM3cBbhWddGlr\u0026ngj;klj\u00B7snB5FB9dz4BvM1WtCnK8NmjmWLdvsjHcPtRssSJzPjFwTZBfKtXns5bfshF9KMGmq2gdQPhcvgTtFWVnvHRmFzFlQKRwW7kmVfmdpDxpMFPsrKgnvRLbK2WmK7PttK2xVKR3XTW0HrW1ZnPpFnfpZBN4SCGbfQgdnrLvmpQjMDH0QvfnJxpcwWX6N5Lht0R1K6tzGjxrKBc7NrSqCFr5HVJ4SqQ3TZGfk0BhrB2fK4LbTVS0dsG9MBHnZvHdJ9PsHFGnn9NzbGQjFbJvBSL7FJHnrMMckQlnmp3zPnx5XGNmtGZjHJBnWmbzDDZ9HMn1STD2scrjGN4hz095pmFnJgkgx8c7Nt7%1F\u0026pxs;qsp\u00B773-0\u0026bfh;_cd_nkl\u00B7fQV-rK63GtpRsm6S1l2BcR\u0026wgr;_mh_bw\u00B78h40c\u0026dbr;_jr_tf\u00B740\u0026gbt;sd\u00B784_FTDcl1ZTzZXgpWFhSHhb_drClZNQrLine truncated
|
||||
"user": {
|
||||
"strong_id__": "215081405",
|
||||
"fbid_v2": "55370645405178029",
|
||||
"feed_post_reshare_disabled": false,
|
||||
"id": "215081405",
|
||||
"is_unpublished": false,
|
||||
"pk": "215081405",
|
||||
"pk_id": "215081405",
|
||||
"third_party_downloads_enabled": 1,
|
||||
"account_type": 2,
|
||||
"can_see_quiet_post_attribution": true,
|
||||
"account_badges": [],
|
||||
"full_name": "Gqqdcr Vkrmp",
|
||||
"has_anonymous_profile_picture": false,
|
||||
"is_favorite": false,
|
||||
"is_private": false,
|
||||
"is_ring_creator": false,
|
||||
"show_ring_award": false,
|
||||
"aigm_account_label_info": {
|
||||
"is_enabled": false,
|
||||
"is_auto_detected": false,
|
||||
"is_manually_enabled": false
|
||||
},
|
||||
"is_verified": false,
|
||||
"show_account_transparency_details": true,
|
||||
"transparency_product_enabled": false,
|
||||
"username": "dwvqbrgcjf",
|
||||
"eligible_for_text_app_activation_badge": false,
|
||||
"user_activation_info": {},
|
||||
"fan_club_info": {
|
||||
"autosave_to_exclusive_highlight": null,
|
||||
"connected_member_count": null,
|
||||
"fan_club_id": null,
|
||||
"fan_club_name": null,
|
||||
"has_created_ssc": null,
|
||||
"has_enough_subscribers_for_ssc": null,
|
||||
"is_fan_club_gifting_eligible": null,
|
||||
"is_fan_club_referral_eligible": null,
|
||||
"is_free_trial_eligible": null,
|
||||
"largest_public_bc_id": null,
|
||||
"subscriber_count": null,
|
||||
"should_show_playlists_in_profile_tab": null,
|
||||
"fan_consideration_page_revamp_eligiblity": null
|
||||
},
|
||||
"friendship_status": {
|
||||
"following": false,
|
||||
"is_bestie": false,
|
||||
"is_feed_favorite": false,
|
||||
"is_private": false,
|
||||
"is_restricted": false,
|
||||
"followed_by": false,
|
||||
"is_muting_reel": false
|
||||
},
|
||||
"hd_profile_pic_url_info": {
|
||||
"height": 960,
|
||||
"url": "https://cdn.esempio/4c74479rv6zw0pp5.jpg",
|
||||
"width": 960
|
||||
},
|
||||
"hd_profile_pic_versions": [
|
||||
{
|
||||
"height": 320,
|
||||
"url": "https://cdn.esempio/q5pz0293nmsd9nz9.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 640,
|
||||
"url": "https://cdn.esempio/2b806015288zl984.jpg",
|
||||
"width": 640
|
||||
}
|
||||
],
|
||||
"profile_pic_id": "6460827721051748069_181896617",
|
||||
"profile_pic_url": "https://cdn.esempio/l77dd7l0fd384l17.jpg",
|
||||
"is_embeds_disabled": false,
|
||||
"text_post_app_is_private": false,
|
||||
"is_active_on_text_post_app": true,
|
||||
"latest_reel_media": 1792602930
|
||||
},
|
||||
"owner": {
|
||||
"strong_id__": "215081405",
|
||||
"fbid_v2": "55370645405178029",
|
||||
"feed_post_reshare_disabled": false,
|
||||
"id": "215081405",
|
||||
"is_unpublished": false,
|
||||
"pk": "215081405",
|
||||
"pk_id": "215081405",
|
||||
"third_party_downloads_enabled": 1,
|
||||
"account_type": 2,
|
||||
"can_see_quiet_post_attribution": true,
|
||||
"account_badges": [],
|
||||
"full_name": "Gqqdcr Vkrmp",
|
||||
"has_anonymous_profile_picture": false,
|
||||
"is_favorite": false,
|
||||
"is_private": false,
|
||||
"is_ring_creator": false,
|
||||
"show_ring_award": false,
|
||||
"aigm_account_label_info": {
|
||||
"is_enabled": false,
|
||||
"is_auto_detected": false,
|
||||
"is_manually_enabled": false
|
||||
},
|
||||
"is_verified": false,
|
||||
"show_account_transparency_details": true,
|
||||
"transparency_product_enabled": false,
|
||||
"username": "dwvqbrgcjf",
|
||||
"eligible_for_text_app_activation_badge": false,
|
||||
"user_activation_info": {},
|
||||
"fan_club_info": {
|
||||
"autosave_to_exclusive_highlight": null,
|
||||
"connected_member_count": null,
|
||||
"fan_club_id": null,
|
||||
"fan_club_name": null,
|
||||
"has_created_ssc": null,
|
||||
"has_enough_subscribers_for_ssc": null,
|
||||
"is_fan_club_gifting_eligible": null,
|
||||
"is_fan_club_referral_eligible": null,
|
||||
"is_free_trial_eligible": null,
|
||||
"largest_public_bc_id": null,
|
||||
"subscriber_count": null,
|
||||
"should_show_playlists_in_profile_tab": null,
|
||||
"fan_consideration_page_revamp_eligiblity": null
|
||||
},
|
||||
"friendship_status": {
|
||||
"following": false,
|
||||
"is_bestie": false,
|
||||
"is_feed_favorite": false,
|
||||
"is_private": false,
|
||||
"is_restricted": false,
|
||||
"followed_by": false,
|
||||
"is_muting_reel": false
|
||||
},
|
||||
"hd_profile_pic_url_info": {
|
||||
"height": 960,
|
||||
"url": "https://cdn.esempio/4c74479rv6zw0pp5.jpg",
|
||||
"width": 960
|
||||
},
|
||||
"hd_profile_pic_versions": [
|
||||
{
|
||||
"height": 320,
|
||||
"url": "https://cdn.esempio/q5pz0293nmsd9nz9.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 640,
|
||||
"url": "https://cdn.esempio/2b806015288zl984.jpg",
|
||||
"width": 640
|
||||
}
|
||||
],
|
||||
"profile_pic_id": "6460827721051748069_181896617",
|
||||
"profile_pic_url": "https://cdn.esempio/l77dd7l0fd384l17.jpg",
|
||||
"is_embeds_disabled": false,
|
||||
"text_post_app_is_private": false,
|
||||
"is_active_on_text_post_app": true,
|
||||
"latest_reel_media": 1792602930
|
||||
},
|
||||
"community_notes_info": {
|
||||
"has_viewer_submitted_note": false,
|
||||
"note_submission_disabled": false,
|
||||
"enable_submission_friction": false,
|
||||
"is_eligible_for_request_a_note": true
|
||||
},
|
||||
"has_high_risk_gen_ai_inform_treatment": false,
|
||||
"caption_is_edited": false,
|
||||
"code": "NkNCTkwnbp8",
|
||||
"device_timestamp": 1868754255900570,
|
||||
"enable_media_notes_production": true,
|
||||
"filter_type": 0,
|
||||
"has_views_fetching": true,
|
||||
"is_post_live_clips_media": false,
|
||||
"is_eligible_for_rta": false,
|
||||
"like_and_view_counts_disabled": false,
|
||||
"is_meta_ai_invocation_blocked_by_author": false,
|
||||
"tya_media_related_topics": [],
|
||||
"teen_project_info": null,
|
||||
"is_educational": null,
|
||||
"meta_ai_suggested_prompts": [],
|
||||
"is_eligible_for_poe_premium": false,
|
||||
"is_longform_player_eligible": false,
|
||||
"collaborator_edit_eligibility": false,
|
||||
"is_organic_product_tagging_eligible": true,
|
||||
"can_viewer_reshare": true,
|
||||
"has_shared_to_fb": 0,
|
||||
"media_reposter_bottomsheet_enabled": false,
|
||||
"can_viewer_save": true,
|
||||
"is_comments_gif_composer_enabled": true,
|
||||
"translated_langs_for_autodub": []
|
||||
}
|
||||
],
|
||||
"auto_load_more_enabled": false,
|
||||
"status": "ok"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,607 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/34m6543g18c0k202",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "text/javascript",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:39:03Z"
|
||||
},
|
||||
"corpo": {
|
||||
"data": {
|
||||
"xdt_api__v1__feed__reels_media__connection": {
|
||||
"edges": [
|
||||
{
|
||||
"node": {
|
||||
"id": "mtmlprbdv:62008803167428297",
|
||||
"items": [
|
||||
{
|
||||
"pk": "9704657468886935049",
|
||||
"id": "0224021262026182334_702528115",
|
||||
"has_audio": false,
|
||||
"story_music_stickers": null,
|
||||
"ai_label_info": null,
|
||||
"carousel_media": null,
|
||||
"code": "RzZX1JHhJNG",
|
||||
"image_versions2": {
|
||||
"candidates": [
|
||||
{
|
||||
"height": 1276,
|
||||
"url": "https://cdn.esempio/3m6x3548q708c84w.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 1134,
|
||||
"url": "https://cdn.esempio/324647f1l7pt1n80.jpg",
|
||||
"width": 640
|
||||
},
|
||||
{
|
||||
"height": 851,
|
||||
"url": "https://cdn.esempio/329m6914172rf1kp.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 567,
|
||||
"url": "https://cdn.esempio/hc4g542p6d2s1t19.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 425,
|
||||
"url": "https://cdn.esempio/p88051bs2w1412mc.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 720,
|
||||
"url": "https://cdn.esempio/154sg73t10wnj81f.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 720,
|
||||
"url": "https://cdn.esempio/154sg73t10wnj81f.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 640,
|
||||
"url": "https://cdn.esempio/s864785cwb5gkm08.jpg",
|
||||
"width": 640
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/hbgq9m2wt9x946p5.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 320,
|
||||
"url": "https://cdn.esempio/b5l52zm8f2k79z34.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 240,
|
||||
"url": "https://cdn.esempio/l04w59br24162l62.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 150,
|
||||
"url": "https://cdn.esempio/d53475r2kg9z9jg3.jpg",
|
||||
"width": 150
|
||||
}
|
||||
]
|
||||
},
|
||||
"original_width": 640,
|
||||
"original_height": 1136,
|
||||
"taken_at": 1535615772,
|
||||
"is_dash_eligible": 1,
|
||||
"number_of_qualities": 2,
|
||||
"video_dash_manifest": "\u00B7?wwb qkkqkwc\u00B7\u00223.8\u0022?\u00B7\n\u00B7VSF vnnzs\u00B7\u0022bjz:ltmg:xqfv:tfslbk:wqt:7521\u0022 ndhGptpdcKlwb\u00B7\u0022PH0.101P\u0022 xgqg\u00B7\u0022nqmwjc\u0022 tjxfpWfdxgrpxjtzdWnqhrbpd\u00B7\u0022PD5W0G3.607P\u0022 tfmQcxvznrDqxcxxgc\u00B7\u0022SR3Q3C8.137N\u0022 kfmqnvxp\u00B7\u0022xwk:nznw:wkld:flzhklb:knmqj-dv-chwsmj:7373,pwzd://mmvvfp.pvj/wsckzctcxb/fpcb905\u0022 HNNnxkcgqsHnscssspr\u00B7\u00224162876904\u0022 PHPljrrqtjCzmdkqcnwk\u00B7\u0022Qn7wm54JZTTfD11mCQFdP2Dxt0TgvF3hXPfJdW\u00B7QhKjQZpWFd2XSjmVTNknhJLRxvKlcrTDch9B1C4Dlfj0bDKfjHdBbx40phSB2QbgJDBpwrTDhXJ7lgMlfpVQMzKQGZRVCHMqCKx3ZW1JGQKQLRSPPDHLD\u0022\u00B7\u00B7Mbdsvw wmpcbspc\u00B7\u0022DS8D5C1.713C\u0022\u00B7\u00B7WqpndndcmjZzc hnfgwjqQwmwslndf\u00B7\u0022cjmp\u0022 ltzVzkvn\u00B7\u0022099\u0022 jdqMbdtlr\u00B7\u00229292\u0022 cfqSchlcBspk\u00B7\u002297\u0022 dzs\u00B7\u00229:89\u0022 ljlh\u00B7\u0022hcl\u0022 gxqjmmclrnJqxlqcgbj\u00B7\u0022zsfc\u0022 sfwgtgxsvtXcbzlzKksxJWR\u00B7\u00223\u0022 mf\u00B7\u00225\u0022\u00B7\u00B7Nkrfrcdpkntgrq gg\u00B7\u0022482151444703656c\u0022 pfdtZrsv\u00B7\u0022kptzp/fj2\u0022 ncljpw\u00B7\u0022ggt7.5V806Z\u0022 mkntl\u00B7\u0022124\u0022 ndzmsd\u00B7\u00229577\u0022 drzjlGzss\u00B7\u002242\u0022 tkl\u00B7\u00227:1\u0022 vjfpcHghrNHR\u00B7\u00228\u0022 xlfsdcffb\u00B7\u0022091868\u0022 ZJKpgphhjgTcc\u00B7\u0022lvhw_vflmtbcz_9_r6\u0022 WKNhjcrljBglkms\u00B7\u0022078865\u0022 QLLftNwmggsJkbj\u00B7\u0022\u0022 CPHdsvbgnQhphm\u00B7\u0022rd\u0022 FJHmshfqrJlnfl\u00B7\u0022648k\u0022\u00B7\u00B7KjzwNHH\u00B7xcbmp://bzmhpgpz-kws4-4.dfwcpflnwjwm.lhz/c9/j/c21/q1/h08/LWRQCv4JT9WSTdZvcTTmKdCD_XtqxgVfwgp26mfkDF_pTdXG8T23gBf43RZtPv9H9CMsKjXv9Pz5SXnJc8-ZqFPHZKV6Td3ZsFGrnMb.fq2?_rv_kts\u00B7608\u0026mqz;_qf_mrz\u00B78kd078\u0026wdj;_mw_gg\u00B7zhbcmdgb-nml3-9.cfnkflsntnxc.jbx\u0026qqf;_vs_wmm\u00B7DtCLQ3bgm-ZL9jXwzXLN2kX\u0026ffx;xlv\u00B7xzB9VG3qf6KkH6VwBgZ5HgdqVZrsnkSbHwR3c8F3Xxwsl0n3MCSqPkPqn7ngMsQxCXfpzdSgDV39JRNbFcFlKSQxC2wkHwrzlBqrBVLmgCkbkCZcB2DfL0QhlN4fRPN5QPZ4XxJ5MtJhLwdvGQZ2MGVbtQwqsxSdqhRrBVP9BmthVptfhJD1Z4Xmx2G7M5czZjt6CFLrMMB7HDD2MTD2XJQxJwKjc1R9D8QmPS4sSBthKtglGBtsTGD2tJ82p4JtMRVtB2xnCgtrHXwkCzplNCLdRPScx99tzgD7LLbmZmr6blQ8CWK5FlD7GTG9NPX9wktpJB6hd764vfFmXjlph2r6Tk8%2Z\u0026wkt;bjz\u00B739-8\u0026hcx;_zv_klp\u00B70V8ndm4BsRzTv4LT4MWJpw\u0026tpt;_hx_lt\u00B75fsgx\u0026chb;_fq_tn\u00B723\u0026bhg;ls\u00B742_SHGczhCzFRp5Nvrk2VpPffQ9QkQwNGHqlkG7cBPzsHHrqX\u0026djp;sd\u00B73QNLR7Q2\u00B7/VlfhDZR\u00B7\u00B7MlcvxhnDllb jtwvhFmtpcQptwp\u00B7\u0022fsln\u0022 qsvjmWknpc\u00B7\u0022737-351\u0022 DZXwcdwDjnlfrdLmxnd\u00B7\u0022887-144580\u0022 JZQwqjdTndwkngRgwmgbkx\u00B7\u00229653\u0022 MGSwctrghbGljmlqfCsfgb\u00B7\u0022062-392591\u0022 WTGfwtgsxnGvclxnvRmxgpplc\u00B7\u00225055\u0022\u00B7\u00B7Fmtgdrkcmmrmrv fbppn\u00B7\u00229-710\u0022/\u00B7\u00B7/PsrwkmlSlfw\u00B7\u00B7/Ngrgknqmkblkpl\u00B7\u00B7Zvqcjchcztfxdx zh\u00B7\u0022666047318082679m\u0022 gscxrrrxz\u00B7\u002250080\u0022 mjmhgx\u00B7\u0022xfx1.4t787g\u0022 wpwbDkjg\u00B7\u0022pzlfh/rq1\u0022 bjm\u00B7\u0022536:139\u0022 SQLqjvlkxvMkc\u00B7\u0022whgj_cpfrqhcd_5_n5\u0022 GNRqcbqkfPjcrrx\u00B7\u002237317\u0022 JRQpvmbgmkZgdjcdwsbwQxp\u00B7\u00224:656,651:61.2,275:70,786:13.2\u0022 VVXrmljbdhLrwchgjsjsZzxRsgggwzgfkMqwfj\u00B7\u0022zgmd\u0022 KNKddbwddbPnlwpjzfbvLlmqf\u00B7\u00224:530,971:07.5,097:38.7,285:46.6\u0022 DSCbmTlxgczPbbf\u00B7\u0022\u0022 rfrvw\u00B7\u0022094\u0022 xcwnmz\u00B7\u0022289\u0022 nlgngJjwn\u00B7\u002273760/418\u0022 PFMtbjxplMdnrj\u00B7\u0022wc\u0022 CZMndlnlzXmhnt\u00B7\u0022294l\u0022\u00B7\u00B7RtprJZQ\u00B7spknw://vmprdgtb-cvh4-9.ccmtfshfkcbw.zhw/s3/h/m22/j3/g82/KZZHsDth05NvXL5JgKqFvrn4V7mhChzkqLgxpq5Rkjp0lBVmcgsTqRxf8GqWrK2N9QxVsqSSw9Wt6k2q0KKZkhSSfP-Lm2r4vdl2FL9.pd8?_tr_hgl\u00B7217\u0026zdx;_hv_jlg\u00B73tz091\u0026vtd;_pm_tc\u00B7bhdzljjm-dml0-2.jjbhktwdwmrk.gdj\u0026zlc;_qm_nwk\u00B7rJ-9VVf8F3vD8sFxrSsZdMh\u0026knt;vtn\u00B7vqL7FG7pr8KzL4ZwLdD5RtsmFHcsxbJhBhP9z2H4Qvxzd1l6KBQfFlHbx8zwVmHsPNdlptSkRf45LDTvLwMbRMKtS5hwNlwbgRhnSCThjRrrsHJmV8KmL3RnxW7gPXK9QWT9NpK4MnLqHsmvSTS2LWKsvQtdzbHstmChFCC5XsvqBrpmvHQ2P9Djv0G6D3mnSfx7HQWrWVQ8FBQ4QJC2RVQlLjVcw8W9J0ZsVC5lVCwgQpqlXFxdSWR2qQ30s0SsXJDzM8xfZjwtVTlrKfbmPCMrSHNbt92bqvN5ZZjmMzl9ntK9BMZ7Tds4JhhbXsQgdWjrbx8dq1KpM3LfFvF4x5zwbH%7D%1K\u0026nmp;bzz\u00B762-0\u0026rqq;_zl_mdm\u00B79J0dch0NtMdWf5BT7XNDng\u0026zvt;_cz_wh\u00B71xtnf\u0026lgg;_qn_kf\u00B735\u0026pnc;zb\u00B734_PJWgPv8hBCWMDpZN2W8M2DV6NTZqVMgXP15g95Jx0qjsLm\u0026nnf;rq\u00B74PJPB5J8\u00B7/BrgnGCG\u00B7\u00B7WqzkppfDhtx vdgcdMpjnn\u00B7\u0022031-464\u0022 qpncssclq\u00B7\u002294893\u0022 JRKjwspmdKzhzvqdgJvsqx\u00B7\u0022779-76519\u0022 ZDFfphjKtmzhnqKndxp\u00B7\u0022787-34921\u0022 JDQxcwpNvqqwwcSgrxrzcb\u00B7\u00226974\u0022 NSRjvrjzpjKwgqrflQxhsw\u00B7\u0022725-70931\u0022 HQNjnmctswKqdhzglSxkdqlrl\u00B7\u00221843\u0022\u00B7\u00B7Mbxqhlgpsqjrsp vvnrc\u00B7\u00223-428\u0022/\u00B7\u00B7/XdxwztmGpxk\u00B7\u00B7/Lgmnbcsmvnfxtc\u00B7\u00B7/VcljpsfcgnWtb\u00B7\u00B7/Fnsgxc\Line truncated
|
||||
"video_versions": [
|
||||
{
|
||||
"type": 101,
|
||||
"url": "https://cdn.esempio/w6plz52z5749r9g8.mp4"
|
||||
},
|
||||
{
|
||||
"type": 102,
|
||||
"url": "https://cdn.esempio/w6plz52z5749r9g8.mp4"
|
||||
},
|
||||
{
|
||||
"type": 103,
|
||||
"url": "https://cdn.esempio/w6plz52z5749r9g8.mp4"
|
||||
}
|
||||
],
|
||||
"media_type": 2,
|
||||
"visual_comment_reply_sticker_info": null,
|
||||
"story_bloks_stickers": null,
|
||||
"story_hashtags": null,
|
||||
"story_locations": null,
|
||||
"text_post_share_to_ig_story_stickers": null,
|
||||
"story_countdowns": null,
|
||||
"story_questions": null,
|
||||
"story_sliders": null,
|
||||
"link": null,
|
||||
"reel_media_background": null,
|
||||
"video_duration": 5,
|
||||
"custom_list_info": null,
|
||||
"is_story_edited": false,
|
||||
"product_type": "story",
|
||||
"reshared_story_media_author": null,
|
||||
"story_app_attribution": null,
|
||||
"audience": null,
|
||||
"has_liked": false,
|
||||
"viewer_count": null,
|
||||
"viewers": [],
|
||||
"can_reshare": true,
|
||||
"user": {
|
||||
"pk": "215081405",
|
||||
"id": "215081405",
|
||||
"is_ai_user": null,
|
||||
"aigm_account_label_info": {
|
||||
"is_enabled": false
|
||||
},
|
||||
"instagram_pk": "215081405",
|
||||
"interop_messaging_user_fbid": "068866421413642"
|
||||
},
|
||||
"inventory_source": null,
|
||||
"carousel_media_count": null,
|
||||
"media_overlay_info": null,
|
||||
"caption": null,
|
||||
"accessibility_caption": null,
|
||||
"organic_tracking_token": "xxx7xxxxxx7xxxx7xxxxxxxxx7xxxxx7xxxxx7xxxxx7xxxxx777xxxxx7xxxxx7xxxxxxx7xxxxxxxxxxx7xxxxxxxxxxxxxx77xxxxxxxxxxxxxxx7xxx7xxxxxxx7xxx7xxxxxxx7xxx7xxx7xxx7xxxxxxxxxxxxxx77x7xxxxx7xxx7xxx7xxxxxxx7xxx7xxx7xxxxxxx7xxx7xxx7xxx7xxx7xxxxxxxxxxx7xxxxxxxxxxx7xxx7xxxxxxxxxxxxxxxxxxxxxxx7xxxxx7xxx7x7xxx7xxxxxxx7xxxxxxx7xxx7xxx7xxxxxxx7xxxxxxxxxxx7xxxxxxxxxx\u00B7\u00B7",
|
||||
"story_link_stickers": null,
|
||||
"story_bloks_tappables": null,
|
||||
"story_feed_media": null,
|
||||
"story_cta": null,
|
||||
"preview": null,
|
||||
"is_paid_partnership": false,
|
||||
"sponsor_tags": null,
|
||||
"wearable_attribution_info": null,
|
||||
"has_translation": false,
|
||||
"boosted_status": null,
|
||||
"can_see_insights_as_brand": false,
|
||||
"boost_unavailable_identifier": null,
|
||||
"boost_unavailable_reason": null,
|
||||
"can_viewer_reshare": null,
|
||||
"expiring_at": 1535702172,
|
||||
"ig_media_sharing_disabled": false,
|
||||
"sharing_friction_info": {
|
||||
"should_have_sharing_friction": false,
|
||||
"bloks_app_url": null
|
||||
},
|
||||
"can_reply": true,
|
||||
"__typename": "JGPZxtzzMglf"
|
||||
},
|
||||
{
|
||||
"pk": "0136776105441301518",
|
||||
"id": "1919041622766888881_764140925",
|
||||
"has_audio": null,
|
||||
"story_music_stickers": null,
|
||||
"ai_label_info": null,
|
||||
"carousel_media": null,
|
||||
"code": "Pf_jnh4jjGx",
|
||||
"image_versions2": {
|
||||
"candidates": [
|
||||
{
|
||||
"height": 1278,
|
||||
"url": "https://cdn.esempio/64277767bs4g22l3.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 1136,
|
||||
"url": "https://cdn.esempio/1l76q9n05v433q8z.jpg",
|
||||
"width": 640
|
||||
},
|
||||
{
|
||||
"height": 852,
|
||||
"url": "https://cdn.esempio/tv49354p66z3fb11.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 568,
|
||||
"url": "https://cdn.esempio/h4576h51s0k2qg8c.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 426,
|
||||
"url": "https://cdn.esempio/568w418p1jmzlxr9.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 720,
|
||||
"url": "https://cdn.esempio/8f89j8p2b9109j5t.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 720,
|
||||
"url": "https://cdn.esempio/8f89j8p2b9109j5t.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 640,
|
||||
"url": "https://cdn.esempio/q046570l2m6860j3.jpg",
|
||||
"width": 640
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/458xvr038d7nr57d.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 320,
|
||||
"url": "https://cdn.esempio/lmjkwb9v6qq0xnpc.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 240,
|
||||
"url": "https://cdn.esempio/785x3klnzc3l6240.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 150,
|
||||
"url": "https://cdn.esempio/p8018t8149r793v6.jpg",
|
||||
"width": 150
|
||||
}
|
||||
]
|
||||
},
|
||||
"original_width": 720,
|
||||
"original_height": 1278,
|
||||
"taken_at": 1537547068,
|
||||
"is_dash_eligible": null,
|
||||
"number_of_qualities": null,
|
||||
"video_dash_manifest": null,
|
||||
"video_versions": null,
|
||||
"media_type": 1,
|
||||
"visual_comment_reply_sticker_info": null,
|
||||
"story_bloks_stickers": null,
|
||||
"story_hashtags": null,
|
||||
"story_locations": [
|
||||
{
|
||||
"x": 0.5,
|
||||
"y": 9.78327953178594,
|
||||
"width": 0.875,
|
||||
"height": 0.097790492957746,
|
||||
"rotation": 0,
|
||||
"location": {
|
||||
"pk": 348843475
|
||||
},
|
||||
"id": "08921590880713343"
|
||||
}
|
||||
],
|
||||
"text_post_share_to_ig_story_stickers": null,
|
||||
"story_countdowns": null,
|
||||
"story_questions": null,
|
||||
"story_sliders": null,
|
||||
"link": null,
|
||||
"reel_media_background": null,
|
||||
"video_duration": null,
|
||||
"custom_list_info": null,
|
||||
"is_story_edited": false,
|
||||
"product_type": "story",
|
||||
"reshared_story_media_author": null,
|
||||
"story_app_attribution": null,
|
||||
"audience": null,
|
||||
"has_liked": false,
|
||||
"viewer_count": null,
|
||||
"viewers": [],
|
||||
"can_reshare": true,
|
||||
"user": {
|
||||
"pk": "215081405",
|
||||
"id": "215081405",
|
||||
"is_ai_user": null,
|
||||
"aigm_account_label_info": {
|
||||
"is_enabled": false
|
||||
},
|
||||
"instagram_pk": "215081405",
|
||||
"interop_messaging_user_fbid": "068866421413642"
|
||||
},
|
||||
"inventory_source": null,
|
||||
"carousel_media_count": null,
|
||||
"media_overlay_info": null,
|
||||
"caption": null,
|
||||
"accessibility_caption": null,
|
||||
"organic_tracking_token": "xxx7xxxxxx7xxxx7xxxxxxxxx7xxxxx7xxxxx7xxxxx7xxxxx777xxxxx7xxxxx7xxxxxxx7xxxxxxxxxxx7xxxxxxxxxxxxxx77xxxxxxxxxxxxxxx7xxx7xxxxxxx7xxx7xxxxxxx7xxx7xxx7xxx7xxxxxxxxxxxxxx77x7xxxxx7xxx7xxx7xxxxxxx7xxx7xxx7xxxxxxx7xxx7xxx7xxx7xxx7xxxxxxxxxxx7xxx7xxxxxxx7xxxxxxxxxxx7xxxxxxxxxxxxxxx7xxx7xxx7xxxxxxxxx7x7xxxxxxx7xxxxxxx7xxxxxxx7xxx7xxxxxxxxxxx7xxxxxxxxxx\u00B7\u00B7",
|
||||
"story_link_stickers": null,
|
||||
"story_bloks_tappables": null,
|
||||
"story_feed_media": null,
|
||||
"story_cta": null,
|
||||
"preview": null,
|
||||
"is_paid_partnership": false,
|
||||
"sponsor_tags": null,
|
||||
"wearable_attribution_info": null,
|
||||
"has_translation": false,
|
||||
"boosted_status": null,
|
||||
"can_see_insights_as_brand": false,
|
||||
"boost_unavailable_identifier": null,
|
||||
"boost_unavailable_reason": null,
|
||||
"can_viewer_reshare": null,
|
||||
"expiring_at": 1537633468,
|
||||
"ig_media_sharing_disabled": false,
|
||||
"sharing_friction_info": {
|
||||
"should_have_sharing_friction": false,
|
||||
"bloks_app_url": null
|
||||
},
|
||||
"can_reply": true,
|
||||
"__typename": "JGPZxtzzMglf"
|
||||
},
|
||||
{
|
||||
"pk": "3134868844340144332",
|
||||
"id": "7652716589938419222_411682419",
|
||||
"has_audio": true,
|
||||
"story_music_stickers": null,
|
||||
"ai_label_info": null,
|
||||
"carousel_media": null,
|
||||
"code": "G-NPTmQzpkD",
|
||||
"image_versions2": {
|
||||
"candidates": [
|
||||
{
|
||||
"height": 916,
|
||||
"url": "https://cdn.esempio/fs6632cb872701wc.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 611,
|
||||
"url": "https://cdn.esempio/b5244m81x5d26316.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 458,
|
||||
"url": "https://cdn.esempio/p41f04n0vt13070h.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/65912pv25ms50257.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/65912pv25ms50257.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/65912pv25ms50257.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/65912pv25ms50257.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 320,
|
||||
"url": "https://cdn.esempio/n246l4s386791637.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 240,
|
||||
"url": "https://cdn.esempio/r7010z76j203fm48.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 150,
|
||||
"url": "https://cdn.esempio/p20352l4w88k9715.jpg",
|
||||
"width": 150
|
||||
}
|
||||
]
|
||||
},
|
||||
"original_width": 480,
|
||||
"original_height": 916,
|
||||
"taken_at": 1585040589,
|
||||
"is_dash_eligible": 1,
|
||||
"number_of_qualities": 2,
|
||||
"video_dash_manifest": "\u00B7?tdn rjmxjmk\u00B7\u00225.8\u0022?\u00B7\n\u00B7RPJ mfzdh\u00B7\u0022rgh:qrhp:szsl:bdspdk:wll:1069\u0022 rvkKgkznjHkpq\u00B7\u0022KR9.413B\u0022 tpvl\u00B7\u0022gltczb\u0022 frvmtQnmxpgxmmwfbWgcbdmhv\u00B7\u0022FQ6W8B9.433T\u0022 jpvWxlhhshXkmtwhdk\u00B7\u0022HR9L9S8.805C\u0022 dltcmrdt\u00B7\u0022kzq:dvjf:lkpx:bngkmjb:wbzjb-dc-wwztzh:7351,qzdw://bgvkrp.dbd/pmdhkrfvss/jpkl074\u0022 BVKnhnbnqqDdmvhkjpg\u00B7\u00226467737323\u0022 PJQqgwkgrlFcjprltgkn\u00B7\u0022Fs7gr87DHWCsS96rBLGnT3Skv3PwvK6dLJl5dbxP2/0SNKLx2/8mxt8Djqlkb2Gf/DXqBFDlFQQfG7Ncq9SmvD9nJ2V3LDbbVsqSTHcsdKWwGZ3ndWmpnKMDmDHTBCPXBQbDBm1QX4KNKRQHMDTNNPKL\u0022\u00B7\u00B7Bxkvcr dmppbgwb\u00B7\u0022GJ2D4B8.614P\u0022\u00B7\u00B7MbwnfglwxgLmz cmdqqmrTxkjrmkjv\u00B7\u0022pfzd\u0022 ttjSjbbf\u00B7\u0022426\u0022 fjgQpksll\u00B7\u0022586\u0022 hqsDjnjbNqgg\u00B7\u002279\u0022 swd\u00B7\u002233:94\u0022 qrfz\u00B7\u0022rkh\u0022 nnhtsdkzmfVftwmmwbw\u00B7\u0022khtp\u0022 vvjfbrshnrWhqscqHnccVJS\u00B7\u00221\u0022 nk\u00B7\u00221\u0022\u00B7\u00B7Klvxfjdpgmkcbm nf\u00B7\u00222105064258901257c\u0022 bjfpTfmh\u00B7\u0022mnmgp/xx2\u0022 drjhtt\u00B7\u0022mbv3.34S28P\u0022 xmnfx\u00B7\u0022015\u0022 dnrjpl\u00B7\u0022783\u0022 svvnbWbgr\u00B7\u002290\u0022 pzn\u00B7\u00225:0\u0022 cshnzKjbcNTH\u00B7\u00224\u0022 htkdvtxss\u00B7\u0022535086\u0022 TXPpnsrrttRdh\u00B7\u0022phjf_mtjggqnp_9_t9\u0022 TQFsjbkdsDjfzmc\u00B7\u0022682788\u0022 WBTfxqfdsNdpfd\u00B7\u0022tr\u0022 QHZvvdrzqZrzlt\u00B7\u0022388c\u0022\u00B7\u00B7BzkpHTX\u00B7ptzrd://djtpgnnr-gdm7-5.chqjnggtxcnw.hbz/t6/n/g77/v0/s85/LNFcTLDTPwFs5rG45zQ5GcpTbPW51VgxS-gxLbBrX7Lp1_ZBpHqw1f1jkk7FVH68Kt05rqw71q5tDxmLK0dPK_MlpwGWDfRxDktFw4j.pc0?_fg_fvr\u00B7091\u0026bmt;_vr_dln\u00B70kq244\u0026npf;_pf_qj\u00B7nxxhgmjb-dgx1-4.vcjhbjhtqdzf.ncv\u0026zkx;_tg_kwp\u00B74zJPs9rxLb7H7jTqsLRtxCD\u0026rrl;jwr\u00B7skR7CK9xh7FmL4ZjJgZ8JcswKFsdsbXhRxC2v8T2Xnkvd4h8LSLlWdQdb6llSfFvDPtbzdKqCS36RXCtDdRcXMTrW7rgLlzbgHjwGSRjgLbfnTXwM6HmT3SrdT7qWJP9HLT9QxG6ZdNxKcllJQD7WCSmsQdstzWzrqTgTWZ9GpmcFmdltBX7S2Rrb3N0T1gbLbbjJTS5JgPcSNxlRKW1FDB7VJXrj3MlpL8zR1PxXXR2tsT6ZnClGtpwlwtlpSXzF9PtSH4jHPV6GFStSMFdPvZ0dmR5gN1vD1JlDjCmJpTtlZKprWTbZzN0FCCsCWxhzXCrH4LxR9MvkJHwLDF7Gsm4jnC5\u0026bcw;gxx\u00B721-3\u0026chn;_lt_rxw\u00B79C2pdx6LfVwGh9LB9KDJdl\u0026lzm;_jl_ql\u00B79mrrb\u0026xbh;_jk_ws\u00B775\u0026rqd;mt\u00B743_LXLnvSpHs_MGXGZtM6P_RZ3f3DJVBvwjDkKn0j9sSQM3KS\u0026dsx;kz\u00B75LFCZH01\u00B7/PshwFDJ\u00B7\u00B7PljvwwlKxmh xmgssFmqtxKtswx\u00B7\u0022cstc\u0022 cjmzhNzkrl\u00B7\u0022760-044\u0022 ZXDksrdZbgdnmnHpcvz\u00B7\u0022675-807615\u0022 DFKrwnnFdrcgdjPzslkxlv\u00B7\u00225006\u0022 VGQpmtnkjcSghrjssGttpl\u00B7\u0022707-284425\u0022 CGZxgqfzkqSkxvlbjKmjzrsjk\u00B7\u00225995\u0022\u00B7\u00B7Zdlpbbqjtddvbg kqzhj\u00B7\u00223-022\u0022/\u00B7\u00B7/HxjhswmXlsw\u00B7\u00B7/Dmkhtdjvmngqqg\u00B7\u00B7Hgvgkntcpkcgkh ww\u00B7\u00223087880308574554p\u0022 rqtpsnxbh\u00B7\u0022793589\u0022 fbzqqw\u00B7\u0022lzb3.3h343v\u0022 hgppCzjz\u00B7\u0022vbhhh/ql9\u0022 ssp\u00B7\u00226:6\u0022 QQRlrvxmndPjp\u00B7\u0022pzsj_qlvsscnr_7_c8\u0022 GFVgrlhtbLbmvkg\u00B7\u0022692823\u0022 DGKtwshdvjJjtvhhstbzWgk\u00B7\u00228:856,840:89.5,372:06.2,171:03.2\u0022 NJXksjglbzVbphmkfgkdRlvCqprcdlxlxWbptk\u00B7\u0022tvpb\u0022 KDZkdktghlKxshktthrjCsfmh\u00B7\u00221:122,024:36.6,698:71.9,996:34.4,334:39.9\u0022 zpxbk\u00B7\u0022208\u0022 kgzpwj\u00B7\u0022751\u0022 bbzmnRcbf\u00B7\u002243632/639\u0022 TLGlmkljzHslsm\u00B7\u0022pn\u0022 TNZcdvtncBbntg\u00B7\u0022249m\u0022\u00B7\u00B7HpccTXS\u00B7vdctg://qdbdqbfr-gls5-9.wptvrlzzwrdq.xhr/f4/d/g09/l5/m45/TQWbq6b-TbVwMtc2T7fdQq0gCPhvTw-HHRbBGTwPF6QCNRSS8cBkmsZs7bJ4Rbd9tDbhthVPZ0fGBRhfTCwXJdQcM6LsTvhPNtwWQcC.hm3?_mn_cdz\u00B7262\u0026nfj;_gh_xxg\u00B73th305\u0026cpl;_gj_nj\u00B7wzgkczvp-htk6-2.dhsxnxbbvrgx.jrx\u0026ndz;_ld_qts\u00B7S0S6pQvmrsJS8mPjmRwr3Pk\u0026wqf;wkl\u00B7ncD2MS8qc8RlT9VfGvD2GbkqTGlgmdZvNrL4r3P7Qmqgg2g4DDKdSpJtd1wvQgDcRCdkbzTkQc59HLTsKzXkZPSbL3hgJvpdzWtrGGMkgLdxgDKqR0JvD9WwbD2nLTC7RBX1QkX4JlRpDqlzQNX6RHPzcCjcjsDsltGnTKR4CwddKrxdkSH7X2Vvc3R8L7qlWgmkMTD1QnLfXNpnXSP3ZCB0HQZks8BbgM0tL4ZmBGW5xxV1NgThXwqgwlwsxKKpB6MkQW1tNDH8GXCzTKJhXcZ1qsD6dQ9cJ5KxLbCjVmZcmQJcgPVfLfJzQFDzKMbmgFGgW6QbC5DcmRHgVBJ2Dpj9ckQ8\u0026mkw;rdf\u00B749-5\u0026mhg;_wk_bdg\u00B74J7hdl2WnBxJl2JJ5NPWmt\u0026zvk;_lp_qv\u00B78bmwr\u0026nps;_lp_fh\u00B786\u0026jxf;nj\u00B735_NFP0BKLchBzPn1jtBGHkSMpN-dflLnZgVfjfW7Xm_sbBjb\u0026mmc;lj\u00B76XQGV2N8\u00B7/MqwgKTB\u00B7\u00B7XphkckcQldx kqtrmHhwkx\u00B7\u0022107-805\u0022 hrfknnnxx\u00B7\u002234837\u0022 SKLzqgxchJpxbmflwGhgjb\u00B7\u0022859-42393\u0022 NBGlwkfKzdfhlqXsslg\u00B7\u0022538-083992\u0022 LSGpkhpQmdpmqqRwljmfgw\u00B7\u00228653\u0022 HHBhxxzxftXclxhktNsdxg\u00B7\u0022602-948251\u0022 RQDrchdbdsSxjwkgsNgrskjpz\u00B7\u00224931\u0022\u00B7\u00B7Rmhlcfxvznqjsb wbdjc\u00B7\u00223-460\u0022/\u00B7\u00B7/MdthlrsFlhg\u00B7\u00B7/Xxpndlrwkszvnj\u00B7\u00B7/DvfzgjfshsHrg\u00B7\u00B7ShfdrnhlnwSnh pdjkrcrGkfsgdmbm\u00B7\u0022ddpq\u0022 pkdqqqngkdFxntwmcch\u00B7\Line truncated
|
||||
"video_versions": [
|
||||
{
|
||||
"type": 101,
|
||||
"url": "https://cdn.esempio/q81g83s37b162509.mp4"
|
||||
},
|
||||
{
|
||||
"type": 102,
|
||||
"url": "https://cdn.esempio/q81g83s37b162509.mp4"
|
||||
},
|
||||
{
|
||||
"type": 103,
|
||||
"url": "https://cdn.esempio/q81g83s37b162509.mp4"
|
||||
}
|
||||
],
|
||||
"media_type": 2,
|
||||
"visual_comment_reply_sticker_info": null,
|
||||
"story_bloks_stickers": [
|
||||
{
|
||||
"x": 6.0729408,
|
||||
"y": 5.1558897,
|
||||
"width": 0.15614899,
|
||||
"height": 0.01749242,
|
||||
"rotation": -4.0158431704,
|
||||
"bloks_sticker": {
|
||||
"sticker_data": {
|
||||
"ig_mention": {
|
||||
"full_name": "Jkft",
|
||||
"username": "ltgb_llltjlq"
|
||||
}
|
||||
},
|
||||
"id": "dxtrs_nzwbbld_pf"
|
||||
},
|
||||
"id": "77352604007748140"
|
||||
},
|
||||
{
|
||||
"x": 0.2172182,
|
||||
"y": 4.0015787,
|
||||
"width": 0.10810314,
|
||||
"height": 0.01749242,
|
||||
"rotation": -4.0158431704,
|
||||
"bloks_sticker": {
|
||||
"sticker_data": {
|
||||
"ig_mention": {
|
||||
"full_name": "Qlhxtpjrt Fdkxddh",
|
||||
"username": "pvcbbkcm"
|
||||
}
|
||||
},
|
||||
"id": "dxtrs_nzwbbld_pf"
|
||||
},
|
||||
"id": "84808036527115787"
|
||||
},
|
||||
{
|
||||
"x": 3.9762111,
|
||||
"y": 8.20447074,
|
||||
"width": 0.15614899,
|
||||
"height": 0.01749242,
|
||||
"rotation": -4.0158431704,
|
||||
"bloks_sticker": {
|
||||
"sticker_data": {
|
||||
"ig_mention": {
|
||||
"full_name": "Bwxrlz Fktpv",
|
||||
"username": "vqkkjw_xlpmd"
|
||||
}
|
||||
},
|
||||
"id": "dxtrs_nzwbbld_pf"
|
||||
},
|
||||
"id": "59768694316706370"
|
||||
},
|
||||
{
|
||||
"x": 0.505518,
|
||||
"y": 9.11380160,
|
||||
"width": 0.14413752,
|
||||
"height": 0.01749242,
|
||||
"rotation": -4.0158431704,
|
||||
"bloks_sticker": {
|
||||
"sticker_data": {
|
||||
"ig_mention": {
|
||||
"full_name": "Gdwjmhmqf Hbvkbkff",
|
||||
"username": "dxvmxzdcwrv"
|
||||
}
|
||||
},
|
||||
"id": "dxtrs_nzwbbld_pf"
|
||||
},
|
||||
"id": "79509364456252542"
|
||||
},
|
||||
{
|
||||
"x": 0.3920282,
|
||||
"y": 9.52808700,
|
||||
"width": 0.19218336,
|
||||
"height": 0.01749242,
|
||||
"rotation": -4.0158431704,
|
||||
"bloks_sticker": {
|
||||
"sticker_data": {
|
||||
"ig_mention": {
|
||||
"full_name": "Rtdrq ZvpBksknl",
|
||||
"username": "mtdqqpdwvndhnbv"
|
||||
}
|
||||
},
|
||||
"id": "dxtrs_nzwbbld_pf"
|
||||
},
|
||||
"id": "20963016712538816"
|
||||
}
|
||||
],
|
||||
"story_hashtags": null,
|
||||
"story_locations": null,
|
||||
"text_post_share_to_ig_story_stickers": null,
|
||||
"story_countdowns": null,
|
||||
"story_questions": null,
|
||||
"story_sliders": null,
|
||||
"link": null,
|
||||
"reel_media_background": null,
|
||||
"video_duration": 6.06,
|
||||
"custom_list_info": null,
|
||||
"is_story_edited": false,
|
||||
"product_type": "story",
|
||||
"reshared_story_media_author": null,
|
||||
"story_app_attribution": null,
|
||||
"audience": null,
|
||||
"has_liked": false,
|
||||
"viewer_count": null,
|
||||
"viewers": [],
|
||||
"can_reshare": true,
|
||||
"user": {
|
||||
"pk": "215081405",
|
||||
"id": "215081405",
|
||||
"is_ai_user": null,
|
||||
"aigm_account_label_info": {
|
||||
"is_enabled": false
|
||||
},
|
||||
"instagram_pk": "215081405",
|
||||
"interop_messaging_user_fbid": "068866421413642"
|
||||
},
|
||||
"inventory_source": null,
|
||||
"carousel_media_count": null,
|
||||
"media_overlay_info": null,
|
||||
"caption": null,
|
||||
"accessibility_caption": null,
|
||||
"organic_tracking_token": "xxx7xxxxxx7xxxx7xxxxxxxxx7xxxxx7xxxxx7xxxxx7xxxxx777xxxxx7xxxxx7xxxxxxx7xxxxxxxxxxx7xxxxxxxxxxxxxx77xxxxxxxxxxxxxxx7xxx7xxxxxxx7xxx7xxxxxxxxxxx7xxxxxxxxxxxxxxxxxxxxxx77x7xxxxx7xxx7xxx7xxxxxxx7xxx7xxx7xxxxxxxxxxx7xxxxxxxxxxx7xxxxxxxxxxx7xxxxxxx7x7xxxxxxxxxxxxx7xxx7xxxxxxx7xxxxxxxxx7x7xxxxxxx7xxx7xxx7x7x7xxxxxxxxxxxxxxx7xxx7xxxxxxxxxxx7xxxxxxxxxx\u00B7\u00B7",
|
||||
"story_link_stickers": null,
|
||||
"story_bloks_tappables": null,
|
||||
"story_feed_media": null,
|
||||
"story_cta": null,
|
||||
"preview": null,
|
||||
"is_paid_partnership": false,
|
||||
"sponsor_tags": null,
|
||||
"wearable_attribution_info": null,
|
||||
"has_translation": false,
|
||||
"boosted_status": null,
|
||||
"can_see_insights_as_brand": false,
|
||||
"boost_unavailable_identifier": null,
|
||||
"boost_unavailable_reason": null,
|
||||
"can_viewer_reshare": null,
|
||||
"expiring_at": 1585126989,
|
||||
"ig_media_sharing_disabled": false,
|
||||
"sharing_friction_info": {
|
||||
"should_have_sharing_friction": false,
|
||||
"bloks_app_url": null
|
||||
},
|
||||
"can_reply": true,
|
||||
"__typename": "JGPZxtzzMglf"
|
||||
}
|
||||
],
|
||||
"unviewable_authors_infos": [],
|
||||
"user": {
|
||||
"__typename": "KGTWcdxBfxp",
|
||||
"pk": "215081405",
|
||||
"id": "215081405",
|
||||
"interop_messaging_user_fbid": "068866421413642",
|
||||
"username": "dwvqbrgcjf",
|
||||
"profile_pic_url": "https://cdn.esempio/w8282f33028f3207.jpg",
|
||||
"is_private": false,
|
||||
"user_id": "215081405",
|
||||
"is_verified": false,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_auto_detected": false,
|
||||
"is_enabled": false,
|
||||
"is_manually_enabled": false
|
||||
},
|
||||
"transparency_label": null,
|
||||
"transparency_product": null,
|
||||
"transparency_product_enabled": false
|
||||
},
|
||||
"seen": null,
|
||||
"reel_type": "highlight_reel",
|
||||
"cover_media": {
|
||||
"cropped_image_version": {
|
||||
"url": "https://cdn.esempio/149tj2dp394sl651.jpg"
|
||||
},
|
||||
"full_image_version": null
|
||||
},
|
||||
"title": "Ggwgm \u00B7\u00B7",
|
||||
"can_reshare": true,
|
||||
"latest_reel_media": 1772734155,
|
||||
"muted": null,
|
||||
"__typename": "DWVDlmdMnfr"
|
||||
},
|
||||
"cursor": null
|
||||
}
|
||||
],
|
||||
"page_info": {
|
||||
"end_cursor": "vjbwtfskq:72329892632403300",
|
||||
"has_next_page": true,
|
||||
"has_previous_page": true,
|
||||
"start_cursor": "mtmlprbdv:62008803167428297"
|
||||
}
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"server_metadata": {
|
||||
"request_start_time_ms": 5400924782018,
|
||||
"time_at_flush_ms": 9344386158027
|
||||
},
|
||||
"is_final": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/vgw3tpjgl1868811",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "text/javascript",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:39:03Z"
|
||||
},
|
||||
"corpo": {
|
||||
"data": {
|
||||
"xdt_mark_story_reel_seen": {
|
||||
"__typename": "HZKNvqbMqjwNgsxngwm"
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"server_metadata": {
|
||||
"request_start_time_ms": 9970054667900,
|
||||
"time_at_flush_ms": 1713075827507
|
||||
},
|
||||
"is_final": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
# Campioni ripuliti di Instagram
|
||||
|
||||
Risposte **reali** di Instagram, ripulite. Servono alle prove dei lettori di Instagram
|
||||
(`tests/Febe.Tests/Collection/InstagramReaderTests.cs`) e al controllo dei campioni del repository
|
||||
(`SanitizerTests`), e sono la fonte di `src/Febe.Core/Config/lettori.instagram.json` (regola 9: i lettori si
|
||||
scrivono solo su campioni reali ripuliti).
|
||||
|
||||
## Da dove vengono
|
||||
|
||||
Da un file HAR esportato da Alberto dal suo browser il **21 ottobre 2026**, mentre navigava a mano su Instagram con
|
||||
l'accesso fatto. Il pannello Rete era filtrato su **Fetch/XHR**: nel file ci sono solo le risposte che la pagina ha
|
||||
chiesto da sé, nessun documento, nessuna immagine, nessuno script (per questo i bersagli e i dati incorporati nelle
|
||||
pagine mancano: `docs/prove-dal-vivo.md`, parte A bis).
|
||||
|
||||
Il percorso è quello di specifica §14.5:
|
||||
|
||||
1. campioni grezzi scritti **fuori dal repository**, nel formato della sonda (descrittore + corpo), con le sole
|
||||
risposte che interessano; i corpi più lunghi sono stati accorciati **sul lato grezzo**, prima della ripulitura,
|
||||
tenendo l'ordine e le chiavi originali:
|
||||
- pagina delle raccolte in evidenza: 2 raccolte × 4 contenuti, scelti in modo da avere una foto, un video con
|
||||
l'audio e un video senza;
|
||||
- pagina successiva delle raccolte: 1 raccolta × 3 contenuti;
|
||||
- profili suggeriti: i primi 3;
|
||||
- tutte le altre risposte intere;
|
||||
2. ripulitura, in una sola esecuzione per tutti i file (i valori finti cambiano a ogni esecuzione):
|
||||
`febe-sonda ripulisci --da <grezzi> --a tests/Febe.Tests/campioni/instagram`;
|
||||
3. verifica: `febe-sonda verifica --grezzi <grezzi> --ripuliti tests/Febe.Tests/campioni/instagram` →
|
||||
«Verifica superata».
|
||||
|
||||
Da un nuovo file HAR i grezzi si ricavano con `febe-sonda da-har` (stesso formato, stessi nomi dei file), poi si
|
||||
procede dal punto 2.
|
||||
|
||||
## Che cosa resta e che cosa no
|
||||
|
||||
Struttura, chiavi, booleani, `null`, dimensioni, durate, conteggi, codici di tipo e date restano come sono (elenco
|
||||
`tools/Febe.Sonda/ripulitura.json`). Nomi, didascalie, identificativi, cursori e indirizzi sono valori finti della
|
||||
stessa forma: valori uguali hanno lo stesso valore finto in tutti i file, quindi i collegamenti fra le risposte
|
||||
restano. Gli indirizzi diventano `https://sito.esempio/…` o `https://cdn.esempio/…` con la sola estensione del file.
|
||||
I valori sotto chiavi che sembrano chiavi segrete (`organic_tracking_token`, `rank_token` e simili) sono un
|
||||
riempitivo neutro di `x` e `7` della stessa forma, perché gitleaks non li scambi per segreti. Le prove controllano
|
||||
forme, dimensioni, date e conteggi, mai i valori.
|
||||
|
||||
## I file
|
||||
|
||||
| File | Operazione o indirizzo | Tipo | Che cosa contiene |
|
||||
|---|---|---|---|
|
||||
| `000001-promozioni` | `QuickPromotionSupportIGSchemaBatchFetchQuery` | `text/javascript` | promozioni dell'interfaccia: nessun contenuto né profilo (risposta estranea, ignorata) |
|
||||
| `000002-ricerca-profili` | `PolarisSearchBoxRefetchableQuery` | `text/javascript` | profili trovati dalla casella di ricerca (5) |
|
||||
| `000003-profili-suggeriti` | `PolarisProfileSuggestedUsersWithPreloadableQuery` | `text/javascript` | profili suggeriti, non seguiti (i primi 3) |
|
||||
| `000004-commenti` | `/api/v1/media/…/comments/` | `application/json` | commenti di un post, con la didascalia |
|
||||
| `000005-post-video` | `/api/v1/media/…/info/` | `application/json` | un post video (reel) con autore, didascalia e versioni |
|
||||
| `000006-raccolta-in-evidenza` | `PolarisStoriesV3HighlightsPageQuery` | `text/javascript` | pagina delle raccolte in evidenza (2 × 4) e l'account collegato, con il solo identificativo |
|
||||
| `000007-raccolta-pagina-successiva` | `PolarisStoriesV3HighlightsPagePaginationQuery` | `text/javascript` | pagina successiva delle raccolte (1 × 3) |
|
||||
| `000008-storia-vista` | `PolarisStoriesV3SeenMutation` | `text/javascript` | la pagina segna una storia come vista: nessun dato (risposta estranea, ignorata) |
|
||||
|
||||
Le operazioni GraphQL (le righe con un nome) arrivano con il tipo `text/javascript`, non `application/json`: la
|
||||
cattura le legge lo stesso (`src/Febe.Core/Collection/DataResponses.cs`).
|
||||
@@ -0,0 +1,365 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
|
||||
namespace Febe.Sonda;
|
||||
|
||||
/// <summary>What a HAR conversion did: counts only, never a value.</summary>
|
||||
/// <param name="Entries">Entries of the HAR.</param>
|
||||
/// <param name="DataResponses">Site answers written because their body is data (<see cref="DataResponses.IsData"/>).</param>
|
||||
/// <param name="Documents">Page documents that embed JSON: each of their blocks is written as a sample of its own.</param>
|
||||
/// <param name="DocumentBlocks">Samples written from page documents: one per JSON block they embed, the way Febe's capture
|
||||
/// hands the blocks to the readers.</param>
|
||||
/// <param name="OtherHosts">Left out: not an answer of the site (CDN, other sites).</param>
|
||||
/// <param name="NotData">Left out: files, images, scripts, styles, or a type or status that is not data.</param>
|
||||
/// <param name="WithoutBody">Left out: the HAR does not hold the body.</param>
|
||||
/// <param name="NotJson">Left out: a body that is not valid JSON (for example one that starts with <c>for (;;);</c>).</param>
|
||||
/// <param name="DocumentsWithoutData">Left out: page documents that embed no JSON.</param>
|
||||
public sealed record HarImportReport(int Entries, int DataResponses, int Documents, int DocumentBlocks, int OtherHosts, int NotData, int WithoutBody, int NotJson, int DocumentsWithoutData)
|
||||
{
|
||||
public int Written => DataResponses + DocumentBlocks;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a HAR exported from the browser's DevTools (Chrome, Edge) into the probe's RAW format (spec §14.5), so that
|
||||
/// <c>ripulisci</c> and <c>verifica</c> work on it as on a recording of the probe: flat files <c>NNNNNN-<kind>.json</c>,
|
||||
/// each <c>{"descrittore":{indirizzo, host, stato, tipo, risorsa, quando}, "corpo": <body>}</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It keeps what Febe's own capture keeps (<c>ResponseTap</c>), in the same pieces: site answers whose body is data, and
|
||||
/// the JSON blocks embedded in page documents, one sample per block with the document's descriptor
|
||||
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>). Everything else is left out. Headers, cookies, query strings and
|
||||
/// request bodies are never copied: the address keeps scheme, host and path only, and of the request body only the
|
||||
/// GraphQL operation name is read, to name the file, when it has the shape of a name in the site's code (never a path:
|
||||
/// paths contain user names).
|
||||
/// The output is still RAW (bodies hold other people's data): it must stay outside any repository.
|
||||
/// </remarks>
|
||||
public static partial class HarImporter
|
||||
{
|
||||
/// <summary>Request parameter that names the GraphQL operation of a POST (a fixed name in the site's code).</summary>
|
||||
public const string OperationParameter = "fb_api_req_friendly_name";
|
||||
|
||||
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 };
|
||||
|
||||
/// <summary>Converts <paramref name="harPath"/> into the new, empty folder <paramref name="rawFolder"/>.</summary>
|
||||
/// <exception cref="InvalidOperationException">A folder is inside a git repository, or the output folder is not empty.</exception>
|
||||
/// <exception cref="InvalidDataException">The file is not a HAR.</exception>
|
||||
public static HarImportReport Import(string harPath, string rawFolder, HostClassifier? hosts = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(harPath);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(rawFolder);
|
||||
hosts ??= HostClassifier.Instagram;
|
||||
var har = Path.GetFullPath(harPath);
|
||||
if (!File.Exists(har))
|
||||
{
|
||||
throw new FileNotFoundException($"Il file HAR non esiste: {har}", har);
|
||||
}
|
||||
|
||||
// The HAR holds cookies and other people's data, and so does the output: neither belongs in a repository.
|
||||
RepositoryGuard.EnsureOutside(Path.GetDirectoryName(har)!);
|
||||
var folder = Path.GetFullPath(rawFolder);
|
||||
RepositoryGuard.EnsureOutside(folder);
|
||||
if (Directory.Exists(folder) && Directory.EnumerateFileSystemEntries(folder).Any())
|
||||
{
|
||||
throw new InvalidOperationException($"La cartella «{folder}» non è vuota: indica una cartella nuova, solo per questa conversione.");
|
||||
}
|
||||
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
using var stream = File.OpenRead(har);
|
||||
document = JsonDocument.Parse(stream);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR valido (riga {ex.LineNumber + 1}).", ex);
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
if (document.RootElement.ValueKind != JsonValueKind.Object
|
||||
|| !document.RootElement.TryGetProperty("log", out var log) || log.ValueKind != JsonValueKind.Object
|
||||
|| !log.TryGetProperty("entries", out var entries) || entries.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR (manca «log.entries»).");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(folder);
|
||||
File.WriteAllText(
|
||||
Path.Combine(folder, "LEGGIMI.txt"),
|
||||
"Campioni GREZZI convertiti da un file HAR con «febe-sonda da-har»: contengono dati personali di Alberto e di altre persone.\n"
|
||||
+ "Non vanno nel repository e non si inviano: si ripuliscono con «febe-sonda ripulisci», si controllano con «febe-sonda verifica»\n"
|
||||
+ "e si cancellano, insieme al file HAR, quando lettori e mappa sono scritti (specifica §14.5).\n");
|
||||
|
||||
int count = 0, written = 0, data = 0, documents = 0, blocks = 0, otherHosts = 0, notData = 0, withoutBody = 0, notJson = 0, documentsWithoutData = 0;
|
||||
foreach (var entry in entries.EnumerateArray())
|
||||
{
|
||||
count++;
|
||||
var outcome = ConvertEntry(entry, hosts, out var sample);
|
||||
if (sample is not null)
|
||||
{
|
||||
// One block at a time: each is written and disposed before the next one is parsed.
|
||||
var bodies = 0;
|
||||
foreach (var body in sample.Bodies)
|
||||
{
|
||||
using (body)
|
||||
{
|
||||
written++;
|
||||
Write(Path.Combine(folder, $"{written.ToString("000000", CultureInfo.InvariantCulture)}-{sample.Kind}.json"), sample, body);
|
||||
}
|
||||
|
||||
bodies++;
|
||||
}
|
||||
|
||||
if (outcome == EntryOutcome.Document)
|
||||
{
|
||||
blocks += bodies;
|
||||
outcome = bodies > 0 ? EntryOutcome.Document : EntryOutcome.DocumentWithoutData;
|
||||
}
|
||||
}
|
||||
|
||||
switch (outcome)
|
||||
{
|
||||
case EntryOutcome.Data:
|
||||
data++;
|
||||
break;
|
||||
case EntryOutcome.Document:
|
||||
documents++;
|
||||
break;
|
||||
case EntryOutcome.OtherHost:
|
||||
otherHosts++;
|
||||
break;
|
||||
case EntryOutcome.WithoutBody:
|
||||
withoutBody++;
|
||||
break;
|
||||
case EntryOutcome.NotJson:
|
||||
notJson++;
|
||||
break;
|
||||
case EntryOutcome.DocumentWithoutData:
|
||||
documentsWithoutData++;
|
||||
break;
|
||||
default:
|
||||
notData++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new HarImportReport(count, data, documents, blocks, otherHosts, notData, withoutBody, notJson, documentsWithoutData);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The name of the GraphQL operation of a request, when it is one: a word of the site's code (letters and digits,
|
||||
/// ending in Query, Mutation or Subscription, no run of three digits), the same for everyone. Otherwise null.
|
||||
/// </summary>
|
||||
public static string? OperationName(string? value)
|
||||
{
|
||||
var name = value?.Trim();
|
||||
return name is not null && OperationShape().IsMatch(name) && !DigitRun().IsMatch(name) ? name : null;
|
||||
}
|
||||
|
||||
private static EntryOutcome ConvertEntry(JsonElement entry, HostClassifier hosts, out RawSample? sample)
|
||||
{
|
||||
sample = null;
|
||||
if (entry.ValueKind != JsonValueKind.Object
|
||||
|| !entry.TryGetProperty("request", out var request) || request.ValueKind != JsonValueKind.Object
|
||||
|| !entry.TryGetProperty("response", out var response) || response.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return EntryOutcome.NotData;
|
||||
}
|
||||
|
||||
// Chrome's resource types, written as the browser's protocol names them (what ResponseTap sees).
|
||||
var resource = Text(entry, "_resourceType")?.ToLowerInvariant() switch
|
||||
{
|
||||
"xhr" => "XHR",
|
||||
"fetch" => "Fetch",
|
||||
"document" => "Document",
|
||||
_ => null,
|
||||
};
|
||||
if (resource is null)
|
||||
{
|
||||
return EntryOutcome.NotData;
|
||||
}
|
||||
|
||||
var url = Text(request, "url");
|
||||
var host = hosts.Classify(url);
|
||||
if (host != HostKind.Site)
|
||||
{
|
||||
return EntryOutcome.OtherHost;
|
||||
}
|
||||
|
||||
var status = response.TryGetProperty("status", out var s) && s.TryGetInt32(out var code) ? code : 0;
|
||||
var content = response.TryGetProperty("content", out var c) && c.ValueKind == JsonValueKind.Object ? c : default;
|
||||
var mime = (content.ValueKind == JsonValueKind.Object ? Text(content, "mimeType") : null)?.Split(';')[0].Trim().ToLowerInvariant() ?? string.Empty;
|
||||
var isData = DataResponses.IsData(mime, resource) && status is >= 200 and < 600 && status != 204;
|
||||
var isDocument = !isData && resource == "Document" && status is >= 200 and < 300 && DataResponses.IsPageDocument(mime, isMainFrameDocument: true);
|
||||
if (!isData && !isDocument)
|
||||
{
|
||||
return EntryOutcome.NotData;
|
||||
}
|
||||
|
||||
var bytes = Body(content);
|
||||
if (bytes is null)
|
||||
{
|
||||
return EntryOutcome.WithoutBody;
|
||||
}
|
||||
|
||||
var address = UrlSanitizer.Sanitize(url).Url;
|
||||
var at = When(Text(entry, "startedDateTime"));
|
||||
if (isDocument)
|
||||
{
|
||||
// Only the JSON the page embeds, one block per sample, as Febe's capture hands it to the readers: parsed
|
||||
// while the samples are written (a document without any becomes DocumentWithoutData there).
|
||||
sample = new RawSample("documento", address, host, status, mime, resource, at, DataResponses.EmbeddedJsonBlocks(Encoding.UTF8.GetString(bytes)));
|
||||
return EntryOutcome.Document;
|
||||
}
|
||||
|
||||
JsonDocument body;
|
||||
try
|
||||
{
|
||||
body = JsonDocument.Parse(bytes, BodyOptions);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return EntryOutcome.NotJson;
|
||||
}
|
||||
|
||||
var kind = resource == "Document" ? "documento" : OperationName(Operation(request)) ?? "risposta";
|
||||
sample = new RawSample(kind, address, host, status, mime, resource, at, [body]);
|
||||
return EntryOutcome.Data;
|
||||
}
|
||||
|
||||
/// <summary>The value of <see cref="OperationParameter"/> in a form-encoded request body; nothing else is read.</summary>
|
||||
private static string? Operation(JsonElement request)
|
||||
{
|
||||
if (!request.TryGetProperty("postData", out var post) || post.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (post.TryGetProperty("params", out var parameters) && parameters.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var parameter in parameters.EnumerateArray())
|
||||
{
|
||||
if (parameter.ValueKind == JsonValueKind.Object && Text(parameter, "name") == OperationParameter)
|
||||
{
|
||||
return Unescape(Text(parameter, "value"));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ((Text(post, "mimeType") ?? string.Empty).Contains("x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) && Text(post, "text") is { } text)
|
||||
{
|
||||
foreach (var pair in text.Split('&'))
|
||||
{
|
||||
var equals = pair.IndexOf('=', StringComparison.Ordinal);
|
||||
if (equals > 0 && Unescape(pair[..equals]) == OperationParameter)
|
||||
{
|
||||
return Unescape(pair[(equals + 1)..]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? Unescape(string? value)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return Uri.UnescapeDataString(value.Replace('+', ' '));
|
||||
}
|
||||
catch (UriFormatException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[]? Body(JsonElement content)
|
||||
{
|
||||
if (content.ValueKind != JsonValueKind.Object || Text(content, "text") is not { Length: > 0 } text)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!string.Equals(Text(content, "encoding"), "base64", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return Encoding.UTF8.GetBytes(text);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return Convert.FromBase64String(text);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? When(string? value) =>
|
||||
DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var at)
|
||||
? at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture)
|
||||
: null;
|
||||
|
||||
private static string? Text(JsonElement element, string property) =>
|
||||
element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
|
||||
|
||||
/// <summary>The same descriptor the probe writes (<see cref="ProbeRecorder"/>), then the body as it arrived.</summary>
|
||||
private static void Write(string path, RawSample sample, JsonDocument body)
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
|
||||
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { MaxDepth = 300 });
|
||||
writer.WriteStartObject();
|
||||
writer.WriteStartObject("descrittore");
|
||||
writer.WriteString("indirizzo", sample.Url);
|
||||
writer.WriteString("host", sample.Host switch { HostKind.Site => "sito", HostKind.Cdn => "cdn", _ => "altro" });
|
||||
writer.WriteNumber("stato", sample.Status);
|
||||
writer.WriteString("tipo", sample.MimeType);
|
||||
writer.WriteString("risorsa", sample.ResourceType);
|
||||
if (sample.At is { } at)
|
||||
{
|
||||
writer.WriteString("quando", at);
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteNull("quando");
|
||||
}
|
||||
|
||||
writer.WriteEndObject();
|
||||
writer.WritePropertyName("corpo");
|
||||
body.RootElement.WriteTo(writer);
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
// A GraphQL operation name: an identifier of the site's code (e.g. a «...PageQuery»), never free text.
|
||||
[GeneratedRegex("^[A-Za-z][A-Za-z0-9_]{1,96}(Query|Mutation|Subscription)$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex OperationShape();
|
||||
|
||||
[GeneratedRegex("[0-9]{3}", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex DigitRun();
|
||||
|
||||
private enum EntryOutcome
|
||||
{
|
||||
Data,
|
||||
Document,
|
||||
OtherHost,
|
||||
NotData,
|
||||
WithoutBody,
|
||||
NotJson,
|
||||
DocumentWithoutData,
|
||||
}
|
||||
|
||||
/// <summary>What is written of one entry: its descriptor, and its body (a data answer) or the JSON blocks it embeds (a page document).</summary>
|
||||
private sealed record RawSample(string Kind, string Url, HostKind Host, int Status, string MimeType, string ResourceType, string? At, IEnumerable<JsonDocument> Bodies);
|
||||
}
|
||||
@@ -10,9 +10,11 @@ using Febe.Sonda;
|
||||
// [--sito <host> --cdn <host>] (solo per provarla sul sito di prova)
|
||||
// febe-sonda ripulisci --da <grezzi> --a <ripuliti> [--ammessi <ripulitura.json>] [--sito <host> --cdn <host>]
|
||||
// febe-sonda verifica --grezzi <grezzi> --ripuliti <ripuliti> [--ammessi <ripulitura.json>]
|
||||
// febe-sonda da-har --har <file .har> --a <cartella nuova fuori dal repository> [--sito <host> --cdn <host>]
|
||||
return args.Length == 0 ? Usage() : args[0] switch
|
||||
{
|
||||
"registra" => await RecordAsync(args[1..]),
|
||||
"da-har" => FromHar(args[1..]),
|
||||
"ripulisci" => Sanitize(args[1..]),
|
||||
"verifica" => Verify(args[1..]),
|
||||
_ => Usage(),
|
||||
@@ -25,7 +27,11 @@ static int Usage()
|
||||
febe-sonda registra --cartella <cartella fuori dal repository> [--display :0 | --xvfb] [--porta 9333] [--chromium <file>] [--no-sandbox]
|
||||
febe-sonda ripulisci --da <campioni grezzi> --a <campioni ripuliti> [--ammessi <ripulitura.json>]
|
||||
febe-sonda verifica --grezzi <campioni grezzi> --ripuliti <campioni ripuliti> [--ammessi <ripulitura.json>]
|
||||
febe-sonda da-har --har <file .har esportato dal browser> --a <cartella nuova fuori dal repository>
|
||||
La sonda è passiva: apre il browser e registra ciò che la pagina riceve mentre navighi tu. Non compie gesti.
|
||||
«da-har» converte nello stesso formato grezzo un file HAR esportato dagli strumenti per sviluppatori del browser:
|
||||
tiene le sole risposte di dati del sito e i dati incorporati nelle pagine; mai intestazioni, cookie, parametri
|
||||
degli indirizzi o corpi delle richieste. Poi si usano «ripulisci» e «verifica» come per la sonda.
|
||||
""");
|
||||
return 2;
|
||||
}
|
||||
@@ -109,6 +115,40 @@ static async Task<int> RecordAsync(string[] args)
|
||||
}
|
||||
}
|
||||
|
||||
static int FromHar(string[] args)
|
||||
{
|
||||
var har = Option(args, "--har");
|
||||
var to = Option(args, "--a");
|
||||
if (string.IsNullOrWhiteSpace(har) || string.IsNullOrWhiteSpace(to))
|
||||
{
|
||||
Console.Error.WriteLine("Indicare --har <file .har> e --a <cartella nuova fuori dal repository>.");
|
||||
return 2;
|
||||
}
|
||||
|
||||
HarImportReport report;
|
||||
try
|
||||
{
|
||||
report = HarImporter.Import(har, to, Hosts(args));
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or InvalidDataException or FileNotFoundException)
|
||||
{
|
||||
Console.Error.WriteLine(ex.Message);
|
||||
return 3;
|
||||
}
|
||||
|
||||
// Counts only: what the answers contain stays on this machine.
|
||||
Console.WriteLine($"Lette {report.Entries} voci del file HAR; scritti {report.Written} campioni grezzi: {report.DataResponses} risposte di dati del sito, {report.DocumentBlocks} blocchi di dati incorporati in {report.Documents} pagine.");
|
||||
Console.WriteLine($"Lasciate fuori: {report.OtherHosts} di altri indirizzi (CDN, altri siti), {report.NotData} che non sono dati (file, immagini, script...), {report.WithoutBody} senza corpo, {report.NotJson} non JSON, {report.DocumentsWithoutData} pagine senza dati incorporati.");
|
||||
if (report.Written == 0 && report.WithoutBody > 0)
|
||||
{
|
||||
Console.WriteLine("Il file HAR non contiene i corpi delle risposte: esportalo di nuovo dal pannello Rete con le risposte incluse.");
|
||||
}
|
||||
|
||||
Console.WriteLine($"Campioni grezzi in: {Path.GetFullPath(to)}");
|
||||
Console.WriteLine("Ora: febe-sonda ripulisci --da <cartella> --a <copia ripulita>, poi febe-sonda verifica.");
|
||||
return report.Written > 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
static int Sanitize(string[] args)
|
||||
{
|
||||
var from = Option(args, "--da");
|
||||
|
||||
@@ -21,7 +21,7 @@ public sealed record SanitizeReport(int Files, int Lines, int ReplacedStrings, i
|
||||
/// sensitive run of any raw sample (it is drawn again). Fake letters are consonants only, so they cannot spell the
|
||||
/// words of a caption. The browser profile folder of the probe is never read.
|
||||
/// </remarks>
|
||||
public sealed class SampleSanitizer
|
||||
public sealed partial class SampleSanitizer
|
||||
{
|
||||
/// <summary>The probe's browser profile: holds the session, never part of the samples.</summary>
|
||||
public const string BrowserProfileFolder = "profilo-browser";
|
||||
@@ -188,12 +188,26 @@ public sealed class SampleSanitizer
|
||||
}
|
||||
|
||||
_strings++;
|
||||
return JsonValue.Create(Fake(text, "s"));
|
||||
return JsonValue.Create(LooksLikeSecretKey(key) ? Filler(text) : Fake(text, "s"));
|
||||
default:
|
||||
return JsonValue.Create(element);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True for the keys under which a site keeps tokens and keys of its own (Instagram: «organic_tracking_token»,
|
||||
/// «rank_token», «client_cache_key»). Their fakes would look like real secrets to a secret scanner (gitleaks in the
|
||||
/// CI): they get a neutral filler of the same shape instead.
|
||||
/// </summary>
|
||||
internal static bool LooksLikeSecretKey(string? key) => key is not null && SecretKey().IsMatch(key);
|
||||
|
||||
/// <summary>Letters become «x», digits «7», symbols «·»: the shape stays, nothing of the value and no entropy.</summary>
|
||||
private static string Filler(string text) =>
|
||||
new([.. text.Select(c => char.IsLetter(c) ? 'x' : char.IsDigit(c) ? '7' : char.IsSurrogate(c) || char.IsSymbol(c) ? '·' : c)]);
|
||||
|
||||
[System.Text.RegularExpressions.GeneratedRegex("token|secret|passw|credential|cookie|csrf|session|signature|auth|key", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant)]
|
||||
private static partial System.Text.RegularExpressions.Regex SecretKey();
|
||||
|
||||
private string FakeKey(string key)
|
||||
{
|
||||
_keys++;
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
"keys": ["type", "*_type", "status", "tipo", "stato", "risorsa", "host", "role", "tag", "evento"]
|
||||
},
|
||||
"date": {
|
||||
"note": "Date: si tengono i numeri e i testi che hanno la forma di una data. taken_at è uno degli indizi di §6.4.",
|
||||
"keys": ["taken_at", "*_at", "pubblicato", "scade", "ultima_storia", "quando"]
|
||||
"note": "Date: si tengono i numeri e i testi che hanno la forma di una data. taken_at è uno degli indizi di §6.4; latest_reel_media è la data dell'ultima storia di un profilo (campioni del 21/10/2026).",
|
||||
"keys": ["taken_at", "*_at", "latest_reel_media", "pubblicato", "scade", "ultima_storia", "quando"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# Raccolta dei bersagli dal browser di tutti i giorni
|
||||
|
||||
`raccogli-bersagli.js` serve a compilare i **bersagli** di `src/Febe.Core/Config/bersagli.instagram.json` (ipotesi
|
||||
H11): l'anello delle storie, la zona «avanti» e la X del visualizzatore, le schede del profilo, le raccolte in evidenza.
|
||||
Si usa come spiegato in `docs/prove-dal-vivo.md`, parte **A bis**.
|
||||
|
||||
## Come si usa
|
||||
|
||||
1. Nel browser con cui navighi di solito, già entrato nel sito, apri gli strumenti per sviluppatori (F12) e la scheda
|
||||
**Console**.
|
||||
2. Incolla tutto il contenuto di `raccogli-bersagli.js` e premi Invio. Compare «Febe: raccolta dei bersagli attiva».
|
||||
Se la pagina si ricarica del tutto, la raccolta si perde: incollalo di nuovo.
|
||||
3. Naviga e clicca come al solito. A ogni clic la Console scrive «Febe: clic N registrato».
|
||||
4. Alla fine scrivi `febeBersagli()` nella Console: copia negli appunti i clic registrati (se la copia non riesce, li
|
||||
scrive nella Console e li copi da lì).
|
||||
|
||||
## Che cosa fa e che cosa non fa
|
||||
|
||||
- **Sola lettura.** Aggiunge un solo ascoltatore dei clic, che non blocca e non cambia il clic, e legge attributi.
|
||||
Non modifica la pagina, non manda nulla a nessuno, non legge cookie né le memorie del browser. I dati restano nella
|
||||
memoria della scheda finché non chiami `febeBersagli()`.
|
||||
- Per ogni clic registra la forma dell'indirizzo prima e circa 1,5 secondi dopo, e del comando cliccato (il più vicino
|
||||
fra collegamento, pulsante, elemento con un ruolo o con `tabindex`): elemento, ruolo, `aria-label`, `alt`, `title`, il
|
||||
testo (solo per pulsanti, collegamenti, schede e simili), il **nome accessibile calcolato come lo calcola Febe**
|
||||
(`src/Febe.Browser/Targets/TargetResolver.cs`), se il nome viene da un'icona `svg` con `aria-label`, la forma del
|
||||
collegamento, e quanti elementi visibili hanno lo stesso ruolo e lo stesso nome (con la posizione di quello cliccato).
|
||||
- La voce `perLaMappa` è già nella forma dei campi `role`, `name`, `href` e `index` della mappa.
|
||||
- **Nomi.** Negli indirizzi restano solo le parole fisse (`stories`, `highlights`, `p`, `reel`, `reels`, `tagged`,
|
||||
`following`, `followers`, `explore`); ogni altro pezzo diventa `<x>`. Nei testi registrati, i nomi visti negli
|
||||
indirizzi e ogni `@parola` diventano `NOME`. I nomi scritti per esteso (per esempio «Mario Rossi») **non** si
|
||||
riconoscono: prima di inviare il testo, sostituisci a mano con `NOME` ogni nome di persona rimasto.
|
||||
- Un nome utente che è anche una parola dell'interfaccia può far diventare `NOME` anche quella parola: va bene così,
|
||||
meglio un nome di comando in meno che un nome di persona in più.
|
||||
@@ -0,0 +1,258 @@
|
||||
// Febe: targets from the everyday browser (docs/prove-dal-vivo.md, part «A bis»; hypothesis H11).
|
||||
//
|
||||
// Paste it in the Console of the browser's DevTools, with the site open and already logged in, then browse by hand.
|
||||
// For every click it records the shape of the address before and about 1.5 s after, and the attributes of the clicked
|
||||
// command that Febe's target map uses (src/Febe.Core/Config/bersagli.<sito>.json): role, accessible name computed as
|
||||
// src/Febe.Browser/Targets/TargetResolver.cs computes it, link shape. At the end, febeBersagli() copies the records.
|
||||
//
|
||||
// READ-ONLY with respect to the page: one capturing click listener that never blocks or changes the click, and
|
||||
// attribute reads. It never changes the DOM, never sends anything anywhere, never reads cookies or the browser's
|
||||
// storage. Records stay in this tab's memory; reloading the page drops them (paste it again after a reload).
|
||||
// Address segments that are not fixed words become «<x>»; user names seen in the addresses and @words become «NOME».
|
||||
(() => {
|
||||
'use strict';
|
||||
if (typeof globalThis.febeBersagli === 'function') {
|
||||
console.log('Febe: la raccolta dei bersagli è già attiva. febeBersagli() copia ciò che è stato registrato.');
|
||||
return;
|
||||
}
|
||||
|
||||
const FIXED = new Set(['stories', 'highlights', 'p', 'reel', 'reels', 'tagged', 'following', 'followers', 'explore']);
|
||||
const MAX_TEXT = 80;
|
||||
const records = [];
|
||||
const names = new Set();
|
||||
|
||||
// Same as TargetResolver.cs: collapsed whitespace.
|
||||
const clean = (s) => (s || '').replace(/\s+/g, ' ').trim();
|
||||
|
||||
// The shape of a path: fixed words stay, every other segment becomes «<x>». The segments that are not fixed words
|
||||
// are kept aside (in memory only) to mask them in the recorded texts.
|
||||
const shapeOf = (path) => {
|
||||
if (typeof path !== 'string') return null;
|
||||
return path.split('/').map((segment) => {
|
||||
if (segment === '' || FIXED.has(segment.toLowerCase())) return segment;
|
||||
let decoded = segment;
|
||||
try { decoded = decodeURIComponent(segment); } catch { /* keep it as it is */ }
|
||||
if (decoded.length >= 2) names.add(decoded.toLowerCase());
|
||||
return '<x>';
|
||||
}).join('/');
|
||||
};
|
||||
|
||||
// Same as TargetResolver.cs roleOf: explicit role first, then the implicit role of the tag.
|
||||
const roleOf = (el) => {
|
||||
const explicit = clean(el.getAttribute('role')).split(' ')[0];
|
||||
if (explicit) return explicit.toLowerCase();
|
||||
const tag = el.tagName.toLowerCase();
|
||||
const type = (el.getAttribute('type') || '').toLowerCase();
|
||||
switch (tag) {
|
||||
case 'a': case 'area': return el.hasAttribute('href') ? 'link' : '';
|
||||
case 'button': return 'button';
|
||||
case 'input':
|
||||
if (['button', 'submit', 'reset', 'image'].includes(type)) return 'button';
|
||||
if (type === 'checkbox') return 'checkbox';
|
||||
if (type === 'radio') return 'radio';
|
||||
if (type === 'search') return 'searchbox';
|
||||
if (['', 'text', 'email', 'tel', 'url', 'password'].includes(type)) return 'textbox';
|
||||
return '';
|
||||
case 'textarea': return 'textbox';
|
||||
case 'select': return 'combobox';
|
||||
case 'img': return el.getAttribute('alt') === '' ? 'presentation' : 'img';
|
||||
case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return 'heading';
|
||||
case 'nav': return 'navigation';
|
||||
case 'main': return 'main';
|
||||
case 'dialog': return 'dialog';
|
||||
case 'article': return 'article';
|
||||
case 'ul': case 'ol': return 'list';
|
||||
case 'li': return 'listitem';
|
||||
case 'section': return (el.hasAttribute('aria-label') || el.hasAttribute('aria-labelledby')) ? 'region' : '';
|
||||
default: return '';
|
||||
}
|
||||
};
|
||||
|
||||
// Same as TargetResolver.cs textOf: a child's aria-label stands for its subtree, aria-hidden children are skipped.
|
||||
const textOf = (node, depth) => {
|
||||
if (depth > 25) return '';
|
||||
let out = '';
|
||||
for (const child of node.childNodes) {
|
||||
if (child.nodeType === 3) { out += child.nodeValue + ' '; continue; }
|
||||
if (child.nodeType !== 1) continue;
|
||||
if (child.getAttribute('aria-hidden') === 'true') continue;
|
||||
const label = clean(child.getAttribute('aria-label'));
|
||||
if (label) { out += label + ' '; continue; }
|
||||
const tag = child.tagName.toLowerCase();
|
||||
if (tag === 'img') { out += (child.getAttribute('alt') || '') + ' '; continue; }
|
||||
if (tag === 'script' || tag === 'style' || tag === 'template') continue;
|
||||
out += textOf(child, depth + 1) + ' ';
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// Roles named from their content (TargetResolver.cs fromContent): only these get their text recorded.
|
||||
const fromContent = new Set(['button', 'link', 'tab', 'menuitem', 'heading', 'cell', 'gridcell', 'option',
|
||||
'checkbox', 'radio', 'switch', 'listitem', 'treeitem', 'columnheader', 'rowheader', 'tooltip']);
|
||||
|
||||
// Same as TargetResolver.cs nameOf: the accessible name the «name» field of the map is matched against.
|
||||
const nameOf = (el, role) => {
|
||||
const ids = clean(el.getAttribute('aria-labelledby'));
|
||||
if (ids) {
|
||||
const joined = clean(ids.split(' ').map((id) => document.getElementById(id)).filter(Boolean).map((e) => e.textContent).join(' '));
|
||||
if (joined) return joined;
|
||||
}
|
||||
const aria = clean(el.getAttribute('aria-label'));
|
||||
if (aria) return aria;
|
||||
const tag = el.tagName.toLowerCase();
|
||||
const type = (el.getAttribute('type') || '').toLowerCase();
|
||||
if (tag === 'img' || (tag === 'input' && type === 'image')) {
|
||||
const alt = clean(el.getAttribute('alt'));
|
||||
if (alt) return alt;
|
||||
}
|
||||
if (tag === 'input' && ['button', 'submit', 'reset'].includes(type)) {
|
||||
const label = clean(el.getAttribute('value'));
|
||||
if (label) return label;
|
||||
}
|
||||
if (fromContent.has(role)) {
|
||||
const text = clean(textOf(el, 0));
|
||||
if (text) return text;
|
||||
}
|
||||
return clean(el.getAttribute('title') || el.getAttribute('placeholder'));
|
||||
};
|
||||
|
||||
const visible = (el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
if (!(r.width > 0 && r.height > 0)) return false;
|
||||
return typeof el.checkVisibility === 'function' ? el.checkVisibility({ opacityProperty: true, visibilityProperty: true }) : true;
|
||||
};
|
||||
|
||||
// Like ProbeRecorder.cs: the path of a link and whether it stays on the site, never the host of another site.
|
||||
const linkOf = (el) => {
|
||||
const href = el.getAttribute('href');
|
||||
if (!href) return null;
|
||||
try {
|
||||
const u = new URL(href, document.baseURI);
|
||||
return { sito: u.origin === location.origin, path: shapeOf(u.pathname) };
|
||||
} catch { return null; }
|
||||
};
|
||||
|
||||
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
|
||||
// User names seen in any recorded address, and every @word, become «NOME»; texts are cut to 80 characters.
|
||||
const mask = (text) => {
|
||||
if (text === null || text === undefined) return null;
|
||||
let out = clean(String(text)).replace(/@[\p{L}\p{N}._]+/gu, 'NOME');
|
||||
for (const name of names) {
|
||||
out = out.replace(new RegExp('(^|[^\\p{L}\\p{N}_])' + escapeRegex(name) + '(?![\\p{L}\\p{N}_])', 'giu'), '$1NOME');
|
||||
}
|
||||
return out.length > MAX_TEXT ? out.slice(0, MAX_TEXT) : out;
|
||||
};
|
||||
|
||||
const describe = (el, inner) => {
|
||||
const role = roleOf(el);
|
||||
const name = nameOf(el, role);
|
||||
const svg = el.querySelector('svg[aria-label]');
|
||||
const svgLabel = svg ? clean(svg.getAttribute('aria-label')) : '';
|
||||
let same = null;
|
||||
let position = null;
|
||||
if (role) {
|
||||
// How many visible elements share role and name, and which one this is: the «index» field of the map.
|
||||
same = 0;
|
||||
for (const other of document.querySelectorAll('*')) {
|
||||
if (roleOf(other) !== role || nameOf(other, role) !== name || !visible(other)) continue;
|
||||
if (other === el) position = same;
|
||||
same++;
|
||||
}
|
||||
}
|
||||
return {
|
||||
tag: el.tagName.toLowerCase(),
|
||||
interno: inner && inner !== el && inner.tagName ? inner.tagName.toLowerCase() : null,
|
||||
roleAttributo: el.getAttribute('role'),
|
||||
ruolo: role,
|
||||
ariaLabel: el.getAttribute('aria-label'),
|
||||
alt: el.getAttribute('alt'),
|
||||
titolo: el.getAttribute('title'),
|
||||
testo: fromContent.has(role) ? clean(el.textContent) : null,
|
||||
nome: name,
|
||||
svg: svgLabel || null,
|
||||
nomeDaSvg: !!svgLabel && !clean(el.getAttribute('aria-label')) && name === clean(textOf(el, 0)) && name.includes(svgLabel),
|
||||
collegamento: linkOf(el),
|
||||
tabindex: el.getAttribute('tabindex'),
|
||||
uguali: same,
|
||||
posizione: position,
|
||||
};
|
||||
};
|
||||
|
||||
const onClick = (event) => {
|
||||
try {
|
||||
const inner = event.target && event.target.nodeType === 1 ? event.target : null;
|
||||
const el = inner && inner.closest ? inner.closest('a[href], button, [role], [tabindex]') : null;
|
||||
const record = {
|
||||
n: records.length + 1,
|
||||
ora: new Date().toTimeString().slice(0, 8),
|
||||
prima: shapeOf(location.pathname),
|
||||
dopo: null,
|
||||
elemento: el ? describe(el, inner) : null,
|
||||
};
|
||||
records.push(record);
|
||||
setTimeout(() => {
|
||||
try { record.dopo = shapeOf(location.pathname); } catch { /* the record stays without it */ }
|
||||
}, 1500);
|
||||
console.log(`Febe: clic ${record.n} registrato${el ? '' : ' (nessun comando sotto il puntatore)'}.`);
|
||||
} catch {
|
||||
// Never disturb the page: a click that cannot be described is just not recorded.
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('click', onClick, { capture: true, passive: true });
|
||||
|
||||
// The records, masked, ready for bersagli.<sito>.json: «<x>» becomes «*» (one segment), «NOME» becomes «.+».
|
||||
const output = () => records.map((r) => {
|
||||
const e = r.elemento;
|
||||
if (!e) return { n: r.n, ora: r.ora, prima: r.prima, dopo: r.dopo, elemento: null };
|
||||
const element = {
|
||||
...e,
|
||||
roleAttributo: mask(e.roleAttributo),
|
||||
ariaLabel: mask(e.ariaLabel),
|
||||
alt: mask(e.alt),
|
||||
titolo: mask(e.titolo),
|
||||
testo: mask(e.testo),
|
||||
nome: mask(e.nome),
|
||||
svg: mask(e.svg),
|
||||
};
|
||||
const name = element.nome ? '^' + escapeRegex(element.nome).replace(/NOME/g, '.+') + '$' : '';
|
||||
return {
|
||||
n: r.n,
|
||||
ora: r.ora,
|
||||
prima: r.prima,
|
||||
dopo: r.dopo,
|
||||
elemento: element,
|
||||
perLaMappa: {
|
||||
role: e.ruolo,
|
||||
name,
|
||||
href: e.collegamento && e.collegamento.sito ? e.collegamento.path.replace(/<x>/g, '*') : '',
|
||||
index: e.posizione,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// copy() is a utility of the DevTools Console, there while the Console runs a command: kept from the paste too.
|
||||
const copier = typeof copy === 'function' ? copy : null;
|
||||
globalThis.febeBersagli = () => {
|
||||
const text = JSON.stringify(output(), null, 2);
|
||||
let copied = true;
|
||||
if (typeof copy === 'function') {
|
||||
copy(text);
|
||||
} else if (copier) {
|
||||
copier(text);
|
||||
} else {
|
||||
copied = false;
|
||||
}
|
||||
|
||||
if (copied) {
|
||||
console.log(`Febe: copiati negli appunti ${records.length} clic registrati. Incollali in un file di testo e controlla che non resti nessun nome.`);
|
||||
} else {
|
||||
console.log(text);
|
||||
console.log(`Febe: ${records.length} clic registrati, scritti qui sopra: copiali da qui.`);
|
||||
}
|
||||
return records.length;
|
||||
};
|
||||
|
||||
console.log('Febe: raccolta dei bersagli attiva (sola lettura). Naviga come al solito; alla fine scrivi febeBersagli().');
|
||||
})();
|
||||
Reference in new issue
Block a user