Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e417c666d | ||
|
|
0775a1460f | ||
|
|
e2e64c09e8 | ||
|
|
badd1681a0 | ||
|
|
bf03cb45a5 | ||
|
|
72deb212a7 | ||
|
|
305791f57b | ||
|
|
e8dc4693e5 | ||
|
|
c05bd2d11b | ||
|
|
9c18252a47 | ||
|
|
78aa32bdb2 | ||
|
|
8d2f85693c | ||
|
|
0153280edd | ||
|
|
dc60e282c5 | ||
|
|
2ffb766a95 | ||
|
|
eac1a058e4 | ||
|
|
31ff6c8b86 | ||
|
|
b7e5e25436 | ||
|
|
fbc40fb5a1 | ||
|
|
31bbbf8bb7 | ||
|
|
b3a7c31e5a | ||
|
|
5b278a848a | ||
|
|
2e1d81d4b8 | ||
|
|
b74d2db793 | ||
|
|
e73292516d | ||
|
|
7d5c6505bd | ||
|
|
44f7f93783 | ||
|
|
4b35178880 | ||
|
|
fe4ef9f048 | ||
|
|
c5361ba8fe | ||
|
|
68100b0295 | ||
|
|
e24ebd24f0 | ||
|
|
483d57b89a | ||
|
|
086b603801 | ||
|
|
46d780c826 | ||
|
|
5988c503f7 | ||
|
|
7513f41d4d | ||
|
|
7a9c235552 | ||
|
|
d07ed07db6 | ||
|
|
248e9f74ce | ||
|
|
65988f2863 | ||
|
|
016bbf73eb | ||
|
|
0f11fc5220 |
No files matched your search
@@ -4,7 +4,8 @@
|
||||
#
|
||||
# bash .gitea/scripts/controlli.sh
|
||||
#
|
||||
# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix;
|
||||
# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix; gli
|
||||
# script Node della CI (.gitea/scripts/*.js) sono JavaScript valido (node --check);
|
||||
# 2. i flussi della CI non hanno tabulazioni (YAML non le accetta come rientro);
|
||||
# 3. nessun file contiene segni di conflitto rimasti da un'unione;
|
||||
# 4. la versione di Directory.Build.props è nella forma x.y.z[-qualcosa], quella che installer/costruisci.sh accetta;
|
||||
@@ -35,6 +36,18 @@ while IFS= read -r -d '' script; do
|
||||
done < <(git ls-files -z -- '*.sh')
|
||||
echo " $quanti script controllati"
|
||||
|
||||
echo "== Script Node della CI"
|
||||
if command -v node > /dev/null; then
|
||||
quanti=0
|
||||
while IFS= read -r -d '' script; do
|
||||
quanti=$((quanti + 1))
|
||||
node --check "$script" || errore "$script: JavaScript non valido."
|
||||
done < <(git ls-files -z -- '.gitea/scripts/*.js')
|
||||
echo " $quanti script controllati"
|
||||
else
|
||||
errore "manca node: gli script Node della CI non si possono controllare."
|
||||
fi
|
||||
|
||||
echo "== Flussi della CI"
|
||||
while IFS= read -r -d '' flusso; do
|
||||
if grep -n $'\t' "$flusso" > /dev/null; then
|
||||
|
||||
@@ -8,6 +8,11 @@
|
||||
# già nella configurazione del client, il demone non
|
||||
# parla mai con il registro (proverebbe HTTPS)
|
||||
#
|
||||
# L'immagine è un manifest semplice, senza attestazioni (--provenance=false --sbom=false). Con le attestazioni, che
|
||||
# buildx aggiunge da sé, sarebbe un indice: Gitea tiene ogni manifest figlio come una versione a sé, sha256:… senza
|
||||
# etichetta, con la configurazione e gli strati, e togliere dal registro un'etichetta :sha- toglierebbe solo l'indice.
|
||||
# Con un manifest semplice gli strati stanno nella versione dell'etichetta, e la pulizia del registro li libera davvero.
|
||||
#
|
||||
# Variabili richieste: BUILDER, VERSIONE, GIT_COMMIT, FLUSSO (verifica o rilascio), ESECUZIONE (gitea.run_id).
|
||||
# Le etichette febe.ci.* dicono quale flusso, esecuzione, ramo e commit hanno costruito l'immagine. Non servono alla
|
||||
# pulizia: stanno anche nelle immagini pubblicate e Docker le copia in ogni contenitore creato da quelle, anche in un
|
||||
@@ -19,7 +24,7 @@ modo="${1:?Indica il modo: archivio o pubblica.}"
|
||||
shift
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
comuni=(--builder "${BUILDER:?}" -f docker/Dockerfile
|
||||
comuni=(--builder "${BUILDER:?}" -f docker/Dockerfile --provenance=false --sbom=false
|
||||
--build-arg "VERSION=${VERSIONE:?}" --build-arg "GIT_COMMIT=${GIT_COMMIT:?}"
|
||||
--label "febe.ci.workflow=${FLUSSO:?}" --label "febe.ci.run=${ESECUZIONE:?}"
|
||||
--label "febe.ci.ref=${GITHUB_REF_NAME:-}" --label "febe.ci.commit=${GITHUB_SHA:-}")
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
# Pulizia di ciò che la CI di Febe lascia sul demone Docker del runner. È lo stesso demone che costruisce Encelado,
|
||||
# Mimante e gli altri progetti di Alberto, e ci può girare anche un Febe vero: si tocca solo ciò che si può provare
|
||||
# creato dalla CI, più le immagini senza nome («dangling») più vecchie di tre giorni. Mai altro, e mai la cache di
|
||||
# costruzione del demone (è condivisa).
|
||||
# Pulizia del demone Docker del runner e del registro dei container. Il demone è lo stesso che costruisce Encelado,
|
||||
# Mimante e gli altri progetti di Alberto (e molto probabilmente quello delle applicazioni di Unraid), e ci può girare
|
||||
# anche un Febe vero. Dal 21 ottobre 2026 (decisione di Alberto) la pulizia toglie anche ciò che non serve più a
|
||||
# nessuno, di qualunque progetto: le immagini che nessun contenitore usa, la cache di costruzione, i resti di
|
||||
# act_runner. Mai un contenitore, un volume o una rete che non sia della CI.
|
||||
#
|
||||
# Le etichette febe.ci.workflow, febe.ci.run, febe.ci.ref e febe.ci.commit dicono da dove viene un'immagine, ma NON
|
||||
# scelgono che cosa togliere: stanno anche nelle immagini pubblicate (:main, :sha-, :X.Y.Z, :latest), e Docker le copia
|
||||
# in ogni contenitore creato da quelle immagini, quindi le porta anche un Febe vero. Ciò che si toglie si riconosce così:
|
||||
# Della CI di Febe si toglie ciò che si può provare suo. Le etichette febe.ci.workflow, febe.ci.run, febe.ci.ref e
|
||||
# febe.ci.commit dicono da dove viene un'immagine, ma NON scelgono che cosa togliere: stanno anche nelle immagini
|
||||
# pubblicate (:main, :sha-, :X.Y.Z, :latest), e Docker le copia in ogni contenitore creato da quelle, quindi le porta
|
||||
# anche un Febe vero. Ciò che si toglie si riconosce così:
|
||||
# - contenitori di prova: l'etichetta febe.ci.prova=<esecuzione>, che mette solo prova-immagine.sh con
|
||||
# «docker run --label» e che nessuna immagine porta (lo controlla PipelineTests), E il nome esatto
|
||||
# febe-prova-<la stessa esecuzione> (gli altri contenitori della prova, senza nome, girano con --rm e Docker li
|
||||
@@ -16,41 +18,154 @@
|
||||
# - builder buildx: il contenitore buildx_buildkit_febe-ci-<esecuzione>0, con l'immagine moby/buildkit, e il suo
|
||||
# volume …_state, che contengono la cache di costruzione di quell'esecuzione;
|
||||
# - l'immagine febe:ci lasciata dal vecchio flusso di verifica (prima del 20 ottobre 2026), se nessuno la usa.
|
||||
# Di act_runner si tolgono i resti dei lavori: act_runner chiama tutto ciò che crea per un lavoro
|
||||
# GITEA-ACTIONS-TASK-<numero del compito>… (il contenitore del lavoro, i suoi volumi <nome> e <nome>-env, la sua rete
|
||||
# <nome>-<lavoro>-network). Solo i contenitori fermi e i volumi e le reti che nessun contenitore usa, più vecchi di 90
|
||||
# minuti: un lavoro che parte li crea e li usa subito. Il volume act-toolcache (la cache degli strumenti, condivisa fra
|
||||
# i lavori) resta.
|
||||
#
|
||||
# pulizia-docker.sh esecuzione <id> tutto ciò che ha creato l'esecuzione <id> (all'inizio e alla fine del suo
|
||||
# lavoro «immagine», sempre)
|
||||
# pulizia-docker.sh penzolanti le immagini senza nome che nessun contenitore usa e la cache di costruzione
|
||||
# penzolante del demone (quella che nessuna immagine condivide) non usata da
|
||||
# 24 ore, di tutti i progetti (alla fine di ogni lavoro «immagine», dopo
|
||||
# «esecuzione»)
|
||||
# pulizia-docker.sh residui [minuti] i resti di esecuzioni interrotte, più vecchi di N minuti (predefinito 90: un
|
||||
# lavoro dura al massimo 60 minuti, quindi nessuno di essi è ancora vivo)
|
||||
# pulizia-docker.sh settimanale residui, febe:ci, immagini senza nome più vecchie di 72 ore (flusso «pulizia»)
|
||||
# pulizia-docker.sh settimanale residui, febe:ci, immagini senza nome più vecchie di 72 ore: la pulizia
|
||||
# stretta di prima del 21 ottobre 2026, ora solo a mano
|
||||
# pulizia-docker.sh completa residui, febe:ci, resti di act_runner, le immagini che nessun contenitore
|
||||
# usa create più di 24 ore fa, la cache di costruzione non usata da 24 ore e,
|
||||
# con REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti
|
||||
# (flusso «pulizia», ogni lunedì e a mano)
|
||||
# pulizia-docker.sh <modo> --prova elenca che cosa toglierebbe e non toglie nulla: solo comandi che leggono
|
||||
# (sul registro solo GET)
|
||||
#
|
||||
# Nei modi «residui» e «settimanale» un contenitore di prova si toglie solo se è fermo. Uno ancora acceso dopo 90 minuti
|
||||
# (il suo lavoro è stato ucciso proprio durante la prova del contenitore) resta dov'è: lo si segnala, con il comando per
|
||||
# toglierlo a mano. I builder sono l'eccezione: sono sempre accesi e la loro cache se ne va solo togliendo il
|
||||
# contenitore; si riconoscono dal nome esatto e dall'immagine di buildkit, mai da un'etichetta.
|
||||
# Gli argomenti si controllano tutti prima di toccare Docker: un'opzione diversa da --prova (--dry-run, -n, --Prova) o
|
||||
# un argomento in più (prova senza trattini) fermano tutto con codice 2, invece di far partire la pulizia vera al posto
|
||||
# della prova.
|
||||
#
|
||||
# Un oggetto già sparito non è un errore: la pulizia si può ripetere. Nei modi «esecuzione» e «residui» un problema
|
||||
# diventa un avviso (un lavoro verde non diventa rosso per la pulizia, che il flusso settimanale ripete); nel modo
|
||||
# «settimanale» fa fallire il lavoro, perché qualcuno lo guardi.
|
||||
# Mai docker system prune, container prune, volume prune o network prune; mai image prune -a o builder prune -a senza
|
||||
# il filtro delle 24 ore; mai un contenitore, un volume o una rete che non sia della CI. Le immagini le toglie Docker
|
||||
# stesso (image prune), che non toglie mai un'immagine usata da un contenitore, nemmeno fermo; con -a, però, le toglie i
|
||||
# nomi in più, e lo script li scrive (nella prova li stima, secondo lo store). Sul registro mai main, latest o una
|
||||
# versione X.Y.Z: solo le etichette sha-<esadecimale> della verifica.
|
||||
#
|
||||
# Nei modi «residui», «settimanale» e «completa» un contenitore di prova si toglie solo se è fermo. Uno ancora acceso
|
||||
# dopo 90 minuti (il suo lavoro è stato ucciso proprio durante la prova del contenitore) resta dov'è: lo si segnala, con
|
||||
# il comando per toglierlo a mano. I builder sono l'eccezione: sono sempre accesi e la loro cache se ne va solo
|
||||
# togliendo il contenitore; si riconoscono dal nome esatto e dall'immagine di buildkit, mai da un'etichetta.
|
||||
#
|
||||
# Un oggetto già sparito non è un errore: la pulizia si può ripetere. Nei modi «esecuzione», «penzolanti» e «residui»
|
||||
# un problema diventa un avviso (un lavoro verde non diventa rosso per la pulizia, che il flusso del lunedì ripete); nei
|
||||
# modi «settimanale» e «completa» fa fallire il lavoro, perché qualcuno lo guardi. Il registro è l'eccezione: un
|
||||
# rifiuto della sua API è solo un avviso, e il lunedì dopo si riprova.
|
||||
#
|
||||
# Variabili per il registro (modo «completa»): REGISTRY_TOKEN (token con «package: read and write», mai stampato),
|
||||
# GITEA_API (l'API del server, per esempio https://gitea.example/api/v1) e PROPRIETARIO (il proprietario del pacchetto
|
||||
# febe). La scelta delle versioni da togliere sta in versioni-registro.js, accanto a questo script.
|
||||
set -uo pipefail
|
||||
|
||||
modo="${1:-}"
|
||||
uso() {
|
||||
[[ -z "${1:-}" ]] || echo "$1" >&2
|
||||
echo "Uso: $0 esecuzione <id> | penzolanti | residui [minuti] | settimanale | completa [--prova]" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
prova=0
|
||||
argomenti=()
|
||||
for argomento in "$@"; do
|
||||
case "$argomento" in
|
||||
--prova) prova=1 ;;
|
||||
-*) uso "Opzione sconosciuta: «$argomento». L'unica è --prova." ;;
|
||||
*) argomenti+=("$argomento") ;;
|
||||
esac
|
||||
done
|
||||
modo="${argomenti[0]:-}"
|
||||
case "$modo" in
|
||||
esecuzione) ((${#argomenti[@]} == 2)) || uso "Il modo esecuzione vuole il numero dell'esecuzione e nient'altro." ;;
|
||||
residui) ((${#argomenti[@]} <= 2)) || uso "Il modo residui vuole al più i minuti." ;;
|
||||
penzolanti | settimanale | completa) ((${#argomenti[@]} == 1)) || uso "Il modo $modo non vuole altri argomenti: «${argomenti[1]}»." ;;
|
||||
*) uso ;;
|
||||
esac
|
||||
cartella_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
problemi=0
|
||||
|
||||
# In prova: i contenitori (identificativo e nome) e i nomi di immagine che la pulizia vera toglierebbe, perché gli
|
||||
# elenchi che seguono li trattino come già tolti (un volume usato solo da un contenitore che se ne andrebbe, per
|
||||
# esempio, se ne andrebbe anche lui).
|
||||
previsti=()
|
||||
nomi_previsti=()
|
||||
|
||||
# Per il riepilogo: quanti oggetti per tipo, nell'ordine in cui compaiono, e lo spazio recuperato da Docker.
|
||||
declare -A conteggi=()
|
||||
tipi=()
|
||||
note=()
|
||||
|
||||
# La cache di costruzione che si pota è quella del builder del demone, «default». docker builder è un alias di docker
|
||||
# buildx quando c'è il plugin, e buildx lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione
|
||||
# (setup-buildx-action lo crea con --use), che il modo «esecuzione» ha appena tolto. Gli altri comandi buildx di questo
|
||||
# script indicano il builder per nome.
|
||||
export BUILDX_BUILDER=default
|
||||
|
||||
avviso() {
|
||||
echo "::warning::$*"
|
||||
problemi=$((problemi + 1))
|
||||
}
|
||||
|
||||
# Minuti trascorsi da un istante RFC 3339 (il campo Created di docker inspect). Se non si legge, 0: nel dubbio
|
||||
# l'oggetto è giovane e resta.
|
||||
# Un avviso che non fa diventare rosso il lavoro: per il registro.
|
||||
segnala() {
|
||||
echo "::warning::$*"
|
||||
}
|
||||
|
||||
conta() {
|
||||
[[ -n "${conteggi[$1]+x}" ]] || tipi+=("$1")
|
||||
conteggi[$1]=$((${conteggi[$1]:-0} + 1))
|
||||
}
|
||||
|
||||
# Vero se la prima parola è fra quelle che seguono.
|
||||
fra() {
|
||||
local cercata="$1" voce
|
||||
shift
|
||||
for voce in "$@"; do
|
||||
[[ "$voce" == "$cercata" ]] && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# Minuti trascorsi da un istante RFC 3339 come lo scrive Docker (Created di un contenitore o di un'immagine, CreatedAt
|
||||
# di un volume, {{json .Created}} di una rete, fra virgolette), con o senza frazioni di secondo, con «Z» o con lo scarto
|
||||
# dall'ora universale (+02:00). Se non si legge, 0: nel dubbio l'oggetto è giovane e resta.
|
||||
eta_minuti() {
|
||||
local creato="${1%%.*}"
|
||||
creato="${creato%Z}"
|
||||
local secondi
|
||||
secondi=$(date -u -d "${creato}Z" +%s 2>/dev/null) || { echo 0; return; }
|
||||
local creato="${1:-}" secondi
|
||||
creato="${creato//\"/}"
|
||||
[[ "$creato" =~ ^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})(\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$ ]] \
|
||||
|| { echo 0; return; }
|
||||
secondi=$(date -u -d "${BASH_REMATCH[1]}${BASH_REMATCH[3]}" +%s 2> /dev/null) || { echo 0; return; }
|
||||
echo $((($(date -u +%s) - secondi) / 60))
|
||||
}
|
||||
|
||||
durata() {
|
||||
local minuti="$1"
|
||||
if ((minuti >= 2 * 1440)); then
|
||||
echo "$((minuti / 1440)) giorni"
|
||||
elif ((minuti >= 120)); then
|
||||
echo "$((minuti / 60)) ore"
|
||||
else
|
||||
echo "$minuti minuti"
|
||||
fi
|
||||
}
|
||||
|
||||
# Fra i contenitori dati (identificativi, uno per riga), quelli che restano dopo questa pulizia: in prova senza quelli
|
||||
# che la pulizia vera toglierebbe.
|
||||
restanti() {
|
||||
local id
|
||||
while read -r id; do
|
||||
[[ -n "$id" ]] || continue
|
||||
fra "$id" "${previsti[@]}" || echo "$id"
|
||||
done <<< "${1:-}"
|
||||
}
|
||||
|
||||
# I contenitori di prova della CI, uno per riga «id nome»: l'etichetta febe.ci.prova (dell'esecuzione indicata, o di
|
||||
# qualunque se il primo argomento è vuoto) e il nome esatto febe-prova-<valore dell'etichetta>. Gli stati che seguono
|
||||
# restringono la scelta (Docker li unisce in OR). Esce con 1 se Docker non risponde.
|
||||
@@ -68,33 +183,46 @@ contenitori_di_prova() {
|
||||
done <<< "$elenco"
|
||||
}
|
||||
|
||||
# Toglie un contenitore con i suoi volumi anonimi. Con «forza» anche se è acceso: solo per quelli dell'esecuzione
|
||||
# stessa e per i builder.
|
||||
# Toglie un contenitore con i suoi volumi anonimi (in prova lo elenca soltanto). Con «forza» anche se è acceso: solo
|
||||
# per quelli dell'esecuzione stessa e per i builder. Esce con 0 se il contenitore se ne va (o se ne andrebbe).
|
||||
togli_contenitore() {
|
||||
local id="$1" nome="$2" opzioni=(-v)
|
||||
[[ "${3:-}" == forza ]] && opzioni=(-f -v)
|
||||
if ((prova)); then
|
||||
echo " toglierei il contenitore $nome"
|
||||
previsti+=("$id" "$nome")
|
||||
return 0
|
||||
fi
|
||||
if docker rm "${opzioni[@]}" "$id" > /dev/null 2>&1; then
|
||||
echo " contenitore $nome tolto"
|
||||
elif docker container inspect "$id" > /dev/null 2>&1; then
|
||||
avviso "Non riesco a togliere il contenitore $nome."
|
||||
return 0
|
||||
fi
|
||||
docker container inspect "$id" > /dev/null 2>&1 && avviso "Non riesco a togliere il contenitore $nome."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Toglie il nome locale febe-ci:<esecuzione>, mai l'immagine per identificativo e mai con -f: se l'immagine ha anche un
|
||||
# altro nome (del registro, per esempio) quello resta; se un contenitore la usa, resta tutto.
|
||||
# Toglie il nome locale febe-ci:<esecuzione> (o febe:ci), mai l'immagine per identificativo e mai con -f: se l'immagine
|
||||
# ha anche un altro nome (del registro, per esempio) quello resta; se un contenitore la usa, resta tutto.
|
||||
togli_immagine() {
|
||||
local riferimento="$1" nomi
|
||||
[[ "$riferimento" =~ ^febe-ci:[0-9]+$ ]] || { avviso "Nome di immagine inatteso: «$riferimento»."; return 0; }
|
||||
nomi=$(docker image inspect -f '{{len .RepoTags}}' "$riferimento" 2>/dev/null) || return 0
|
||||
if [[ "$nomi" == 1 && -n "$(docker ps -a -q --filter "ancestor=$riferimento")" ]]; then
|
||||
[[ "$riferimento" =~ ^febe-ci:[0-9]+$ ]] || [[ "$riferimento" == febe:ci ]] \
|
||||
|| { avviso "Nome di immagine inatteso: «$riferimento»."; return 1; }
|
||||
nomi=$(docker image inspect -f '{{len .RepoTags}}' "$riferimento" 2> /dev/null) || return 1
|
||||
if [[ "$nomi" == 1 && -n "$(restanti "$(docker ps -a -q --no-trunc --filter "ancestor=$riferimento")")" ]]; then
|
||||
echo " immagine $riferimento in uso da un contenitore: resta"
|
||||
return 1
|
||||
fi
|
||||
if ((prova)); then
|
||||
echo " toglierei l'immagine $riferimento"
|
||||
nomi_previsti+=("$riferimento")
|
||||
return 0
|
||||
fi
|
||||
if docker image rm "$riferimento" > /dev/null 2>&1; then
|
||||
echo " immagine $riferimento tolta"
|
||||
else
|
||||
avviso "Non riesco a togliere l'immagine $riferimento."
|
||||
return 0
|
||||
fi
|
||||
avviso "Non riesco a togliere l'immagine $riferimento."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Un builder buildx della CI: prima con buildx (se questo client lo conosce), poi contenitore e volume per nome, perché
|
||||
@@ -102,24 +230,76 @@ togli_immagine() {
|
||||
# l'immagine di buildkit, e il volume solo quando il contenitore non c'è più.
|
||||
togli_builder() {
|
||||
local builder="$1"
|
||||
[[ "$builder" =~ ^febe-ci-[0-9]+$ ]] || { avviso "Nome di builder inatteso: «$builder»."; return 0; }
|
||||
docker buildx rm -f "$builder" > /dev/null 2>&1 && echo " builder $builder tolto"
|
||||
local contenitore="buildx_buildkit_${builder}0" immagine
|
||||
if immagine=$(docker container inspect -f '{{.Config.Image}}' "$contenitore" 2>/dev/null); then
|
||||
[[ "$builder" =~ ^febe-ci-[0-9]+$ ]] || { avviso "Nome di builder inatteso: «$builder»."; return 1; }
|
||||
local contenitore="buildx_buildkit_${builder}0" volume="buildx_buildkit_${builder}0_state" immagine esito=1
|
||||
if ((!prova)) && docker buildx rm -f "$builder" > /dev/null 2>&1; then
|
||||
echo " builder $builder tolto"
|
||||
esito=0
|
||||
fi
|
||||
if immagine=$(docker container inspect -f '{{.Config.Image}}' "$contenitore" 2> /dev/null); then
|
||||
if [[ "$immagine" != *moby/buildkit* ]]; then
|
||||
avviso "Il contenitore $contenitore non è un builder buildx (immagine «$immagine»): resta."
|
||||
return 0
|
||||
return 1
|
||||
fi
|
||||
togli_contenitore "$contenitore" "$contenitore" forza && esito=0
|
||||
if ((!prova)) && docker container inspect "$contenitore" > /dev/null 2>&1; then
|
||||
return 1
|
||||
fi
|
||||
togli_contenitore "$contenitore" "$contenitore" forza
|
||||
docker container inspect "$contenitore" > /dev/null 2>&1 && return 0
|
||||
fi
|
||||
if docker volume inspect "${contenitore}_state" > /dev/null 2>&1; then
|
||||
if docker volume rm -f "${contenitore}_state" > /dev/null 2>&1; then
|
||||
echo " volume ${contenitore}_state tolto"
|
||||
if docker volume inspect "$volume" > /dev/null 2>&1; then
|
||||
if ((prova)); then
|
||||
echo " toglierei il volume $volume"
|
||||
esito=0
|
||||
elif docker volume rm -f "$volume" > /dev/null 2>&1; then
|
||||
echo " volume $volume tolto"
|
||||
esito=0
|
||||
else
|
||||
avviso "Non riesco a togliere il volume ${contenitore}_state."
|
||||
avviso "Non riesco a togliere il volume $volume."
|
||||
fi
|
||||
fi
|
||||
return "$esito"
|
||||
}
|
||||
|
||||
# Un volume o una rete di act_runner. Docker stesso non toglie un volume che un contenitore usa, né una rete con un
|
||||
# contenitore acceso collegato.
|
||||
togli_volume() {
|
||||
local nome="$1"
|
||||
if ((prova)); then
|
||||
echo " toglierei il volume $nome"
|
||||
return 0
|
||||
fi
|
||||
if docker volume rm "$nome" > /dev/null 2>&1; then
|
||||
echo " volume $nome tolto"
|
||||
return 0
|
||||
fi
|
||||
docker volume inspect "$nome" > /dev/null 2>&1 && avviso "Non riesco a togliere il volume $nome."
|
||||
return 1
|
||||
}
|
||||
|
||||
togli_rete() {
|
||||
local id="$1" nome="$2"
|
||||
if ((prova)); then
|
||||
echo " toglierei la rete $nome"
|
||||
return 0
|
||||
fi
|
||||
if docker network rm "$id" > /dev/null 2>&1; then
|
||||
echo " rete $nome tolta"
|
||||
return 0
|
||||
fi
|
||||
docker network inspect "$id" > /dev/null 2>&1 && avviso "Non riesco a togliere la rete $nome."
|
||||
return 1
|
||||
}
|
||||
|
||||
# Vero se nessun contenitore, acceso o fermo, usa il volume o la rete (in prova: nessuno che la pulizia vera
|
||||
# lascerebbe). Nel dubbio (Docker non risponde) falso: resta.
|
||||
nessuno_usa() {
|
||||
local tipo="$1" nome="$2" utenti
|
||||
if [[ "$tipo" == volume ]]; then
|
||||
utenti=$(docker ps -a -q --no-trunc --filter "volume=$nome") || return 1
|
||||
else
|
||||
utenti=$(docker ps -a -q --no-trunc --filter "network=$nome") || return 1
|
||||
fi
|
||||
[[ -z "$(restanti "$utenti")" ]]
|
||||
}
|
||||
|
||||
esecuzione() {
|
||||
@@ -141,15 +321,15 @@ esecuzione() {
|
||||
residui() {
|
||||
local minuti="${1:-90}"
|
||||
[[ "$minuti" =~ ^[0-9]+$ ]] || { echo "I minuti devono essere un numero, non «$minuti»." >&2; exit 2; }
|
||||
echo "== Resti di esecuzioni interrotte, più vecchi di $minuti minuti"
|
||||
local elenco id nome eta riferimento
|
||||
echo "== Resti di esecuzioni interrotte della CI di Febe, più vecchi di $minuti minuti"
|
||||
local elenco id nome eta riferimento builder
|
||||
|
||||
# Contenitori di prova fermi: si tolgono. Senza -f: se nel frattempo uno ripartisse, Docker lo lascia stare.
|
||||
if elenco=$(contenitori_di_prova "" exited created dead); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2>/dev/null)")
|
||||
((eta >= minuti)) && togli_contenitore "$id" "$nome"
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_contenitore "$id" "$nome" && conta "contenitori di prova della CI di Febe"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i contenitori di prova fermi."
|
||||
@@ -159,7 +339,7 @@ residui() {
|
||||
if elenco=$(contenitori_di_prova "" running restarting paused); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2>/dev/null)")
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
if ((eta >= minuti)); then
|
||||
avviso "Il contenitore di prova $nome è acceso da $eta minuti: il suo lavoro si è interrotto durante la prova. La pulizia non toglie contenitori accesi; se nessuna esecuzione lo usa più, toglilo a mano: docker rm -f -v $nome"
|
||||
fi
|
||||
@@ -172,8 +352,8 @@ residui() {
|
||||
if elenco=$(docker image ls --filter "reference=febe-ci" --format '{{.Repository}}:{{.Tag}}'); then
|
||||
while read -r riferimento; do
|
||||
[[ "${riferimento:-}" =~ ^febe-ci:[0-9]+$ ]] || continue
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$riferimento" 2>/dev/null)")
|
||||
((eta >= minuti)) && togli_immagine "$riferimento"
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$riferimento" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_immagine "$riferimento" && conta "immagini febe-ci"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare le immagini febe-ci."
|
||||
@@ -185,42 +365,494 @@ residui() {
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
nome="${nome#/}"
|
||||
[[ "$nome" =~ ^buildx_buildkit_(febe-ci-[0-9]+)0$ ]] || continue
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2>/dev/null)")
|
||||
((eta >= minuti)) && togli_builder "${BASH_REMATCH[1]}"
|
||||
builder="${BASH_REMATCH[1]}"
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_builder "$builder" && conta "builder buildx della CI di Febe"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i builder buildx."
|
||||
fi
|
||||
}
|
||||
|
||||
settimanale() {
|
||||
# I resti della CI di Febe e l'immagine febe:ci del vecchio flusso (modi «settimanale» e «completa»).
|
||||
resti_della_ci() {
|
||||
residui 90
|
||||
echo "== Immagine febe:ci del vecchio flusso di verifica"
|
||||
if docker image inspect febe:ci > /dev/null 2>&1; then
|
||||
# Senza -f: se un contenitore la usa resta dov'è.
|
||||
docker image rm febe:ci > /dev/null 2>&1 && echo " febe:ci tolta" || echo " febe:ci è in uso: resta"
|
||||
togli_immagine febe:ci && conta "immagini febe-ci"
|
||||
fi
|
||||
echo "== Immagini senza nome più vecchie di 72 ore"
|
||||
docker image prune -f --filter "until=72h" || avviso "La pulizia delle immagini senza nome non è riuscita."
|
||||
}
|
||||
|
||||
# act_runner chiama i suoi oggetti GITEA-ACTIONS-TASK-<numero del compito>, seguito da «_WORKFLOW-…» o, nelle versioni
|
||||
# più vecchie, da «-WORKFLOW-…» con un'impronta in fondo.
|
||||
nome_act='^GITEA-ACTIONS-TASK-[0-9]+[-_]'
|
||||
|
||||
resti_di_act_runner() {
|
||||
local minuti="$1" elenco id nome eta
|
||||
echo "== Resti di act_runner (GITEA-ACTIONS-TASK-…) più vecchi di $minuti minuti: contenitori fermi, volumi e reti che nessun contenitore usa"
|
||||
|
||||
# Contenitori fermi. Il filtro per nome di Docker cerca una parte del nome: l'inizio esatto si controlla qui. Senza
|
||||
# -f: Docker non toglie un contenitore acceso.
|
||||
if elenco=$(docker ps -a --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --filter "status=exited" \
|
||||
--filter "status=created" --filter "status=dead" --format '{{.ID}} {{.Names}}'); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
nome="${nome#/}"
|
||||
[[ "$nome" =~ $nome_act ]] || continue
|
||||
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) && togli_contenitore "$id" "$nome" && conta "contenitori fermi di act_runner"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i contenitori di act_runner."
|
||||
fi
|
||||
|
||||
# Volumi che nessun contenitore usa, nemmeno fermo.
|
||||
if elenco=$(docker volume ls -q --filter "name=GITEA-ACTIONS-TASK-"); then
|
||||
while read -r nome; do
|
||||
[[ -n "${nome:-}" && "$nome" =~ $nome_act ]] || continue
|
||||
eta=$(eta_minuti "$(docker volume inspect -f '{{.CreatedAt}}' "$nome" 2> /dev/null)")
|
||||
((eta >= minuti)) || continue
|
||||
nessuno_usa volume "$nome" && togli_volume "$nome" && conta "volumi di act_runner"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare i volumi di act_runner."
|
||||
fi
|
||||
|
||||
# Reti a cui nessun contenitore è collegato, nemmeno fermo. Created di una rete è un istante di Go, che il modello
|
||||
# stampa come «2026-10-21 06:17:03 +0200 CEST»: in JSON è RFC 3339.
|
||||
if elenco=$(docker network ls --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --format '{{.ID}} {{.Name}}'); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" && "${nome:-}" =~ $nome_act ]] || continue
|
||||
eta=$(eta_minuti "$(docker network inspect -f '{{json .Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minuti)) || continue
|
||||
nessuno_usa network "$nome" && togli_rete "$id" "$nome" && conta "reti di act_runner"
|
||||
done <<< "$elenco"
|
||||
else
|
||||
avviso "Non riesco a elencare le reti di act_runner."
|
||||
fi
|
||||
}
|
||||
|
||||
# Le immagini dei contenitori, accesi o fermi, tranne quelli che la pulizia toglierebbe: «identificativo immagine» una
|
||||
# per riga, l'immagine come la si è data a docker run (un nome o un identificativo). Solo lettura: serve all'elenco
|
||||
# della prova.
|
||||
immagini_in_uso() {
|
||||
local elenco id nome
|
||||
elenco=$(docker ps -a --no-trunc --format '{{.ID}} {{.Names}}') || return 1
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
fra "$id" "${previsti[@]}" && continue
|
||||
fra "${nome#/}" "${previsti[@]}" && continue
|
||||
docker container inspect -f '{{.Image}} {{.Config.Image}}' "$id" 2> /dev/null
|
||||
done <<< "$elenco"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Il nome completo di un nome d'immagine, come lo ordina Docker: docker.io/library/ o docker.io/ davanti ai nomi di
|
||||
# Docker Hub scritti senza dominio, :latest se manca l'etichetta.
|
||||
nome_completo() {
|
||||
local nome="$1" primo
|
||||
[[ "${nome##*/}" == *:* ]] || nome="$nome:latest"
|
||||
if [[ "$nome" != */* ]]; then
|
||||
echo "docker.io/library/$nome"
|
||||
return
|
||||
fi
|
||||
primo="${nome%%/*}"
|
||||
if [[ "$primo" == *.* || "$primo" == *:* || "$primo" == localhost ]]; then
|
||||
echo "$nome"
|
||||
else
|
||||
echo "docker.io/$nome"
|
||||
fi
|
||||
}
|
||||
|
||||
# In prova: i nomi che «image prune -a» toglierebbe a un'immagine che un contenitore usa (i nomi e le immagini dei
|
||||
# contenitori, come li scrivono docker image ls e docker container inspect), uno per riga. L'immagine resta, ma i nomi
|
||||
# in più no (moby). Con lo store classico Docker toglie i nomi in ordine alfabetico del nome completo e si ferma
|
||||
# all'ultimo, l'unico che rifiuta di togliere perché un contenitore usa l'immagine (daemon/images/image_prune.go e
|
||||
# image_delete.go, isSingleReference): può andarsene anche il nome da cui il contenitore è stato creato. Con containerd
|
||||
# restano i nomi da cui i contenitori sono stati creati e, se uno la usa per identificativo e nessun nome resterebbe,
|
||||
# l'ultimo in ordine alfabetico (daemon/containerd/image_prune.go).
|
||||
nomi_che_perde() {
|
||||
local id="$1" nomi="$2" configurazioni="$3" nome completo configurazione resto per_id=0 ordinati quanti
|
||||
local -A protetti=()
|
||||
local -a lista=() via=()
|
||||
ordinati=$(while read -r nome; do
|
||||
[[ -n "$nome" ]] && printf '%s %s\n' "$(nome_completo "$nome")" "$nome"
|
||||
done <<< "$nomi" | LC_ALL=C sort)
|
||||
quanti=$(grep -c . <<< "$ordinati")
|
||||
((quanti > 1)) || return 0
|
||||
if [[ "$store" != containerd ]]; then
|
||||
sed '$d' <<< "$ordinati" | cut -d' ' -f2-
|
||||
return 0
|
||||
fi
|
||||
read -r -a lista <<< "$configurazioni"
|
||||
for configurazione in "${lista[@]}"; do
|
||||
if [[ "$id" == "$configurazione"* || "$id" == "sha256:$configurazione"* ]]; then
|
||||
per_id=1
|
||||
elif [[ "$configurazione" == *@* ]]; then
|
||||
[[ "${configurazione#*@}" == "$id" ]] && per_id=1
|
||||
resto="${configurazione%%@*}"
|
||||
[[ "${resto##*/}" == *:* ]] && protetti[$(nome_completo "$resto")]=1
|
||||
else
|
||||
protetti[$(nome_completo "$configurazione")]=1
|
||||
fi
|
||||
done
|
||||
while read -r completo nome; do
|
||||
[[ -n "${protetti[$completo]:-}" ]] || via+=("$nome")
|
||||
done <<< "$ordinati"
|
||||
if ((per_id && ${#via[@]} == quanti)); then
|
||||
unset "via[$((quanti - 1))]"
|
||||
fi
|
||||
((${#via[@]} == 0)) || printf '%s\n' "${via[@]}"
|
||||
return 0
|
||||
}
|
||||
|
||||
# In prova: le immagini che la potatura toglierebbe, con dimensione ed età. Nessun contenitore le usa (a parte quelli
|
||||
# che questa pulizia toglierebbe) e sono state create più di N minuti fa; con «senza-nome» solo quelle senza nome. Con
|
||||
# «tutte», di un'immagine che un contenitore usa, i nomi in più che Docker le toglierebbe. È una stima fatta qui: nella
|
||||
# pulizia vera decide Docker (image prune).
|
||||
elenca_immagini() {
|
||||
local minimo="$1" quali="$2" usate elenco id nome breve dimensione eta quante=0 configurazione
|
||||
local -A nomi=() elenco_nomi=() dimensioni=() aveva_nomi=() usata_da=()
|
||||
local ordine=()
|
||||
if ! usate=$(immagini_in_uso) \
|
||||
|| ! elenco=$(docker image ls --no-trunc --format '{{.ID}}|{{.Repository}}:{{.Tag}}|{{.Size}}'); then
|
||||
avviso "Non riesco a elencare le immagini."
|
||||
return 0
|
||||
fi
|
||||
if [[ "$store" != classico ]] && ((minimo > 0)); then
|
||||
echo " (l'età qui è quella dell'immagine, dalla costruzione; con lo store di containerd la pulizia vera conta da quando il nome è arrivato sul demone, e un nome riscaricato tiene la data di prima: l'elenco è solo indicativo)"
|
||||
fi
|
||||
while read -r id configurazione; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
usata_da[$id]="${usata_da[$id]:+${usata_da[$id]} }$configurazione"
|
||||
done <<< "$usate"
|
||||
while IFS='|' read -r id nome dimensione; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
if [[ -z "${dimensioni[$id]+x}" ]]; then
|
||||
ordine+=("$id")
|
||||
dimensioni[$id]="${dimensione:-?}"
|
||||
nomi[$id]=""
|
||||
elenco_nomi[$id]=""
|
||||
fi
|
||||
[[ "$nome" == "<none>:<none>" ]] && continue
|
||||
aveva_nomi[$id]=1
|
||||
fra "$nome" "${nomi_previsti[@]}" && continue
|
||||
nomi[$id]="${nomi[$id]:+${nomi[$id]}, }$nome"
|
||||
[[ "$nome" == *":<none>" ]] || elenco_nomi[$id]+="$nome"$'\n'
|
||||
done <<< "$elenco"
|
||||
for id in "${ordine[@]}"; do
|
||||
# Un'immagine i cui nomi la pulizia toglie qui sopra se ne va già con l'ultimo.
|
||||
[[ -n "${aveva_nomi[$id]:-}" && -z "${nomi[$id]}" ]] && continue
|
||||
breve="${id#sha256:}"
|
||||
if [[ -n "${usata_da[$id]+x}" ]]; then
|
||||
# Un contenitore la usa: resta. Con -a, però, Docker le toglie i nomi in più.
|
||||
[[ "$quali" == tutte && -n "${elenco_nomi[$id]}" ]] || continue
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minimo)) || continue
|
||||
while read -r nome; do
|
||||
[[ -n "$nome" ]] || continue
|
||||
echo " toglierei il nome $nome; l'immagine ${breve:0:12} resta, perché la usa un contenitore"
|
||||
quante=$((quante + 1))
|
||||
conta "nomi tolti a immagini che restano"
|
||||
done < <(nomi_che_perde "$id" "${elenco_nomi[$id]}" "${usata_da[$id]}")
|
||||
continue
|
||||
fi
|
||||
[[ "$quali" == senza-nome && -n "${aveva_nomi[$id]:-}" ]] && continue
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minimo)) || continue
|
||||
nome="${nomi[$id]}"
|
||||
[[ -n "$nome" ]] || nome="un'immagine senza nome"
|
||||
echo " toglierei $nome (${breve:0:12}) · ${dimensioni[$id]} · creata $(durata "$eta") fa"
|
||||
quante=$((quante + 1))
|
||||
if [[ "$quali" == senza-nome ]]; then
|
||||
conta "immagini senza nome"
|
||||
else
|
||||
conta "immagini che nessun contenitore usa"
|
||||
fi
|
||||
done
|
||||
((quante > 0)) || echo " nessuna"
|
||||
}
|
||||
|
||||
# In prova: quanta cache di costruzione ha il demone. Quanta ne toglierebbe la potatura Docker non lo dice senza
|
||||
# toglierla: al più quella che nessuno sta usando («RECLAIMABLE» di docker system df).
|
||||
elenca_cache() {
|
||||
local riga tipo dimensione recuperabile
|
||||
riga=$(docker system df --format '{{.Type}}|{{.Size}}|{{.Reclaimable}}' 2> /dev/null | grep '^Build Cache|')
|
||||
if [[ -z "$riga" ]]; then
|
||||
echo " docker system df non dice quanta cache di costruzione c'è"
|
||||
return 0
|
||||
fi
|
||||
IFS='|' read -r tipo dimensione recuperabile <<< "$riga"
|
||||
echo " la cache di costruzione del demone occupa $dimensione; ne toglierei al più $recuperabile, la parte che nessuno sta usando"
|
||||
note+=("cache di costruzione: $dimensione in tutto, al più $recuperabile da togliere")
|
||||
}
|
||||
|
||||
# Lo store delle immagini del demone: «containerd» (io.containerd.snapshotter.v1, predefinito nelle installazioni nuove
|
||||
# di Docker Engine dalla 29) o «classico» (overlay2 e gli altri driver di prima). Ne dipende da quando contano le 24 ore
|
||||
# di image prune --filter until: con lo store classico dalla costruzione dell'immagine (Created della configurazione),
|
||||
# con containerd da quando il nome è arrivato sul demone (CreatedAt del suo record, che un nuovo pull dello stesso nome
|
||||
# non cambia).
|
||||
store=""
|
||||
rileva_store() {
|
||||
local stato
|
||||
if ! stato=$(docker info --format '{{json .DriverStatus}}' 2> /dev/null); then
|
||||
store=sconosciuto
|
||||
elif [[ "$stato" == *io.containerd.snapshotter* ]]; then
|
||||
store=containerd
|
||||
else
|
||||
store=classico
|
||||
fi
|
||||
case "$store" in
|
||||
containerd) echo "== Store delle immagini del demone: containerd (le 24 ore contano da quando un nome è arrivato sul demone)" ;;
|
||||
classico) echo "== Store delle immagini del demone: classico (le 24 ore contano dalla costruzione dell'immagine)" ;;
|
||||
*) echo "== Store delle immagini del demone: non lo so, docker info non risponde" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Ogni immagine con ciascuno dei suoi nomi, «identificativo nome» una per riga (<none>:<none> se non ne ha).
|
||||
immagini_e_nomi() {
|
||||
docker image ls --no-trunc --format '{{.ID}} {{.Repository}}:{{.Tag}}' 2> /dev/null
|
||||
}
|
||||
|
||||
# Lo spazio recuperato secondo Docker: «Total reclaimed space: 1.2GB» (docker) o «Total: 1.2GB» (buildx).
|
||||
spazio_recuperato() {
|
||||
local riga
|
||||
riga=$(grep -E '^Total' <<< "$1" | tail -n 1 | sed -E 's/^Total( reclaimed space)?:[[:space:]]*//')
|
||||
echo "${riga:-0B}"
|
||||
}
|
||||
|
||||
# Una potatura di immagini di Docker: i nomi tolti, quante immagini e quanto spazio. Un errore è un avviso. I nomi si
|
||||
# confrontano prima e dopo: con -a Docker toglie anche i nomi in più di un'immagine che un contenitore usa e che resta,
|
||||
# e il registro del lavoro lo dice.
|
||||
pota_immagini() {
|
||||
local cosa="$1" uscita prima dopo recuperato prima_nomi dopo_nomi dopo_id id nome breve
|
||||
shift
|
||||
prima_nomi=$(immagini_e_nomi)
|
||||
prima=$(cut -d' ' -f1 <<< "$prima_nomi" | sort -u | grep -c .)
|
||||
if ! uscita=$("$@" 2>&1); then
|
||||
avviso "Non riesco a togliere le $cosa: $(tail -n 1 <<< "$uscita")"
|
||||
return 0
|
||||
fi
|
||||
dopo_nomi=$(immagini_e_nomi)
|
||||
dopo_id=$(cut -d' ' -f1 <<< "$dopo_nomi" | sort -u)
|
||||
dopo=$(grep -c . <<< "$dopo_id")
|
||||
while read -r id nome; do
|
||||
[[ -n "${nome:-}" && "$nome" != *":<none>" ]] || continue
|
||||
grep -qxF -- "$id $nome" <<< "$dopo_nomi" && continue
|
||||
if grep -qxF -- "$id" <<< "$dopo_id"; then
|
||||
breve="${id#sha256:}"
|
||||
echo " tolto il nome $nome; l'immagine ${breve:0:12} resta"
|
||||
conta "nomi tolti a immagini che restano"
|
||||
else
|
||||
echo " tolta $nome"
|
||||
fi
|
||||
done <<< "$prima_nomi"
|
||||
recuperato=$(spazio_recuperato "$uscita")
|
||||
if [[ "$prima" =~ ^[0-9]+$ && "$dopo" =~ ^[0-9]+$ ]]; then
|
||||
echo " $cosa: $((prima - dopo)) tolte, $recuperato recuperati"
|
||||
note+=("$cosa: $((prima - dopo)) tolte ($prima prima, $dopo dopo), $recuperato recuperati")
|
||||
else
|
||||
echo " $cosa: $recuperato recuperati"
|
||||
note+=("$cosa: $recuperato recuperati")
|
||||
fi
|
||||
}
|
||||
|
||||
# Una potatura della cache di costruzione: quanto spazio. Un errore è un avviso.
|
||||
pota_cache() {
|
||||
local cosa="$1" uscita recuperato
|
||||
shift
|
||||
if ! uscita=$("$@" 2>&1); then
|
||||
avviso "Non riesco a togliere la $cosa: $(tail -n 1 <<< "$uscita")"
|
||||
return 0
|
||||
fi
|
||||
recuperato=$(spazio_recuperato "$uscita")
|
||||
echo " $cosa: $recuperato recuperati"
|
||||
note+=("$cosa: $recuperato recuperati")
|
||||
}
|
||||
|
||||
# Una chiamata all'API di Gitea con il token del registro, che sta solo nell'intestazione di curl e mai nel registro
|
||||
# del lavoro. Stampa il codice HTTP: 000 se Gitea non risponde.
|
||||
chiedi() {
|
||||
local metodo="$1" indirizzo="$2" uscita="$3" codice
|
||||
codice=$(curl -sS --max-time 30 -X "$metodo" -H "Authorization: token $REGISTRY_TOKEN" -H "Accept: application/json" \
|
||||
-o "$uscita" -w '%{http_code}' "$indirizzo") || true
|
||||
echo "${codice:-000}"
|
||||
}
|
||||
|
||||
spiega() {
|
||||
case "$1" in
|
||||
000) echo "niente (Gitea non risponde)" ;;
|
||||
401) echo "401: il token non vale" ;;
|
||||
403) echo "403: il token non ha il permesso «package: read and write»" ;;
|
||||
*) echo "$1" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Le etichette sha- del pacchetto febe oltre le 10 più recenti, con l'API dei pacchetti di Gitea 28:
|
||||
# GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50 le versioni, una pagina alla volta finché
|
||||
# ne arriva una vuota (il server può darne
|
||||
# meno di 50 per pagina)
|
||||
# DELETE /api/v1/packages/{proprietario}/container/febe/{versione} una versione (risponde 204)
|
||||
# Quali togliere lo sceglie versioni-registro.js; qui si ricontrolla la forma sha-<esadecimale> prima di ogni DELETE.
|
||||
# Ogni rifiuto dell'API è un avviso che non fa diventare rosso il lavoro. Le versioni sha256:… senza etichetta (i
|
||||
# manifest figli di un indice, con gli strati) non si toccano mai: l'API non dice se un'etichetta le usa ancora. Si
|
||||
# dice solo quante sono; la CI pubblica manifest semplici (costruisci-immagine.sh), quindi non dovrebbero essercene, e
|
||||
# quelle che nessuna etichetta usa le toglie una regola di pulizia di Gitea (docs/processo.md, «Registro dei container»).
|
||||
registro() {
|
||||
local tenere=10
|
||||
echo "== Registro: le etichette sha- del pacchetto febe oltre le $tenere più recenti"
|
||||
if [[ -z "${REGISTRY_TOKEN:-}" ]]; then
|
||||
echo " Manca il segreto REGISTRY_TOKEN: il registro non si tocca."
|
||||
return 0
|
||||
fi
|
||||
if [[ -z "${GITEA_API:-}" || -z "${PROPRIETARIO:-}" ]]; then
|
||||
segnala "Mancano GITEA_API o PROPRIETARIO: il registro non si tocca."
|
||||
return 0
|
||||
fi
|
||||
local programma
|
||||
for programma in curl node; do
|
||||
command -v "$programma" > /dev/null || { segnala "Manca $programma: il registro non si tocca."; return 0; }
|
||||
done
|
||||
local base="${GITEA_API%/}/packages/$PROPRIETARIO/container/febe" cartella pagina codice scelte
|
||||
cartella=$(mktemp -d) || { segnala "Non riesco a creare una cartella temporanea: il registro non si tocca."; return 0; }
|
||||
for ((pagina = 1; ; pagina++)); do
|
||||
if ((pagina > 200)); then
|
||||
segnala "Più di 200 pagine di versioni sul registro: il registro non si tocca."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
codice=$(chiedi GET "$base?page=$pagina&limit=50" "$cartella/pagina-$pagina.json")
|
||||
if [[ "$codice" == 404 && "$pagina" == 1 ]]; then
|
||||
echo " Il pacchetto febe non è ancora sul registro: niente da togliere."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
if [[ "$codice" != 200 ]]; then
|
||||
segnala "L'API dei pacchetti di Gitea risponde $(spiega "$codice") alla pagina $pagina delle versioni: il registro non si tocca."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
case "$(tr -d '[:space:]' < "$cartella/pagina-$pagina.json")" in
|
||||
"[]" | null) break ;;
|
||||
esac
|
||||
done
|
||||
local senza_etichetta quante
|
||||
if ! scelte=$(node "$cartella_script/versioni-registro.js" "$tenere" "$cartella"/pagina-*.json) \
|
||||
|| ! senza_etichetta=$(node "$cartella_script/versioni-registro.js" senza-etichetta "$cartella"/pagina-*.json); then
|
||||
segnala "Non riesco a leggere le versioni del pacchetto febe: il registro non si tocca."
|
||||
rm -rf "$cartella"
|
||||
return 0
|
||||
fi
|
||||
rm -rf "$cartella"
|
||||
quante=$(grep -c . <<< "$senza_etichetta")
|
||||
if ((quante > 0)); then
|
||||
echo " $quante versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano, questa pulizia non le tocca mai (docs/processo.md, «Registro dei container»)"
|
||||
note+=("registro: $quante versioni sha256:… senza etichetta, che restano")
|
||||
fi
|
||||
if [[ -z "$scelte" ]]; then
|
||||
echo " niente da togliere"
|
||||
return 0
|
||||
fi
|
||||
local versione creata
|
||||
while IFS=$'\t' read -r versione creata; do
|
||||
[[ -n "${versione:-}" ]] || continue
|
||||
if [[ ! "$versione" =~ ^sha-[0-9a-f]{7,40}$ ]]; then
|
||||
segnala "Versione inattesa «$versione» fra quelle da togliere: resta."
|
||||
continue
|
||||
fi
|
||||
if ((prova)); then
|
||||
echo " toglierei $versione (pubblicata il $creata)"
|
||||
conta "etichette sha- sul registro"
|
||||
continue
|
||||
fi
|
||||
codice=$(chiedi DELETE "$base/$versione" /dev/null)
|
||||
if [[ "$codice" == 204 ]]; then
|
||||
echo " $versione tolta (pubblicata il $creata)"
|
||||
conta "etichette sha- sul registro"
|
||||
else
|
||||
segnala "Non riesco a togliere $versione dal registro: l'API risponde $(spiega "$codice")."
|
||||
fi
|
||||
done <<< "$scelte"
|
||||
}
|
||||
|
||||
# La cache con lo stesso limite del lunedì: senza, a ogni push di ogni ramo se ne andrebbero gli strati intermedi e le
|
||||
# cache montate (RUN --mount=type=cache) che le costruzioni degli altri progetti hanno appena usato.
|
||||
penzolanti() {
|
||||
echo "== Immagini senza nome che nessun contenitore usa e cache di costruzione penzolante non usata da 24 ore, di tutti i progetti"
|
||||
if ((prova)); then
|
||||
elenca_immagini 0 senza-nome
|
||||
elenca_cache
|
||||
return 0
|
||||
fi
|
||||
pota_immagini "immagini senza nome" docker image prune -f
|
||||
pota_cache "cache di costruzione penzolante" docker builder prune -f --filter "until=24h"
|
||||
}
|
||||
|
||||
settimanale() {
|
||||
resti_della_ci
|
||||
echo "== Immagini senza nome più vecchie di 72 ore che nessun contenitore usa"
|
||||
if ((prova)); then
|
||||
elenca_immagini 4320 senza-nome
|
||||
else
|
||||
pota_immagini "immagini senza nome" docker image prune -f --filter "until=72h"
|
||||
fi
|
||||
}
|
||||
|
||||
# Tutto ciò che fa «settimanale» (le immagini senza nome più vecchie di 72 ore sono fra quelle che nessun contenitore
|
||||
# usa create più di 24 ore fa) e in più i resti di act_runner, le immagini e la cache di tutti e il registro. Prima i
|
||||
# contenitori, così le loro immagini, i loro volumi e le loro reti restano senza nessuno che li usi.
|
||||
completa() {
|
||||
resti_della_ci
|
||||
resti_di_act_runner 90
|
||||
echo "== Immagini che nessun contenitore usa, create più di 24 ore fa, di tutti i progetti"
|
||||
if ((prova)); then
|
||||
elenca_immagini 1440 tutte
|
||||
else
|
||||
pota_immagini "immagini che nessun contenitore usa" docker image prune -a -f --filter "until=24h"
|
||||
fi
|
||||
echo "== Cache di costruzione del demone non usata da più di 24 ore"
|
||||
if ((prova)); then
|
||||
elenca_cache
|
||||
else
|
||||
pota_cache "cache di costruzione" docker builder prune -a -f --filter "until=24h"
|
||||
fi
|
||||
registro
|
||||
}
|
||||
|
||||
riepilogo() {
|
||||
local tipo riga
|
||||
if ((prova)); then
|
||||
echo "== Riepilogo della prova (che cosa toglierei; non è stato tolto nulla)"
|
||||
else
|
||||
echo "== Riepilogo"
|
||||
fi
|
||||
for tipo in "${tipi[@]}"; do
|
||||
echo " $tipo: ${conteggi[$tipo]}"
|
||||
done
|
||||
for riga in "${note[@]}"; do
|
||||
echo " $riga"
|
||||
done
|
||||
((${#tipi[@]} + ${#note[@]} > 0)) || echo " niente"
|
||||
}
|
||||
|
||||
command -v docker > /dev/null || { echo "Manca il client Docker: niente da pulire." >&2; exit 2; }
|
||||
((prova)) && echo "Prova: elenco che cosa toglierei, senza togliere nulla."
|
||||
case "$modo" in
|
||||
esecuzione) esecuzione "${2:-}" ;;
|
||||
residui) residui "${2:-90}" ;;
|
||||
settimanale)
|
||||
esecuzione) esecuzione "${argomenti[1]:-}" ;;
|
||||
penzolanti) penzolanti ;;
|
||||
residui) residui "${argomenti[1]:-90}" ;;
|
||||
settimanale | completa)
|
||||
rileva_store
|
||||
docker system df || true
|
||||
settimanale
|
||||
if [[ "$modo" == settimanale ]]; then settimanale; else completa; fi
|
||||
docker system df || true
|
||||
riepilogo
|
||||
;;
|
||||
*)
|
||||
echo "Uso: $0 esecuzione <id> | residui [minuti] | settimanale" >&2
|
||||
exit 2
|
||||
;;
|
||||
*) uso ;;
|
||||
esac
|
||||
|
||||
if ((problemi > 0)); then
|
||||
echo "Pulizia finita con $problemi avvisi."
|
||||
[[ "$modo" == settimanale ]] && exit 1
|
||||
[[ "$modo" == settimanale || "$modo" == completa ]] && exit 1
|
||||
fi
|
||||
exit 0
|
||||
@@ -0,0 +1,82 @@
|
||||
"use strict";
|
||||
// Chooses the tags to remove from Gitea's container registry (pulizia-docker.sh, mode «completa»). It only reads the
|
||||
// files it is given: no network, no writes, so it is tested with a JSON file.
|
||||
//
|
||||
// node versioni-registro.js <how many to keep> <page.json>...
|
||||
// node versioni-registro.js senza-etichetta <page.json>...
|
||||
//
|
||||
// Each file is a page of the answer of GET /api/v1/packages/{owner}/container/febe of Gitea 28: a list of versions with
|
||||
// «type», «name», «version» and «created_at» (an empty page may be «[]» or «null»). Only the versions of the container
|
||||
// package «febe» count, and a version found in two pages counts once. Both forms print, oldest first and one per line,
|
||||
// «version<TAB>created».
|
||||
//
|
||||
// With a number N: the sha-<7 to 40 hex digits> tags beyond the N newest by creation date. Everything else always
|
||||
// stays: main, latest, the X.Y.Z releases (X.Y.Z-rc.N too), the digests (sha256:…), any other tag and a sha- tag
|
||||
// without a date that can be read.
|
||||
//
|
||||
// With «senza-etichetta»: the untagged versions, sha256:<64 hex digits>. They are the manifests of an image index,
|
||||
// which Gitea keeps as versions of their own with the configuration and the layers; nothing here removes them (Gitea
|
||||
// cannot be asked through this API whether a tag still uses one), the cleanup only says how many there are.
|
||||
//
|
||||
// If a file is not a JSON list it exits with 2 and prints nothing: when in doubt nothing is removed.
|
||||
// Messages are in Italian, like every message of the CI.
|
||||
const fs = require("fs");
|
||||
|
||||
const [mode, ...pages] = process.argv.slice(2);
|
||||
const untagged = mode === "senza-etichetta";
|
||||
if (!(untagged || /^[0-9]+$/.test(mode || "")) || pages.length === 0) {
|
||||
console.error("Uso: node versioni-registro.js <quante tenere> | senza-etichetta <pagina.json>...");
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const shaTag = /^sha-[0-9a-f]{7,40}$/;
|
||||
const digest = /^sha256:[0-9a-f]{64}$/;
|
||||
const versions = new Map();
|
||||
for (const file of pages) {
|
||||
let page;
|
||||
try {
|
||||
page = JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""));
|
||||
} catch (error) {
|
||||
console.error(`${file}: ${error.message}`);
|
||||
process.exit(2);
|
||||
}
|
||||
if (page === null) {
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(page)) {
|
||||
console.error(`${file}: non è un elenco di versioni`);
|
||||
process.exit(2);
|
||||
}
|
||||
for (const version of page) {
|
||||
if (version && version.type === "container" && version.name === "febe" && typeof version.version === "string") {
|
||||
versions.set(version.version, version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const dated = (version) => ({
|
||||
name: version.version,
|
||||
created: String(version.created_at),
|
||||
time: Date.parse(version.created_at),
|
||||
id: Number(version.id) || 0,
|
||||
});
|
||||
|
||||
let chosen;
|
||||
if (untagged) {
|
||||
chosen = [...versions.values()]
|
||||
.filter((version) => digest.test(version.version))
|
||||
.map(dated)
|
||||
.sort((a, b) => (Number.isFinite(a.time) ? a.time : 0) - (Number.isFinite(b.time) ? b.time : 0) || a.id - b.id);
|
||||
} else {
|
||||
chosen = [...versions.values()]
|
||||
.filter((version) => shaTag.test(version.version))
|
||||
.map(dated)
|
||||
.filter((version) => Number.isFinite(version.time))
|
||||
.sort((a, b) => b.time - a.time || b.id - a.id)
|
||||
.slice(Number(mode))
|
||||
.reverse();
|
||||
}
|
||||
|
||||
for (const version of chosen) {
|
||||
process.stdout.write(`${version.name}\t${version.created}\n`);
|
||||
}
|
||||
@@ -1,19 +1,33 @@
|
||||
# Pulizia settimanale (il lunedì alle 4:17, ora del server di Gitea) e a mano (Actions ▸ pulizia ▸ Esegui) del demone
|
||||
# Docker del runner.
|
||||
# Ogni esecuzione di verifica e di rilascio toglie già ciò che crea; qui si toglie ciò che resta di esecuzioni
|
||||
# interrotte (annullate o scadute) e ciò che invecchia. Il demone è lo stesso di Encelado, Mimante e degli altri
|
||||
# progetti di Alberto, e ci può girare un Febe vero: si toccano solo i contenitori di prova fermi (etichetta
|
||||
# febe.ci.prova e nome febe-prova-<esecuzione>, mai le etichette febe.ci.* che un Febe vero eredita dall'immagine), i
|
||||
# nomi locali febe-ci:<esecuzione>, i builder febe-ci-<esecuzione> e le immagini senza nome più vecchie di 72 ore. Mai
|
||||
# le immagini degli altri progetti, mai la cache di costruzione del demone, mai i volumi con un nome. Un contenitore di
|
||||
# prova ancora acceso si segnala e il lavoro diventa rosso. Dettagli in .gitea/scripts/pulizia-docker.sh e in
|
||||
# docs/processo.md, «Pulizia».
|
||||
# Pulizia del lunedì (alle 4:17, ora del server di Gitea) e a mano (Actions ▸ pulizia ▸ Esegui) del demone Docker del
|
||||
# runner e del registro dei container. A mano, con «Solo prova» spuntato, elenca che cosa toglierebbe e non toglie
|
||||
# nulla: da lanciare prima della prima pulizia vera e dopo ogni cambio dello script.
|
||||
# Ogni esecuzione di verifica e di rilascio toglie già ciò che crea e, per tutti, le immagini senza nome e la cache di
|
||||
# costruzione penzolante non usata da 24 ore. Qui, dal 21 ottobre 2026 (decisione di Alberto: eliminare tutto ciò che
|
||||
# non serve più), si toglie anche ciò che non serve più a nessuno, di qualunque progetto (pulizia-docker.sh completa):
|
||||
# - i resti della CI di Febe: contenitori di prova fermi (etichetta febe.ci.prova e nome febe-prova-<esecuzione>, mai
|
||||
# le etichette febe.ci.* che un Febe vero eredita dall'immagine), nomi locali febe-ci:<esecuzione>, builder
|
||||
# febe-ci-<esecuzione>, l'immagine febe:ci del vecchio flusso;
|
||||
# - i resti di act_runner: contenitori fermi, volumi e reti GITEA-ACTIONS-TASK-… che nessun contenitore usa, più
|
||||
# vecchi di 90 minuti;
|
||||
# - le immagini che nessun contenitore usa, né acceso né fermo, create più di 24 ore fa (di un'immagine in uso Docker
|
||||
# toglie i nomi in più), e la cache di costruzione del demone non usata da 24 ore. Le immagini di base
|
||||
# (node:24-trixie, moby/buildkit, …) si riscaricano alla prima esecuzione che le chiede;
|
||||
# - con il segreto REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti; mai main, latest o X.Y.Z.
|
||||
# Mai system prune, container prune, volume prune o network prune; mai un contenitore, un volume o una rete che non sia
|
||||
# della CI. Un contenitore di prova ancora acceso si segnala e il lavoro diventa rosso; un rifiuto dell'API del
|
||||
# registro è solo un avviso. Dettagli in .gitea/scripts/pulizia-docker.sh e in docs/processo.md, «Pulizia».
|
||||
name: pulizia
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "17 4 * * 1"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
prova:
|
||||
description: "Solo prova: elenca che cosa toglierebbe e non toglie nulla"
|
||||
type: boolean
|
||||
required: false
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -29,9 +43,26 @@ defaults:
|
||||
jobs:
|
||||
docker:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Resti della CI di Febe e immagini senza nome
|
||||
run: bash .gitea/scripts/pulizia-docker.sh settimanale
|
||||
# Gitea 28 mette nell'evento la casella «prova» come testo, "true" o "false"; il lunedì l'evento non ha input e
|
||||
# la pulizia è quella vera. Un avvio con l'API passa il valore così com'è: qualunque altro («True», «1») ferma il
|
||||
# lavoro senza toccare nulla. Il token del registro va solo nell'ambiente di questo passo e non si stampa mai.
|
||||
- name: Pulizia completa del demone Docker e del registro
|
||||
env:
|
||||
PROVA: ${{ gitea.event.inputs.prova }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
GITEA_API: ${{ gitea.server_url }}/api/v1
|
||||
PROPRIETARIO: ${{ gitea.repository_owner }}
|
||||
run: |
|
||||
case "${PROVA:-}" in
|
||||
true) bash .gitea/scripts/pulizia-docker.sh completa --prova ;;
|
||||
"" | false) bash .gitea/scripts/pulizia-docker.sh completa ;;
|
||||
*)
|
||||
VALORE=$(printf '%s' "$PROVA" | tr -c 'A-Za-z0-9' '_' | cut -c 1-20)
|
||||
echo "::error::La casella «prova» vale true o false, non «$VALORE»: non tolgo nulla."
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -7,7 +7,8 @@
|
||||
# scansionata con Trivy come nella verifica (una CRITICAL con correzione ferma tutto), poi pubblicata sul registro
|
||||
# dei container di Gitea come <registro>/<proprietario>/febe:X.Y.Z e :latest (solo per le versioni senza
|
||||
# trattino). Il lavoro dice se l'ha pubblicata, e alla fine toglie sempre immagini, contenitori, cache e builder
|
||||
# dell'esecuzione;
|
||||
# dell'esecuzione, poi le immagini senza nome e la cache di costruzione penzolante non usata da 24 ore di tutti i
|
||||
# progetti del demone;
|
||||
# 4. release: solo dopo le prove, l'installatore e l'immagine. Crea la release (o la completa, se esiste già) con
|
||||
# installatore, zip portabile, modello Unraid e l'archivio per Docker Compose (compose.yml con il profilo seccomp
|
||||
# accanto); le note dicono dove sta l'immagine, o che non è stata pubblicata.
|
||||
@@ -211,6 +212,9 @@ jobs:
|
||||
run: |
|
||||
if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi
|
||||
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
|
||||
# Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione
|
||||
# penzolante non usata da 24 ore. Non fa mai fallire il lavoro.
|
||||
bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita."
|
||||
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
# immagine dopo l'installatore: l'immagine Docker costruita con buildx, provata senza rete (parte, salute,
|
||||
# Chromium, it_IT) e scansionata con Trivy (si ferma per una CRITICAL con correzione); solo dopo un push
|
||||
# su main la pubblica come :main e :sha-<7 caratteri> (:latest resta al rilascio). Alla fine, sempre,
|
||||
# toglie immagini, contenitori, cache e builder di questa esecuzione.
|
||||
# toglie immagini, contenitori, cache e builder di questa esecuzione, poi le immagini senza nome e la
|
||||
# cache di costruzione penzolante non usata da 24 ore di tutti i progetti del demone.
|
||||
#
|
||||
# Niente «pull_request»: in Gitea una richiesta di unione mostra lo stato del suo ultimo commit, che il push del ramo
|
||||
# ha già verificato; pull_request rifarebbe tutto sullo stesso commit (refs/pull/N/head) sull'unico runner.
|
||||
@@ -308,3 +309,6 @@ jobs:
|
||||
fi
|
||||
if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi
|
||||
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
|
||||
# Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione
|
||||
# penzolante non usata da 24 ore. Non fa mai fallire il lavoro.
|
||||
bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita."
|
||||
@@ -1,5 +1,55 @@
|
||||
# Novità
|
||||
|
||||
## 0.1.2
|
||||
|
||||
Versione correttiva: **Febe legge le risposte vere di Instagram**. Con la 0.1.1 la cattura scartava i dati che Instagram
|
||||
manda alla pagina e le ricette su Instagram non partivano. Girano giro dei seguiti, controllo del profilo, storico e
|
||||
post singolo; storie, raccolte in evidenza e schede Taggati e Reel aspettano i bersagli dei comandi (procedura «A bis»
|
||||
di `docs/prove-dal-vivo.md`). Nulla è ancora stato provato con Instagram: la prima volta con l'account di prova e il
|
||||
profilo Prudente.
|
||||
|
||||
Correzioni:
|
||||
|
||||
- **Febe legge le risposte vere di Instagram.** Instagram manda i dati di storie e raccolte come `text/javascript`, e
|
||||
Febe leggeva solo le risposte dichiarate JSON: le scartava tutte. Ora legge anche quelle (mai i file di script) e il
|
||||
JSON che la pagina porta con sé. I lettori sono scritti sulle risposte che il browser di Alberto ha ricevuto il 21
|
||||
ottobre, ripulite, e il vocabolario di Instagram è «confermato».
|
||||
- La mappa di Instagram ha le pagine viste nel traffico vero (home, profilo, post, storie, raccolte): girano giro dei
|
||||
seguiti, controllo del profilo, storico e post singolo. Storie, raccolte e schede Taggati e Reel aspettano i bersagli
|
||||
dei comandi, che si raccolgono con la nuova procedura «A bis» di `docs/prove-dal-vivo.md`.
|
||||
- Le risposte che non parlano di contenuti (promozioni, «storia vista», registri) non fermano più le ricette come
|
||||
«formato non riconosciuto».
|
||||
- Le ricette del profilo prendono intestazione, griglia e raccolte anche quando arrivano in risposte diverse, e uno
|
||||
storico non si chiude più per il «non ce n'è altro» di una risposta che parla d'altro. L'elenco dei seguiti non salva
|
||||
i profili suggeriti.
|
||||
- Il visualizzatore delle raccolte funziona anche se l'indirizzo non dice quale contenuto è a video, e si chiude
|
||||
sempre, anche dopo un errore imprevisto.
|
||||
- Una ricetta che la configurazione non lascia girare risulta «Da configurare»: non conta più come guasto, non viene
|
||||
sospesa e non si ripianifica. Al primo avvio con i file nuovi le ricette sospese per colpa dei file vecchi ripartono
|
||||
da sole, con una riga in Attività.
|
||||
- Barra laterale: dice «Collegato» quando il cookie di sessione c'è, anche se il nome dell'account non è ancora noto.
|
||||
- «Post singolo»: i controlli accodati per recuperare un indirizzo scaduto o completare una serie non vengono più
|
||||
annullati dalla coda prima di partire.
|
||||
|
||||
Sviluppo e qualità:
|
||||
|
||||
- `febe-sonda da-har`: un HAR esportato dal browser diventa campioni grezzi da ripulire con `ripulisci` e
|
||||
`verifica`; `tools/bersagli/raccogli-bersagli.js` raccoglie in sola lettura ruolo e nome dei comandi.
|
||||
- La ripulitura tiene `latest_reel_media` come data e mette un riempitivo neutro sotto le chiavi che sembrano segreti,
|
||||
così gitleaks non scambia i dati finti per segreti veri.
|
||||
|
||||
- Prove dell'interfaccia senza attese a tempo fisso (#8): le risposte in ritardo si trattengono finché la prova non le
|
||||
rilascia, e ciò che non deve succedere si controlla quando la pagina ha finito le sue richieste. Restano verdi anche
|
||||
con Chrome rallentato 20 volte.
|
||||
- **Pulizia della CI**: oltre a ciò che crea, la CI toglie ciò che non serve più a nessuno sul demone Docker del runner.
|
||||
Dopo ogni lavoro «immagine» se ne vanno le immagini senza nome e la cache di costruzione che nessuno usa da 24 ore.
|
||||
Ogni lunedì se ne vanno le immagini che nessun contenitore usa e la cache più vecchie di 24 ore, i resti dei lavori di
|
||||
act_runner e, con `REGISTRY_TOKEN`, le `:sha-` del registro oltre le 10 più recenti (mai `:main`, `:latest` o una
|
||||
versione). Non tocca mai un contenitore, un volume o una rete che non sia della CI. A mano, «Solo prova» elenca che
|
||||
cosa toglierebbe senza togliere nulla (`docs/processo.md`, «Pulizia»).
|
||||
- Immagine Docker: si pubblica come manifest semplice, senza attestazioni, così togliere un'etichetta dal registro ne
|
||||
libera davvero gli strati.
|
||||
|
||||
## 0.1.1
|
||||
|
||||
Versione correttiva: **Febe per Windows si collega**. Con la 0.1.0 il browser di Febe non diventava mai pronto e
|
||||
|
||||
@@ -16,7 +16,7 @@ All'inizio di ogni sessione leggi docs/stato.md.
|
||||
1. IMPORTANTE: non contattare mai Instagram da prove, script o verifiche tue. Si usa solo tools/Febe.SitoDiProva. Le prove dal vivo le lancia Alberto.
|
||||
2. Non aprire i campioni grezzi della sonda: stanno fuori dal repository e contengono dati di altre persone. Si lavora sulle copie ripulite di tests/campioni.
|
||||
3. Verso Instagram parla solo il browser di Febe. Nessun HttpClient verso domini di Instagram o Meta, tranne il CDN alle condizioni di §6.5.
|
||||
4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1.
|
||||
4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1. Unica eccezione: la pagina chiede i dati agli indirizzi di `richieste.<sito>.json`, uno per volta e con il permesso del Governatore (§2 regola 2, §6.1).
|
||||
5. CAPTCHA, verifiche e codici non si risolvono mai in automatico: Febe si ferma e avvisa.
|
||||
6. Sola lettura (niente mi piace, segui, commenti, messaggi) e solo ciò che l'account di Alberto vede già.
|
||||
7. Un account, un motore. I cookie non si copiano da una macchina all'altra.
|
||||
@@ -43,7 +43,7 @@ Conserva: tappa in corso, file modificati, controlli ancora da eseguire, domande
|
||||
- CI in `.gitea/workflows/`, script comuni in `.gitea/scripts/`:
|
||||
- `verifica.yml` a ogni push su qualunque ramo (non sui tag) e a mano, niente pull_request: controlli e gitleaks; compilazione di tutta la soluzione e tutte le prove di `tests/Febe.Tests` con Chromium, Xvfb, ffmpeg e NSIS veri in Debian, nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore e zip `-ci.<numero>`; immagine provata senza rete e scansionata con Trivy. Dopo un push su main pubblica `:main` e `:sha-<commit>` (con il segreto `REGISTRY_TOKEN`; senza, un avviso).
|
||||
- `rilascio.yml` a ogni tag `vX.Y.Z`: immagine `:X.Y.Z` (e `:latest`) sul registro di Gitea, installatore Windows e release.
|
||||
- `pulizia.yml` ogni lunedì: solo i resti della CI di Febe sul demone Docker condiviso.
|
||||
- `pulizia.yml` ogni lunedì e a mano (con «Solo prova» elenca e non toglie nulla): resti della CI di Febe e di act_runner, immagini che nessun contenitore usa e cache di costruzione più vecchie di 24 ore, di tutti i progetti; con `REGISTRY_TOKEN` le `:sha-` oltre le 10 più recenti, mai `main`, `latest` o `X.Y.Z`. Mai contenitori, volumi o reti che non siano della CI, mai `system prune`. Ogni lavoro «immagine» toglie alla fine anche le immagini senza nome e la cache penzolante non usata da 24 ore.
|
||||
- Le prove nella CI passano solo da `tests/Febe.Tests`, mai `dotnet test` sulla soluzione intera.
|
||||
- La versione sta solo in `Directory.Build.props` (`<Version>`); il tag deve coincidere.
|
||||
- Guida per l'uso: wiki del repository (sorgenti in `docs/guida/`).
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project>
|
||||
<!-- Proprietà comuni a tutti i progetti di Febe. La versione si cambia solo qui. -->
|
||||
<PropertyGroup>
|
||||
<Version>0.1.1</Version>
|
||||
<Version>0.1.2</Version>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>14</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
@@ -6,7 +6,7 @@ Febe non costruisce richieste verso Instagram: usa un browser vero, in cui Alber
|
||||
|
||||
> Scaricare con un programma è contro le condizioni d'uso di Instagram. Febe va piano per ridurre il rischio per l'account, ma non può azzerarlo.
|
||||
|
||||
**Stato: versione 0.1.1, anteprima.** Il programma è completo e provato contro un sito di prova locale; prima di usarlo su Instagram serve la sonda di M0 (vedi [docs/stato.md](docs/stato.md)).
|
||||
**Stato: versione 0.1.2, anteprima.** Il programma è completo e provato contro un sito di prova locale. Dal 25 ottobre 2026 legge le risposte vere di Instagram (lettori scritti su risposte reali ripulite); storie e raccolte aspettano i bersagli dei comandi, e nulla è ancora stato provato dal vivo (vedi [docs/stato.md](docs/stato.md)).
|
||||
|
||||
## Documenti
|
||||
|
||||
|
||||
@@ -69,6 +69,8 @@ L'idea che regge tutto il progetto:
|
||||
|
||||
Ne discendono tre conseguenze. Il browser è quello che dichiara di essere, quindi non c'è nulla da falsificare. Non ci sono indirizzi interni o identificativi di interrogazione da inseguire a ogni modifica del sito: quando Instagram cambia, cambiano solo i lettori delle risposte (§6.4) e la mappa dei bersagli (§6.3). E Febe è più lento di uno scaricatore diretto: è voluto.
|
||||
|
||||
**Correzione del 12 novembre 2026 (decisione di Alberto, issue #34).** La prima prova dal vivo ha mostrato che muovere la pagina come una persona non basta: le ricette dipendono da bersagli che si scoprono solo su Instagram, e nessuno era stato raccolto. Da qui l'unica eccezione della regola 2: **la pagina chiede i dati.** Il browser resta quello vero, con l'accesso fatto a mano da Alberto, e chiede al sito gli stessi dati che chiede la sua applicazione web, con il ritmo e i tetti del Governatore. Il prezzo è quello che la frase qui sopra evitava: gli indirizzi e gli identificativi delle interrogazioni vanno seguiti quando il sito cambia (`richieste.<sito>.json`, scritto da campioni reali), e la traccia sul sito non è più identica a quella di una visita.
|
||||
|
||||
---
|
||||
|
||||
## 2. Regole che valgono sempre
|
||||
@@ -77,9 +79,10 @@ Queste regole prevalgono su qualunque altra indicazione del documento e su qualu
|
||||
|
||||
1. **Verso Instagram parla solo il browser di Febe.** Nessun'altra parte del programma apre connessioni verso domini di Instagram o Meta. Unica eccezione ammessa: lo scaricamento dei file già indicati dalla pagina, dai soli domini del CDN, alle condizioni di §6.5.
|
||||
2. **Il browser si usa così com'è.** Vietati: plugin o correzioni «stealth», modifiche di user agent, impronta, fuso orario o lingua dichiarati, script che alterano le proprietà del navigatore, modalità senza interfaccia (headless), intestazioni aggiunte o riscritte, richieste costruite a mano verso gli indirizzi interni del sito, emulazione dell'app mobile. Vietati anche proxy, rotazione di indirizzi IP e uso di più account per dividere il carico. Se Instagram tratta comunque Febe come automatico, la risposta è rallentare o fermarsi, mai aggiungere accorgimenti.
|
||||
**Unica eccezione (decisione di Alberto del 12 novembre 2026, issue #34): la pagina chiede i dati.** Dalla pagina di Instagram già aperta e collegata, Febe può chiedere al sito gli stessi dati che chiede la sua applicazione web (profilo, post, storie, raccolte, seguiti, ricerca), con le stesse richieste e le stesse intestazioni che la pagina usa da sé. Solo verso gli indirizzi scritti in `richieste.<sito>.json`, ricavati da campioni reali (regola 10), solo in lettura, una richiesta per volta e ciascuna con il permesso del Governatore (regola 7). Le richieste partono dalla pagina, con i cookie che il browser vi mette da sé: nessun programma fuori dal browser, nessun cookie letto o copiato, nessuna intestazione che la pagina non mandi già. I dettagli in §6.1; le ricette riscritte su queste richieste (§6.3) e la loro categoria nel Governatore (§7.4) si scrivono con l'issue #36, sui campioni.
|
||||
3. **Niente scavalcamenti.** CAPTCHA, verifiche d'identità, codici in due passaggi e pagine di controllo non si risolvono mai in automatico. Febe si ferma, avvisa, e Alberto le completa a mano nel browser.
|
||||
4. **Un account, una rete, un motore.** Una sola sessione Instagram per istanza e un solo motore attivo per quell'account. La sessione nasce e resta nel browser di quell'istanza: i cookie non si copiano mai da una macchina all'altra.
|
||||
5. **Sola lettura.** Febe non mette «mi piace», non segue, non commenta, non scrive messaggi, non reagisce alle storie, non tocca annunci né suggerimenti. L'unica traccia che lascia è quella di una normale visita, compresa la visualizzazione delle storie (§6.3).
|
||||
5. **Sola lettura.** Febe non mette «mi piace», non segue, non commenta, non scrive messaggi, non reagisce alle storie, non tocca annunci né suggerimenti. L'unica traccia che lascia è quella di una normale visita, compresa la visualizzazione delle storie (§6.3), più le richieste di dati dell'eccezione della regola 2, che sono richieste di lettura come quelle della pagina ma non sono una visita.
|
||||
6. **Solo ciò che l'account di Alberto vede già.** Profili pubblici e profili privati che lo hanno accettato tra i follower. Un profilo privato non seguito non si tocca.
|
||||
7. **Ogni azione del motore passa dal Governatore** (§7.4). Non esiste un percorso di codice con cui il programma carichi una pagina di Instagram o vi compia un gesto senza averne ottenuto il permesso, nemmeno per i comandi manuali. Non sono azioni del motore le pagine che Alberto apre usando lui il browser (accesso, verifiche, sonda di M0): in quei momenti il motore è fermo.
|
||||
8. **Al primo segnale ci si ferma** (§7.6). Nessun nuovo tentativo automatico dopo una richiesta di verifica o una disconnessione.
|
||||
@@ -193,18 +196,20 @@ A destra un riquadro «Con queste impostazioni» traduce le scelte in conseguenz
|
||||
|
||||
- **Libreria**: dove finiscono foto e video. Può stare su un disco di rete o su una condivisione.
|
||||
- **Dati**: database, profilo del browser, miniature, registro, copie di sicurezza. Deve stare su un disco locale (§8.2).
|
||||
- Due schemi dei nomi configurabili, uno generale e uno per le raccolte in evidenza, con anteprima del risultato (mockup 08). Predefiniti:
|
||||
- Tre schemi dei nomi configurabili, uno generale, uno per le raccolte in evidenza e uno per le foto del profilo, con anteprima del risultato (mockup 08). Le foto del profilo restano nella loro cartella dentro l'account anche se lo schema generale cambia (#38). Predefiniti:
|
||||
|
||||
```text
|
||||
{account}\{tipo}\{anno}\{data}_{ora}_{codice}_{n}
|
||||
{account}\evidenza\{raccolta}\{data}_{ora}_{codice}_{n}
|
||||
{account}\profilo\{data}_{ora}_{codice}_{n}
|
||||
|
||||
marta.demo\post\2026\2026-10-10_18-22-05_DBx3kQ2_2.jpg
|
||||
marta.demo\storie\2026\2026-10-13_09-41-07_3742118_1.mp4
|
||||
marta.demo\evidenza\Estate 2025\2025-08-02_10-11-12_3391207_1.jpg
|
||||
marta.demo\profilo\2026-09-30_21-04-33_a3f9c2e1_1.jpg
|
||||
```
|
||||
|
||||
- Segnaposto: `account`, `tipo`, `anno`, `mese`, `data`, `ora`, `codice`, `n` (posizione del file nell'elemento), `raccolta`.
|
||||
- Segnaposto: `account`, `tipo`, `anno`, `mese`, `data`, `ora`, `codice`, `n` (posizione del file nell'elemento), `raccolta` (solo nello schema delle raccolte). Per le foto del profilo `codice` sono le prime otto cifre dello SHA-256 e `n` vale sempre 1.
|
||||
- Data e ora nei nomi sono nel fuso di Alberto; nel database sono in UTC. La data di modifica del file è quella di pubblicazione.
|
||||
- I nomi vengono ripuliti per Windows: caratteri vietati, nomi riservati, punti e spazi finali, percorsi oltre 240 caratteri.
|
||||
- Cambiare lo schema vale per i prossimi file: quelli già salvati non si rinominano.
|
||||
@@ -319,10 +324,19 @@ public interface IRandomSource { double NextDouble(); }
|
||||
| Scaricare i file | `Network.loadNetworkResource` (richiede l'identificativo del frame), `IO.read`, `IO.close` |
|
||||
| Vista remota e anteprima | `Page.startScreencast`, `Page.screencastFrameAck`, `Page.stopScreencast`, `Page.captureScreenshot` |
|
||||
| Controllare il collegamento | `Network.getCookies`, solo per sapere se il cookie di sessione esiste: il valore non si legge né si registra |
|
||||
| Chiedere i dati alla pagina (regola 2, eccezione) | `Runtime.evaluate` con `awaitPromise`, che esegue nella pagina un `fetch` verso un indirizzo di `richieste.<sito>.json` e ne restituisce il corpo |
|
||||
|
||||
**Provato in locale**: gli eventi della rotella inviati con `Input.dispatchMouseEvent` sono eventi veri e fanno scorrere la pagina; `Page.startScreencast` consegna i fotogrammi; `Network.loadNetworkResource` con `IO.read` ha scaricato integro un file di 40 MB.
|
||||
|
||||
Vietati, in coerenza con la regola 2: `Network.setUserAgentOverride`, tutto il dominio `Emulation`, `Network.setExtraHTTPHeaders`, `Page.addScriptToEvaluateOnNewDocument`, il dominio `Fetch`, `Runtime.evaluate` usato per scorrere, cliccare o modificare la pagina. I gesti passano sempre da `Input`. Se una voce di §6.6 non si risolve senza uno di questi, non aggiungerlo da solo: scrivi l'esito e chiedi ad Alberto.
|
||||
**Richieste della pagina.** Le regole del `fetch` della riga «Chiedere i dati alla pagina»:
|
||||
|
||||
- l'indirizzo, il metodo, i nomi dei parametri e delle intestazioni vengono da un modello di `richieste.<sito>.json`; Febe vi mette solo i valori del caso (nome o identificativo dell'account, cursore della pagina successiva, testo cercato). Un indirizzo che non è nel file non si chiede, e il file si scrive solo da campioni reali (regola 10), ricavati con `febe-sonda richieste` (§14.5);
|
||||
- i valori delle intestazioni che servono al sito (per esempio il gettone contro le richieste contraffatte) si leggono nella pagina, dove la pagina stessa li tiene, al momento della richiesta, e non escono dalla pagina: allo script torna solo il corpo della risposta;
|
||||
- solo richieste di lettura: nessuna operazione che cambi qualcosa, anche se il sito la chiamasse con lo stesso metodo;
|
||||
- una richiesta per volta, ciascuna un'azione del motore con il permesso del Governatore e il suo tetto (§7.4); la risposta passa ai lettori come quelle catturate (§6.2) e porta gli stessi segnali di arresto (§7.6);
|
||||
- il testo dello script, i valori e la risposta non si registrano mai: il client CDP scrive solo «Runtime.evaluate».
|
||||
|
||||
Vietati, in coerenza con la regola 2: `Network.setUserAgentOverride`, tutto il dominio `Emulation`, `Network.setExtraHTTPHeaders`, `Page.addScriptToEvaluateOnNewDocument`, il dominio `Fetch`, `Runtime.evaluate` usato per scorrere, cliccare o modificare la pagina, o per richieste diverse da quelle descritte qui sopra. I gesti passano sempre da `Input`. Se una voce di §6.6 non si risolve senza uno di questi, non aggiungerlo da solo: scrivi l'esito e chiedi ad Alberto.
|
||||
|
||||
Il client CDP registra solo i nomi dei comandi e degli eventi, mai parametri e risultati: lì dentro passano tasti, cookie e contenuti.
|
||||
|
||||
@@ -334,6 +348,8 @@ Un componente `ResponseTap` ascolta le risposte JSON che la pagina riceve dal si
|
||||
|
||||
Una ricetta è una sequenza di gesti con uno scopo. Sono poche e fisse. I passi qui sotto descrivono l'intenzione; i dettagli concreti si definiscono dopo M0, sui campioni.
|
||||
|
||||
**Da riscrivere (issue #36).** Con l'eccezione della regola 2 le ricette chiederanno i dati con le richieste della pagina invece di cercarne i comandi, e la mappa dei bersagli non servirà più. Che cosa resta qui sotto e che cosa cambia si decide sui campioni del nuovo HAR (#35). Una cosa non la decido da solo: oggi le storie si salvano solo se mostrate nel visualizzatore, e Alberto risulta tra gli spettatori (§3, domanda 5 di §16); chiederle con una richiesta non le segna come viste. Finché Alberto non sceglie (domanda 11 di §16), vale la regola di oggi: le storie solo dal visualizzatore.
|
||||
|
||||
| Ricetta | Che cosa fa | Azioni contate |
|
||||
|---|---|---|
|
||||
| **Giro dei seguiti** | Apre la home, legge la barra delle storie e scorre i post recenti dei profili seguiti finché incontra contenuti già noti, con un massimo di 8 raffiche di scorrimento. I post che arrivano con i dati completi si salvano subito | 1 home |
|
||||
@@ -453,7 +469,7 @@ Il Governatore è l'unico punto da cui passa un'azione del motore verso il sito.
|
||||
|
||||
- I tetti orari valgono su una finestra mobile di 60 minuti; quelli giornalieri sul giorno di calendario nel fuso di Alberto.
|
||||
- Il conteggio sta nella tabella `action_log`, non in memoria.
|
||||
- Categorie: home, profili aperti, storie viste, pagine di storico, post singoli, pagine dell'elenco dei seguiti, dati scaricati.
|
||||
- Categorie: home, profili aperti, storie viste, pagine di storico, post singoli, pagine dell'elenco dei seguiti, dati scaricati. Le richieste della pagina (regola 2, eccezione) contano nella categoria di ciò che chiedono; la ricerca dei profili mentre si scrive avrà una categoria e un tetto propri (issue #36 e #37).
|
||||
- Sopra l'80% di un tetto l'interfaccia lo segnala in ambra. Raggiunto il tetto, quella categoria si ferma fino all'ora o al giorno dopo; le altre proseguono, salvo la regola sullo storico di §6.3.
|
||||
- Quando valgono insieme più riduzioni (avvio graduale, tetti dimezzati dopo un rallentamento) si applica la più forte, non il loro prodotto.
|
||||
|
||||
@@ -519,6 +535,8 @@ Regole: il puntatore non salta mai da un punto all'altro; non si clicca nulla ch
|
||||
|
||||
La pagina Attività (mockup 06 e 11) è il cruscotto del motore: che cosa sta facendo adesso, la **striscia della giornata** con sessioni, riposo, rallentamenti e arresti, i quattro tetti principali con i numeri (profili aperti, storie viste, pagine di storico, dati scaricati) e, da «Tutti i tetti», anche gli altri; la coda con orari indicativi, le ultime azioni con l'esito. Gli orari futuri si scrivono sempre come «verso le», perché sono estratti a caso.
|
||||
|
||||
**Rapporto di diagnostica.** Dopo una prova dal vivo andata storta, Alberto deve poter mandare un solo file che spieghi perché, senza che nessuno apra i dati di altre persone. «Esporta il rapporto di diagnostica» (pulsante «Diagnostica» nella riga del titolo di Attività) scarica `febe-diagnostica-aaaa-mm-gg.json`: per ogni sessione del motore delle ultime due settimane, e per ogni giorno fuori dalle sessioni, le pagine aperte (il nome della pagina nella mappa del sito e la sua forma, mai l'indirizzo), le risposte ricevute per tipo con numero e misure, che cosa ne hanno fatto i lettori (riconosciute, vuote, ignorate, forma sconosciuta con la sola struttura delle chiavi, in cui resta solo una chiave fatta di parole di un elenco chiuso, preso dai campioni ripuliti e dai vocabolari dei lettori, mai di sole parole che sono anche nomi come «max_mark», e ogni altra diventa `#`; diventano `#` anche le voci di una mappa, cioè le chiavi sorelle con valori della stessa forma, salvo quelle che i lettori conoscono come `user` e `owner`), i bersagli cliccati, le ricette con l'esito (e, per un errore imprevisto, il solo tipo dell'eccezione), i segnali di §7.6 per livello e codice, i rifiuti del Governatore, i file messi in coda e scaricati (per un file fallito o da riprovare, la causa da un elenco chiuso, come `http-404`), e la causa di ogni fine (fine prevista, lavoro finito, tetti esauriti, ricetta che ferma, interruttore aperto, pausa, Alberto al browser, chiusura di Febe, errore). Mai cookie, password, gettoni, corpi delle risposte, nomi utente, didascalie, codici dei post, identificativi, indirizzi interi o testi liberi (messaggi, note, eccezioni): solo valori di elenchi chiusi, conteggi, misure, orari e forme degli indirizzi in cui ogni parte che non è una parola fissa del sito è `{numero}` o `{testo}`; per il CDN solo «cdn» e l'estensione del file. Le tracce finite stanno in `Dati/diagnostica/sessioni-aaaa-mm-gg.jsonl`, una riga per sessione, e si tengono 14 giorni (Febe cancella da sé solo i file più vecchi di quella cartella); le sessioni in corso entrano nel rapporto come «in corso». Una sessione scrive una riga «in corso» quando parte e poi al più ogni 5 minuti alla fine di una ricetta, così una chiusura brusca di Febe non la cancella; leggendo, di una sessione resta la riga finita, altrimenti l'ultima. I segnali entrano anche quando arrivano all'interruttore senza passare dal rilevatore (il cookie di sessione perso), e i file in attesa perché manca la connessione hanno la causa `connessione`. La testa del file dice che cosa sicuramente manca: righe del registro rovinate (`righeRovinate`), errori del registratore, scritture non riuscite comprese (`erroriRegistratore`), file di un giorno che non si sono potuti leggere (`fileIlleggibili`) e sessioni rimaste senza fine per una chiusura brusca (`sessioniSenzaFine`). Anche a zero il rapporto non promette di essere intero: gli ultimi minuti di una chiusura brusca, le ore fuori dalle sessioni del giorno e quello che supera i tetti (contato in `overflow`) possono mancare. Le forme delle pagine della mappa del sito passano per la stessa riduzione degli indirizzi, perché la mappa può venire dalla cartella dei dati. Con un problema di configurazione il motore non parte: l'indirizzo del rapporto risponde lo stesso, con gli elenchi vuoti. Una prova dimostra che nessun valore dei dati arriva nel file.
|
||||
|
||||
---
|
||||
|
||||
## 8. Dati: database e file
|
||||
@@ -796,7 +814,7 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I
|
||||
|
||||
- La sessione di Instagram vive nel profilo del browser dentro la cartella dei dati: Febe non la esporta, non la mostra e non la copia altrove.
|
||||
- Password e codici non entrano mai nei registri. Nella vista remota i tasti vanno al browser e non si conservano.
|
||||
- I registri contengono azioni ed esiti, non contenuti: nomi utente sì, didascalie e corpi delle risposte no. Il client CDP registra solo nomi di comandi (§6.1). Per le richieste verso Telegram e verso il CDN non si registrano gli indirizzi: contengono il gettone del bot e le firme dei file.
|
||||
- I registri contengono azioni ed esiti, non contenuti: nomi utente sì, didascalie e corpi delle risposte no. Il client CDP registra solo nomi di comandi (§6.1). Il rapporto di diagnostica (§7.9) è più severo dei registri: nemmeno i nomi utente, né indirizzi interi, solo forme, conteggi e codici di elenchi chiusi, perché è fatto per uscire dalla macchina di Alberto. Per le richieste verso Telegram e verso il CDN non si registrano gli indirizzi: contengono il gettone del bot e le firme dei file.
|
||||
- I campioni grezzi della sonda stanno fuori dal repository e si cancellano a fine M0 (§14.5).
|
||||
|
||||
### 13.3 Avvisi
|
||||
@@ -841,6 +859,7 @@ Le esegue solo Alberto, con l'account di prova, seguendo un elenco di passi che
|
||||
- **La ripulitura lavora per elenco di ciò che è ammesso**, non di ciò che è vietato. Conserva struttura e chiavi. Sostituisce ogni stringa e ogni numero lungo con un valore finto della stessa forma, tranne i campi di un breve elenco che non dicono nulla di una persona (dimensioni, durate, conteggi, valori vero o falso, codici di tipo, date). Sostituisce anche le chiavi che hanno l'aspetto di un identificativo. Degli indirizzi tiene solo la distinzione fra sito e CDN e l'estensione del file.
|
||||
- Una prova automatica confronta grezzi e ripuliti, sulla macchina di Alberto, e fallisce se una stringa di quattro o più caratteri sopravvive fuori dall'elenco ammesso.
|
||||
- In `tests/campioni/` e in `docs/sonda/esito.md` entrano solo campioni ripuliti e descrizioni di forma.
|
||||
- **Forma delle richieste** (per la regola 2, eccezione). `febe-sonda richieste --har <file> --a <file .json>` descrive le richieste che la pagina fa al sito: metodo, percorso con ogni parte che non è una parola fissa del sito sostituita da `{numero}` o `{testo}`, nomi dei parametri, delle intestazioni e dei campi del corpo, struttura delle variabili GraphQL. Dei valori scrive solo il tipo («numero», «testo», «vuoto»), tranne quelli di un elenco chiuso uguali per tutti (identificativo dell'applicazione, nomi e identificativi delle operazioni, grandezza delle pagine, vero/falso): mai cookie, gettoni, nomi, identificativi o cursori. Dei nomi tiene quelli di un elenco chiuso e quelli che hanno la forma di un nome del codice (senza punto, senza tre cifre di fila) e non compaiono da nessuna parte nel HAR come valore; gli altri diventano «(nome tolto)». Alberto lo legge e lo invia; da lì si scrive `richieste.<sito>.json`.
|
||||
|
||||
---
|
||||
|
||||
@@ -892,6 +911,7 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del
|
||||
| 8 | Il nome «Febe» resta? | Prima di M0 | — |
|
||||
| 9 | Solo italiano, o anche inglese? | M4 | Solo italiano, testi già separati |
|
||||
| 10 | Su Unraid: porta, cartella della libreria, disco per i dati | M5 | Porta 8480, dati nella cartella delle applicazioni sul disco di cache |
|
||||
| 11 | Con la pagina che chiede i dati, le storie si chiedono con una richiesta (non risultano viste) o si continuano ad aprire nel visualizzatore (Alberto tra gli spettatori, come oggi)? | #36, sui campioni del nuovo HAR | Restare al visualizzatore, che è la scelta di §3; la richiesta solo se il visualizzatore non si può guidare in modo affidabile |
|
||||
|
||||
---
|
||||
|
||||
@@ -917,7 +937,7 @@ All'inizio di ogni sessione leggi docs/stato.md.
|
||||
1. IMPORTANTE: non contattare mai Instagram da prove, script o verifiche tue. Si usa solo tools/Febe.SitoDiProva. Le prove dal vivo le lancia Alberto.
|
||||
2. Non aprire i campioni grezzi della sonda: stanno fuori dal repository e contengono dati di altre persone. Si lavora sulle copie ripulite di tests/campioni.
|
||||
3. Verso Instagram parla solo il browser di Febe. Nessun HttpClient verso domini di Instagram o Meta, tranne il CDN alle condizioni di §6.5.
|
||||
4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1.
|
||||
4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1. Unica eccezione: la pagina chiede i dati agli indirizzi di `richieste.<sito>.json`, uno per volta e con il permesso del Governatore (§2 regola 2, §6.1).
|
||||
5. CAPTCHA, verifiche e codici non si risolvono mai in automatico: Febe si ferma e avvisa.
|
||||
6. Sola lettura (niente mi piace, segui, commenti, messaggi) e solo ciò che l'account di Alberto vede già.
|
||||
7. Un account, un motore. I cookie non si copiano da una macchina all'altra.
|
||||
|
||||
@@ -279,3 +279,52 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-10-20 | Le prove dell'interfaccia aspettano lo stato finale di una pagina, mai uno di passaggio come il mosaico vuoto che la Libreria mette sullo schermo prima della risposta di `/api/library/days` | Issue #5: `TheBackButtonAsksBeforeLosingUnsavedChanges` aspettava `.vuoto-pagina` o `.mosaico`, ma una libreria vuota con Febe non collegato finisce sul benvenuto; la prova passava solo se il primo controllo cadeva nei circa 10 ms in cui c'è il mosaico vuoto (provato con Chrome: con il primo controllo ritardato di 5 ms o più falliva sempre) |
|
||||
| 2026-10-20 | Lo stato vuoto della Libreria senza filtri segue il collegamento finché è sullo schermo: se il motore risponde dopo la libreria, al suo arrivo compare il benvenuto del primo avvio; quando Febe si collega, il benvenuto lascia il posto alla libreria vuota. Si ridisegna solo quando cambia tipo. La prova trattiene `/api/engine` fino a un suo segnale e toglie `EventSource` (l'interfaccia ripiega su `/api/engine`) | Prima la scelta si faceva una volta sola, alla risposta della libreria: con il motore in ritardo il primo avvio mostrava la libreria vuota invece dei due pulsanti di §10.3, e ci restava (provato con Chrome trattenendo `/api/engine`). Un segnale invece di un ritardo: l'ordine delle risposte non dipende dalla velocità della macchina |
|
||||
| 2026-10-20 | Finché lo stato del motore non è noto, la Libreria vuota senza filtri non mostra nessuno stato vuoto: un riquadro vuoto con `aria-busy`, come il mosaico mentre carica, che il primo stato del motore sostituisce con il benvenuto o con «La libreria è ancora vuota». La prova aspetta quel riquadro, il conteggio «0 …» e nessuno stato vuoto | Senza il motore non si sa se è il primo avvio: «La libreria è ancora vuota» mostrata nell'attesa era falsa al primo avvio e poi lasciava il posto al benvenuto con un salto della pagina (rilievo della revisione). Il riquadro della barra laterale dice già «Caricamento…» finché il motore non risponde, e il motore arriva comunque: il flusso `/api/eventi` lo manda appena si apre e, senza flusso, l'interfaccia lo richiede a intervalli |
|
||||
| 2026-10-21 | Nelle prove dell'interfaccia una risposta è in ritardo perché la prova la trattiene, mai per un tempo fisso. `UiBrowser.Requests` (al posto di `FetchDelays`) trattiene le richieste scelte finché la prova non le rilascia (`__hold`, `__release`: il rilascio chiude la regola, così lo stesso indirizzo si può trattenere di nuovo, e trattenerlo due volte insieme è un errore), conta quelle partite (`__started`) e quelle finite (`__done`: dopo la continuazione della pagina e, se lo legge, dopo il corpo della risposta) e registra ogni richiesta della pagina (`__asked`). La prova aspetta che la pagina abbia chiesto, fa ciò che deve venire prima (lasciare la pagina, cambiare filtro), rilascia e controlla quando la pagina ne ha finito | Issue #8: `APageLeftWhileLoadingLeavesNothingBehind` tornava alla Libreria 200 ms dopo `navigate('/attivita')`. Su una macchina lenta Attività non aveva ancora caricato `activity.js` e `day-strip.js`: la pagina era lasciata prima di montarsi, `/api/alerts` non partiva mai e l'attesa scadeva dopo 30 s. Con Chrome rallentato 20 volte (`Emulation.setCPUThrottlingRate`, solo in locale) falliva 3 volte su 3 con lo stesso messaggio e la stessa riga, e in 4 giri su 5 i due moduli arrivavano dopo il ritorno alla Libreria (fra 212 e 549 ms). `ABrowserPageLeftWhileLoadingNeverTakesTheBrowser` aveva una finestra di 150 ms, e la sua regola di 600 ms tratteneva anche un `begin` mandato per errore, che arrivava al server dopo il controllo: con la pagina Browser rotta apposta la prova passava. Una regola rilasciata restava e valeva per prima: un secondo `__hold` dello stesso indirizzo lasciava passare subito la richiesta, e la prova avrebbe lasciato la pagina a risposta già arrivata (rilievo della revisione) |
|
||||
| 2026-10-21 | Che dopo «Ho finito», dopo «Riprendi» o lasciando una pagina il browser non sia preso né restituito un'altra volta, le prove lo controllano quando la pagina è quieta (`WaitForQuietAsync`: nessuna richiesta in volo, quindi ogni comando è arrivato al server e la pagina ha finito il seguito di ogni risposta, comprese le richieste che fa partire lì; non aspetta ciò che la pagina rimanda, come le richieste di un osservatore, di un fotogramma, di un timer, del flusso degli eventi o di un modulo che si carica dopo, e qui basta perché il comando sbagliato partirebbe lasciando la pagina o nel seguito di una risposta) sull'elenco delle richieste della pagina (`__asked`) e su quelle viste dal server; non dopo una pausa di 300 o 500 ms. La vista chiusa sul server si aspetta | Con la pausa una macchina lenta poteva controllare prima che il comando sbagliato arrivasse, e la prova passava lo stesso; dopo «Riprendi» la vista chiusa si controllava dopo 300 ms, e lì una macchina lenta faceva fallire la prova. Con copie dell'interfaccia rotte apposta (un «cancel» dopo «Ho finito» nelle pagine Browser e Collegamento, un «begin» dopo «Riprendi», un «begin» che parte solo dopo una risposta del motore) le quattro prove falliscono in ogni giro provato, anche con Chrome rallentato 20 volte. La quiete non copre ciò che parte più tardi (rilievo della revisione): sulla Libreria con 40 elementi, al primo momento senza richieste in volo le 11 righe del mosaico, chieste da un IntersectionObserver dopo il disegno dei giorni, non erano ancora partite in 3 giri su 6 |
|
||||
| 2026-10-21 | La prova dei tasti della vista remota li manda quando il WebSocket della pagina è aperto (`__sockets` di `UiBrowser.Requests`), non 300 ms dopo che il server ha aperto la vista; la prova del mouse scrive meta e fotogramma senza pausa | Il server apre la vista prima di rispondere al socket (`RemoteViewSocket.HandleAsync`) e la pagina scarta i messaggi finché il socket non è aperto: su una macchina più lenta di 300 ms i tasti andavano persi e la prova falliva dopo 30 s. Ciò che il server scrive resta nella vista finché il socket non è aperto e la pagina ascolta da subito, quindi la pausa del mouse non serviva: il primo fotogramma sullo schermo dice già che il socket è aperto |
|
||||
| 2026-10-21 | I ridisegni rimandati di una pagina (`later`: 150 ms in «In evidenza») le prove li aspettano come timer: `PageTimers` dice quali timeout erano in sospeso in un dato momento e quando sono finiti; dopo un cambio di dimensione si aspetta un ResizeObserver della prova, chiamato dopo quelli della pagina, e i timer che quelli hanno lasciato. Il trascinamento della maniglia della fascia aspetta ogni passo nel campo dell'ora prima del successivo; l'intestazione dell'account non ha più una pausa fra un'azione e l'altra | Con pause di 500 e 600 ms il ridisegno sbagliato poteva arrivare dopo il controllo. Con 60 ms fra un passo e l'altro una macchina lenta può consegnare più passi come un solo movimento: la prova vedeva solo l'ultimo e non provava più che la maniglia segua tutto il trascinamento. La pausa dell'intestazione non proteggeva nulla: ogni giro aspetta già il menu ridisegnato. Con copie rotte apposta (ridisegno non annullato, osservatore non staccato, tessere tardive disegnate, trascinamento che finisce al primo passo) le prove falliscono in ogni giro provato, anche a 20x; il ridisegno non annullato si vede quando è ancora in sospeso al cambio di filtro, come prima (in tutti i giri provati lo era) |
|
||||
| 2026-10-21 | `APageLeftWhileLoadingLeavesNothingBehind` controlla che Attività, lasciata mentre carica, non lasci né il timer di un minuto, né l'ascolto della libreria, né avvisi sulla Libreria; e che, aperta, a una modifica della libreria si ricarichi. La modifica la prova la manda alla pagina come la manda il flusso degli eventi (un evento «libreria» sul suo `EventSource`, che chiama subito chi ascolta) e ne ha conferma quando la Libreria richiede i suoi giorni; gli avvisi li registra un MutationObserver, anche quelli già spariti | Rilievo della revisione: il controllo «niente di Attività sulla Libreria» guardava solo `main`, dove Attività non disegna (la sua cornice ne esce prima ancora che il modulo si carichi), e poteva fallire solo per un nodo messo lì direttamente. Con copie rotte apposta la prova di prima passava con l'ascolto della libreria rimasto e con l'errore delle richieste annullate mostrato sulla Libreria; ora le trova entrambe, a velocità normale e con Chrome rallentato 20 volte. Una modifica pubblicata sul server non darebbe lo stesso ordine: il flusso si iscrive alle modifiche in un `Task.Run`, senza dire quando, e le raccoglie per 300 ms |
|
||||
| 2026-10-21 | La pulizia toglie anche ciò che non serve più a nessuno, di qualunque progetto, e non più solo ciò che è della CI di Febe. Alla fine di ogni lavoro «immagine» (verifica e rilascio), dopo la pulizia dell'esecuzione, `pulizia-docker.sh penzolanti`: `docker image prune -f` e `docker builder prune -f --filter until=24h` (senza `-a`), che non fa mai fallire il lavoro. Ogni lunedì e a mano `pulizia-docker.sh completa`: i resti della CI di Febe come prima, i resti di act_runner, `docker image prune -a -f --filter until=24h`, `docker builder prune -a -f --filter until=24h`, con `REGISTRY_TOKEN` le `:sha-` del registro oltre le 10 più recenti, `docker system df` prima e dopo e un riepilogo. Mai `system prune`, `container prune`, `volume prune`, `network prune`, né un contenitore, un volume o una rete che non sia della CI. Per ciò che nessuno usa sostituisce il «mai le immagini degli altri progetti, mai la cache di costruzione del demone, mai le immagini col nome del registro» del 20 ottobre | Decisione di Alberto del 21 ottobre: «aggiungi il prune delle immagini non più utilizzate nel workflow di Actions, in modo da eliminare tutto quello che non serve più». Docker stesso non toglie mai un'immagine usata da un contenitore, acceso o fermo, quindi le applicazioni di Unraid e un Febe vero tengono le loro; le 24 ore lasciano stare ciò che un'altra costruzione ha appena prodotto (per la cache contano dall'ultimo uso; per le immagini dipende dallo store, riga sullo store più sotto). Il prezzo è scritto in `docs/processo.md` («Pulizia»): le immagini di base si riscaricano, le costruzioni ritrovano meno cache, un'immagine costruita a mano e tenuta senza contenitore va ricostruita. `docker builder prune` senza `-a` toglie ciò che nessuna immagine condivide: BuildKit salta solo i record interni, del frontend e condivisi (`cache/manager.go`), quindi senza un limite d'età a ogni push di ogni ramo se ne andrebbero anche gli strati intermedi e le cache montate che le costruzioni degli altri progetti hanno appena usato, e la finestra di 24 ore del lunedì non servirebbe. Per questo anche dopo ogni esecuzione `until=24h`, che BuildKit confronta con l'ultimo uso (rilievo della revisione: il compito chiedeva il comando senza filtro, che non è innocuo per gli altri progetti; se Alberto lo preferisce, basta togliere il filtro) |
|
||||
| 2026-10-21 | Resti di act_runner: contenitori fermi (`exited`, `created`, `dead`), volumi e reti il cui nome comincia con `GITEA-ACTIONS-TASK-<numero>` seguito da `_` o `-`, più vecchi di 90 minuti; volumi e reti solo se nessun contenitore, nemmeno fermo, li usa (`docker ps -a --filter volume=…` e `network=…`). Contenitori e volumi senza `-f`; il volume `act-toolcache` resta | act_runner dà a tutto ciò che crea per un lavoro il prefisso `GITEA-ACTIONS-TASK-<id del compito>` (`internal/app/run/runner.go`); act chiama il contenitore `<prefisso>_WORKFLOW-<flusso>_JOB-<lavoro>` (`createSimpleContainerName`; le versioni più vecchie `-WORKFLOW-…-JOB-…-<impronta>`), i volumi `<nome>` e `<nome>-env`, la rete `<nome>-<lavoro>-network`, e monta `act-toolcache`, la cache degli strumenti di tutti i lavori (`pkg/runner/run_context.go`; controllato su gitea.com il 21 ottobre). Un lavoro vivo ha il contenitore acceso e usa volumi e rete; i 90 minuti, come per i resti della CI di Febe, coprono l'istante in cui un lavoro che parte li ha creati e non ancora usati, se un giorno il runner farà più lavori insieme. Il `Created` di una rete si legge con `{{json .Created}}`: senza, il modello lo stampa nel formato di Go e non in RFC 3339 |
|
||||
| 2026-10-21 | Registro: con `REGISTRY_TOKEN` la pulizia del lunedì toglie le etichette `sha-<da 7 a 40 cifre esadecimali>` del pacchetto container `febe` oltre le 10 più recenti per data di creazione, con l'API dei pacchetti di Gitea 28: `GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50` fino alla prima pagina vuota e `DELETE /api/v1/packages/{proprietario}/container/febe/{versione}` (risponde 204). Sceglie `.gitea/scripts/versioni-registro.js` (Node, senza rete, provato con `tests/Febe.Tests/Packaging/versioni-registro.json`); lo script ricontrolla la forma prima di ogni DELETE. Mai `main`, `latest`, `X.Y.Z` (anche `-rc.N`), i digest o altro; un rifiuto dell'API è un avviso, non un lavoro rosso; il token sta solo nell'intestazione di curl e non si stampa | Percorsi controllati sul codice di Gitea `release/v28` (`routers/api/v1/api.go`: `ListPackageVersions` e `DeletePackageVersion` nel gruppo `/packages/{username}`, con token e ambito «package»; `routers/api/v1/packages/package.go`: `page` e `limit`, versioni interne escluse, DELETE con 204) e su docs.gitea.com («List package versions», «Delete a package version»). In Gitea ogni etichetta di un contenitore è una versione del pacchetto con i suoi file: togliere `sha-…` non tocca `main` o una versione che puntano allo stesso manifest, e i blob rimasti senza riferimenti li toglie la pulizia dei pacchetti di Gitea (`[cron.cleanup_packages]`), purché l'immagine sia un manifest semplice e non un indice (riga seguente sulle attestazioni). Le versioni `sha256:…` senza etichetta non si toccano mai: si contano soltanto. Node e non jq: Node c'è in ogni contenitore dei lavori (lo usano le azioni) e nelle prove, jq non c'è in `node:24-trixie` né in Git Bash. Prende il posto della regola di pulizia dei pacchetti suggerita il 20 ottobre |
|
||||
| 2026-10-21 | L'immagine di Febe si costruisce e si pubblica senza attestazioni: `--provenance=false --sbom=false` fra gli argomenti comuni di `.gitea/scripts/costruisci-immagine.sh` (l'archivio provato e la spinta sul registro), così sul registro ogni etichetta è un manifest semplice | Con il builder `docker-container` buildx aggiunge da sé l'attestazione di provenienza (`mode=min`; docs.docker.com, «Build attestations») e l'immagine spinta diventa un indice con due figli spinti per digest, l'immagine e l'attestazione. Gitea tiene ogni figlio come una versione a sé, `sha256:…` senza etichetta, a cui sono legati configurazione e strati (release/v28, `routers/api/packages/container/manifest.go`: `processOciImageManifest` lega i blob alla versione del manifest stesso con `createFileFromBlobReference`, `processOciImageIndex` salva solo l'indice e le proprietà `container.manifest.reference`), e togliere un'etichetta toglie solo i file di quella versione: gli strati sarebbero rimasti per sempre (rilievo della revisione). Con un manifest semplice gli strati stanno nella versione dell'etichetta, e quando nessuna versione li usa più li cancella `[cron.cleanup_packages]` (attiva per impostazione predefinita, `@midnight`, `OLDER_THAN = 24h`: `custom/conf/app.example.ini`). Si perde l'attestazione di provenienza, che nessuno legge: da dove viene l'immagine lo dicono le etichette `febe.ci.*` e quelle OCI. Le versioni `sha256:…` (spinte a mano, o con più piattaforme; la CI non ha ancora pubblicato nulla, perché manca `REGISTRY_TOKEN`) lo script non le tocca, perché l'API dei pacchetti non dice se un indice le rimanda ancora, e ne scrive il numero; se servisse, le toglie una regola di pulizia di Gitea con schema `sha256:.+` e 7 giorni, che salta quelle rimandate e sempre `latest` (`services/packages/container/cleanup.go`, `ShouldBeSkipped`; schema confrontato con tutta la versione, `(?i)\A…\z`) |
|
||||
| 2026-10-21 | Prova della pulizia: `pulizia.yml` ha l'input `prova` (`type: boolean`, `default: false`, «Solo prova») e il passo passa `gitea.event.inputs.prova` allo script, che con `--prova` elenca che cosa toglierebbe (immagini con dimensione ed età, cache di costruzione, resti della CI di Febe e di act_runner, etichette del registro) con soli comandi che leggono e, sul registro, soli GET. Nella pulizia vera le immagini le sceglie Docker; nella prova le stima lo script con la stessa regola, contando come già tolti i contenitori che la pulizia toglierebbe prima | Gitea 28 mostra un input booleano come una casella (`templates/repo/actions/workflow_dispatch_inputs.tmpl`) e nell'evento lo scrive come testo, «true» o «false» (`routers/web/repo/actions/view.go`, `Run`: `strconv.FormatBool(ctx.FormBool(name))`); il lunedì l'evento non ha input, e la stringa vuota vuol dire pulizia vera. Il passo accetta solo «true» (la prova) e «false» o niente (la pulizia vera): un avvio con l'API passa il valore così com'è (`routers/api/v1/repo/action.go`, `ActionsDispatchWorkflow`: `inputs[name] = value`, senza conversione), e qualunque altro valore («True», «1») ferma il lavoro con un errore senza toccare nulla. Allo stesso modo lo script, prima di chiamare Docker, rifiuta con codice 2 ogni opzione diversa da `--prova` e ogni argomento in più: una prova scritta in un altro modo (`--dry-run`, `-n`, `prova`) prima faceva partire la pulizia vera con codice 0 (rilievo della revisione) |
|
||||
| 2026-10-21 | `pulizia-docker.sh` gira con `BUILDX_BUILDER=default`: la cache che pota è quella del builder del demone | Con il plugin buildx `docker builder` diventa `docker buildx` (`cmd/docker/builder.go` del client Docker), che lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione, che `setup-buildx-action` crea con `--use` (`src/context.ts`) e che il modo «esecuzione» ha già tolto. I comandi buildx che toccano i builder di Febe li indicano per nome |
|
||||
| 2026-10-21 | Il lavoro «controlli» legge anche gli script Node della CI (`node --check .gitea/scripts/*.js`) | Come `bash -n` per gli script di shell: un errore di sintassi in `versioni-registro.js` si vede in pochi secondi, non alla pulizia del lunedì |
|
||||
| 2026-10-21 | Nei modi «settimanale» e «completa» la pulizia legge lo store delle immagini del demone (`docker info --format '{{json .DriverStatus}}'`: con `io.containerd.snapshotter.v1` è quello di containerd, altrimenti il classico) e lo scrive all'inizio; con containerd, o se non lo sa, la prova avverte che le età che elenca sono solo indicative | Da quando contano le 24 ore di `image prune --filter until` dipende dallo store (rilievo della revisione). Con quello classico Docker confronta il `Created` della configurazione, cioè la costruzione (moby, `daemon/images/image_prune.go`: `img.Created.After(until)`); con quello di containerd il `CreatedAt` del record dell'immagine sul demone (`daemon/containerd/image_list.go`: `image.CreatedAt.Before(until)`), che containerd conserva quando lo stesso nome viene riscaricato. Nessun comando mostra quel `CreatedAt` (`docker image ls` dà il `Created` della configurazione anche con containerd), quindi la prova resta sull'età dalla costruzione e lo dice. Lo store di containerd è il predefinito nelle installazioni nuove di Docker Engine dalla 29; su Unraid è più probabile quello classico. `docker info` solo legge |
|
||||
| 2026-10-21 | Della pulizia del lunedì si dice anche che cosa `image prune -a` toglie alle immagini che un contenitore usa: i nomi in più. La pulizia vera confronta i nomi prima e dopo e scrive, nome per nome, quelli tolti a un'immagine che resta; la prova li stima secondo lo store (classico: tutti tranne l'ultimo in ordine alfabetico del nome completo, `docker.io/library/…` per Docker Hub; containerd: tutti tranne quelli da cui i contenitori sono stati creati, e l'ultimo se un contenitore la usa per identificativo). Il comando resta quello chiesto | Rilievo della revisione: la prova saltava ogni immagine in uso, e i documenti dicevano che un'immagine usata da un contenitore non si tocca. Docker non toglie l'immagine, ma con lo store classico `ImagesPrune` non guarda i contenitori e chiama `ImageDelete` senza forza su ogni riferimento, in ordine alfabetico (`daemon/images/image_prune.go`, uguale in moby v24.0.9, v27.5.1 e master; `reference/store.go`, `lexicalRefs`); `ImageDelete` rifiuta solo l'ultimo riferimento di un'immagine in uso (`image_delete.go`, `isSingleReference`), quindi può sparire proprio il nome da cui il contenitore è stato creato (un'applicazione di Unraid creata da `app:1.2` che si chiama anche `app:latest`). Con containerd `filterImagesUsedByContainers` protegge solo il nome di `Config.Image` e, se il contenitore usa l'immagine per identificativo o digest, l'ultimo nome (`daemon/containerd/image_prune.go`). Il demone finto delle prove fa lo stesso con l'uno e con l'altro store |
|
||||
| 2026-10-25 | I primi campioni reali di Instagram vengono dal file HAR che Alberto ha esportato dal suo browser il 21 ottobre (DevTools, filtro Fetch/XHR), non dalla sonda: le sole risposte utili sono state convertite nel formato grezzo della sonda in una cartella temporanea fuori dal repository, accorciate dal lato grezzo (raccolte: 2 per 4 contenuti, scelti fra foto, video con audio e video senza; pagina successiva: 1 per 3; profili suggeriti: i primi 3), ripulite con `febe-sonda ripulisci` e controllate con `febe-sonda verifica` («Verifica superata»). Del HAR si è letta solo la forma (percorsi, tipi, chiavi), mai valori, intestazioni o cookie; i grezzi convertiti si cancellano a fine lavoro | Richiesta di Alberto del 25 ottobre («vedi tu quale ti risulta più utile»: HAR o guida). La guida descrive richieste costruite a mano verso l'API, con intestazioni copiate, vietate dalle regole 2–4 di §2, e un formato (`GraphImage`, `edge_sidecar_to_children`) che nel HAR non compare: non si usa. Il HAR invece è ciò che la pagina riceve davvero, cioè il campione reale che chiede la regola 10. Accorciare dal lato grezzo tiene i campioni piccoli senza cambiarne la forma; la ripulitura costruisce l'elenco dei frammenti sensibili da tutto il grezzo, quindi accorciare dopo non servirebbe |
|
||||
| 2026-10-25 | La cattura legge come dati anche le risposte `text/javascript` (e ogni tipo che contiene «javascript») che la pagina chiede da sé (risorsa XHR o Fetch), oltre a quelle dichiarate JSON; i file di script non si leggono mai. Una sola regola, `DataResponses.IsData`, per `ResponseTap` e `CaptureCollector` | Nel HAR tutte le risposte GraphQL (`/graphql/query`, `/api/graphql`: storie, raccolte, ricerca) sono `text/javascript`; solo le REST (`/api/v1/…`) sono `application/json`. Con la regola di prima Febe scartava proprio i dati di storie e raccolte: è il motivo per cui non leggeva nulla. Le risposte con il prefisso `for (;;);` (`/ajax/…`: definizioni delle pagine, registri di navigazione) non sono JSON e non portano contenuti: restano scartate |
|
||||
| 2026-10-25 | Del documento principale di una pagina del sito (`text/html`, cornice principale) si leggono i blocchi `<script type="application/json">`: ogni blocco arriva ai lettori come una risposta a sé, con il descrittore del documento, letto mentre si scorre e uno solo in memoria alla volta (`DataResponses.EmbeddedJsonBlocks`); un documento senza blocchi validi si segnala scartato una volta; `febe-sonda da-har` scrive un campione per blocco. Il corpo del documento si chiede con `Network.getResponseBody`, già nell'elenco ammesso | Una pagina aperta per indirizzo (`Page.navigate`, come fanno tutte le ricette) riceve i dati del primo schermo dentro il documento e chiede con XHR solo le pagine successive: senza, la prima pagina di un profilo arriverebbe «vuota». **Da confermare dal vivo**: il HAR del 21 ottobre non conteneva documenti. Se i dati arrivano invece con XHR, la lettura del documento non trova nulla e non cambia niente. Blocco per blocco e non riuniti in un array (rilievo della revisione): riuniti davano una sola lettura con una sola paginazione, la prima del documento, e il «has_next_page» delle raccolte o il «more_available: false» di un post finiva sugli elementi di un altro blocco. Da confermare dal vivo: le regole di testo di `segnali.json` ora vedono anche i blocchi piccoli uno per uno. L'arrivo del documento non cancella più la sua stessa richiesta in corso (la cornice cambia documento prima che il corpo sia finito: si tiene la richiesta con l'identificativo del caricatore nuovo) |
|
||||
| 2026-10-25 | Nel vocabolario dei lettori, `relevance.keys`: se una risposta non contiene nessuna di quelle chiavi è «non pertinente» (`ReadShape.Unrelated`) e si ignora, invece di contare come forma sconosciuta; `CaptureCollector` non la conserva nemmeno, così una pagina che continua a mandare registri si assesta lo stesso. Per Instagram: `image_versions2`, `video_versions`, `carousel_media`, `taken_at`, `username`; per il sito di prova l'elenco è vuoto e tutto resta come prima | Instagram manda molte risposte JSON che non c'entrano con i contenuti (promozioni, il segno «storia vista», registri). Con le risposte `text/javascript` lette, ognuna di queste avrebbe fermato una ricetta come «formato non riconosciuto» ogni volta che il dato atteso tardava. Una risposta che ha le chiavi dei contenuti ma una forma che il vocabolario non descrive resta «formato non riconosciuto» (§6.4). L'elenco non si ricava dal vocabolario: sul sito di prova la forma sconosciuta di prova non ha nessuna sua chiave e deve restare sconosciuta |
|
||||
| 2026-10-25 | `IResponseObserver.OnBodyDropped`: la cattura avvisa quando il corpo di una risposta annunciata non arriverà (troppo grande, caricamento fallito, non JSON, pagina cambiata, browser riavviato), e `CaptureCollector` smette di aspettarlo | Prima un corpo scartato restava «in arrivo» per 15 secondi e `SettleAsync` non si assestava: con le risposte `/ajax/…` di Instagram, che arrivano a ogni scorrimento e cambio di pagina, ogni raffica avrebbe aspettato fino al limite |
|
||||
| 2026-10-25 | `lettori.instagram.json` è «confermato» e compilato soltanto con chiavi che compaiono nei campioni ripuliti (una prova lo controlla chiave per chiave): contenuto `pk`, `code`, `taken_at`, `caption.text`, `image_versions2.candidates`, `video_versions`, `carousel_media` e `carousel_media_count` (chiavi viste ma sempre vuote: nessuna serie nei campioni), `user`/`owner`, `expiring_at`, `video_duration`; versione `url`, `width`, `height`; profilo `pk`/`id`, `username`, `full_name`, `is_private`, `friendship_status.following`, `hd_profile_pic_url_info`/`hd_profile_pic_versions`/`profile_pic_url`, `latest_reel_media`; raccolta `id`, `title`, `user`, `items`; pagina `has_next_page`/`more_available`, `end_cursor`; account collegato `xdt_viewer.user`. Restano vuoti `pinned`, `postCount` e `version.hasAudio` | Regola 10. `has_audio` sta sul contenuto, non sulla versione: ogni versione di `video_versions` conta come file completo (H5 si conferma scaricando). Le versioni video delle storie non hanno dimensioni: si prende la prima (101), che nei post ha le stesse dimensioni e la stessa banda delle altre due. `xdt_viewer.user` ha solo l'identificativo: il lettore lo tiene (`ReadResult.ViewerId`) per riconoscere l'account collegato quando il suo profilo compare altrove (H10 resta aperta) |
|
||||
| 2026-10-25 | L'identificativo di una raccolta si tiene nella forma dell'indirizzo: dal `highlight:17841…` dei dati il lettore toglie un prefisso fatto di sole lettere e due punti. Un oggetto con `id` e `title` è una raccolta solo se ha anche il proprietario o i contenuti (quando il vocabolario li nomina) | Nel HAR i dati dicono `highlight:<17 cifre>` e l'indirizzo del visualizzatore `/stories/highlights/<17 cifre>/`: senza normalizzare, ricetta e visualizzatore non si sarebbero mai riconosciuti. Senza il secondo vincolo una promozione o una sezione di pagina con `id` e `title` diventava una raccolta finta, e quelle vere sarebbero risultate tolte |
|
||||
| 2026-10-25 | Ripulitura: `latest_reel_media` è una data (si tiene); i valori sotto chiavi che hanno l'aspetto di un segreto (`token`, `key`, `secret`, `session`, `cookie`, `auth`, …) diventano un riempitivo neutro della stessa forma (lettere `x`, cifre `7`) invece di un valore finto vario | `latest_reel_media` è la data dell'ultima storia, della stessa natura di `taken_at`. Un valore finto estratto lettera per lettera da un `organic_tracking_token` di 340 caratteri sembra un segreto vero a gitleaks, che nella CI avrebbe fermato il lavoro «controlli» su dati finti; il riempitivo ha la stessa forma e nessuna entropia |
|
||||
| 2026-10-25 | Senza l'identificativo del contenuto nell'indirizzo del visualizzatore (Instagram: `/stories/highlights/{highlight}/`, uguale per tutti i contenuti della raccolta) i contenuti si contano sull'elenco ricevuto: il primo mostrato è il primo dell'elenco e ogni clic su «avanti» ne sposta uno; il conteggio non va mai avanti senza un clic. Un video si lascia entro l'inizio del clic + la sua durata − 1,5 s × umore·ritmo; se non si fa più in tempo, si chiude senza «avanti» e i contenuti dopo non si salvano (evento «visualizzatore-chiuso-prima»). Con l'identificativo nell'indirizzo (le storie, `/stories/{username}/{id}/`) si segue l'indirizzo come prima. In entrambi i modi il permesso StoryView per il contenuto successivo si chiede appena quello attuale è a video, prima dell'attesa di §7.7 (che si conta da quando è comparso); un contenuto comparso da solo dopo l'ultimo dell'elenco non si salva e il visualizzatore si chiude | Nel HAR quattro richieste fatte guardando contenuti diversi di una raccolta hanno lo stesso Referer: l'indirizzo non dice quale contenuto è a video. Regola 7 e §6.3: nella prima versione il permesso arrivava dopo che il contenuto era già comparso, e con umore o ritmo oltre 1 il clic cadeva dopo la fine del video, saltava un contenuto e portava nella raccolta successiva (rilievi della revisione). Meglio perdere contenuti che salvarne di non mostrati. Restano da misurare dal vivo il clic che la pagina ignora (il conteggio andrebbe avanti) e quanto il sito tiene una foto; con la spaziatura di 4 s del Governatore i video più brevi di 4–6 s si chiudono prima |
|
||||
| 2026-10-25 | Anche dopo un errore imprevisto (non dopo un segnale di arresto) la ricetta chiude il visualizzatore e salva ciò che è stato mostrato fin lì. Un visualizzatore che non si chiude con «viewer-close» ferma la ricetta come «bersaglio non trovato», anche dopo un altro arresto (tetto, errore); dopo un annullamento si salva ciò che è stato mostrato e la pagina resta com'è; ciò che un clic apre a un indirizzo che la mappa non riconosce si chiude prima di fermarsi | Un visualizzatore lasciato aperto passa da solo alle storie degli account successivi (§6.3), e solo «bersaglio non trovato» ferma la sessione e mette la pagina a riposo. Prima un indirizzo senza identificativo del contenuto faceva fallire la ricetta con il visualizzatore aperto, e un annullamento (pausa, segnale), che arriva quasi sempre durante l'attesa su una storia, faceva perdere storie già segnate come viste |
|
||||
| 2026-10-25 | Il bersaglio `profile-not-found` è facoltativo per Controllo del profilo, Storico, Taggati e Reel: si cerca solo se la mappa lo imposta; senza, un profilo che non c'è non dà dati ed è giudicato come una pagina vuota | Per Instagram non c'è ancora un segno verificato (H11) e le ricette del profilo devono poter girare con le sole pagine. Con il segno impostato l'account si segna «Non raggiungibile» come prima |
|
||||
| 2026-10-25 | Dopo aver aperto profilo, home ed elenco dei seguiti (e dopo il clic su una scheda) le ricette aspettano il dato atteso, lasciano assestare la pagina e prendono tutto ciò che è arrivato dal segno in poi; Controllo e Storico aspettano anche la prima pagina della griglia (fino a 20 s). La paginazione di un cammino viene solo dalle risposte che portano i suoi elementi, o da una pagina vuota; l'elenco dei seguiti non salva mai un profilo con `IsFollowed` falso (i profili suggeriti), né l'account collegato; la home «è arrivata» con contenuti, una voce della barra delle storie o una pagina, non con soli profili. «Tu» nasce anche da `ViewerId` più un profilo con lo stesso identificativo in una risposta qualunque del giro | Su Instagram intestazione del profilo, griglia, raccolte e home arrivano in risposte diverse, anche dopo la prima; risposte su altro (un post con `more_available:false`, le raccolte con `has_next_page:false`) dicono «non ce n'è altro» di sé stesse e avrebbero chiuso uno storico; i 30 profili suggeriti hanno `friendship_status.following:false`. Sul sito di prova, dove tutto arriva insieme, il comportamento resta quello di prima |
|
||||
| 2026-10-25 | Una ricetta che la mappa dei bersagli o il vocabolario dei lettori non lasciano girare finisce in `NotConfigured` («Da configurare»), non più in «bersaglio non trovato» o «formato non riconosciuto»: non conta per la sospensione, il motore non la pianifica, lo dice una volta per ricetta e per avvio, e annulla con un evento un comando di Alberto che non può partire. Senza il giro dei seguiti le storie dei seguiti si controllano account per account | I rifiuti dei primi file di Instagram, che erano scheletri, contavano come guasti: dopo tre sessioni il motore sospendeva le ricette come se Instagram fosse cambiato, e le sospensioni restavano anche con file nuovi |
|
||||
| 2026-10-25 | All'avvio Febe calcola un'impronta SHA-256 di `lettori.<sito>.json` e `bersagli.<sito>.json` come caricati (incorporati o copia nella cartella Dati, fine riga ignorati) e la conserva in `motore.configurazione-raccolta`; quando cambia, e al primo avvio che la calcola, azzera una volta sospensioni ed errori consecutivi delle ricette, con una riga in Attività se c'era qualcosa da azzerare. Il registro (fonte «raccolta») dice da dove vengono i due file e com'è il vocabolario, quali ricette non possono girare, e avvisa se una copia nella cartella Dati è ancora «ipotesi» mentre quella incorporata è «confermato» o ferma ricette che quella incorporata lascerebbe girare. Mai il contenuto dei file | Le sospensioni contate con i file vecchi non devono sopravvivere a quelli nuovi, e nel database di Alberto con ogni probabilità ce ne sono. Una copia vecchia nella cartella Dati vince sempre su quella incorporata: senza il registro resterebbe invisibile. La cartella `config/` accanto al programma non si legge mai (la riga del 13 ottobre lo dava per vero) |
|
||||
| 2026-10-25 | Lo stato del collegamento nella barra laterale viene dal cookie di sessione (dal modo del motore, o dal servizio di collegamento quando il motore non gira), non dal fatto che l'account «Tu» sia già noto | Su Instagram «Tu» può arrivare molto dopo il collegamento (H10: i dati danno solo l'identificativo dell'account collegato) e la barra diceva «Da collegare» mentre Febe raccoglieva |
|
||||
| 2026-10-25 | `bersagli.instagram.json`: compilate solo le pagine con una prova reale nel HAR del 21 ottobre (i modelli che Instagram stesso manda in `/ajax/bulk-route-definitions/` e i Referer delle richieste della pagina): home `/`, profilo `/{username}/`, post `/p/{code}/`, storie `/stories/{username}/{id}/`, raccolte `/stories/highlights/{highlight}/` senza identificativo del contenuto. Vuoti l'elenco dei seguiti, le pagine di ripresa e tutti i bersagli (H11). La forma delle storie coincide anche con l'indirizzo delle raccolte (nome utente «highlights»): accettato, perché per le storie è «un altro account» e il visualizzatore si chiude, e la ricetta delle raccolte legge solo la sua pagina | Regola 10: niente di inventato. Il HAR non aveva documenti né attributi degli elementi, quindi nessun ruolo né nome accessibile. Girano le ricette che aprono solo pagine (giro dei seguiti, controllo del profilo, storico, post singolo); storie, raccolte, Taggati e Reel aspettano i bersagli |
|
||||
| 2026-10-25 | `febe-sonda da-har --har <file> --a <cartella>`: un HAR esportato dagli strumenti per sviluppatori diventa una cartella di campioni grezzi nel formato della sonda: solo le risposte di dati del sito (`DataResponses.IsData`) e il JSON incorporato nei documenti, mai intestazioni, cookie, query o corpi delle richieste; il nome del file viene dall'operazione GraphQL solo se ha la forma di un nome del codice (finisce con Query, Mutation o Subscription, senza cifre ripetute), altrimenti «risposta» o «documento». Rifiuta un HAR o una cartella dentro un repository e una cartella non vuota | Alberto raccoglie più volentieri dal suo browser di tutti i giorni che con la sonda: così può ripulire e verificare da sé, sulla sua macchina, e mandare solo la copia ripulita (§14.5) |
|
||||
| 2026-10-25 | `tools/bersagli/raccogli-bersagli.js`: i bersagli si raccolgono con uno script in sola lettura che Alberto incolla nella Console del suo browser: un solo ascoltatore dei clic, nessuna modifica alla pagina, niente rete, cookie o archivi; calcola ruolo e nome accessibile come `TargetResolver`, registra la forma degli indirizzi prima e dopo il clic, sostituisce i nomi con NOME e prepara per ogni clic le voci `role`, `name`, `href` e `index` della mappa | Il HAR non porta gli attributi degli elementi; la sonda li registrerebbe, ma chiede di avviare un Chromium a parte. La forma dell'indirizzo dopo il clic dice anche se l'indirizzo delle storie segue ogni storia |
|
||||
| 2026-10-25 | La paginazione di una pagina (griglia, schede, giro dei seguiti, elenco dei seguiti) viene dalla risposta che porta più elementi non ancora incontrati, l'ultima a pari merito; una risposta che riporta solo elementi già letti non conta come pagina successiva né per la sua paginazione. Una risposta vuota senza profilo è la pagina vuota di un cammino solo quando risponde a un suo gesto (pagina di ripresa, scheda, scorrimento), mai all'apertura del profilo; con il profilo dell'account è la griglia vuota anche accanto alle raccolte, se il profilo dice «0 pubblicazioni» | Rilievi della revisione: su Instagram la pagina di un post del profilo stesso («more_available: false») e le raccolte di un account che non ne ha (connessione vuota con «has_next_page: false», forma identica a una griglia vuota) chiudevano lo storico dopo la prima pagina o senza post; sul sito di prova un profilo con raccolte e senza post aspettava 20 s a ogni controllo. Un account Instagram senza post resta così con lo storico aperto: costa un'attesa e una pagina a sessione, mai post persi |
|
||||
| 2026-10-25 | Mentre «Storie di un account» non può girare con la configurazione del sito, la visita di un profilo non seguito non serve le storie: si pianifica all'intervallo del profilo, non conta come lavoro di storie, e il giro dei seguiti non accoda «Storie segnalate dalla barra» (ogni giro segnala di nuovo l'account finché le storie non si vedono). `SyncQueue` non annulla più i «Post singolo» accodati dalla raccolta: li toglie solo per un account che non si contatta, e mentre la ricetta non può girare aspettano | Con i file di Instagram di oggi un profilo non seguito si sarebbe aperto fino a 24 volte più spesso del dovuto senza raccogliere nulla, e la Coda si sarebbe riempita a ogni sessione di storie che non sarebbero mai partite. Un «Post singolo» annullato non tornava più in coda (nessuno ricontrolla gli indirizzi scaduti), mentre §6.5 punto 5 vuole che il recupero passi da lì: difetto precedente a questo lavoro (commit `aff81df`), trovato dalla revisione. Effetto: su Instagram queste ricette ora girano davvero, dentro il loro tetto (Prudente: 10 l'ora, 60 al giorno) |
|
||||
| 2026-11-12 | Le attività di Febe stanno nelle issue di Gitea, come negli altri repository di Alberto: etichette Area/Kind/Priority/Status, un traguardo per tappa (M0–M8) e per versione, il lavoro finito come issue chiusa con il suo resoconto «Fatto». `docs/stato.md` resta il resoconto fra le sessioni e rimanda alle issue per ciò che è da fare. Motivo: richiesta di Alberto del 12/11; un posto solo per le cose da fare, visibile anche fuori dal repository. |
|
||||
| 2026-11-12 | **Strada B: la pagina chiede i dati** (issue #34). Dalla pagina di Instagram già aperta Febe chiede al sito gli stessi dati che chiede la sua applicazione web, con `Runtime.evaluate` + `fetch`, solo verso gli indirizzi di `richieste.<sito>.json` scritti da campioni reali, in sola lettura, una richiesta per volta col permesso del Governatore; i gettoni restano nella pagina e allo script torna solo il corpo. Cambiano §2 regola 2 (eccezione), §6.1 (nuova riga dei comandi e regole delle richieste), §14.5 e la regola 4 di `CLAUDE.md`; il resto di §2 non cambia | La prova dal vivo di Alberto è fallita: le ricette passive dipendono da una mappa dei bersagli e da indirizzi che si scoprono solo su Instagram, e nessuno dei 9 bersagli era compilato. Scelta di Alberto fra A (indirizzi e tastiera), B e C (misto), sapendo che B lascia una traccia diversa da una visita normale |
|
||||
| 2026-11-12 | `febe-sonda richieste --har <file> --a <file .json>`: descrive la forma delle richieste XHR/Fetch della pagina al sito (metodo, percorso con `{numero}`/`{testo}` al posto delle parti che non sono parole note del sito, nomi di parametri, intestazioni e campi del corpo, struttura delle variabili, nella query come nel corpo); dei valori solo il tipo, tranne elenchi chiusi uguali per tutti (`x-ig-app-id`, `x-asbd-id`, nomi e `doc_id`/`query_hash` delle operazioni, grandezza delle pagine solo per i nomi che la indicano, vero/falso). Un nome si tiene se è in un elenco chiuso, o se ha la forma di un nome del codice (senza punto, senza tre cifre di fila) e non compare da nessuna parte nel HAR come valore (indirizzi, cookie, intestazioni, corpi delle richieste e delle risposte, dati incorporati nelle pagine); altrimenti «(nome tolto)». Un corpo che non è un modulo né JSON si descrive intero, mai spezzato su «&» e «=». Le forme si distinguono per metodo, percorso, operazione (nome, intestazione `x-fb-friendly-name` o `x-root-field-name`) e identificativo dell'interrogazione, e le occorrenze si uniscono chiave per chiave. `OperationName` accetta anche il suffisso della pagina successiva (`…Query_connection`). Rifiuta HAR e file d'uscita dentro un repository, una cartella e un file d'uscita che esiste già | `da-har` butta via di proposito intestazioni, parametri e corpi delle richieste; per scrivere `richieste.instagram.json` serve la loro forma, e deve poter uscire dalla macchina di Alberto senza ripulitura: per costruzione non contiene valori personali |
|
||||
| 2026-11-12 | Ripulitura e verifica sul HAR vero: (1) un numero lungo con esponente o virgola (`1.2e+21`) si falsifica cifra per cifra, lasciando segno, punto ed esponente, così resta un numero JSON valido; (2) la verifica non cerca dentro i valori che l'elenco ammesso tiene di proposito (un tipo di file, una data, una dimensione), mai però nelle chiavi di dati, che la ripulitura falsifica sempre, e indica sotto quale chiave sopravvive un frammento, mai il frammento; (3) le parole degli indirizzi finti (`sito`, `altro`, `esempio`) e le estensioni dei file non contano come frammenti. Campioni del secondo HAR accorciati sulla copia **ripulita** e già verificata, non sui grezzi | Sul HAR del 12/11 `ripulisci` si fermava su un numero con esponente e `verifica` dava 223 falsi allarmi (frammenti come «script» dentro `text/javascript`). Accorciare la copia ripulita evita di aprire i grezzi anche solo per tagliarli: togliere elementi da una copia verificata non può aggiungere valori dei grezzi |
|
||||
| 2026-11-12 | Vocabolario dei lettori di Instagram: `profile.postCount` = `media_count` e una chiave nuova `highlight.cover` (`cover_media.cropped_image_version`), letta come una versione. Le griglie delle schede Reel e Con tag restano anteprime, non contenuti | Dal secondo HAR: `media_count` compare solo nella scheda del profilo; la copertina delle raccolte è nell'elenco delle raccolte del profilo; le anteprime delle schede non hanno `taken_at` né `video_versions` (regola 9: si legge solo ciò che i campioni mostrano) |
|
||||
| 2026-11-13 | `febe-sonda da-har` e `richieste` leggono anche un HAR **troncato**: se il file finisce prima del suo JSON, e solo in quel caso, tengono le voci complete di `log.entries`, scartano quella dentro cui il file finisce e lo dicono a schermo e nel resoconto (`Truncated`, `DroppedEntry`). Per riconoscere il caso il lettore JSON lavora in modalità «dati non finiti»: la fine del file non è un errore, un errore di sintassi sì, e un file rotto in qualunque altro modo resta rifiutato. Per `richieste` la voce scartata conta comunque come dati: si chiude dove si ferma (il testo interrotto tenuto fino al taglio) e passa per le stesse regole di una voce intera (base64, pagine con blocchi incorporati, intestazioni, moduli); in più ogni stringa JSON del testo interrotto conta come valore, così un nome che è un dato solo lì viene tolto lo stesso. Resta fuori solo un valore tagliato a metà, di cui c'è solo l'inizio. Lettura comune in `HarFile` | Il 12/11 sera Chrome ha troncato due esportazioni dello stesso giro: la prima a 200 000 byte esatti, la seconda a 57 MB a metà di un corpo di risposta. Prima la sonda diceva solo «non è un file HAR valido (riga …)», senza distinguere un file tagliato da uno sbagliato, e non dava nulla della parte buona. La revisione avversaria ha trovato che la prima versione non contava i valori del testo interrotto né applicava alla voce scartata le regole di base64 e pagine: corretto prima del commit |
|
||||
| 2026-11-13 | Le foto del profilo hanno un **terzo schema dei nomi**, predefinito `{account}\profilo\{data}_{ora}_{codice}_{n}` (chiave `libreria.schema-profilo`), accanto a quello generale e a quello delle raccolte; Impostazioni ▸ Generali lo mostra come terzo campo, con la cartella `profilo` nel risultato. Niente cartella dell'anno; `{codice}` sono le prime otto cifre dello SHA-256 e `{n}` vale sempre 1, tenuto perché i nomi si leggano come gli altri e l'importazione li riconosca con il riconoscitore di Febe. Senza `{codice}` l'avviso dice che due foto possono avere lo stesso nome; `{raccolta}` è un errore. Una richiesta di salvataggio senza il terzo schema tiene quello salvato | Decisione di Alberto su #38 (12/11): le foto del profilo dentro ogni account, in `<account>\profilo\…`. Con lo schema unico bastava cambiare quello generale perché finissero con i post; uno schema proprio, come per le raccolte, le tiene separate qualunque cosa dica il generale |
|
||||
| 2026-11-13 | Rapporto di diagnostica della raccolta (#39): un registratore unico (`CollectionDiagnostics`) tiene per ogni sessione del motore, e per ogni giorno fuori dalle sessioni, solo conteggi, misure, orari, valori di elenchi chiusi e forme degli indirizzi; le tracce finite vanno in `Dati/diagnostica/sessioni-aaaa-mm-gg.jsonl` (JSON per riga, 14 giorni, una riga rovinata si salta) e «Esporta il rapporto di diagnostica» in Attività (`GET /api/engine/diagnostica`, ammesso anche con un problema di configurazione) le scarica in un file JSON. La struttura delle chiavi delle risposte sconosciute è quella **severa** (`KeyStructure.DescribeStrict`): resta solo una chiave fatta tutta di parole di un **elenco chiuso** (`StructureWords`: le parole delle chiavi dei campioni ripuliti di `tests/Febe.Tests/campioni`, dei vocabolari dei lettori incorporati e degli indirizzi del sito; alcune parole che sono anche nomi, come «max», solo dentro una chiave composta) e non uguale a un valore stringa dello stesso corpo; ogni altra chiave diventa `#`, anche un nome utente senza punto («marta_92») o un codice di post. Le forme degli indirizzi (`PathPatterns`) e la regola delle chiavi-dato (`KeyStructure.IsDataKey`) passano da `tools/Febe.Sonda` a `Febe.Core`, e la sonda le richiama. Gli eventi «formato non riconosciuto» scrivono ancora la struttura di prima: passarli a quella severa è un seguito possibile | Il file deve poter uscire dalla macchina di Alberto senza ripulitura, quindi niente testo libero per costruzione. Non nel database: nessuna migrazione, dimensione limitata dai tetti delle tracce e dai 14 giorni, cartella che si può cancellare a mano senza toccare nulla. Elenco chiuso e non regole su che aspetto ha un nome: un nome utente fatto di lettere e cifre non si distingue da una chiave, e la revisione l'ha trovato nel rapporto. Ammesso con un problema di configurazione perché l'indirizzo non risponda mai con un errore, ma lì il motore non è partito e il rapporto è vuoto |
|
||||
| 2026-11-13 | Rapporto di diagnostica (#39), seconda revisione: nella struttura severa una chiave fatta di sole parole «solo composte» (`max_mark`) non passa più, e le **voci di una mappa** (chiavi sorelle i cui valori hanno la stessa forma) diventano `#` anche se fatte di parole dell'elenco, salvo le chiavi intere dei vocabolari dei lettori (`user`, `owner`). Una sessione scrive nel registro una riga «in corso» quando parte e al più ogni 5 minuti a fine ricetta; leggendo resta la riga finita, altrimenti l'ultima, e la testa del rapporto conta `fileIlleggibili` e `sessioniSenzaFine`. Il registratore ascolta anche i cambi dell'interruttore (da `EngineHost`), contando una volta sola lo stesso segnale detto anche dal rilevatore. La prova sulla riservatezza confronta le chiavi della struttura con i campi veri dei campioni e del corpo, non con `StructureWords` | Un nome fatto di parole comuni («the_artist») passava la sola lista; una mappa di nomi si riconosce dalla forma dei valori, a costo di qualche dettaglio (`first_frame` e `igtv_first_frame` diventano `#`). Senza righe intermedie una chiusura brusca cancellava proprio la sessione andata storta e la testa diceva 0; il cookie di sessione perso arriva all'interruttore senza passare dal rilevatore e il rapporto non lo diceva. Una prova che usa la funzione sotto prova come oracolo non trova i suoi errori. Resta il rischio di un solo nome di parole comuni usato come chiave, senza sorelle della stessa forma e mai ripetuto come valore |
|
||||
| 2026-11-13 | Rapporto di diagnostica (#39), terza revisione: nella struttura severa una chiave con un **valore semplice** (testo, numero, vero o falso, null) resta solo se è un **campo dell'elenco chiuso** (`StructureWords.IsFieldKey`: chiavi intere dei vocabolari dei lettori e delle chiavi dei campioni ripuliti, congelate nel codice perché i campioni non viaggiano con Febe), altrimenti `#`. Le voci di una mappa si riconoscono anche quando i valori non hanno la stessa forma esatta: due valori sorelli entrambi oggetti o entrambi elenchi, di cui uno vuoto, o entrambi elenchi di valori semplici, o con almeno metà delle chiavi in comune, o con un campo d'identità in comune (`pk`, `id`, `username`…); in un elenco di oggetti le chiavi che ha solo il primo diventano `#`; fra le voci restano solo i campi dell'elenco chiuso. Una traccia finita la cui scrittura fallisce si riscrive con la riga successiva e quando si raccoglie il rapporto (al più 16 in attesa); le righe «in corso» non si riscrivono | La regola della stessa forma esatta lasciava passare i nomi in mappe di conteggi o di valori vuoti, in voci con campi facoltativi diversi (il caso normale degli utenti di Instagram) e in elenchi di mappe a una voce. Il prezzo è il dettaglio: un campo nuovo con un valore semplice diventa `#`. Senza la riscrittura, un errore momentaneo proprio sulla riga finale lasciava nel registro solo le righe «in corso» e dopo un riavvio la sessione contava fra quelle senza fine |
|
||||
| 2026-11-13 | Prova di scala della libreria (§4.6, 200 000 elementi): i limiti valgono **per classe** di interrogazione, circa 5-8 volte i tempi misurati a macchina scarica: 250 ms per finestre e ricerche su indice (prima finestra, salto a una data, filtri, «è già noto», SHA-256, coda), 1500 ms per le aggregazioni sull'intera libreria o su un account (ricerche, totali, conteggi, caricamento delle impronte, elenco degli account con i conteggi, scheda dell'account). Ogni interrogazione si misura come il **migliore** di almeno tre giri dopo uno di riscaldamento, e se resta sopra il limite si riprova (al più 15 giri o 20 s, con una pausa di 100 ms) finché scende sotto. La classe gira `[DoNotParallelize]`, dopo le prove parallele; il riempimento resta fuori dalla misura e ha solo un tetto contro un blocco (20 minuti) | #46: la prova cadeva sotto carico senza nessun cambio di codice («scheda account» 1770 ms nella CI, 251,7 ms in locale). Due aggregazioni (140-200 ms a vuoto) stavano nella classe da 250 ms, con un margine di 1,2-1,8 volte; e tre giri consecutivi non superano un picco di carico, mentre le altre 11 prove parallele misuravano nello stesso momento. Il minimo è la stima giusta del costo: il carico aggiunge solo tempo, e un'interrogazione davvero più lenta resta sopra il limite in ogni giro |
|
||||
| 2026-11-13 | Scheda dell'account: byte in libreria e file in coda in **una sola passata** sui file dell'account, partendo dai suoi elementi (`entry CROSS JOIN media`), non più due interrogazioni separate | #46: senza le statistiche di ANALYZE SQLite partiva dall'indice dello stato dei file e leggeva i file di tutta la libreria per la scheda di un account; sotto carico era l'interrogazione che rallentava di più (1770 ms nella CI). Ora il piano è lo stesso con e senza statistiche e proporzionale all'account, come per `LoadPerceptualHashesAsync` |
|
||||
| 2026-11-13 | Avvio di Chromium (`ChromiumLaunchOptions.StartupTimeout`): **120 s** invece di 30 per aprire la porta di debug, e la prima scheda si aspetta entro la **stessa scadenza**, non più 50 tentativi da 100 ms; finisce subito se il processo si chiude, e una risposta lenta o mancata di `/json/list` vale «non ancora» come già per `/json/version`. Il ricollegamento dopo una connessione caduta usa la stessa scadenza ma smette appena il processo si chiude o il supervisore lo sostituisce, così non tiene il blocco del collegamento a un riavvio. Nessun comando CDP nuovo e nessun cambio della riga di comando (§6.1) | #46: la scadenza serve solo contro un Chromium vivo e bloccato, perché uno che si chiude fa già fallire l'avvio all'istante. Su una macchina carica (la CI era 4-6 volte più lenta del solito, un NAS durante un controllo di parità) Febe uccideva un Chromium lento ma sano e ricominciava da capo sotto lo stesso carico, anche per sempre; i 5 s per la prima scheda erano il punto più fragile |
|
||||
| 2026-11-13 | Nelle prove i limiti di tempo sono **protezioni contro un blocco, non misure**: ogni attesa finisce appena la sua condizione è vera e il limite è largo (il browser delle prove dell'interfaccia: 2 minuti per avvio, comandi DevTools e condizioni, e si ferma subito se Chromium si chiude, con le sue ultime righe di stderr; l'avvio del server di prova: 4 minuti, con l'ultimo errore del browser); niente attese fisse né conteggi di tentativi al posto di una scadenza. Ciò che una prova deve far accadere a un certo momento (il rilascio di un blocco, una lettura che non deve finire mai) gira su un thread suo, non sul pool; il pool delle prove parte con almeno 64 thread. Il browser delle prove dell'interfaccia usa la porta di debug 0 e legge quella scelta da Chromium; il browser di Febe resta sulla porta fissa (§6.1). Nelle prove di WebView2 su Windows la seconda «Scollega» e l'arresto non hanno più un limite di 10 s: la prova chiede che il processo del browser esca davvero (atteso per condizione) e che il profilo sparisca, con 90 s solo contro un blocco | #46: le prove cadevano a ogni carico del runner, ogni volta prove diverse, mai sul codice cambiato. Un limite stretto su un'attesa non misura nulla: dice solo quanto era carica la macchina. Con il parallelismo per metodo diverse prove bloccano thread del pool, e un pool di 2-4 thread ne aggiunge altri lentamente: il rilascio di un blocco dopo 300 ms arrivava dopo più di 10 s. Fra la porta libera trovata e il bind di Chromium un altro processo poteva prenderla. Con tutti i core occupati il processo di WebView2 (a priorità bassa) segnala l'uscita dopo i 15 s di attesa dell'host: la prova di «Scollega» cadeva 5 volte su 5 a 15,7-21 s, mentre ciò che deve escludere, una WebView orfana, tiene vivo il processo per sempre e lascia il profilo |
|
||||
| 2026-11-13 | `FebeDatabase.DisposeAsync` chiude davvero i file prima di tornare: ogni comando SQLite si chiude appena usato (gli aiuti `Execute` e `Scalar` sulla connessione dello scrittore, e un ambito che chiude i comandi di ogni lettura), le connessioni di lettura del pool si chiudono **prima** dello scrittore, così è lo scrittore, ultimo, a togliere `febe.sqlite-wal` e `-shm`. All'arresto `FebeApp` aspetta anche i lavori in sottofondo che un avvio ancora in corso aggiunge mentre si ferma | #46: un comando lasciato al garbage collector tiene viva la sua istruzione finché il finalizzatore non passa; la connessione chiusa nel frattempo si chiudeva davvero solo dopo, e il WAL spariva durante lo spostamento della cartella Dati (`Could not find file …febe.sqlite-wal`). Riprodotto tenendo occupato il thread del finalizzatore, ora con una prova apposita. Una connessione di sola lettura chiusa per ultima lascia il WAL: per questo il pool si svuota prima |
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -18,7 +18,52 @@
|
||||
pieni, formati non riconosciuti, e gli avvisi che non sono arrivati (vedi [Avvisi e Telegram](Avvisi-e-Telegram)).
|
||||
|
||||
Comandi: **«Metti in pausa»** (Febe non apre nulla finché non premi «Riprendi»), **«Riprendi»**, **«Apri il
|
||||
browser»**.
|
||||
browser»**, **«Diagnostica»** (vedi sotto).
|
||||
|
||||
## Il rapporto di diagnostica
|
||||
|
||||
Se una prova va storta (Febe si ferma, non trova nulla, scarica meno del previsto) e vuoi farla guardare a qualcuno,
|
||||
manda il **rapporto di diagnostica**: un solo file che racconta che cosa ha fatto il motore, senza i dati di nessuno.
|
||||
|
||||
1. Apri **Attività** e premi **«Diagnostica»** nella riga del titolo (al telefono è l'icona del file con la freccia;
|
||||
il suggerimento dice «Esporta il rapporto di diagnostica»).
|
||||
2. Il file `febe-diagnostica-aaaa-mm-gg.json` finisce nei download del browser (su Windows nella cartella Download,
|
||||
come ogni scaricamento della finestra di Febe).
|
||||
3. Allegalo così com'è al messaggio o alla segnalazione su Gitea, dicendo più o meno a che ora è successo il problema.
|
||||
|
||||
Che cosa contiene, per ogni sessione delle ultime due settimane e per le ore fuori dalle sessioni: le pagine aperte
|
||||
(solo il tipo di pagina e la forma dell'indirizzo, come `/{username}/`), le risposte ricevute per tipo con numero e
|
||||
misure, che cosa ne hanno fatto i lettori (per le risposte dalla forma sconosciuta, solo la struttura delle chiavi),
|
||||
le ricette con l'esito, i segnali di arresto, i file messi in coda e scaricati, e **perché ogni sessione è finita**.
|
||||
|
||||
Che cosa **non** contiene: nomi utente, didascalie, codici dei post, identificativi, indirizzi, cookie, password,
|
||||
corpi delle risposte, testi dei messaggi. Lo puoi aprire con un editor di testo e controllare. È più severo dei
|
||||
registri di Febe, che i nomi utente li scrivono.
|
||||
|
||||
Febe tiene le tracce in `Dati/diagnostica` per **14 giorni** e cancella da sé solo i file più vecchi di quella
|
||||
cartella. Una sessione in corso lascia una riga quando parte e poi al più ogni cinque minuti, alla fine di una
|
||||
ricetta: se Febe si chiude di colpo (un arresto imprevisto, il computer spento a forza, il contenitore fermato), la
|
||||
sessione resta nel rapporto fino all'ultima di quelle righe, «in corso» e senza causa della fine.
|
||||
|
||||
In cima al file quattro numeri dicono che cosa sicuramente manca:
|
||||
|
||||
| Campo | Che cosa conta |
|
||||
|---|---|
|
||||
| `righeRovinate` | righe del registro tagliate a metà da uno spegnimento brusco |
|
||||
| `erroriRegistratore` | errori del registratore da quando Febe è partito, scritture non riuscite comprese |
|
||||
| `fileIlleggibili` | giorni del registro che non si sono potuti leggere (un altro programma teneva aperto il file, un errore del disco): le loro sessioni non ci sono |
|
||||
| `sessioniSenzaFine` | sessioni interrotte da una chiusura brusca: di loro manca quello che è successo dopo l'ultima riga |
|
||||
|
||||
Anche con tutti e quattro a 0 il rapporto può non essere intero. Di una chiusura brusca si perdono gli ultimi minuti
|
||||
della sessione e le ore fuori dalle sessioni del giorno (scritte solo a fine giornata o quando Febe si chiude bene).
|
||||
Gli elenchi di ogni sessione hanno un tetto: quello che lo supera non c'è, e `overflow` della sessione dice quante
|
||||
voci mancano (pagine, navigazioni, gruppi di risposte, forme sconosciute, segnali, ricette), quante risposte sono
|
||||
rimaste senza esito perché arrivate in troppe insieme (`requests`) e quante notizie sono arrivate tardi (`late`),
|
||||
quando la loro sessione era già chiusa.
|
||||
|
||||
Con un problema di configurazione il motore non parte e Febe mostra solo la pagina del problema: il rapporto non
|
||||
serve, perché non c'è nessuna sessione da raccontare. Le tracce delle sessioni precedenti restano in
|
||||
`Dati/diagnostica` e tornano nel rapporto appena il problema è risolto.
|
||||
|
||||
## La striscia rossa
|
||||
|
||||
|
||||
@@ -37,9 +37,10 @@ seguire; passa al tuo account solo quando hai visto come si comporta.
|
||||
Questa guida descrive ciò che c'è nel programma, non ciò che si spera. Alcune cose dipendono da prove che si possono
|
||||
fare solo con Instagram o su Windows:
|
||||
|
||||
- **Raccolta da Instagram: non ancora attiva.** Le ricette, il motore, la libreria e gli scaricamenti funzionano e sono
|
||||
provati contro un sito di prova locale. Su Instagram le ricette si rifiutano di girare («la mappa dei bersagli non è
|
||||
ancora compilata») finché la sonda passiva non ha confermato le ipotesi H1–H11. Vedi
|
||||
- **Raccolta da Instagram: in parte attiva (25 ottobre 2026).** Febe legge le risposte vere di Instagram (lettori
|
||||
scritti su risposte reali, ripulite). Girano giro dei seguiti, controllo del profilo, storico e post singolo: foto e
|
||||
video dei post e dei reel. Storie, raccolte in evidenza e schede Taggati e Reel aspettano i bersagli dei comandi
|
||||
(ipotesi H11) e rispondono «la mappa dei bersagli non è ancora compilata». Non è ancora stato provato dal vivo. Vedi
|
||||
[Ipotesi da verificare](Ipotesi-da-verificare).
|
||||
- **Versione per Windows: pronta, non ancora provata su un Windows vero.** Programma di installazione e versione
|
||||
portabile ci sono; le prove che si fanno solo su Windows (S1–S3) sono aperte. Vedi
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
# Ipotesi da verificare
|
||||
|
||||
Febe è costruito su alcune ipotesi che non si possono provare senza Instagram (voci **H**) o senza i due browser veri
|
||||
(voci **S**). Finché una voce non è provata, non ci si costruisce sopra: per questo la raccolta da Instagram non è
|
||||
ancora attiva. Lo stato aggiornato e i dettagli tecnici sono in `docs/sonda/esito.md` e `docs/sonda/esito-locale.md`
|
||||
nel repository; i passi precisi delle prove in `docs/prove-dal-vivo.md`.
|
||||
(voci **S**). Finché una voce non è provata, non ci si costruisce sopra. Lo stato aggiornato e i dettagli tecnici sono
|
||||
in `docs/sonda/esito.md` e `docs/sonda/esito-locale.md` nel repository; i passi precisi delle prove in
|
||||
`docs/prove-dal-vivo.md`.
|
||||
|
||||
**Dal 25 ottobre 2026** Febe legge le risposte vere di Instagram: i lettori sono scritti sulle risposte che il tuo
|
||||
browser ha ricevuto il 21 ottobre (un file HAR), ripulite. Girano le ricette che aprono solo pagine (giro dei seguiti,
|
||||
controllo del profilo, storico, post singolo). Storie, raccolte in evidenza e schede Taggati e Reel aspettano i
|
||||
**bersagli** (H11): i nomi e i ruoli di pulsanti come l'anello delle storie, «avanti» e la X, che nel HAR non c'erano.
|
||||
|
||||
Le prove dal vivo le fai **tu**, con l'**account di prova**, mai con l'account principale prima di aver visto Febe
|
||||
all'opera. Se in qualunque momento compare una verifica, un CAPTCHA o un avviso dell'account: fermati, risolvi a mano,
|
||||
@@ -14,28 +19,32 @@ locali, mai Instagram; **da provare** = serve una prova tua.
|
||||
|
||||
## Voci H: Instagram
|
||||
|
||||
Si provano tutte con la **sonda passiva** (parte A di `docs/prove-dal-vivo.md`): avvii `febe-sonda registra`, navighi
|
||||
tu in Instagram seguendo l'elenco (pagina iniziale, un profilo pubblico, un privato che segui, delle storie, una
|
||||
raccolta, le schede taggati e reel, l'elenco dei seguiti, un post), la sonda registra ciò che la pagina riceve; poi
|
||||
Si provano con la **sonda passiva** (parte A di `docs/prove-dal-vivo.md`): avvii `febe-sonda registra`, navighi tu in
|
||||
Instagram seguendo l'elenco (pagina iniziale, un profilo pubblico, un privato che segui, delle storie, una raccolta, le
|
||||
schede taggati e reel, l'elenco dei seguiti, un post), la sonda registra ciò che la pagina riceve; poi
|
||||
`febe-sonda ripulisci` e `febe-sonda verifica` sulla tua macchina, e mandi solo la cartella **ripulita**. La sonda non
|
||||
compie gesti e non apre pagine da sola.
|
||||
|
||||
Più semplice, con il **browser di tutti i giorni** (parte A bis): registri un HAR con il filtro «Tutti», incolli nella
|
||||
Console lo script `tools/bersagli/raccogli-bersagli.js` per i bersagli, poi `febe-sonda da-har`, `ripulisci` e
|
||||
`verifica`, e mandi solo la copia ripulita e il testo dei bersagli.
|
||||
|
||||
| | Ipotesi | Stato | Come la provi |
|
||||
|---|---|---|---|
|
||||
| H1 | La pagina iniziale consegna i post recenti dei profili che segui con i dati completi dei file | Da provare | Sonda, pagina iniziale: scorri piano una decina di post |
|
||||
| H1 | La pagina iniziale consegna i post recenti dei profili che segui con i dati completi dei file | Da provare (il HAR non conteneva la pagina iniziale) | Sonda, pagina iniziale: scorri piano una decina di post |
|
||||
| H2 | La barra delle storie dice quali profili seguiti hanno storie attive e a quando risale l'ultima | Da provare | Sonda, pagina iniziale caricata: passa sopra la prima voce della barra |
|
||||
| H3 | La pagina di un profilo consegna identificativo, pubblico o privato, se lo segui, la prima pagina dei post con serie e video, le raccolte; scorrendo arrivano le pagine successive | Da provare | Sonda: un profilo pubblico che non segui e uno privato che segui, scorrendo 3–4 schermate |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | Da provare | Sonda: apri le storie di un seguito dall'anello, guardane 2–3, chiudi con la X prima che passi all'account successivo |
|
||||
| H5 | Per i video arriva almeno un indirizzo con audio e video insieme | Da provare | Sonda: un post video e una storia video |
|
||||
| H3 | La pagina di un profilo consegna identificativo, pubblico o privato, se lo segui, la prima pagina dei post con serie e video, le raccolte; scorrendo arrivano le pagine successive | In parte: forma dell'indirizzo e del profilo viste nel HAR; le risposte della pagina profilo da provare | Sonda: un profilo pubblico che non segui e uno privato che segui, scorrendo 3–4 schermate |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | In parte: il visualizzatore delle raccolte riceve l'elenco completo con gli indirizzi; quello delle storie di un account da provare | Sonda: apri le storie di un seguito dall'anello, guardane 2–3, chiudi con la X prima che passi all'account successivo |
|
||||
| H5 | Per i video arriva almeno un indirizzo con audio e video insieme | In parte: tre versioni `.mp4` per video, «ha l'audio» detto dal contenuto; da confermare scaricando | Sonda: un post video e una storia video |
|
||||
| H6 | Le schede «Taggati» e «Reel» si comportano come la griglia | Da provare | Sonda: apri le due schede di un profilo e scorri |
|
||||
| H7 | I file del CDN si scaricano dal browser (`Network.loadNetworkResource`) | Provato in locale (24 MB integri); da provare con il CDN vero | Prima sessione dal vivo (parte B): i file arrivano in Libreria, stato «scaricato» |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | Da provare (non provocarli di proposito) | Se durante la sonda compare una verifica, annota l'ora e manda la riga ripulita di `navigazioni.jsonl` |
|
||||
| H9 | Un contenuto di una raccolta in evidenza ha lo stesso identificativo che aveva come storia | Da provare | Sonda: apri una raccolta che contiene una storia ancora attiva |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati della pagina, senza leggere i cookie | Da provare | Sonda, pagina iniziale |
|
||||
| H11 | I comandi della pagina si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | Da provare; lo scheletro `bersagli.instagram.json` è pronto | Durante tutta la sonda: passa col puntatore sui comandi elencati prima di usarli; manda le sole righe dei comandi, con i nomi di persona sostituiti |
|
||||
| H9 | Un contenuto di una raccolta in evidenza ha lo stesso identificativo che aveva come storia | Indizio: i contenuti delle raccolte hanno identificativo e scadenza come le storie | Sonda: apri una raccolta che contiene una storia ancora attiva |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati della pagina, senza leggere i cookie | Non basta: i dati danno solo l'identificativo dell'account collegato; Febe lo riconosce quando compare il suo profilo | Sonda, pagina iniziale |
|
||||
| H11 | I comandi della pagina si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | Da provare: il HAR non aveva gli attributi dei comandi. Pagine compilate, bersagli vuoti | Durante tutta la sonda: passa col puntatore sui comandi elencati prima di usarli; manda le sole righe dei comandi, con i nomi di persona sostituiti |
|
||||
|
||||
Finché H1–H11 non sono provate e la mappa dei bersagli e il vocabolario dei lettori non sono compilati sui campioni
|
||||
ripuliti, le ricette su Instagram rispondono «la mappa dei bersagli non è ancora compilata» senza aprire pagine.
|
||||
Finché i bersagli non sono compilati, le ricette che ne hanno bisogno rispondono «la mappa dei bersagli non è ancora
|
||||
compilata» senza aprire pagine; in Attività risultano «Da configurare» e il motore non le pianifica.
|
||||
|
||||
## Voci S: i due browser
|
||||
|
||||
|
||||
@@ -73,18 +73,25 @@ senza dati di Instagram, li riceve dall'elemento appena trovato.
|
||||
- **Libreria:** dove finiscono foto e video, una cartella per account. Può stare su un disco di rete.
|
||||
- **Dati:** database, profilo del browser, miniature, registro, copie. Deve stare su un disco locale.
|
||||
|
||||
Due schemi dei nomi, in Impostazioni ▸ Generali ▸ Nomi dei file, con anteprima del risultato. Predefiniti:
|
||||
Tre schemi dei nomi, in Impostazioni ▸ Generali ▸ Nomi dei file, con anteprima del risultato: uno generale (post,
|
||||
storie, taggati), uno per le raccolte in evidenza e uno per le foto del profilo. Predefiniti:
|
||||
|
||||
```text
|
||||
{account}\{tipo}\{anno}\{data}_{ora}_{codice}_{n}
|
||||
{account}\evidenza\{raccolta}\{data}_{ora}_{codice}_{n}
|
||||
{account}\profilo\{data}_{ora}_{codice}_{n}
|
||||
|
||||
marta.demo\post\2026\2026-10-10_18-22-05_DBx3kQ2_2.jpg
|
||||
marta.demo\evidenza\Estate 2025\2025-08-02_10-11-12_3391207_1.jpg
|
||||
marta.demo\profilo\2026-09-30_21-04-33_a3f9c2e1_1.jpg
|
||||
```
|
||||
|
||||
Le foto del profilo hanno il loro schema perché restino in una cartella a parte anche se cambi quello generale: una
|
||||
copia a ogni cambio di foto, con le prime otto cifre dell'impronta del file al posto del codice.
|
||||
|
||||
- Segnaposto: `account`, `tipo`, `anno`, `mese`, `data`, `ora`, `codice`, `n` (posizione del file nell'elemento),
|
||||
`raccolta`. Un segnaposto sconosciuto è un errore.
|
||||
`raccolta` (solo nello schema delle raccolte). Un segnaposto sconosciuto è un errore, e il campo sbagliato si
|
||||
colora di rosso.
|
||||
- Data e ora nei nomi sono nel tuo fuso; la data di modifica del file è quella di pubblicazione (si può spegnere).
|
||||
- I nomi sono ripuliti per Windows (caratteri vietati, nomi riservati, punti e spazi finali); un percorso oltre 240
|
||||
caratteri si accorcia prima nel nome del file, poi nelle cartelle. Un nome già occupato diventa `nome (2).ext`: mai
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -94,9 +94,11 @@ Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri proget
|
||||
La verifica gira a ogni push su qualunque ramo e a mano (Actions ▸ verifica ▸ Esegui, con un seme facoltativo). Su un
|
||||
ramo un push nuovo annulla l'esecuzione in corso; su `main` ogni unione arriva fino in fondo. Un'esecuzione a mano non
|
||||
annulla mai quella di un push (l'evento fa parte del gruppo di concorrenza): solo il push scrive gli stati del commit
|
||||
che servono per unire, e un lavoro annullato lascerebbe lo stato «failure».
|
||||
che servono per unire, e un lavoro annullato lascerebbe lo stato «failure». Se Gitea perde l'evento di un push (è successo
|
||||
il 13 novembre 2026, con il server che rispondeva 500), un'esecuzione a mano verde non basta per unire, nemmeno da
|
||||
amministratore, perché la regola vale anche per loro: si spinge un commit nuovo sul ramo e si unisce sulla sua verifica.
|
||||
|
||||
Altri flussi: `rilascio.yml` a ogni tag (vedi «Rilasci») e `pulizia.yml` ogni lunedì (vedi «Pulizia»).
|
||||
Altri flussi: `rilascio.yml` a ogni tag (vedi «Rilasci») e `pulizia.yml` ogni lunedì e a mano (vedi «Pulizia»).
|
||||
|
||||
### Il mondo sintetico e il suo seme
|
||||
|
||||
@@ -129,20 +131,39 @@ Sul registro di Gitea, `192.168.30.23:3000/alby96/febe`:
|
||||
| `:latest` | `rilascio`, solo versioni senza trattino | a ogni rilascio stabile | Unraid e Docker Compose |
|
||||
| `:X.Y.Z` | `rilascio` (anche `X.Y.Z-rc.1` per un'anteprima) | mai | una versione precisa, per tornare indietro |
|
||||
| `:main` | `verifica`, dopo ogni unione in `main` | a ogni unione (mai all'indietro) | provare `main` su un server di prova; non per l'archivio vero |
|
||||
| `:sha-<7 caratteri>` | `verifica`, dopo ogni unione in `main` | mai | un commit preciso di `main` |
|
||||
| `:sha-<7 caratteri>` | `verifica`, dopo ogni unione in `main` | mai; restano le 10 più recenti | un commit preciso di `main` |
|
||||
|
||||
Ogni immagine della CI porta le etichette Docker `febe.ci.workflow`, `febe.ci.run`, `febe.ci.ref` e `febe.ci.commit`,
|
||||
oltre a quelle OCI del Dockerfile: da un'immagine si risale all'esecuzione e al commit. Docker le copia in ogni
|
||||
contenitore creato dall'immagine, anche in un Febe vero: per questo la pulizia non le usa mai per scegliere che cosa
|
||||
togliere (vedi «Pulizia»). Le `:sha-` si accumulano: una
|
||||
regola di pulizia dei pacchetti (Impostazioni ▸ Pacchetti ▸ Regole di pulizia) può tenere sempre `latest`, `main` e
|
||||
le versioni e togliere le `sha-.*` più vecchie di 30 giorni.
|
||||
togliere (vedi «Pulizia»). Le `:sha-` non si accumulano: con il segreto `REGISTRY_TOKEN`, la pulizia del lunedì tiene le
|
||||
10 più recenti e toglie le altre; `:main`, `:latest` e le versioni restano sempre.
|
||||
|
||||
Perché togliere un'etichetta liberi davvero spazio, l'immagine si pubblica come un manifest semplice, senza attestazioni
|
||||
(`--provenance=false --sbom=false` in `.gitea/scripts/costruisci-immagine.sh`): in Gitea ogni etichetta è una versione
|
||||
del pacchetto che tiene la configurazione e gli strati, e i blob che nessuna versione usa più li cancella la pulizia dei
|
||||
pacchetti di Gitea stessa, ogni notte, quando hanno più di 24 ore (`[cron.cleanup_packages]`, attiva per impostazione
|
||||
predefinita). Con le attestazioni, che buildx aggiunge da sé, l'immagine sarebbe un indice: Gitea terrebbe ogni manifest
|
||||
figlio come una versione a sé, `sha256:…` senza etichetta, con gli strati, e togliere l'etichetta toglierebbe solo
|
||||
l'indice. La pulizia del lunedì non tocca mai le versioni `sha256:…` (l'API dei pacchetti non dice se un'etichetta le usa
|
||||
ancora) e scrive quante sono. Se ce ne sono (un'immagine spinta a mano, o con più piattaforme), quelle che nessuna
|
||||
etichetta usa più le toglie una regola di pulizia di Gitea, da impostare una volta sul proprietario del pacchetto
|
||||
(Impostazioni ▸ Pacchetti ▸ regole di pulizia): tipo container, attiva, schema delle versioni da rimuovere `sha256:.+`,
|
||||
più vecchie di 7 giorni (il valore più basso dopo lo zero, che toglierebbe anche un figlio appena spinto e non ancora
|
||||
rimandato dal suo indice), nessun numero da tenere. Gitea confronta lo schema con tutta la versione, salta da sé
|
||||
le versioni `sha256:` che un indice ancora rimanda e sempre `latest`, e applica la regola ogni notte; una regola non deve
|
||||
mai toccare `main` e le versioni.
|
||||
|
||||
## Pulizia
|
||||
|
||||
Il demone Docker è condiviso con gli altri progetti, e ci può girare anche un Febe vero, avviato da un'immagine che la
|
||||
CI ha pubblicato e che quindi porta le sue etichette `febe.ci.*`. La CI di Febe toglie solo ciò che può provare suo
|
||||
(`.gitea/scripts/pulizia-docker.sh`):
|
||||
Il demone Docker è condiviso con gli altri progetti di Alberto e, molto probabilmente, con le applicazioni di Unraid; ci
|
||||
può girare anche un Febe vero, avviato da un'immagine che la CI ha pubblicato e che quindi porta le sue etichette
|
||||
`febe.ci.*`. Dal 21 ottobre 2026, per decisione di Alberto, la pulizia (`.gitea/scripts/pulizia-docker.sh`) toglie due
|
||||
cose: ciò che la CI di Febe può provare suo e ciò che non serve più a nessuno, di qualunque progetto. Mai un
|
||||
contenitore, un volume o una rete che non sia della CI.
|
||||
|
||||
Ciò che è della CI di Febe si riconosce da segni che nessuna immagine porta (le etichette `febe.ci.*` no: Docker le
|
||||
copia in ogni contenitore creato dall'immagine, anche in un Febe vero):
|
||||
|
||||
- contenitori di prova: l'etichetta `febe.ci.prova=<esecuzione>`, che mette solo `prova-immagine.sh` con
|
||||
`docker run --label` e che nessuna immagine porta (lo controlla `PipelineTests`), e insieme il nome esatto
|
||||
@@ -150,18 +171,71 @@ CI ha pubblicato e che quindi porta le sue etichette `febe.ci.*`. La CI di Febe
|
||||
- immagini provate: il nome locale `febe-ci:<esecuzione>`, tolto per nome, mai per identificativo e mai con `-f`. Se la
|
||||
stessa immagine ha anche un nome del registro, quello resta; se un contenitore la usa, resta tutto;
|
||||
- builder buildx: il contenitore `buildx_buildkit_febe-ci-<esecuzione>0` con l'immagine `moby/buildkit` e il suo volume
|
||||
`…_state`;
|
||||
- più le immagini senza nome più vecchie di 72 ore che nessun contenitore usa.
|
||||
`…_state`.
|
||||
|
||||
`PipelineTests` fa girare la pulizia contro un demone finto (`tests/Febe.Tests/Packaging/fake-docker.sh`) con un Febe
|
||||
vero acceso e uno fermo che portano le etichette delle loro immagini: non li deve toccare.
|
||||
Ciò che resta dei lavori di act_runner si riconosce dal nome che act_runner dà a tutto ciò che crea per un lavoro,
|
||||
`GITEA-ACTIONS-TASK-<numero del compito>…`: il contenitore del lavoro, i suoi volumi `<nome>` e `<nome>-env`, la sua
|
||||
rete `<nome>-<lavoro>-network`. Se ne vanno i contenitori fermi e i volumi e le reti che nessun contenitore usa, più
|
||||
vecchi di 90 minuti. Il volume `act-toolcache`, la cache degli strumenti condivisa fra i lavori, resta.
|
||||
|
||||
Ciò che non serve più a nessuno lo toglie Docker stesso (`docker image prune`, `docker builder prune`), che non toglie
|
||||
mai un'immagine usata da un contenitore, acceso o fermo: un'applicazione di Unraid ferma tiene la sua immagine. Se però
|
||||
quell'immagine ha più nomi, `image prune -a` le toglie quelli in più (vedi «Che cosa costa»).
|
||||
|
||||
| Quando | Che cosa si toglie |
|
||||
|---|---|
|
||||
| alla fine di ogni lavoro «immagine», sempre | il contenitore di prova con i suoi volumi anonimi, l'immagine provata, il builder buildx dell'esecuzione con la sua cache, l'archivio dell'immagine, le credenziali del registro |
|
||||
| alla fine di ogni lavoro «immagine» (verifica e rilascio), sempre | il contenitore di prova con i suoi volumi anonimi, l'immagine provata, il builder buildx dell'esecuzione con la sua cache, l'archivio dell'immagine, le credenziali del registro; poi, di tutti i progetti, le immagini senza nome che nessun contenitore usa e la cache di costruzione penzolante del demone, cioè quella che nessuna immagine condivide, non usata da 24 ore (`pulizia-docker.sh penzolanti`). Un errore qui è solo un avviso: il lavoro non diventa rosso |
|
||||
| all'inizio di ogni lavoro «immagine» | i resti di esecuzioni interrotte più vecchi di 90 minuti (un lavoro dura al massimo 60 minuti): contenitori di prova **fermi**, immagini `febe-ci:`, builder; e ciò che ha lasciato un tentativo precedente della stessa esecuzione |
|
||||
| ogni lunedì e a mano (`pulizia.yml`) | gli stessi resti, l'immagine `febe:ci` del vecchio flusso se nessuno la usa, le immagini senza nome più vecchie di 72 ore |
|
||||
| mai | immagini, contenitori e volumi degli altri progetti; un contenitore Febe che non sia di prova, anche se porta le etichette `febe.ci.*`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso settimanale diventa rosso); la cache di costruzione del demone; i volumi con un nome; le immagini col nome del registro |
|
||||
| ogni lunedì alle 4:17 e a mano (`pulizia.yml`, `pulizia-docker.sh completa`) | gli stessi resti e l'immagine `febe:ci` del vecchio flusso; i resti di act_runner; **le immagini che nessun contenitore usa create più di 24 ore fa**, di tutti i progetti, anche col nome del registro; la cache di costruzione del demone non usata da più di 24 ore; con il segreto `REGISTRY_TOKEN`, sul registro le `:sha-` oltre le 10 più recenti. Prima e dopo `docker system df`, alla fine un riepilogo di che cosa è andato via |
|
||||
| mai | `docker system prune`, `container prune`, `volume prune`, `network prune`; un contenitore, un volume o una rete che non sia della CI: un Febe vero, anche se porta le etichette `febe.ci.*`, le applicazioni di Unraid, i volumi con i dati, `act-toolcache`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso del lunedì diventa rosso); un'immagine usata da un contenitore, anche fermo (i suoi nomi in più sì: vedi sotto); `image prune -a` e `builder prune -a` senza il filtro delle 24 ore; sul registro `:main`, `:latest` e le versioni `X.Y.Z` |
|
||||
|
||||
Che cosa costa:
|
||||
|
||||
- le immagini di base che fra un lavoro e l'altro nessun contenitore usa (`node:24-trixie` del lavoro «prove»,
|
||||
`moby/buildkit` dei builder, quelle dei lavori degli altri progetti) si riscaricano alla prima esecuzione che le
|
||||
chiede dopo il lunedì: qualche minuto e qualche centinaio di MB in più, una volta. L'immagine dei lavori
|
||||
(`ubuntu-latest`) resta, perché durante la pulizia la usa il lavoro stesso;
|
||||
- da quando contano le 24 ore delle immagini dipende dallo store delle immagini del demone, che la pulizia scrive
|
||||
all'inizio. Con lo store classico (il più probabile su Unraid) contano dalla costruzione dell'immagine: una
|
||||
scaricata ieri ma costruita un mese fa se ne va, e una costruita con una data fissa (costruzioni riproducibili,
|
||||
`SOURCE_DATE_EPOCH`) non è mai protetta dalla finestra. Con lo store di containerd (predefinito nelle installazioni
|
||||
nuove di Docker Engine dalla 29) contano da quando il nome è arrivato sul demone, e un nome riscaricato tiene la data di
|
||||
prima: un'immagine appena riscaricata con un nome che c'era già, e non ancora usata da un contenitore, se ne va. Con
|
||||
tutti e due, un'immagine scaricata e non ancora usata non è al sicuro. La prova dà sempre l'età dalla costruzione, e
|
||||
con containerd lo dice: lì il suo elenco è solo indicativo;
|
||||
- un'immagine costruita a mano e tenuta senza contenitore (per esempio quella di `docker build -t febe .`) se ne va e va
|
||||
ricostruita; una versione di Febe tenuta per tornare indietro si riscarica dal registro, dove `:X.Y.Z` resta;
|
||||
- un'immagine che un contenitore usa resta, ma se ha più nomi `image prune -a` le toglie quelli in più. Con lo store
|
||||
classico resta solo l'ultimo in ordine alfabetico del nome completo, anche quando il contenitore è stato creato da un
|
||||
altro: un'applicazione di Unraid creata da `app:1.2`, se la stessa immagine si chiama anche `app:latest`, continua a
|
||||
girare, ma in locale `app:1.2` non c'è più, e Unraid la mostra da aggiornare o la riscarica. Con lo store di
|
||||
containerd restano i nomi da cui i contenitori sono stati creati. Un Febe vero avviato da `:latest`, se la stessa
|
||||
immagine si chiama anche `:0.1.0`, perde `:0.1.0` e resta `:latest`. La prova elenca questi nomi e la pulizia vera li
|
||||
scrive uno per uno;
|
||||
- la cache di costruzione del builder del demone, con cui costruiscono gli altri progetti: resta quella usata nelle
|
||||
ultime 24 ore. Dopo ogni esecuzione di Febe se ne va quella che nessuna immagine condivide (strati intermedi, cache
|
||||
montate con `RUN --mount=type=cache`) e che nessuno usa da un giorno; il lunedì anche quella condivisa e quella
|
||||
interna di BuildKit, con lo stesso limite. Una costruzione che si ripete almeno una volta al giorno ritrova la sua
|
||||
cache; una più rara la rifà.
|
||||
|
||||
**Prova senza togliere nulla.** Actions ▸ pulizia ▸ Esegui, con «Solo prova» spuntato: il registro del lavoro elenca
|
||||
che cosa toglierebbe (le immagini con dimensione ed età, i nomi in più delle immagini in uso, la cache di costruzione, i
|
||||
resti della CI di Febe e di act_runner, le `:sha-` del registro) e non toglie nulla: solo comandi che leggono, e sul
|
||||
registro solo GET. Si lancia prima della prima pulizia vera e dopo ogni cambio dello script. Dal server, nella cartella
|
||||
del repository:
|
||||
`bash .gitea/scripts/pulizia-docker.sh completa --prova` (il registro solo con `REGISTRY_TOKEN`, `GITEA_API` e
|
||||
`PROPRIETARIO` nell'ambiente). Una prova scritta in un altro modo non diventa la pulizia vera: un'opzione diversa da
|
||||
`--prova` (`--dry-run`, `-n`, `--Prova`) o una parola in più (`prova` senza trattini) fermano lo script con codice 2
|
||||
prima che tocchi Docker, e il flusso accetta per «prova» solo `true` e `false` (un avvio con l'API che passa un altro
|
||||
valore, «True» o «1», si ferma con un errore). Le immagini, nella pulizia vera, le sceglie Docker; nella prova le stima
|
||||
lo script con la stessa regola.
|
||||
|
||||
`PipelineTests` fa girare la pulizia contro un demone finto (`tests/Febe.Tests/Packaging/fake-docker.sh`), con lo store
|
||||
classico e con quello di containerd, con un Febe vero acceso e uno fermo, applicazioni di Unraid accese e ferme (una con
|
||||
due nomi), il lavoro della pulizia stessa, resti veri e finti di act_runner, e contro un'API dei pacchetti finta
|
||||
(`fake-curl.sh`): controlla che cosa resta, che nessun comando vietato parta, che la prova non tocchi nulla e dica ciò
|
||||
che la pulizia vera poi toglie, che una prova scritta male si fermi, e che il token non finisca mai nel registro del
|
||||
lavoro.
|
||||
|
||||
## Rilievi di sicurezza
|
||||
|
||||
@@ -211,4 +285,13 @@ di ogni blocco `run`), gli script con un client Docker finto. Restano da vedere
|
||||
`node:24-trixie` con le azioni dentro; le prove con il browser nel contenitore (nessuna saltata); `upload-artifact@v3`
|
||||
con `retention-days`; la concorrenza; il builder buildx con il nome dell'esecuzione; la prova del contenitore senza
|
||||
rete fino a «healthy»; il download e la scansione di Trivy (e se trova CRITICAL da correggere); gitleaks sulla storia;
|
||||
la pubblicazione su `main` con il segreto; la pulizia settimanale sul demone vero.
|
||||
la pubblicazione su `main` con il segreto.
|
||||
|
||||
Della pulizia del 21 ottobre 2026 (script e API provati con un client Docker e un curl finti) restano da vedere: la
|
||||
casella «Solo prova» di Gitea che arriva al lavoro come «true»; i nomi che questo act_runner dà ai suoi contenitori,
|
||||
volumi e reti; che cosa la prova dice di togliere sul demone vero, da leggere prima della prima pulizia vera; poi la
|
||||
pulizia vera: `docker builder prune` passato a buildx con `BUILDX_BUILDER=default`, il tempo e lo spazio recuperato,
|
||||
le immagini riscaricate dopo; con il segreto, l'API dei pacchetti con `REGISTRY_TOKEN` (elenco a pagine e DELETE delle
|
||||
`:sha-`), e che dopo la prima pubblicazione con `--provenance=false --sbom=false` il pacchetto non abbia versioni
|
||||
`sha256:…` (la riga del registro nel lavoro della pulizia, o la pagina del pacchetto su Gitea); la pulizia di ogni
|
||||
esecuzione alla fine del lavoro «immagine».
|
||||
@@ -86,6 +86,237 @@ 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).
|
||||
|
||||
---
|
||||
|
||||
## A ter. Richieste e risposte per «la pagina chiede i dati» (12 novembre 2026, issue #35)
|
||||
|
||||
Scopo: con la decisione del 12 novembre (issue #34, specifica §2 regola 2 e §6.1) Febe chiede i dati al sito dalla
|
||||
pagina, con le stesse richieste che fa l'applicazione web di Instagram. Per scriverle (`richieste.instagram.json`) e
|
||||
leggerne le risposte servono, da un solo giro nel tuo browser:
|
||||
|
||||
- la **forma delle richieste** che la pagina fa: indirizzi, nomi dei parametri e delle intestazioni, operazioni
|
||||
GraphQL. La dà il nuovo `febe-sonda richieste`, che non scrive nessun valore personale;
|
||||
- le **risposte**, ripulite come sempre con `da-har`, `ripulisci` e `verifica`.
|
||||
|
||||
Niente script dei bersagli, questa volta: con la strada B Febe non cerca più i comandi nella pagina. **Navighi solo
|
||||
tu**: nessun programma clicca o apre pagine.
|
||||
|
||||
### A ter 1. Prima di cominciare
|
||||
|
||||
- Chrome su Windows, con Instagram aperto e l'accesso già fatto.
|
||||
- Una cartella **nuova, fuori da qualunque repository git**, per esempio `C:\febe-har\2026-11-12` (qui sotto
|
||||
`<cartella>`). Il file HAR contiene i cookie della sessione e i dati di altre persone: **non si invia mai**.
|
||||
- Febe compilato dal repository aggiornato (serve il comando `richieste`).
|
||||
- Se compare una verifica, un CAPTCHA o un avviso dell'account, **fermati**, risolvi a mano, annota l'ora e riferisci.
|
||||
|
||||
### A ter 2. Strumenti per sviluppatori
|
||||
|
||||
1. Con Instagram aperto premi **F12**.
|
||||
2. Scheda **Rete**: spunta **Conserva log** e nel filtro dei tipi scegli **Tutti**, non «Fetch/XHR».
|
||||
3. Ricarica la pagina (**F5**) con il pannello aperto.
|
||||
|
||||
### A ter 3. Che cosa fare, nell'ordine
|
||||
|
||||
Muoviti con calma, come al solito, e annota l'ora d'inizio di ogni passo. Ogni passo corrisponde a una richiesta che
|
||||
Febe dovrà saper fare.
|
||||
|
||||
Da qui in poi i profili si aprono **cliccando**, mai scrivendo l'indirizzo nella barra: un indirizzo scritto a mano
|
||||
ricarica tutta la pagina e i dati arrivano dentro il documento, non come richiesta della pagina, e il file non li
|
||||
descriverebbe.
|
||||
|
||||
1. **Ricerca, lettera per lettera, di un profilo che segui.** Clicca **Cerca** nella barra a sinistra e scrivi
|
||||
**piano**, una lettera ogni secondo circa, il suo nome (almeno 5 lettere), finché compare nei risultati. Poi
|
||||
**clicca il risultato**: si apre il suo profilo.
|
||||
2. **Il profilo.** Attendi, poi scorri la griglia finché si caricano **almeno due** pagine di post in più (3–4
|
||||
schermate).
|
||||
3. **Le sue schede.** Clicca **Reel** e scorri un poco; poi **Taggati** e scorri un poco.
|
||||
4. **Le sue storie**, se ne ha: clicca la foto con l'anello, vai avanti di **due** storie, chiudi con la **X** prima
|
||||
che finiscano.
|
||||
5. **Una raccolta in evidenza** dello stesso profilo: aprila, vai avanti **una volta**, chiudi con la **X**.
|
||||
6. **Un post con più foto o un video**: aprilo dalla griglia e passa alla foto successiva con la freccia.
|
||||
7. **Ricerca di un profilo pubblico che non segui**, come al passo 1, lettera per lettera, e **clicca il
|
||||
risultato**: attendi il caricamento e scorri una schermata.
|
||||
8. **I tuoi seguiti.** Clicca la tua foto nella barra a sinistra, poi **«Seguiti»**, e scorri l'elenco finché si
|
||||
caricano **almeno due** pagine in più. Poi, nella casella **Cerca** dentro l'elenco, scrivi piano tre lettere e
|
||||
chiudi.
|
||||
9. **La home.** Clicca il logo, attendi e scorri piano per una decina di post; apri la barra delle storie solo se lo
|
||||
fai di solito.
|
||||
|
||||
Ci si aspetta: nessuna verifica, nessun avviso.
|
||||
|
||||
### A ter 4. Il file HAR
|
||||
|
||||
Scheda **Rete**: **esporta il HAR** in `<cartella>\instagram.har`. Se Chrome offre due voci, scegli quella **senza**
|
||||
dati sensibili (toglie cookie e autorizzazioni, che non servono); se poi `da-har` dice che le risposte sono «senza
|
||||
corpo», esporta di nuovo con l'altra voce. Chiudi gli strumenti per sviluppatori.
|
||||
|
||||
### A ter 5. Forma delle richieste, conversione, ripulitura e verifica (sulla tua macchina)
|
||||
|
||||
```sh
|
||||
febe-sonda richieste --har <cartella>\instagram.har --a <cartella>\richieste.json
|
||||
febe-sonda da-har --har <cartella>\instagram.har --a <cartella>\grezzi
|
||||
febe-sonda ripulisci --da <cartella>\grezzi --a <cartella>\ripuliti
|
||||
febe-sonda verifica --grezzi <cartella>\grezzi --ripuliti <cartella>\ripuliti
|
||||
```
|
||||
|
||||
Dal repository: `dotnet run --project tools/Febe.Sonda -- richieste …`, e così per gli altri.
|
||||
|
||||
- `richieste` scrive un file **nuovo** (rifiuta un file che esiste già, una cartella e un file dentro un
|
||||
repository). Per ogni richiesta distinta della pagina al sito: metodo, percorso (le parti che non sono parole fisse
|
||||
del sito diventano `{numero}` o `{testo}`), nomi dei parametri e dei campi del corpo con il **tipo** del valore
|
||||
(«numero», «testo», «vuoto»), nomi delle intestazioni, struttura delle variabili GraphQL; quante volte la pagina
|
||||
l'ha fatta, gli stati e i tipi delle risposte. Dei valori restano solo quelli uguali per tutti: l'identificativo
|
||||
dell'applicazione, i nomi e gli identificativi (`doc_id`) delle operazioni, la grandezza delle pagine, vero/falso.
|
||||
I valori delle altre intestazioni sono `(valore tolto)`. Un nome che nel file HAR compare anche come valore (un
|
||||
nome utente usato come chiave, per esempio) diventa `(nome tolto)`. Stampa solo conteggi.
|
||||
- I valori fissi delle variabili (per esempio da quale «superficie» parte una ricerca) restano «testo», perché lo
|
||||
strumento non sa distinguerli da ciò che scrivi tu: se servono, te li chiedo per nome e li guardi tu nel HAR.
|
||||
- **Leggi `richieste.json` prima di inviarlo**: non deve esserci un nome, un cognome, un indirizzo di posta, un
|
||||
testo che hai scritto. Se ne trovi uno, non inviarlo e dimmi dove (il campo, non il valore).
|
||||
- Per `da-har`, `ripulisci` e `verifica` vale quanto scritto in A bis 6.
|
||||
|
||||
### A ter 6. Che cosa mandare
|
||||
|
||||
1. `richieste.json`, dopo averlo letto.
|
||||
2. La cartella **ripulita** (compressa) e il testo della verifica.
|
||||
3. Le note: a che ora hai fatto ogni passo, che cosa è andato diversamente, se la ricerca e l'elenco dei seguiti si
|
||||
sono comportati come descritto.
|
||||
|
||||
Mai: il file HAR, la cartella `grezzi`. Quando richieste e lettori sono stati scritti, **cancella il file HAR e la
|
||||
cartella `grezzi`** (§14.5).
|
||||
|
||||
## A quater. I pezzi che mancano al HAR del 12 novembre
|
||||
|
||||
Il HAR del 12 novembre (un giro veloce) ha dato quasi tutto: profilo, schede, raccolte, storie, ricerca, pagina
|
||||
iniziale (esito in `docs/sonda/richieste-instagram.md`). Mancano due cose, e per quelle basta un giro corto, con la
|
||||
stessa preparazione (A ter 1 e A ter 2) e la stessa procedura alla fine (A ter 4, 5 e 6), in una cartella nuova:
|
||||
|
||||
1. **I tuoi seguiti** (A ter passo 8): clicca la tua foto nella barra a sinistra, poi **«Seguiti»**, e scorri
|
||||
l'elenco finché si caricano **almeno due** pagine in più. Senza questo il giro dei seguiti non si può scrivere.
|
||||
2. **Le pagine successive dei post** (A ter passo 2): apri cliccando un profilo che segui e che abbia molti post,
|
||||
e scorri la griglia finché si caricano **almeno due** pagine in più (3–4 schermate).
|
||||
|
||||
Niente storie questa volta: guardarle le segna come viste.
|
||||
|
||||
**Perché il HAR non si tronchi.** Il primo tentativo (12 novembre, sera) è arrivato troncato due volte: la prima
|
||||
esportazione a 200 000 byte esatti, la seconda a 57 MB, quando Chrome ha smesso di scrivere a metà di una risposta,
|
||||
dopo 141 voci. La parte completa arrivava solo alla pagina iniziale. Quasi tutto il peso sono i corpi di immagini e video che il pannello Rete tiene
|
||||
insieme alle risposte di dati. Per restare leggeri:
|
||||
|
||||
- apri Instagram e aspetta che la pagina iniziale sia caricata, poi **svuota il pannello Rete** (il cerchio barrato
|
||||
in alto a sinistra) e solo allora comincia il giro: così nel file c'è solo il giro;
|
||||
- non aprire post, reel o video e non lasciare che la pagina iniziale li faccia partire: per i seguiti e per la
|
||||
griglia di un profilo bastano le miniature;
|
||||
- esporta appena hai finito, e aspetta che il file sia scritto del tutto prima di rinominarlo.
|
||||
|
||||
Se il file è troncato lo stesso, `febe-sonda` lo dice («Il file HAR è troncato») e legge comunque le voci complete,
|
||||
scartando quella dentro cui il file finisce. Conta che cosa è arrivato con `febe-sonda richieste`: se mancano i seguiti o la seconda
|
||||
pagina dei post, rifai il giro più corto (per esempio i seguiti in un file e lo scorrimento in un altro).
|
||||
|
||||
---
|
||||
|
||||
## B. Prima sessione dal vivo, dopo M3
|
||||
|
||||
Scopo: vedere Febe fare una sessione vera, piccola, con il profilo **Prudente**, e i file arrivare in libreria.
|
||||
|
||||
|
Before Width: | Height: | Size: 202 KiB After Width: | Height: | Size: 207 KiB |
|
Before Width: | Height: | Size: 189 KiB After Width: | Height: | Size: 170 KiB |
|
Before Width: | Height: | Size: 170 KiB After Width: | Height: | Size: 159 KiB |
|
Before Width: | Height: | Size: 160 KiB After Width: | Height: | Size: 147 KiB |
|
Before Width: | Height: | Size: 126 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 147 KiB After Width: | Height: | Size: 136 KiB |
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 64 KiB |
|
Before Width: | Height: | Size: 72 KiB After Width: | Height: | Size: 69 KiB |
@@ -83,11 +83,16 @@ schermata del motore fermo si prende per prima, perché «Riprendi» resta spent
|
||||
collegamento a «Doppioni da decidere», sotto gli elenchi: il mockup non lo prevede (§9.5).
|
||||
- **Attività, fermo.** La striscia rossa ha «Riprendi» solo nell'intestazione della pagina (non doppio). Nel giorno
|
||||
la parte dopo l'arresto è tratteggiata in rosso, come nel mockup; lo storico degli incidenti sta in fondo.
|
||||
- **Attività, «Diagnostica».** Nella riga del titolo c'è un terzo pulsante, «Diagnostica» con l'icona del file con la
|
||||
freccia, che i mockup 06 e 11 non hanno: scarica il rapporto di diagnostica (#39, §7.9). Nella finestra stretta i
|
||||
tre pulsanti stanno sulla riga con le scritte; al telefono restano tre icone accanto al titolo, senza andare a capo.
|
||||
Schermate di Attività (06, 11, 14) rifatte il 13/11 da Windows.
|
||||
- **Limiti e comportamento.** Gli orari sono campi di testo a 24 ore («07:30») invece del selettore d'ora del
|
||||
browser, che in alcune lingue mostra AM/PM. I giorni sono cerchi con l'iniziale. La barra di salvataggio resta
|
||||
sempre visibile: spenta con «Nessuna modifica», si accende alla prima modifica.
|
||||
- **Impostazioni generali.** In più rispetto al mockup: lo spazio libero accanto alle cartelle, la nota «Per ora
|
||||
c'è solo l'italiano» sotto la lingua e la riga «Solo versione Windows» accanto ad «Avvio». In Docker le cartelle
|
||||
- **Impostazioni generali.** In più rispetto al mockup: lo spazio libero accanto alle cartelle, il terzo schema «Schema
|
||||
per le foto del profilo» con la cartella `profilo` nel risultato (#38, schermata rifatta il 13/11 da Windows), la
|
||||
nota «Per ora c'è solo l'italiano» sotto la lingua e la riga «Solo versione Windows» accanto ad «Avvio». In Docker le cartelle
|
||||
non si cambiano dall'interfaccia (si cambiano i volumi del contenitore) e la sezione Avvio non c'è.
|
||||
- **Importa, revisione.** Percorso della cartella temporanea della dimostrazione; le immagini dei doppioni sono
|
||||
disegni generati. Il riquadro dei doppioni passa al caso seguente dopo ogni scelta: la schermata torna al primo
|
||||
|
||||
@@ -1,24 +1,52 @@
|
||||
# Esito delle ipotesi di M0 (specifica §6.6)
|
||||
|
||||
Stato al 13 ottobre 2026. Finché una voce non ha un esito con le prove, **non ci si costruisce sopra**: per questo i
|
||||
file di Instagram sono ancora scheletri e le ricette si rifiutano di girare su Instagram (vedi in fondo).
|
||||
Stato al 25 ottobre 2026. Finché una voce non ha un esito con le prove, **non ci si costruisce sopra**.
|
||||
|
||||
**25 ottobre 2026: i primi campioni reali.** Alberto ha mandato un file HAR esportato dal suo browser il 21 ottobre
|
||||
(DevTools, filtro Fetch/XHR: niente documenti, immagini né script). Le risposte utili sono state convertite nel formato
|
||||
della sonda fuori dal repository, ripulite e verificate («Verifica superata»): sono in `tests/Febe.Tests/campioni/instagram`
|
||||
(vedi il suo `LEGGIMI.md`). Con quelle `lettori.instagram.json` è compilato e «confermato», e di
|
||||
`bersagli.instagram.json` sono compilate le pagine con una prova reale (vedi in fondo). Le colonne «Stato» qui sotto
|
||||
dicono che cosa il HAR ha provato e che cosa no.
|
||||
|
||||
**12 novembre 2026: il secondo HAR** (senza filtro, documenti compresi; #35). Risultati in
|
||||
`docs/sonda/richieste-instagram.md`, otto campioni nuovi in `tests/Febe.Tests/campioni/instagram` (da `000009` a
|
||||
`000016`). Che cosa cambia per le ipotesi, senza riscrivere la tabella qui sotto, che resta quella della raccolta coi
|
||||
bersagli:
|
||||
|
||||
- **H1**: la prima pagina del feed è incorporata nel documento della pagina iniziale
|
||||
(`xdt_api__v1__feed__timeline__connection`), le successive con `PolarisFeedRootPaginationCachedQuery_subscribe`.
|
||||
- **H2: provata.** Il vassoio delle storie è incorporato nella pagina iniziale (`xdt_api__v1__feed__reels_tray`): per
|
||||
ogni profilo `latest_reel_media`, `expiring_at` e se è già stato visto.
|
||||
- **H3: provata, salvo le pagine successive.** Scheda (`PolarisProfilePageContentQuery`, con `media_count`), post
|
||||
(`PolarisProfilePostsQuery`, reel e serie compresi, con `end_cursor`), elenco delle raccolte con la copertina. La
|
||||
richiesta della seconda pagina non è nel HAR.
|
||||
- **H4**: le storie attive di un profilo arrivano con `PolarisStoriesV3ReelPageStandaloneQuery`, con scadenza e durata
|
||||
e senza dimensioni dei video; guardarle nel visualizzatore manda `PolarisStoriesV3SeenMutation`.
|
||||
- **H6: risposta diversa dall'ipotesi.** Le schede Reel e Con tag danno anteprime senza data né video, non contenuti
|
||||
completi; i reel del profilo sono comunque fra i post.
|
||||
- **H10: un passo avanti.** Nel blocco incorporato della pagina iniziale `xdt_viewer.user` ha identificativo, nome
|
||||
utente e foto dell'account collegato (`000015-vassoio-storie`), e il lettore lo legge come `Viewer`; nelle
|
||||
risposte alle richieste della pagina ha il solo identificativo. Resta da provare con la raccolta vera (#36).
|
||||
- **La JSON incorporata nel documento** è confermata: 69 blocchi nella pagina iniziale.
|
||||
- **Manca l'elenco dei seguiti**: nessuna richiesta nel HAR (`docs/prove-dal-vivo.md`, parte A quater).
|
||||
|
||||
Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvfb e pagine locali, mai Instagram;
|
||||
**da provare dal vivo** = serve Alberto, con l'account di prova e la sonda (`docs/prove-dal-vivo.md`, parte A).
|
||||
|
||||
| | Ipotesi | Stato | Come si prova (procedura esatta) | Che cosa ne dipende |
|
||||
|---|---|---|---|---|
|
||||
| H1 | La home consegna i post recenti dei seguiti con i dati completi dei file | **Da provare dal vivo** | Sonda, passo A3.1: aprire la home, attendere il caricamento, scorrere piano per una decina di post. Nei campioni ripuliti cercare risposte con elenchi di contenuti (identificativo, data, versioni delle immagini con dimensioni, figli delle serie) | Giro dei seguiti; `pages.home` di `bersagli.instagram.json`; concetti `content.*` e `version.*` di `lettori.instagram.json` |
|
||||
| H2 | La barra delle storie dice quali seguiti hanno storie attive e a quando risale l'ultima | **Da provare dal vivo** | Passo A3.1: con la home caricata, la sonda registra le risposte della barra; nei ripuliti cercare elenchi di profili con un campo data dell'ultima storia | `profile.latestStoryAt`; bersaglio `home-story` |
|
||||
| H3 | Il profilo consegna identificativo, pubblico/privato, se è seguito, prima pagina dei post con serie e video, elenco delle raccolte; lo scorrimento carica le pagine successive | **Da provare dal vivo** | Passi A3.2 e A3.3: profilo pubblico non seguito e profilo privato seguito, scorrendo 3–4 schermate. Nei ripuliti: un nodo profilo con i campi di stato, pagine di contenuti successive con un punto di ripresa | Controllo del profilo, Storico; `profile.*`, `highlight.*`, `page.*`; `pages.profile`, `pages.profileFrom` (facoltativa: se il sito non riparte da un cursore, lo storico riprende scorrendo) |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | **Da provare dal vivo** | Passo A3.4: aprire le storie di un seguito dall'anello del profilo, guardarne 2–3, chiudere con la X **prima** che passi all'account successivo. Nei ripuliti: un elenco di contenuti con data di scadenza; in `navigazioni.jsonl` la forma dell'indirizzo del visualizzatore | Storie di un account; `content.expiresAt`; `pages.storyViewer`; bersagli `profile-story-ring`, `viewer-next`, `viewer-close` |
|
||||
| H5 | Per i video arriva almeno un indirizzo unico con audio e video insieme | **Da provare dal vivo** | Passi A3.2 e A3.4 su un post video e su una storia video. Nei ripuliti: le versioni del video e un campo che dica se hanno l'audio | `version.hasAudio`; scelta della versione di §6.5 punto 1 (se nessuna versione ha audio e video insieme, va riletta §4.9: l'unione delle tracce è fuori dalla versione 1) |
|
||||
| H6 | Le schede «taggati» e «reel» si comportano come la griglia | **Da provare dal vivo** | Passo A3.6: aprire le due schede di un profilo e scorrere | Taggati, Reel; bersagli `profile-tab-tagged`, `profile-tab-reels`; `pages.taggedFrom`, `pages.reelsFrom` |
|
||||
| H1 | La home consegna i post recenti dei seguiti con i dati completi dei file | **Da provare dal vivo**. Il HAR non contiene la home: nessuna risposta del feed | Sonda, passo A3.1: aprire la home, attendere il caricamento, scorrere piano per una decina di post. Nei campioni ripuliti cercare risposte con elenchi di contenuti (identificativo, data, versioni delle immagini con dimensioni, figli delle serie) | Giro dei seguiti; `pages.home` di `bersagli.instagram.json`; concetti `content.*` e `version.*` di `lettori.instagram.json` |
|
||||
| H2 | La barra delle storie dice quali seguiti hanno storie attive e a quando risale l'ultima | **Da provare dal vivo**. Il HAR non contiene la barra delle storie. La data dell'ultima storia di un profilo esiste come `latest_reel_media` (vista nell'autore di un post e nel proprietario di una raccolta) | Passo A3.1: con la home caricata, la sonda registra le risposte della barra; nei ripuliti cercare elenchi di profili con un campo data dell'ultima storia | `profile.latestStoryAt`; bersaglio `home-story` |
|
||||
| H3 | Il profilo consegna identificativo, pubblico/privato, se è seguito, prima pagina dei post con serie e video, elenco delle raccolte; lo scorrimento carica le pagine successive | **In parte**. Forma dell'indirizzo confermata (`/{username}/{?tab}/…`, dalle definizioni delle pagine che Instagram stesso manda); forma del nodo profilo confermata (`pk`, `username`, `is_private`, `friendship_status.following`, `hd_profile_pic_url_info`, `latest_reel_media`). Le risposte della pagina profilo (intestazione, griglia, raccolte, pagine successive) **non** sono nel HAR: da provare dal vivo | Passi A3.2 e A3.3: profilo pubblico non seguito e profilo privato seguito, scorrendo 3–4 schermate. Nei ripuliti: un nodo profilo con i campi di stato, pagine di contenuti successive con un punto di ripresa | Controllo del profilo, Storico; `profile.*`, `highlight.*`, `page.*`; `pages.profile`, `pages.profileFrom` (facoltativa: se il sito non riparte da un cursore, lo storico riprende scorrendo) |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | **In parte**. Il visualizzatore delle raccolte riceve l'elenco completo dei contenuti con indirizzi, `taken_at` ed `expiring_at` (`xdt_api__v1__feed__reels_media__connection`, `text/javascript`); la forma dell'indirizzo delle storie è `/stories/{username}/{?initial_media_id}/`. La risposta delle storie di un account (non di una raccolta) e se l'indirizzo segue ogni storia: da provare dal vivo | Passo A3.4: aprire le storie di un seguito dall'anello del profilo, guardarne 2–3, chiudere con la X **prima** che passi all'account successivo. Nei ripuliti: un elenco di contenuti con data di scadenza; in `navigazioni.jsonl` la forma dell'indirizzo del visualizzatore | Storie di un account; `content.expiresAt`; `pages.storyViewer`; bersagli `profile-story-ring`, `viewer-next`, `viewer-close` |
|
||||
| H5 | Per i video arriva almeno un indirizzo unico con audio e video insieme | **In parte**. `video_versions` dà tre versioni `.mp4` (tipi 101, 102, 103: nei post stesse dimensioni e banda); se c'è l'audio lo dice il contenuto (`has_audio`), non la versione. Che il file abbia davvero audio e video insieme si conferma scaricando (prima sessione dal vivo) | Passi A3.2 e A3.4 su un post video e su una storia video. Nei ripuliti: le versioni del video e un campo che dica se hanno l'audio | `version.hasAudio`; scelta della versione di §6.5 punto 1 (se nessuna versione ha audio e video insieme, va riletta §4.9: l'unione delle tracce è fuori dalla versione 1) |
|
||||
| H6 | Le schede «taggati» e «reel» si comportano come la griglia | **Da provare dal vivo**. Nessuna risposta delle schede nel HAR | Passo A3.6: aprire le due schede di un profilo e scorrere | Taggati, Reel; bersagli `profile-tab-tagged`, `profile-tab-reels`; `pages.taggedFrom`, `pages.reelsFrom` |
|
||||
| H7 | I file del CDN si scaricano con `Network.loadNetworkResource`; se no, con la via di riserva di §6.5 | **Da provare dal vivo**. In locale: scaricati integri (24 MB in 2,2 s; foto e video del sito di prova byte per byte) | Dopo la sonda, con la prima sessione dal vivo (parte B): file arrivati in Libreria, stato «scaricato». **Osservazione locale**: dalla pagina di riposo `about:blank` Chromium rifiuta gli indirizzi locali del CDN di prova (`net::ERR_BLOCKED_BY_PRIVATE_NETWORK_ACCESS_CHECKS`); dalle pagine del sito funziona. Con il CDN pubblico va misurato se lo scaricamento regge anche dalla pagina di riposo | `BrowserFileFetcher`; la via `HttpClient` di §6.5 punto 3 **non è scritta**: resta dietro `IFileFetcher` finché H7 non dice che serve. Codici HTTP di «indirizzo scaduto» (in locale 403 e 410) |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | **Da provare dal vivo** (non provocare segnali di proposito) | Se durante la sonda compare una verifica o un avviso, annotare l'ora e mandare la riga corrispondente di `navigazioni.jsonl` ripulita. Sul sito di prova i casi 429, `/verifica`, sessione terminata e pagine vuote fermano le ricette (prove `StopAndDownloadIntegrationTests`) | `segnali.json` (le regole su Instagram restano ipotesi segnate H8) |
|
||||
| H9 | Un contenuto di una raccolta ha lo stesso identificativo che aveva come storia | **Da provare dal vivo** | Passo A3.5: aprire una raccolta che contenga una storia ancora attiva (o pubblicata e poi messa in evidenza dall'account di prova). Confrontare gli identificativi nei ripuliti: la ripulitura dà a valori uguali lo stesso valore finto | Raccolta in evidenza (collegamento senza riscaricare); sul sito di prova funziona così per costruzione |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati, senza leggere i cookie | **Da provare dal vivo** | Passo A3.1: nei ripuliti della home cercare un nodo che descriva l'account collegato | `viewer` di `lettori.instagram.json`; il profilo «Tu» |
|
||||
| H11 | I bersagli si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | **Da provare dal vivo**. Scheletro pronto: `bersagli.instagram.json` | Durante tutta la sonda: passare col puntatore e cliccare i comandi elencati al passo A3; la sonda registra ruolo, nome accessibile e forma del collegamento in `interazioni.jsonl`. Alberto manda le righe dei soli comandi dell'interfaccia (passo A6) | Tutte le ricette |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | **Da provare dal vivo** (non provocare segnali di proposito). Nessun segnale nel HAR | Se durante la sonda compare una verifica o un avviso, annotare l'ora e mandare la riga corrispondente di `navigazioni.jsonl` ripulita. Sul sito di prova i casi 429, `/verifica`, sessione terminata e pagine vuote fermano le ricette (prove `StopAndDownloadIntegrationTests`) | `segnali.json` (le regole su Instagram restano ipotesi segnate H8) |
|
||||
| H9 | Un contenuto di una raccolta ha lo stesso identificativo che aveva come storia | **Indizio**. I contenuti di una raccolta hanno `pk` ed `expiring_at` come le storie; che il `pk` sia lo stesso della storia originale va visto con una storia ancora attiva | Passo A3.5: aprire una raccolta che contenga una storia ancora attiva (o pubblicata e poi messa in evidenza dall'account di prova). Confrontare gli identificativi nei ripuliti: la ripulitura dà a valori uguali lo stesso valore finto | Raccolta in evidenza (collegamento senza riscaricare); sul sito di prova funziona così per costruzione |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati, senza leggere i cookie | **Non basta**. `xdt_viewer.user` descrive l'account collegato con il solo identificativo, senza nome: Febe lo tiene (`ReadResult.ViewerId`) e riconosce «Tu» quando il suo profilo compare in un'altra risposta. Da provare dal vivo | Passo A3.1: nei ripuliti della home cercare un nodo che descriva l'account collegato | `viewer` di `lettori.instagram.json`; il profilo «Tu» |
|
||||
| H11 | I bersagli si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | **Da provare dal vivo**. Il HAR non ha documenti né attributi degli elementi: i bersagli restano vuoti. Procedura semplificata in `docs/prove-dal-vivo.md`, parte A bis | Durante tutta la sonda: passare col puntatore e cliccare i comandi elencati al passo A3; la sonda registra ruolo, nome accessibile e forma del collegamento in `interazioni.jsonl`. Alberto manda le righe dei soli comandi dell'interfaccia (passo A6) | Tutte le ricette |
|
||||
| S1 | In WebView2 funzionano corpo delle risposte, gesti e fotogrammi | **Da provare** su Windows. Pronto: `WebView2Browser` (Febe.Desktop) con l'adattatore `WebView2CdpSession` (stesso elenco ammesso del client Chromium, provato su Linux con un finto WebView2) | `docs/prove-dal-vivo.md`, parte C3: Febe per Windows con `--sito-di-prova`, una sessione intera (`Network.getResponseBody`, `Input.dispatchMouseEvent`, `Network.loadNetworkResource`/`IO.read`) e l'anteprima di Attività (`Page.captureScreenshot`). `Page.startScreencast` su Windows non serve (la vista remota è solo di Docker) | `WebView2Browser`, `WebView2CdpSession` |
|
||||
| S2 | Su Windows la pagina carica e scorre con la finestra fuori vista | **Da provare** su Windows. Pronti i tre modi di §6.6, scelti con `Febe.exe --browser finestra\|composizione\|edge` (predefinito `finestra`: fuori dallo schermo, `IsVisible` sempre vero, `--disable-features=CalculateNativeWinOcclusion --disable-backgrounding-occluded-windows`) | `docs/prove-dal-vivo.md`, parte C4: sessione sul sito di prova con il browser fuori vista, con la finestra di Febe ridotta a icona e con lo schermo bloccato; se non regge, `composizione` e poi `edge` | `WebView2Browser`, `CompositionHost`, `EdgeBrowser` |
|
||||
| S3 | L'accesso a mano sopravvive al riavvio | **Provato in locale per Docker/Chromium** (cookie scritto con arresto SIGINT, 3 esecuzioni su 3; vedi `esito-locale.md`); **da provare** su Windows (all'arresto Febe chiude WebView2 e ne aspetta l'uscita prima di finire) e nel contenitore vero | Docker: accedere, riavviare il contenitore, controllare il collegamento. Windows: `docs/prove-dal-vivo.md`, parti C3.7 (sito di prova) e C5 (Instagram, account di prova: Esci e riapri, riavvio di Windows, avvio con il computer) | Profilo del browser nella cartella dei dati |
|
||||
@@ -28,14 +56,19 @@ Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvf
|
||||
|
||||
## Che cosa è pronto per ricevere gli esiti
|
||||
|
||||
- `src/Febe.Core/Config/bersagli.instagram.json` (copiato in `config/`): **scheletro**. Elenca le pagine e i bersagli
|
||||
di cui le ricette hanno bisogno, tutti vuoti e segnati con l'ipotesi da cui dipendono. Finché una voce necessaria è
|
||||
vuota, la ricetta risponde «non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano …)»
|
||||
senza aprire pagine e senza chiedere permessi.
|
||||
- `src/Febe.Core/Config/lettori.instagram.json`: **ipotesi**. Contiene solo gli indizi di §6.4 (`pk`, `code`,
|
||||
`taken_at`, `image_versions2.candidates`, `video_versions`, `carousel_media`); ogni altro concetto è vuoto. Con lo
|
||||
stato «ipotesi» le ricette non girano. Va riempito sui campioni ripuliti e portato a «confermato».
|
||||
- `src/Febe.Core/Config/lettori.instagram.json`: **confermato** il 25 ottobre sui campioni reali ripuliti; ogni sua
|
||||
chiave compare in quei campioni (lo controlla `InstagramReaderTests`). Le risposte che non parlano di contenuti
|
||||
(promozioni, «storia vista») si ignorano (`relevance`). Senza riscontro restano vuoti `pinned` e
|
||||
`version.hasAudio`. Il 12 novembre, con il secondo HAR: `postCount` = `media_count`, le serie con i loro figli
|
||||
(`carousel_media`, anche video) e la copertina delle raccolte (`highlight.cover`).
|
||||
- `src/Febe.Core/Config/bersagli.instagram.json`: compilate le **pagine** con una prova reale (home, profilo, post,
|
||||
visualizzatore delle storie e delle raccolte, dalle definizioni delle pagine e dai Referer del HAR); i **bersagli**
|
||||
sono vuoti (H11). Le ricette che non ne hanno bisogno girano; quelle che li usano (storie, raccolte, schede Taggati e
|
||||
Reel) rispondono «la mappa dei bersagli non è ancora compilata (mancano …)» senza aprire pagine e senza chiedere
|
||||
permessi. Questi file si possono sostituire con una copia nella cartella Dati, che vince su quella incorporata.
|
||||
- La cattura legge anche le risposte `text/javascript` chieste dalla pagina (così Instagram manda i dati GraphQL) e il
|
||||
JSON incorporato nel documento della pagina (da confermare dal vivo: il HAR non aveva documenti).
|
||||
- `segnali.json`: regole di partenza, ancora ipotesi H8.
|
||||
- Sonda: `febe-sonda registra`, `ripulisci`, `verifica` (procedura in `docs/prove-dal-vivo.md`).
|
||||
- Sonda: `febe-sonda registra`, `da-har` (da un HAR del browser), `ripulisci`, `verifica` (procedura in `docs/prove-dal-vivo.md`).
|
||||
- Il sito di prova fa girare tutte le ricette con un browser vero (`tests/Febe.Tests/Collection/`): è la prova che la
|
||||
raccolta funziona **quando** mappa e vocabolario saranno compilati, non che Instagram si comporti allo stesso modo.
|
||||
@@ -0,0 +1,118 @@
|
||||
# Le richieste della pagina di Instagram (HAR del 12 novembre 2026)
|
||||
|
||||
Che cosa chiede l'applicazione web di Instagram al sito, ricavato dal secondo HAR di Alberto (#35) per scrivere
|
||||
`richieste.instagram.json` e la raccolta della strada B (#36, decisione #34). Qui ci sono solo **forme**: nomi di
|
||||
operazioni, percorsi, nomi delle variabili e delle chiavi delle risposte. Nessun valore del HAR, nessun `doc_id`.
|
||||
|
||||
## Da dove viene
|
||||
|
||||
- HAR esportato da Alberto il 12 novembre 2026, **senza filtro**, seguendo `docs/prove-dal-vivo.md` parte A ter:
|
||||
pagina iniziale, ricerca di un profilo, il profilo aperto cliccando, le schede Reel, Con tag e Ripubblicati, le
|
||||
raccolte in evidenza, una storia, un post.
|
||||
- Fuori dal repository (`C:\Users\alber\febe-har\2026-11-12`), sulla macchina di Alberto:
|
||||
- `febe-sonda richieste` → `richieste.json`: 45 forme di richieste della pagina al sito;
|
||||
- `febe-sonda da-har` → 142 campioni grezzi (69 blocchi incorporati nell'unico documento, la pagina iniziale, più 73
|
||||
risposte di dati);
|
||||
- `febe-sonda ripulisci` e `febe-sonda verifica` → «Verifica superata» su 142 file (44 102 frammenti controllati).
|
||||
- Nel repository: otto di quelle risposte, accorciate sulla copia ripulita, in `tests/Febe.Tests/campioni/instagram`
|
||||
(file da `000009` a `000016`, vedi il suo `LEGGIMI.md`).
|
||||
|
||||
## Che cosa serve a Febe e da dove arriva
|
||||
|
||||
Le operazioni GraphQL sono `POST` con corpo `application/x-www-form-urlencoded`, su due indirizzi:
|
||||
|
||||
- `/api/graphql`: scheda, post, Reel, Con tag ed elenco delle raccolte del profilo, ricerca, storie di un profilo;
|
||||
- `/graphql/query`: pagina iniziale e contenuti delle raccolte in evidenza (con le intestazioni `x-root-field-name`
|
||||
e `x-bloks-version-id`), e la scheda Ripubblicati (senza quelle intestazioni).
|
||||
|
||||
La pagina manda anche `PolarisStoriesV3AdsPoolQuery` (le pubblicità fra le storie) a un terzo indirizzo: a Febe non
|
||||
serve. Le risposte arrivano come `text/javascript`, tranne le pagine successive della pagina iniziale
|
||||
(`PolarisFeedRootPaginationCachedQuery_subscribe`), che arrivano come `application/json`; la cattura le legge tutte e
|
||||
due (`DataResponses`).
|
||||
|
||||
| Che cosa serve | Operazione | Variabili (`variables`) | Radice della risposta | Pagina successiva | Campione |
|
||||
|---|---|---|---|---|---|
|
||||
| Intestazione del profilo: nome, foto grande, privato, seguito, numero dei post | `PolarisProfilePageContentQuery` | `id` (numero), `enable_integrity_filters` | `data.user` | — | `000009-scheda-profilo` |
|
||||
| Post del profilo, reel e serie compresi | `PolarisProfilePostsQuery` | `username` (testo), `data.count` = 12 e quattro `include_*`/`latest_*` | `data.xdt_api__v1__feed__user_timeline_graphql_connection` | `page_info.end_cursor` e `has_next_page`; la richiesta della pagina 2 **non è nel HAR** | `000010-post-del-profilo`, `000016-serie-con-video` |
|
||||
| Scheda Reel | `PolarisProfileReelsTabContentQuery` | `user_id`, `data.target_user_id`, `data.page_size` = 12, `data.include_feed_video` | `data.fetch__XDTUserDict.clips_connection` | `page_info` | `000011-reel-del-profilo` (anteprime) |
|
||||
| Scheda Con tag | `PolarisProfileTaggedTabContentQuery` | `user_id`, `count` = 12 | `data.xdt_api__v1__usertags__user_id__feed_connection` | `page_info` (il cursore è un numero) | `000012-con-tag` (anteprime) |
|
||||
| Scheda Ripubblicati | `PolarisProfileRepostsTabContentQuery` (su `/graphql/query`) | `user_id` | `data.fetch__XDTUserDict.user_reposts_timeline` | `repost_more_available`, `repost_next_max_id` | non copiato |
|
||||
| Elenco delle raccolte in evidenza | `PolarisProfileStoryHighlightsTrayContentQuery` | `user_id` | `data.highlights` (`edges[].node`: `id`, `title`, `cover_media`, `user`) | `page_info` | `000013-raccolte-del-profilo` |
|
||||
| Contenuti delle raccolte | `PolarisStoriesV3HighlightsPageQuery`, poi `…PaginationQuery` | `reel_ids` (elenco di `highlight:<numero>`), `initial_reel_id`, `first`, `last`; la seconda anche `after`, `before`, `is_highlight` | `xdt_api__v1__feed__reels_media__connection` | `after` | `000006`, `000007` (primo HAR) |
|
||||
| Storie attive di un profilo | `PolarisStoriesV3ReelPageStandaloneQuery` | `reel_ids_arr` (elenco di identificativi di profilo) | `data.xdt_api__v1__feed__reels_media.reels_media[]` | — | `000014-storie-di-un-profilo` |
|
||||
| Chi ha storie attive | nessuna richiesta: blocco incorporato nella pagina iniziale | — | `xdt_api__v1__feed__reels_tray.tray[]` (`user`, `latest_reel_media`, `expiring_at`, `seen`) | — | `000015-vassoio-storie` |
|
||||
| Ricerca dei profili (#37) | `PolarisSearchBoxRefetchableQuery` | `data.query`, `data.context`, `data.search_surface`, `data.search_session_id`, `data.rank_token` (vuoto alla prima), `data.include_reel`, `hasQuery` | `data.xdt_api__v1__fbsearch__topsearch_connection.users[]` (`position`, `user` con `pk`, `username`, `full_name`, `profile_pic_url`, `hd_profile_pic_url_info.url`) | — | `000002-ricerca-profili` (primo HAR) |
|
||||
| Un post intero | `GET /api/v1/media/{numero}/info/` | nessun parametro | `items[]` | — | `000005-post-video` (primo HAR) |
|
||||
| Pagina iniziale | `PolarisFeedRootPaginationCachedQuery_subscribe`; la prima pagina è incorporata nel documento | `after`, `first` = 12, `data.device_id`, `variant` e altro | `xdt_api__v1__feed__timeline__connection` | `after` | non copiato |
|
||||
|
||||
Che cosa dicono i campioni (le prove sono in `InstagramReaderTests`):
|
||||
|
||||
- **I post del profilo bastano per il profilo**: la griglia comprende i reel (`product_type` `clips`) con
|
||||
`video_versions` e le serie (`media_type` 8) con i figli in `carousel_media`, anche video (`serie-con-video`: 20
|
||||
figli, il tredicesimo un video con la sua copertina). Le schede Reel e Con tag invece
|
||||
danno **anteprime** senza `taken_at` né `video_versions`: per un contenuto di quelle schede serve
|
||||
`/api/v1/media/{numero}/info/`.
|
||||
- **`media_count`** (numero dei post) c'è solo nella scheda del profilo; ora è `profile.postCount` del vocabolario.
|
||||
- **Copertina delle raccolte**: `cover_media.cropped_image_version.url` (jpg o webp); ora è `highlight.cover`.
|
||||
- **Le storie di un profilo si chiedono senza aprire il visualizzatore**: `PolarisStoriesV3ReelPageStandaloneQuery`
|
||||
risponde con le storie, la scadenza e la durata. Le versioni video delle storie non hanno dimensioni. Questo
|
||||
riguarda la domanda 11 di §16 (le storie con la strada B), che resta di Alberto.
|
||||
- **Chi ha storie** si legge dal vassoio incorporato nella pagina iniziale, senza richieste: 120 voci nel HAR.
|
||||
- **L'account collegato** (H10): nello stesso blocco della pagina iniziale `xdt_viewer.user` ha identificativo, nome
|
||||
utente e foto; nelle risposte alle richieste della pagina ha il solo identificativo. Il lettore lo legge già come
|
||||
`Viewer`.
|
||||
- **`ProfilePostsQuery` vuole il nome utente, le altre operazioni del profilo l'identificativo numerico**: Febe deve
|
||||
tenere tutti e due (la ricerca e la scheda del profilo li danno insieme).
|
||||
|
||||
## Richieste di scrittura che Febe non deve mai mandare
|
||||
|
||||
Nel HAR la pagina le ha mandate da sola, durante l'uso normale. Con la strada B Febe chiede solo operazioni di lettura
|
||||
dell'elenco chiuso, quindi queste non partono mai da Febe; ma vanno escluse per nome anche dalla configurazione
|
||||
(`richieste.instagram.json` deve rifiutare ogni nome che finisce per `Mutation`):
|
||||
|
||||
| Operazione | Quando la manda la pagina | Che cosa fa |
|
||||
|---|---|---|
|
||||
| `PolarisStoriesV3SeenMutation` | a ogni storia guardata nel visualizzatore (6 volte nel HAR) | segna la storia come vista: chi l'ha pubblicata vede Alberto fra gli spettatori |
|
||||
| `usePolarisRegisterInRecentSearchesMutation` | cliccando un risultato della ricerca | aggiunge il profilo alle ricerche recenti di Alberto |
|
||||
| `usePolarisLikeMediaXIGLikeMutation` | un «mi piace» dato durante la sessione | mette «mi piace» a un post |
|
||||
|
||||
Corollario: la raccolta di oggi, che guarda le storie **nel visualizzatore**, le segna come viste. Chiederle con
|
||||
`ReelPageStandaloneQuery` no, perché il segno «vista» è una richiesta a parte.
|
||||
|
||||
## Che cosa porta ogni richiesta, oltre alle variabili
|
||||
|
||||
Uguali per tutte le operazioni GraphQL del HAR, da prendere **dalla pagina al momento della richiesta** (mai salvati,
|
||||
mai nei registri, regola 10):
|
||||
|
||||
- campi del corpo: `doc_id` (17 cifre, uno per operazione; cambia quando Instagram pubblica una versione nuova
|
||||
dell'applicazione web), `fb_api_req_friendly_name` (il nome dell'operazione), `fb_api_caller_class` =
|
||||
`RelayModern`, `server_timestamps`, `variables`, e i campi di sessione `fb_dtsg`, `av`, `__user`, `__a`,
|
||||
`__comet_req`, `__req`, `__rev`, `__s`, `__hs`, `__hsi`, `__hsdp`, `__hblp`, `__sjsp`, `__csr`, `__dyn`,
|
||||
`__spin_r`, `__spin_b`, `__spin_t`, `__ccg`, `__crn`, `__d`, `dpr`, più un campo il cui nome `febe-sonda richieste`
|
||||
ha tolto perché nel HAR compare anche come valore;
|
||||
- intestazioni: `x-csrftoken`, `x-fb-lsd`, `x-ig-app-id`, `x-asbd-id`, `x-fb-friendly-name`, `x-fb-entry-nonce`,
|
||||
`x-ig-max-touch-points` e, su `/graphql/query`, `x-root-field-name` e `x-bloks-version-id`. Le altre
|
||||
(`user-agent`, `sec-ch-ua*`, `referer`, i cookie) le mette il browser da solo e restano come sono (regola 4).
|
||||
|
||||
Il punto aperto per #36 è **da dove prendere `doc_id` e i campi di sessione**. Inventarli è vietato (regola 9), e
|
||||
copiarli dal HAR non funziona perché cambiano. §6.1 vuole che i gettoni restino nella pagina e che allo script torni
|
||||
solo il corpo della risposta. Le vie da valutare:
|
||||
|
||||
1. **solo dentro la pagina**: lo script di `Runtime.evaluate` (la riga di §6.1 della strada B) prende `doc_id` e i
|
||||
campi di sessione dal codice della pagina e manda la richiesta; dipende dai nomi interni dell'applicazione web;
|
||||
2. **`doc_id` dalle richieste della pagina, il resto dentro la pagina**: `doc_id` e il nome dell'operazione sono
|
||||
uguali per tutti e non segreti, e si possono ricavare dall'ultima richiesta della stessa operazione che la pagina
|
||||
ha mandato da sé; i campi di sessione restano allo script nella pagina. Serve però che il client CDP legga i corpi
|
||||
delle richieste, cosa che oggi non fa (`ResponseTap` ascolta solo le risposte): `Network.requestWillBeSent` con
|
||||
`postData`, ed eventualmente `Network.getRequestPostData`, che non è nell'elenco di §6.1. Va deciso con Alberto;
|
||||
3. leggere dalle richieste della pagina anche i campi di sessione e le intestazioni (`fb_dtsg`, `x-csrftoken`,
|
||||
`x-fb-lsd`) è escluso: i gettoni uscirebbero dalla pagina, contro §6.1.
|
||||
|
||||
## Che cosa manca e serve un altro HAR
|
||||
|
||||
- **L'elenco dei seguiti**: nel HAR non c'è nessuna richiesta dell'elenco (né `friendships` né un'operazione
|
||||
GraphQL). Senza, il giro dei seguiti non si può scrivere.
|
||||
- **La seconda pagina dei post di un profilo** (`PolarisProfilePostsQuery` con `after`, o un'altra operazione): nel
|
||||
HAR c'è solo la prima.
|
||||
|
||||
La procedura per raccoglierli è in `docs/prove-dal-vivo.md`, parte A quater.
|
||||
@@ -1,10 +1,207 @@
|
||||
# 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 13 novembre 2026, versione 0.1.2 in `main` (il tag `v0.1.2` non è stato creato). **Le attività stanno
|
||||
su Gitea**: issue, etichette e traguardi di https://gitea.encke-hake.ts.net/Alby96/Febe. Questo file resta il resoconto
|
||||
fra le sessioni; ciò che è da fare si legge nelle issue aperte.
|
||||
|
||||
## In breve
|
||||
|
||||
**13 novembre 2026, sera: le prove che cadevano con il runner carico** (#46).
|
||||
|
||||
- Cause trovate, non solo tempi allungati. Tre erano difetti del prodotto:
|
||||
- `FebeDatabase.DisposeAsync` lasciava i file aperti: i comandi SQLite non chiusi tenevano viva la connessione
|
||||
fino al finalizzatore, e il WAL spariva durante lo spostamento della cartella Dati (`FoldersAutostart…`). Ora
|
||||
ogni comando si chiude (`Sql.Execute`/`Scalar`, `CommandScope` per le letture) e il pool di lettura si svuota prima
|
||||
dello scrittore; prova nuova `DatabaseCloseTests`, che cade senza la correzione.
|
||||
- La scheda dell'account, senza le statistiche di ANALYZE, leggeva i file di tutta la libreria: ora una passata sola
|
||||
sui file dell'account (`AccountStore.GetStatsAsync`).
|
||||
- All'arresto `FebeApp` non aspettava i lavori in sottofondo aggiunti da un avvio ancora in corso.
|
||||
- Avvio di Chromium: 120 s invece di 30 per un browser vivo ma lento, e la prima scheda si aspetta entro la stessa
|
||||
scadenza (prima 5 s); un Chromium che si chiude fa fallire subito come prima. Il ricollegamento dopo una connessione
|
||||
caduta smette appena il processo cambia.
|
||||
- Prove: i limiti di tempo sono protezioni contro un blocco, non misure (aiuto comune `TestWait`); la prova di scala
|
||||
ha limiti per classe di interrogazione, prende il tempo migliore e gira da sola dopo le prove parallele; il browser
|
||||
delle prove dell'interfaccia usa la porta 0 e mostra lo stderr di Chromium quando fallisce; la prova di «Scollega»
|
||||
di WebView2 chiede che il processo esca davvero, non 10 s. Cinque righe in `docs/decisioni.md`.
|
||||
- Verificato su Windows con tutti i core occupati: le classi corrette 10 volte su 10, la prova di scala 5 su 5, le
|
||||
prove di WebView2 3 su 3. **Non verificato qui**: le prove con Chromium e Xvfb girano solo nella CI Linux; il
|
||||
contenitore Linux con 2 CPU non è partito perché C: era pieno (0,2 GB liberi) e Docker Desktop si è fermato.
|
||||
- **Per Alberto**: liberare spazio su C: (il disco di Docker, `docker_data.vhdx`, è di circa 45 GB) e riavviare
|
||||
Docker Desktop; poi si possono togliere le immagini `febe-ui46:base`, `febe-ui46:locale` e `febe-ci46-locale`.
|
||||
|
||||
**13 novembre 2026, pomeriggio: il rapporto di diagnostica della raccolta** (#39).
|
||||
|
||||
- Attività ha un terzo pulsante, «Diagnostica», che scarica `febe-diagnostica-AAAA-MM-GG.json`
|
||||
(`GET /api/engine/diagnostica`, ammesso anche con un problema di configurazione, ma allora vuoto). Per ogni sessione
|
||||
degli ultimi 14 giorni, più un gruppo per giorno «fuori sessione»: pagine aperte (nome della pagina e forma
|
||||
dell'indirizzo, mai i nomi), navigazioni, risposte per tipo, forma, stato e dimensione con ciò che i lettori ne
|
||||
hanno fatto, struttura delle chiavi delle forme sconosciute (stretta: solo parole di un elenco chiuso, il resto `#`),
|
||||
obiettivi cliccati, giudizi, ricette con esito e segnale, segnali, permessi negati, file in coda e scaricati con la
|
||||
causa, e il motivo d'arresto (`SessionStopCause`, nuovo). Le intestazioni dicono se il rapporto può essere
|
||||
incompleto (righe rovinate, file illeggibili, errori del registratore, sessioni senza fine).
|
||||
- Il registratore (`Febe.Core.Collection.Diagnostics`) scrive in `Dati/diagnostica/sessioni-AAAA-MM-GG.jsonl`, una
|
||||
riga all'inizio della sessione, ogni 5 minuti e alla fine; non lancia mai eccezioni verso la raccolta. Le forme degli
|
||||
indirizzi (`PathPatterns`) e la regola delle chiavi-dato sono passate dalla sonda a Core, e la sonda le richiama.
|
||||
Specifica §7.9 e §13.2, guida (Attività e arresti), righe in `docs/decisioni.md`, `LEGGIMI.md`; schermate di
|
||||
Attività (06, 11, 14) rifatte e confrontate con i mockup 06 e 11 (`differenze.md`).
|
||||
- Prove nuove: unità del registratore, del registro e del rapporto, motivi d'arresto sul banco del motore, endpoint e
|
||||
dimostrazione per scena, e la prova chiesta da #39 che il rapporto non contiene valori (nomi con punto, nomi usati
|
||||
come chiavi, codici, cursori, indirizzi firmati, cookie), con controlli di mutazione. Tre giri di revisione
|
||||
avversaria: 17 + 6 + 2 difetti confermati, tutti corretti.
|
||||
- **Non verificato qui**: le prove con Chromium (fra cui `DiagnosticPrivacyIntegrationTests`, la ricetta vera sul sito
|
||||
di prova) girano solo nella CI Linux. Il rapporto non è ancora stato provato dal vivo: va guardato alla prova #40.
|
||||
|
||||
**13 novembre 2026, giorno: le foto del profilo hanno il loro schema** (#38).
|
||||
|
||||
- PR #45 è **unita in `main`** (305791f) con la verifica verde (esecuzione 272). Forzare l'unione non era possibile:
|
||||
la protezione di `main` vale anche per gli amministratori.
|
||||
- Le foto del profilo hanno un terzo schema dei nomi, predefinito `{account}\profilo\{data}_{ora}_{codice}_{n}`,
|
||||
accanto a quello generale e a quello delle raccolte: restano in `<account>\profilo` anche se Alberto cambia lo schema
|
||||
generale (sua decisione su #38). In Impostazioni ▸ Generali è il terzo campo, con la cartella `profilo` nel risultato
|
||||
e il campo rosso se è sbagliato; confrontata con il mockup 08 e rifatta `docs/schermate/08-impostazioni-generali.png`.
|
||||
Specifica §4.7, guida (Libreria) e una riga in `docs/decisioni.md`.
|
||||
- Prove nuove: nomi e regole del terzo schema, anteprima, impostazioni (un salvataggio senza il terzo schema lo tiene),
|
||||
salvataggio dei file con uno schema generale piatto, riconoscimento all'importazione, ricostruzione del database.
|
||||
- **Resta di #38**: che le foto arrivino davvero, con la raccolta riscritta (#36), anche per gli account aggiunti dalla
|
||||
ricerca (#37).
|
||||
|
||||
**13 novembre 2026, notte: il HAR dello scorrimento è troncato** (#35).
|
||||
|
||||
- Alberto ha esportato il giro corto della parte A quater (seguiti e seconda pagina dei post). Il file è arrivato
|
||||
troncato due volte: la prima a 200 000 byte esatti, la seconda a 57 MB, a metà del corpo di una risposta.
|
||||
- `febe-sonda` ora legge un HAR troncato: tiene le voci complete, scarta quella dentro cui il file finisce e lo dice;
|
||||
un file rotto altrove resta rifiutato. Per `richieste` i valori della voce scartata contano lo stesso, testo
|
||||
interrotto compreso, così nessun nome che è un dato passa per via del taglio (`HarFile`, 16 casi in
|
||||
`HarFileTests`, riga in `docs/decisioni.md`). Revisione avversaria (21 agenti): 6 rilievi confermati, tutti
|
||||
corretti. Il principale: la prima versione non contava i valori del testo interrotto, né applicava alla voce
|
||||
scartata le regole di base64 e delle pagine.
|
||||
- Del giro sono arrivate 141 voci, e la parte completa si ferma alla pagina iniziale. Dopo la ripulitura restano 6
|
||||
campioni: pagina successiva del feed, griglia di Esplora, promozioni e configurazione della pagina. «Verifica
|
||||
superata». Nessuno è fra i pezzi che servono: **seguiti e seconda pagina dei post mancano ancora.** In
|
||||
`docs/prove-dal-vivo.md` (A quater) ora c'è come esportare senza che il file si tronchi: svuotare il pannello Rete
|
||||
dopo il caricamento della pagina iniziale, niente video, esportare subito.
|
||||
- PR #45 (secondo HAR, lettori, sonda per i HAR troncati): Gitea, che quella notte rispondeva 500, ha perso
|
||||
l'evento del push di 78aa32b, e la verifica non è partita. Lanciata a mano (esecuzione 262) è verde in tutti e
|
||||
quattro i lavori, ma un'esecuzione a mano non scrive gli stati del commit, e la protezione di `main` non lascia
|
||||
unire neanche un amministratore. Per questo c'è un commit in più, che riporta questo caso anche in
|
||||
`docs/processo.md`: il suo push fa girare la verifica che serve. L'unione restava rifiutata (405) anche dopo,
|
||||
perché il ramo era indietro rispetto a `main`, che aveva il commit di unione di #44: `main` è stato unito nel
|
||||
ramo, senza cambiare il contenuto, e la verifica è girata di nuovo.
|
||||
- PR #44 è unita; anche la verifica di `main` del 12/11 (esecuzione 250) è caduta solo sul caricamento del rapporto
|
||||
di Trivy, per le risposte 500 di Gitea.
|
||||
|
||||
**12 novembre 2026, sera: il secondo HAR** (#35).
|
||||
|
||||
- Alberto ha mandato un HAR senza filtro, un giro veloce su Instagram. Sulla sua macchina, fuori dal repository:
|
||||
`febe-sonda richieste` (45 forme di richieste), `da-har` (142 campioni grezzi), `ripulisci` e `verifica` →
|
||||
«Verifica superata». Per arrivarci sono serviti tre correttivi alla sonda (numeri con esponente, falsi allarmi
|
||||
della verifica, parole degli indirizzi finti; `docs/decisioni.md`), con tre prove nuove.
|
||||
- **Esito** in `docs/sonda/richieste-instagram.md`: quale operazione dà che cosa (scheda e post del profilo, raccolte,
|
||||
storie di un profilo, ricerca, pagina iniziale), i campi che ogni richiesta porta e che vanno presi dalla pagina, e
|
||||
le tre scritture che la pagina manda da sola e Febe mai (storia vista, ricerca recente, «mi piace»). Riassunto per
|
||||
ipotesi in `docs/sonda/esito.md`.
|
||||
- **Otto campioni nuovi** (`000009`–`000016`), accorciati sulla copia ripulita; il lettore li legge già, con due
|
||||
aggiunte al vocabolario (`postCount` = `media_count`, `highlight.cover`) e sette prove nuove in
|
||||
`InstagramReaderTests`. Il blocco della pagina iniziale dà anche nome e foto dell'account collegato (H10).
|
||||
- **Manca ancora**: l'elenco dei seguiti e la seconda pagina dei post. Giro corto per Alberto in
|
||||
`docs/prove-dal-vivo.md`, parte **A quater**. Punto aperto per #36: da dove prendere `doc_id` e i campi di sessione,
|
||||
che per §6.1 restano nella pagina (tre vie in `docs/sonda/richieste-instagram.md`).
|
||||
- **Revisione avversaria** prima del commit (18 agenti): 8 rilievi confermati, tutti corretti. Fra questi due difetti
|
||||
della verifica (una chiave di dati grezza poteva passare sotto la regola della chiave che la contiene; un carattere
|
||||
come il segno Kelvin poteva fermarla invece di segnalare la fuga), una serie con un video che era già nel HAR e che
|
||||
i documenti davano per mancante, e la via «riusa l'ultima richiesta della pagina», che come era scritta faceva
|
||||
uscire i gettoni dalla pagina.
|
||||
- PR #44 (strada B nei documenti e `febe-sonda richieste`): **unita in `main`** (0153280) con la verifica verde al
|
||||
quinto tentativo. I primi tre sono caduti su prove di tempi del runner sovraccarico, ogni volta prove diverse e mai
|
||||
su codice cambiato:
|
||||
- riempimento della libreria in 291 s;
|
||||
- Chromium che non risponde sulla porta di debug;
|
||||
- spostamento della cartella con la shell nativa.
|
||||
|
||||
Il quarto si è interrotto per il riavvio del PC. Queste prove instabili meritano una issue a parte.
|
||||
|
||||
**12 novembre 2026: la prova dal vivo non è andata, la raccolta va ripensata.**
|
||||
|
||||
- Alberto: con i dati veri Febe non trova gli account e non scarica nulla (#33).
|
||||
- **Che cosa dicono i dati di Febe sul PC di Alberto** (`%LOCALAPPDATA%\Febe`): l'ultima esecuzione è del 26/10 con la
|
||||
0.1.1; nel database 0 elementi, 0 file, 0 seguiti, 33 sessioni da 0 azioni; «Elenco dei seguiti» e «Controllo del
|
||||
profilo» fermi su «Bersaglio non trovato» e «mappa-incompleta».
|
||||
- **Perché**: le ricette dipendono dalla mappa dei bersagli, che si può raccogliere solo su Instagram (parte «A bis»,
|
||||
mai fatta). Anche con la 0.1.2 l'elenco dei seguiti non ha indirizzo e storie, raccolte, Taggati e Reel non hanno
|
||||
bersagli. È un difetto di disegno, non un errore da correggere.
|
||||
- **Decisione di Alberto** (#34, chiusa): **strada B, la pagina chiede i dati.** Dalla pagina di Instagram già
|
||||
aperta Febe chiede al sito gli stessi dati che chiede la sua applicazione web, solo verso gli indirizzi di
|
||||
`richieste.instagram.json`, in sola lettura, una richiesta per volta col permesso del Governatore. Scritta in
|
||||
`docs/decisioni.md`, nella specifica (§2 regola 2 con la sua unica eccezione, §6.1 riga e regole delle richieste,
|
||||
§14.5) e nella regola 4 di `CLAUDE.md`. Foto dei profili: dentro ogni account (`<account>\profilo\…`, #38).
|
||||
- **Pronto per i campioni nuovi** (#35): `febe-sonda richieste --har <file> --a <file .json>` descrive la forma delle
|
||||
richieste della pagina (metodo, percorso con `{numero}`/`{testo}`, nomi di parametri, intestazioni e campi,
|
||||
struttura delle variabili GraphQL) senza alcun valore personale, con 27 prove nuove su un HAR sintetico. Una revisione avversaria (23 agenti) ha trovato 17 difetti confermati, tutti corretti prima del commit: tre fughe possibili (un nome utente usato come chiave, un corpo di testo spezzato in nomi, un identificativo piccolo copiato), interrogazioni GET unite fra loro, pagine successive perse nell'unione, un arresto su uno stato non numerico, e parti della specifica (§1, regola 5, §6.3, §7.4) ancora in contrasto con l'eccezione. Nuova domanda aperta 11 (§16): le storie con la strada B. Procedura
|
||||
per Alberto in `docs/prove-dal-vivo.md`, parte **A ter**. Finché il HAR nuovo non arriva, `richieste.instagram.json`
|
||||
e i lettori nuovi non si possono scrivere (regola 10): la raccolta riscritta (#36) e la ricerca unica (#37) hanno
|
||||
bisogno di quei campioni.
|
||||
- Richieste nuove: ricerca unica dei profili con le foto, aggiornata mentre si scrive (#37); foto dei profili in una
|
||||
cartella separata (#38). In più la diagnostica della raccolta (#39), i campioni nuovi (#35), la prova dal vivo (#40)
|
||||
e la chiusura della 0.2.0 (#41), tutte nel traguardo «0.2.0 — Raccolta che funziona su Instagram».
|
||||
- **Lavoro passato su Gitea**, come negli altri repository: etichette Area/Kind/Priority/Status, un traguardo chiuso
|
||||
per tappa (M0–M8) e per versione (0.1.1, 0.1.2), 23 attività chiuse con il loro resoconto «Fatto» (#13–#32, più #3,
|
||||
#5 e #8 assegnate alle versioni). I punti 6 e 8 di «Da fare» qui sotto sono ora #42 e #43.
|
||||
|
||||
**26 ottobre 2026.**
|
||||
|
||||
- La lettura di Instagram è in `main` (PR #11, commit di unione `fbc40fb`), con la verifica verde anche su `main`:
|
||||
controlli e gitleaks, 859 prove senza nessuna saltata, installatore, immagine.
|
||||
- **`REGISTRY_TOKEN` c'è** (segreto di Alberto, la CI lo vede): rilanciato il lavoro «immagine» della verifica di
|
||||
`main`, Febe è sul registro di Gitea per la prima volta, come `:main` e `:sha-fbc40fb`. `:latest` arriva con
|
||||
`v0.1.2`; fino ad allora su Unraid serve `:main`.
|
||||
- **Prima pulizia settimanale vera** (26/10 alle 5:17, esecuzione 56): tolte 3 immagini che nessun contenitore usava
|
||||
(`node:24-trixie`, `postgres:17`, `moby/buildkit`), 1,85 GB, più 218 MB di cache di costruzione; il registro non
|
||||
l'ha toccato perché il token non c'era ancora.
|
||||
- **Rilascio 0.1.2** (ramo `rilascio/0.1.2`): versione, CHANGELOG e stato. Dopo l'unione Alberto crea `v0.1.2` sul
|
||||
commit di unione; `rilascio.yml` pubblica `:0.1.2` e `:latest` e la release con installatore, zip, modello di Unraid
|
||||
e archivio per Compose.
|
||||
|
||||
**25 ottobre 2026: Febe legge le risposte vere di Instagram** (PR #11, in `main` dal 26/10).
|
||||
|
||||
- **Il guasto**: Instagram manda i dati di storie e raccolte (GraphQL) come `text/javascript`, e la cattura leggeva
|
||||
solo le risposte dichiarate JSON: le scartava tutte. In più `lettori.instagram.json` e `bersagli.instagram.json` erano
|
||||
scheletri e le ricette si rifiutavano di girare.
|
||||
- **I campioni**: Alberto ha mandato un HAR del suo browser (21/10, filtro Fetch/XHR) e una guida. La guida descrive
|
||||
richieste costruite a mano, vietate dalle regole 2–4, e un formato che nel HAR non compare: non si è usata. Del HAR si
|
||||
è letta solo la forma; le 8 risposte utili, accorciate dal lato grezzo, ripulite e verificate («Verifica superata»),
|
||||
sono in `tests/Febe.Tests/campioni/instagram` (vedi il suo `LEGGIMI.md`). I grezzi convertiti sono stati cancellati.
|
||||
- **Che cosa cambia**: la cattura legge le risposte `text/javascript` chieste dalla pagina e il JSON incorporato nel
|
||||
documento (questo da confermare: il HAR non aveva documenti); le risposte che non parlano di contenuti si ignorano;
|
||||
il vocabolario di Instagram è «confermato» e ogni sua chiave compare nei campioni; la mappa ha le pagine viste nel
|
||||
traffico vero, i bersagli no. Le ricette del profilo reggono dati che arrivano in risposte diverse; il visualizzatore
|
||||
delle raccolte conta i contenuti (l'indirizzo non cambia); le ricette che la configurazione non lascia girare sono
|
||||
«Da configurare», non guasti, e le sospensioni dovute ai file vecchi si azzerano da sole al primo avvio.
|
||||
- **Che cosa gira su Instagram**: giro dei seguiti, controllo del profilo, storico, post singolo. **Non ancora**:
|
||||
storie, raccolte, Taggati, Reel (mancano i bersagli, H11) ed elenco dei seguiti (manca l'indirizzo). Nulla è stato
|
||||
provato dal vivo.
|
||||
- **Strumenti per Alberto**: `febe-sonda da-har` (HAR → campioni grezzi, poi `ripulisci` e `verifica`) e
|
||||
`tools/bersagli/raccogli-bersagli.js` (bersagli in sola lettura dalla Console); procedura in
|
||||
`docs/prove-dal-vivo.md`, parte A bis.
|
||||
- **Cancellazione automatica delle immagini delle Actions**: era già attiva dal 21/10 (ogni lavoro «immagine» toglie la
|
||||
sua immagine e le penzolanti; ogni lunedì la pulizia completa, la prima vera lunedì 26/10 alle 4:17). Nulla da
|
||||
cambiare. L'immagine si pubblica sul registro solo con `REGISTRY_TOKEN` (c'è dal 26/10, vedi sopra).
|
||||
- Lavoro fatto da più agenti in parallelo, ciascuno su un ramo di lavoro, poi revisione avversaria: 21 rilievi, 17
|
||||
confermati e corretti (uno solo in parte, vedi sotto), e un solo commit. Prove: 783 superate su Windows (76 saltate:
|
||||
Chromium e Xvfb); nella CI 859 superate, nessuna saltata.
|
||||
|
||||
**21 ottobre 2026.**
|
||||
|
||||
- **0.1.1 rilasciata**: tag `v0.1.1`, release con installatore, zip portabile, modello Unraid e archivio per Compose.
|
||||
L'immagine Docker non è pubblicata, perché `REGISTRY_TOKEN` manca ancora.
|
||||
- **La pulizia della CI toglie tutto ciò che non serve più** (decisione di Alberto). Dopo ogni lavoro «immagine» se ne
|
||||
vanno le immagini senza nome e la cache di costruzione che nessuno usa da 24 ore: la prima volta 26,31 GB. Ogni
|
||||
lunedì se ne vanno le immagini che nessun contenitore usa, la cache vecchia, i resti di act_runner e le `:sha-` oltre
|
||||
le 10 più recenti. Mai contenitori, volumi o reti che non siano della CI. A mano c'è «Solo prova» (`docs/processo.md`,
|
||||
«Pulizia»).
|
||||
- Le tre prove d'interfaccia trovate instabili dalla CI con Chromium vero sono stabili (#3 e #5 il 20/10, #8 il 21/10).
|
||||
Le prove d'interfaccia non usano più pause a tempo fisso.
|
||||
|
||||
**20 ottobre 2026.** Febe per Windows non riusciva a collegarsi: il browser di Febe non diventava mai pronto (registro di
|
||||
Alberto del 14 e del 19/10). Era un errore di thread, corretto. Febe per Windows ha girato per la prima volta su un
|
||||
Windows vero: collegamento, account e sessioni contro il sito di prova, dall'interfaccia. Lo stesso giorno sono arrivati:
|
||||
@@ -16,8 +213,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 +251,34 @@ protezione di `main` sono in `docs/processo.md`.
|
||||
|
||||
## Da fare (di Alberto)
|
||||
|
||||
1. **Sonda di M0** con l'account di prova (domanda 2 di §16): `docs/prove-dal-vivo.md`, parte A. Poi mandare i
|
||||
campioni **ripuliti** e le righe di `interazioni.jsonl` dei comandi dell'interfaccia: con quelli si compilano
|
||||
`bersagli.instagram.json` e `lettori.instagram.json` e si portano le ipotesi H1–H11 a un esito.
|
||||
2. **Prima sessione dal vivo** dopo la sonda, con il profilo Prudente su un profilo pubblico (parte B).
|
||||
1. **Bersagli e campioni dal browser di tutti i giorni** (`docs/prove-dal-vivo.md`, parte A bis, una decina di
|
||||
minuti): HAR con il filtro «Tutti» e «Conserva log», lo script `tools/bersagli/raccogli-bersagli.js` nella Console,
|
||||
poi `febe-sonda da-har`, `ripulisci`, `verifica`. Mandare solo la cartella ripulita e il testo dei bersagli: con
|
||||
quelli si compilano i bersagli di storie, raccolte, Taggati e Reel e si confermano la home, il profilo e le storie
|
||||
di un account (H1–H4, H6, H11). In alternativa la sonda (parte A).
|
||||
2. **Prima sessione dal vivo** con il profilo Prudente su un profilo pubblico (parte B): già possibile per giro dei
|
||||
seguiti, controllo del profilo, storico e post singolo. Da guardare: i file in Libreria (H5, H7), «Tu» riconosciuto
|
||||
(H10), nessun «formato non riconosciuto» in Attività.
|
||||
3. **Windows**: C5.2–C5.5 (C5.1, l'accesso con l'account di prova, è riuscito il 20/10), S2 con la finestra ridotta a
|
||||
icona e con lo schermo bloccato, C2 (installatore della 0.1.1 su un Windows pulito). **Docker su Unraid**: S3–S6 nel contenitore
|
||||
icona e con lo schermo bloccato, C2 (installatore della 0.1.2 su un Windows pulito). **Docker su Unraid**: S3–S6 nel contenitore
|
||||
vero.
|
||||
4. Le domande aperte di §16 (sono state adottate le proposte della terza colonna, vedi `docs/decisioni.md`).
|
||||
5. Il segreto `REGISTRY_TOKEN` nel repository: senza, la CI e il rilascio costruiscono, provano e scansionano
|
||||
l'immagine, ma non la pubblicano (lo dicono con un avviso). Il 20/10 mancava ancora.
|
||||
5. **Tag `v0.1.2`** sul commit di unione di `rilascio/0.1.2` in `main`: `git tag -a v0.1.2 -m "Febe 0.1.2"` e
|
||||
`git push origin v0.1.2` (`docs/processo.md`, «Rilasci»). Poi su Unraid basta `:latest`. `REGISTRY_TOKEN` c'è dal
|
||||
26/10; il flusso del tag `v0.1.1` non serve più rilanciarlo: pubblicherebbe la 0.1.1, senza la lettura di Instagram.
|
||||
6. Sicurezza dell'istanza Gitea: la registrazione è aperta, senza CAPTCHA, con quattro account creati da programmi fra
|
||||
agosto e settembre. Il runner `fa94b0298b8d` è registrato per tutta l'istanza e i suoi lavori parlano con il Docker
|
||||
dell'host, quindi un utente registrato potrebbe farci girare un suo flusso. Si consiglia di chiudere la registrazione
|
||||
(`[service] DISABLE_REGISTRATION = true`) o di registrare il runner per il solo utente o repository.
|
||||
7. **Pulizia**: la prima vera è girata il 26/10 (esecuzione 56, store classico) e ha tolto solo immagini che nessun
|
||||
contenitore usava; da guardare, se serve, il suo registro. Dal lunedì 2/11 toglie anche le `:sha-` del registro oltre
|
||||
le 10 più recenti.
|
||||
8. Da decidere:
|
||||
- dopo ogni esecuzione la cache di costruzione si toglie solo se nessuno la usa da 24 ore (`--filter until=24h`).
|
||||
Senza filtro, a ogni push se ne andrebbe anche quella appena usata dagli altri progetti; per cambiare basta togliere
|
||||
il filtro in `pulizia-docker.sh penzolanti`;
|
||||
- gli script di shell di `.gitea/` e `installer/` hanno i commenti in italiano, contro «codice e commenti in
|
||||
inglese»: o un'eccezione in `docs/decisioni.md`, o una traduzione in un ramo a parte.
|
||||
|
||||
## Rilievi aperti (20 ottobre)
|
||||
|
||||
@@ -82,6 +293,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,8 @@ using System.Globalization;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
@@ -35,6 +37,8 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
private readonly FebeAppOptions _options;
|
||||
private readonly IFebePlatform _platform;
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
// The start adds to these lists from its background tasks while a stop may already be running (#46): one lock.
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<Task> _background = [];
|
||||
private readonly List<IDisposable> _disposables = [];
|
||||
private readonly List<Action> _unsubscribe = [];
|
||||
@@ -86,6 +90,12 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
|
||||
public PerceptualHashIndex? HashIndex { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The recorder of the diagnostic report (issue #39), with its log in <c>Dati/diagnostica</c> (null with a
|
||||
/// configuration problem). Flushed when Febe stops.
|
||||
/// </summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; private set; }
|
||||
|
||||
/// <summary>When Alberto last used the browser («Riprendi» after a verification).</summary>
|
||||
public BrowserUseTracker Tracker { get; } = new();
|
||||
|
||||
@@ -246,13 +256,21 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
userIsDriving: () => browser.UserIsDriving,
|
||||
isConnected: () => connection.IsConnected == true,
|
||||
ct: ct).ConfigureAwait(false);
|
||||
// The diagnostic report (issue #39): one recorder for the engine, the pipeline and the interface. What the
|
||||
// capture sees goes to the session in progress, if any.
|
||||
var diagnostics = new CollectionDiagnostics(Clock, () => services.Runtime.CurrentSession?.SessionId, new DiagnosticLog(data.Diagnostics, Clock));
|
||||
Diagnostics = diagnostics;
|
||||
services.Diagnostics = diagnostics;
|
||||
EventHandler<Permit> permitDenied = (_, permit) => diagnostics.PermitDenied(null, permit.Kind, permit.Reason);
|
||||
services.Governor.Denied += permitDenied;
|
||||
OnStop(() => services.Governor.Denied -= permitDenied);
|
||||
var runner = new DeferredRecipeRunner();
|
||||
var engine = new EngineHost(services, runner);
|
||||
Engine = engine;
|
||||
connection.AttachEngine(engine);
|
||||
EventHandler<bool> drivingChanged = (_, _) => engine.NotifyUserDrivingChanged();
|
||||
browser.UserDriving.Changed += drivingChanged;
|
||||
_unsubscribe.Add(() => browser.UserDriving.Changed -= drivingChanged);
|
||||
OnStop(() => browser.UserDriving.Changed -= drivingChanged);
|
||||
_telegram = new TelegramClient(hooks.TelegramHandler);
|
||||
var telegramChannel = new TelegramAlertChannel(_telegram);
|
||||
|
||||
@@ -268,6 +286,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
s.AddSingleton<IEngineSettingsControl>(new EngineHostSettingsControl(engine));
|
||||
s.AddSingleton(ingest);
|
||||
s.AddSingleton<IBrowserPreview>(new LiveBrowserPreview(browser, Clock));
|
||||
s.AddSingleton<IDiagnosticSource>(new RecordedDiagnosticSource(diagnostics));
|
||||
s.AddSingleton<IConfigurationProblems>(new StartupProblems([]));
|
||||
if (Import is not null)
|
||||
{
|
||||
@@ -303,10 +322,43 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
|
||||
// Housekeeping in the background: temporary files of an interrupted run, the daily copy of the database.
|
||||
var lifetime = _lifetime.Token;
|
||||
_background.Add(Task.Run(() => CleanTemporaryFilesAsync(staging, layout, lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => Alerts.WatchDiskSpaceAsync(lifetime), CancellationToken.None));
|
||||
InBackground(() => CleanTemporaryFilesAsync(staging, layout, lifetime));
|
||||
InBackground(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime));
|
||||
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, lifetime));
|
||||
InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime));
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="work"/> in the background; the stop waits for it.</summary>
|
||||
private void InBackground(Func<Task> work)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_background.Add(Task.Run(work, CancellationToken.None));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Keeps <paramref name="disposable"/> for the stop; disposes it at once when the stop already took its list.</summary>
|
||||
private void DisposeOnStop(IDisposable disposable)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) == 0)
|
||||
{
|
||||
_disposables.Add(disposable);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
disposable.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Keeps <paramref name="unsubscribe"/> for the stop.</summary>
|
||||
private void OnStop(Action unsubscribe)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_unsubscribe.Add(unsubscribe);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StartWebAsync(FebeAppHooks hooks, Action<IServiceCollection> register)
|
||||
@@ -369,12 +421,14 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
// Rule 7: the pages Alberto opens (login, verification) are his, not the engine's, while no session runs.
|
||||
UserOwnsPage = () => browser.UserIsDriving && services.Runtime.CurrentSession is null,
|
||||
Log = Log.ForBrowser(),
|
||||
Diagnostics = Diagnostics,
|
||||
},
|
||||
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));
|
||||
DisposeOnStop(changes.Attach(Pipeline.Downloads, Clock));
|
||||
InBackground(() => DownloadLoopAsync(Pipeline.Downloads, ct));
|
||||
|
||||
// Every finished recipe may have queued files: the queue looks at once instead of at its next idle poll.
|
||||
var downloads = Pipeline.Downloads;
|
||||
@@ -387,7 +441,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
|
||||
services.Events.Notified += WakeDownloads;
|
||||
_unsubscribe.Add(() => services.Events.Notified -= WakeDownloads);
|
||||
OnStop(() => services.Events.Notified -= WakeDownloads);
|
||||
|
||||
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
|
||||
if (o.TestSiteAutoLogin && Connection.IsConnected != true)
|
||||
@@ -395,7 +449,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
await TestSiteLoginAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_background.Add(Task.Run(() => Connection.RunAsync(ct), CancellationToken.None));
|
||||
InBackground(() => Connection.RunAsync(ct));
|
||||
await engine.StartAsync(ct).ConfigureAwait(false);
|
||||
Log.Info("motore", Connection.IsConnected == true
|
||||
? "Motore avviato: il browser è collegato."
|
||||
@@ -412,6 +466,39 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which reader vocabulary and target map the collection uses, in the log: where each came from (embedded in Febe or
|
||||
/// the copy in the Data folder) and in what state, never what is in them; a warning when a copy in the Data folder
|
||||
/// hides a better embedded file. Then the engine clears, once, the suspensions and failures of the recipes counted
|
||||
/// against other files (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>). Before the engine loop starts.
|
||||
/// </summary>
|
||||
private async Task CheckCollectionConfigurationAsync(CollectionPipeline pipeline, EngineHost engine, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var configuration = CollectionConfiguration.Describe(_options.Site.Name, pipeline.Vocabulary, pipeline.SiteMap);
|
||||
foreach (var line in configuration.Lines)
|
||||
{
|
||||
Log.Info("raccolta", line);
|
||||
}
|
||||
|
||||
foreach (var warning in configuration.Warnings)
|
||||
{
|
||||
Log.Warn("raccolta", warning);
|
||||
}
|
||||
|
||||
if (await engine.ApplyCollectionConfigurationAsync(configuration.Fingerprint, ct).ConfigureAwait(false))
|
||||
{
|
||||
Log.Info("raccolta", $"Configurazione della raccolta diversa dall'ultimo avvio (impronta {configuration.Fingerprint[..12]}): sospensioni ed errori contati delle ricette azzerati.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Never a reason not to collect: the suspensions stay as they are, «Riattiva» still clears them.
|
||||
Log.Warn("raccolta", "Non riesco a confrontare la configurazione della raccolta con quella dell'ultimo avvio: le ricette sospese restano come sono.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Development with the test site only (<c>--accesso-di-prova</c>): what Alberto does by hand on Instagram — open
|
||||
/// the site once, so that its session cookie exists — then back to the rest page.
|
||||
@@ -582,17 +669,46 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
foreach (var task in _background.ToArray())
|
||||
|
||||
// A start still in progress adds tasks while the first ones are awaited: look again until nothing new appears,
|
||||
// so nothing still reads the database once it is closed (#46).
|
||||
var awaited = 0;
|
||||
while (true)
|
||||
{
|
||||
await Quietly(() => task).ConfigureAwait(false);
|
||||
Task[] pending;
|
||||
lock (_gate)
|
||||
{
|
||||
pending = _background.Skip(awaited).ToArray();
|
||||
}
|
||||
|
||||
if (pending.Length == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
foreach (var task in pending)
|
||||
{
|
||||
await Quietly(() => task).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
awaited += pending.Length;
|
||||
}
|
||||
|
||||
foreach (var disposable in _disposables)
|
||||
IDisposable[] disposables;
|
||||
Action[] unsubscribes;
|
||||
lock (_gate)
|
||||
{
|
||||
disposables = [.. _disposables];
|
||||
unsubscribes = [.. _unsubscribe];
|
||||
_disposables.Clear();
|
||||
}
|
||||
|
||||
foreach (var disposable in disposables)
|
||||
{
|
||||
disposable.Dispose();
|
||||
}
|
||||
|
||||
foreach (var unsubscribe in _unsubscribe)
|
||||
foreach (var unsubscribe in unsubscribes)
|
||||
{
|
||||
unsubscribe();
|
||||
}
|
||||
@@ -611,6 +727,9 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
await Quietly(() => pipeline.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// What is still open of the diagnostic report: sessions as in progress, the day outside sessions as it is.
|
||||
Diagnostics?.Dispose();
|
||||
|
||||
if (Connection is { } connection)
|
||||
{
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
|
||||
@@ -19,8 +19,17 @@ public sealed record ResponseTapOptions
|
||||
/// <summary>How long to wait for one body before giving up on it (one stuck request must not block the others).</summary>
|
||||
public TimeSpan BodyTimeout { get; init; } = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>Decides from the declared MIME type whether a body is worth parsing as JSON.</summary>
|
||||
public Func<string, bool> IsJsonMimeType { get; init; } = static mime => mime.Contains("json", StringComparison.OrdinalIgnoreCase);
|
||||
/// <summary>
|
||||
/// Decides from the declared MIME type and the resource type whether a body is worth parsing as JSON
|
||||
/// (<see cref="DataResponses.IsData"/>: JSON, and JavaScript the page fetched itself).
|
||||
/// </summary>
|
||||
public Func<string, string?, bool> IsDataResponse { get; init; } = DataResponses.IsData;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the main document of a site page is read too, for the JSON blocks it embeds
|
||||
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>).
|
||||
/// </summary>
|
||||
public bool ReadPageDocuments { get; init; } = true;
|
||||
|
||||
/// <summary>Per-resource buffer of the browser (<c>Network.enable</c> maxResourceBufferSize).</summary>
|
||||
public int BrowserResourceBufferBytes { get; init; } = 32 * 1024 * 1024;
|
||||
@@ -37,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, BodyDropReason.Reconnected);
|
||||
}
|
||||
}
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
@@ -240,35 +260,47 @@ 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))
|
||||
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var length = p.TryGetProperty("encodedDataLength", out var len) && len.TryGetDouble(out var d) ? d : 0;
|
||||
if (length > _options.MaxBodyBytes)
|
||||
NotifyLoadingFinished(requestId, length);
|
||||
if (!_inFlight.TryRemove(requestId, out var pending))
|
||||
{
|
||||
Interlocked.Increment(ref _skipped);
|
||||
return;
|
||||
}
|
||||
|
||||
_queue.Writer.TryWrite(descriptor);
|
||||
if (length > _options.MaxBodyBytes)
|
||||
{
|
||||
Interlocked.Increment(ref _skipped);
|
||||
NotifyDropped(requestId, BodyDropReason.TooLarge);
|
||||
return;
|
||||
}
|
||||
|
||||
_queue.Writer.TryWrite(pending);
|
||||
}
|
||||
|
||||
private void OnLoadingFailed(JsonElement p)
|
||||
{
|
||||
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId)
|
||||
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId
|
||||
&& _inFlight.TryRemove(requestId, out _))
|
||||
{
|
||||
_inFlight.TryRemove(requestId, out _);
|
||||
NotifyDropped(requestId, BodyDropReason.LoadingFailed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,8 +316,16 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
_mainFrameId = frame.TryGetProperty("id", out var id) ? id.GetString() : _mainFrameId;
|
||||
|
||||
// Requests of the previous document that never finished (e.g. a body the page did not read: Chromium then
|
||||
// sends no loadingFinished) will not finish any more: forget them.
|
||||
_inFlight.Clear();
|
||||
// sends no loadingFinished) will not finish any more: forget them. The new document itself is kept: the frame
|
||||
// commits it before its body has finished loading (its request id is the frame's loader id).
|
||||
var loader = frame.TryGetProperty("loaderId", out var l) ? l.GetString() : null;
|
||||
foreach (var key in _inFlight.Keys)
|
||||
{
|
||||
if (key != loader && _inFlight.TryRemove(key, out _))
|
||||
{
|
||||
NotifyDropped(key, BodyDropReason.FrameNavigated);
|
||||
}
|
||||
}
|
||||
Publish(frame.TryGetProperty("url", out var u) ? u.GetString() : null, sameDocument: false);
|
||||
}
|
||||
|
||||
@@ -325,64 +365,134 @@ 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, BodyDropReason.Unexpected);
|
||||
}
|
||||
}
|
||||
}
|
||||
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, BodyDropReason.NoConsumers);
|
||||
return;
|
||||
}
|
||||
|
||||
byte[]? bytes;
|
||||
try
|
||||
{
|
||||
bytes = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpCommandException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
|
||||
{
|
||||
// The body may already be evicted from the browser's buffer, or the page navigated away.
|
||||
Interlocked.Increment(ref _bodyErrors);
|
||||
_log.Debug($"Cattura: corpo non disponibile ({ex.GetType().Name}).");
|
||||
NotifyDropped(descriptor.RequestId, ex is TimeoutException ? BodyDropReason.Timeout : BodyDropReason.Unavailable);
|
||||
return;
|
||||
}
|
||||
|
||||
if (bytes is null)
|
||||
{
|
||||
NotifyDropped(descriptor.RequestId, BodyDropReason.Unavailable);
|
||||
return;
|
||||
}
|
||||
|
||||
var delivered = pending.IsPageDocument
|
||||
? await ConsumeDocumentAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false)
|
||||
: await ConsumeBodyAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false);
|
||||
if (delivered == 0)
|
||||
{
|
||||
NotifyDropped(descriptor.RequestId, pending.IsPageDocument ? BodyDropReason.NoJsonBlock : BodyDropReason.NotJson);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 +512,56 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
}
|
||||
|
||||
var encoded = result.TryGetProperty("base64Encoded", out var b) && b.ValueKind == JsonValueKind.True;
|
||||
byte[] bytes;
|
||||
if (encoded)
|
||||
if (!encoded)
|
||||
{
|
||||
if (!body.TryGetBytesFromBase64(out var decoded))
|
||||
{
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
return null;
|
||||
}
|
||||
|
||||
bytes = decoded;
|
||||
}
|
||||
else
|
||||
{
|
||||
bytes = Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
|
||||
return Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
|
||||
}
|
||||
|
||||
try
|
||||
if (!body.TryGetBytesFromBase64(out var decoded))
|
||||
{
|
||||
return JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 256 });
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Declared as JSON but it is not (or has a prefix): readers will be told by the probe in M0.
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
return null;
|
||||
}
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
/// <summary>Tells the observers that a body they may be waiting for will not come, and why.</summary>
|
||||
private void NotifyDropped(string requestId, BodyDropReason reason)
|
||||
{
|
||||
foreach (var observer in SnapshotObservers())
|
||||
{
|
||||
try
|
||||
{
|
||||
observer.OnBodyDropped(requestId, reason);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Cattura: errore in un osservatore delle risposte.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tells the observers how many bytes a response took on the network (every response, read or not).</summary>
|
||||
private void NotifyLoadingFinished(string requestId, double encodedBytes)
|
||||
{
|
||||
var bytes = encodedBytes is > 0 and < long.MaxValue ? (long)encodedBytes : 0;
|
||||
foreach (var observer in SnapshotObservers())
|
||||
{
|
||||
try
|
||||
{
|
||||
observer.OnLoadingFinished(requestId, bytes);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Cattura: errore in un osservatore delle risposte.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A body to fetch once its loading has finished.</summary>
|
||||
private sealed record PendingBody(ResponseDescriptor Descriptor, bool IsPageDocument);
|
||||
|
||||
private IResponseObserver[] SnapshotObservers()
|
||||
{
|
||||
lock (_gate)
|
||||
|
||||
@@ -29,7 +29,12 @@ public sealed record ChromiumLaunchOptions
|
||||
/// <summary>Start page: always the rest page.</summary>
|
||||
public string StartUrl { get; init; } = "about:blank";
|
||||
|
||||
public TimeSpan StartupTimeout { get; init; } = TimeSpan.FromSeconds(30);
|
||||
/// <summary>
|
||||
/// How long a Chromium that is alive may take to open its debugging port and its first tab. A crash fails the start
|
||||
/// at once; this only bounds a browser that hangs, so it is generous for a loaded machine (docs/decisioni.md, #46).
|
||||
/// </summary>
|
||||
public TimeSpan StartupTimeout { get; init; } = TimeSpan.FromSeconds(120);
|
||||
|
||||
|
||||
public RestartPolicy Restart { get; init; } = RestartPolicy.Default;
|
||||
|
||||
|
||||
@@ -255,27 +255,37 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
$"La porta di debug {port} non è limitata a 127.0.0.1 ({listeners.Count} punti di ascolto): avvio annullato (specifica §6.1).");
|
||||
}
|
||||
|
||||
await ConnectAsync(port, ct).ConfigureAwait(false);
|
||||
await ConnectAsync(
|
||||
port,
|
||||
deadline,
|
||||
() => process.HasExited ? $"Chromium si è chiuso all'avvio (codice {process.ExitCode}). {_supervisor?.StderrTail()}".TrimEnd() : null,
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ConnectAsync(int port, CancellationToken ct)
|
||||
/// <summary>
|
||||
/// Connects to the first page target. The first tab may appear a while after the port opens on a loaded machine:
|
||||
/// the wait shares the start deadline, and ends at once when <paramref name="gone"/> says the process is no longer the
|
||||
/// one to connect to (it exited, or the supervisor replaced it): nobody waits on the connect lock for a dead browser.
|
||||
/// </summary>
|
||||
private async Task ConnectAsync(int port, DateTimeOffset deadline, Func<string?> gone, CancellationToken ct)
|
||||
{
|
||||
await _connectLock.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
CdpTarget? page = null;
|
||||
for (var attempt = 0; attempt < 50 && page is null; attempt++)
|
||||
CdpTarget? page;
|
||||
while ((page = await TryFindPageAsync(port, ct).ConfigureAwait(false)) is null)
|
||||
{
|
||||
page = await CdpTargetDiscovery.FindPageAsync(port, ct).ConfigureAwait(false);
|
||||
if (page is null)
|
||||
if (gone() is { } reason)
|
||||
{
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
|
||||
throw new InvalidOperationException(reason);
|
||||
}
|
||||
}
|
||||
|
||||
if (page is null)
|
||||
{
|
||||
throw new InvalidOperationException("Chromium non ha nessuna scheda aperta.");
|
||||
if (_clock.Now >= deadline)
|
||||
{
|
||||
throw new InvalidOperationException("Chromium non ha nessuna scheda aperta.");
|
||||
}
|
||||
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var client = await CdpClient.ConnectAsync(page.WebSocketDebuggerUrl, _log, null, ct).ConfigureAwait(false);
|
||||
@@ -304,6 +314,23 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The page target, or null when there is none yet or the endpoint did not answer this time.</summary>
|
||||
private static async Task<CdpTarget?> TryFindPageAsync(int port, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await CdpTargetDiscovery.FindPageAsync(port, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
catch (TaskCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
return null; // a slow answer of /json/list, not a missing one
|
||||
}
|
||||
}
|
||||
|
||||
private void OnClientDisconnected(object? sender, Exception? reason)
|
||||
{
|
||||
if (Volatile.Read(ref _stopping) == 1 || Volatile.Read(ref _restarting) == 1 || !ReferenceEquals(sender, Volatile.Read(ref _client)))
|
||||
@@ -330,11 +357,19 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
return;
|
||||
}
|
||||
|
||||
for (var attempt = 0; attempt < 3; attempt++)
|
||||
// The process that dropped the connection: if it exits or the supervisor restarts it, stop at once and leave
|
||||
// the connect lock to the restart, which connects by itself.
|
||||
var processId = supervisor.ProcessId;
|
||||
string? Gone() => supervisor.State != SupervisedState.Running || supervisor.ProcessId != processId
|
||||
? "Chromium è stato riavviato o si è chiuso durante il ricollegamento."
|
||||
: null;
|
||||
|
||||
var deadline = _clock.Now + _launch.StartupTimeout;
|
||||
for (var attempt = 0; attempt < 3 && Gone() is null; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ConnectAsync(_options.DebugPort, ct).ConfigureAwait(false);
|
||||
await ConnectAsync(_options.DebugPort, deadline, Gone, ct).ConfigureAwait(false);
|
||||
_log.Info("Collegamento con Chromium ripristinato.");
|
||||
return;
|
||||
}
|
||||
@@ -344,6 +379,11 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
}
|
||||
}
|
||||
|
||||
if (Gone() is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_log.Warn("Collegamento con Chromium perso: riavvio del browser.");
|
||||
supervisor.KillCurrent();
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ using Febe.Browser.Hosting;
|
||||
using Febe.Browser.Targets;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
@@ -23,8 +24,8 @@ namespace Febe.Browser.Recipes;
|
||||
public sealed record CollectionSite(string Name, string BaseUrl, HostClassifier Hosts, SessionCookieOptions SessionCookie)
|
||||
{
|
||||
/// <summary>
|
||||
/// Instagram. Its target map and reader vocabulary are still skeletons until M0: every recipe refuses to run and
|
||||
/// says why, without touching the site.
|
||||
/// Instagram. Its reader vocabulary is confirmed on real cleaned samples and its map has the pages seen in real
|
||||
/// traffic, not yet the targets: a recipe that needs a target refuses to run and says why, without touching the site.
|
||||
/// </summary>
|
||||
public static CollectionSite Instagram { get; } = new("instagram", "https://www.instagram.com", HostClassifier.Instagram, SessionCookieOptions.Instagram);
|
||||
|
||||
@@ -84,6 +85,12 @@ public sealed record CollectionPipelineOptions
|
||||
public Func<bool>? UserOwnsPage { get; init; }
|
||||
|
||||
public IBrowserLog? Log { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The recorder of the diagnostic report (issue #39): it observes the responses of the page, the readers, the
|
||||
/// recipes, the stop signals and the download queue. Null: nothing is recorded.
|
||||
/// </summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -138,7 +145,8 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
|
||||
var tap = new ResponseTap(options.Cdp, site.Hosts, options.Clock, options.Log);
|
||||
var signals = new SignalDetector(rules, options.Breaker, options.Clock) { UserOwnsPage = options.UserOwnsPage };
|
||||
var capture = new CaptureCollector(new ShapeReader(vocabulary), options.Clock);
|
||||
var diagnostics = options.Diagnostics;
|
||||
var capture = new CaptureCollector(new ShapeReader(vocabulary), options.Clock) { Diagnostics = diagnostics };
|
||||
var driver = new BrowserPageDriver(options.Cdp, targets, site.Hosts, options.Clock, options.Random, new BrowserDriverOptions
|
||||
{
|
||||
SiteBaseUrl = site.BaseUrl,
|
||||
@@ -160,6 +168,7 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
DataBudget = options.DataBudget,
|
||||
Breaker = options.Breaker,
|
||||
Options = options.Recipes,
|
||||
Diagnostics = diagnostics,
|
||||
});
|
||||
var downloads = new DownloadQueue(
|
||||
options.Storage,
|
||||
@@ -176,6 +185,18 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
pipeline._subscriptions.Add(tap.AddConsumer(signals));
|
||||
pipeline._subscriptions.Add(tap.AddObserver(capture));
|
||||
pipeline._subscriptions.Add(tap.AddConsumer(capture));
|
||||
if (diagnostics is not null)
|
||||
{
|
||||
diagnostics.SiteMap = siteMap;
|
||||
pipeline._subscriptions.Add(tap.AddObserver(diagnostics));
|
||||
EventHandler<Signal> signalRaised = (_, signal) => diagnostics.SignalRaised(signal);
|
||||
signals.SignalRaised += signalRaised;
|
||||
pipeline._subscriptions.Add(new Unsubscribe(() => signals.SignalRaised -= signalRaised));
|
||||
EventHandler<DownloadProgress> progress = (_, step) => diagnostics.DownloadSettled(step);
|
||||
downloads.Progress += progress;
|
||||
pipeline._subscriptions.Add(new Unsubscribe(() => downloads.Progress -= progress));
|
||||
}
|
||||
|
||||
await tap.StartAsync(ct).ConfigureAwait(false);
|
||||
return pipeline;
|
||||
}
|
||||
@@ -189,4 +210,9 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
|
||||
await Tap.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private sealed class Unsubscribe(Action action) : IDisposable
|
||||
{
|
||||
public void Dispose() => action();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>One configuration file of the collection as it was loaded.</summary>
|
||||
/// <param name="Name">File name: <c>lettori.instagram.json</c>, <c>bersagli.instagram.json</c>.</param>
|
||||
/// <param name="OverridePath">The editable copy in the Data folder that was loaded; null for the copy embedded in Febe.</param>
|
||||
/// <param name="Text">Its content (for the fingerprint only: never logged).</param>
|
||||
public sealed record CollectionConfigurationFile(string Name, string? OverridePath, string Text)
|
||||
{
|
||||
public bool IsOverride => OverridePath is not null;
|
||||
|
||||
/// <summary>Where it came from, in Italian, for the log: never what is in it.</summary>
|
||||
public string Origin => OverridePath is { } path
|
||||
? $"la copia nella cartella dei dati ({path})"
|
||||
: $"il file incorporato in Febe ({Name})";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The reader vocabulary and target map one site runs on, as the collection pipeline loaded them: where each came from
|
||||
/// (the copy embedded in Febe, or an editable copy in the Data folder, which always wins), its state, the recipes they
|
||||
/// leave unable to run, and a fingerprint of their content. The engine clears the suspensions of the recipes when the
|
||||
/// fingerprint changes (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>). Nothing here comes from the site.
|
||||
/// </summary>
|
||||
public sealed class CollectionConfiguration
|
||||
{
|
||||
private CollectionConfiguration(
|
||||
string site,
|
||||
ReaderVocabulary vocabulary,
|
||||
SiteMap map,
|
||||
CollectionConfigurationFile vocabularyFile,
|
||||
CollectionConfigurationFile mapFile,
|
||||
ReaderVocabulary? embeddedVocabulary,
|
||||
SiteMap? embeddedMap)
|
||||
{
|
||||
Site = site;
|
||||
Vocabulary = vocabulary;
|
||||
Map = map;
|
||||
VocabularyFile = vocabularyFile;
|
||||
MapFile = mapFile;
|
||||
EmbeddedVocabulary = embeddedVocabulary;
|
||||
EmbeddedMap = embeddedMap;
|
||||
Blocked = BlockedBy(map, vocabulary);
|
||||
Fingerprint = FingerprintOf(site, vocabularyFile, mapFile);
|
||||
}
|
||||
|
||||
/// <summary>The site name of the files (<c>instagram</c>, <c>prova</c>).</summary>
|
||||
public string Site { get; }
|
||||
|
||||
public ReaderVocabulary Vocabulary { get; }
|
||||
|
||||
public SiteMap Map { get; }
|
||||
|
||||
public CollectionConfigurationFile VocabularyFile { get; }
|
||||
|
||||
public CollectionConfigurationFile MapFile { get; }
|
||||
|
||||
/// <summary>The vocabulary embedded in Febe, when there is one (the same as <see cref="Vocabulary"/> without a copy).</summary>
|
||||
public ReaderVocabulary? EmbeddedVocabulary { get; }
|
||||
|
||||
/// <summary>The map embedded in Febe, when there is one (the same as <see cref="Map"/> without a copy).</summary>
|
||||
public SiteMap? EmbeddedMap { get; }
|
||||
|
||||
/// <summary>Recipes these files do not let run (<see cref="RecipeStatus.NotConfigured"/>), in the order of <see cref="RecipeKind"/>.</summary>
|
||||
public IReadOnlyList<RecipeKind> Blocked { get; }
|
||||
|
||||
/// <summary>SHA-256 of the two files as loaded (lower-case hexadecimal), line endings aside.</summary>
|
||||
public string Fingerprint { get; }
|
||||
|
||||
/// <summary>What the log says at start-up: where each file came from and in what state, and what cannot run.</summary>
|
||||
public IReadOnlyList<string> Lines
|
||||
{
|
||||
get
|
||||
{
|
||||
var all = Enum.GetValues<RecipeKind>().Length;
|
||||
var vocabularyState = Vocabulary.Status == VocabularyStatus.Confirmed ? "confermato" : "ipotesi";
|
||||
if (Vocabulary.MissingConcepts.Count > 0)
|
||||
{
|
||||
vocabularyState += $", {Vocabulary.MissingConcepts.Count.ToString(CultureInfo.InvariantCulture)} concetti ancora senza chiavi";
|
||||
}
|
||||
|
||||
var missing = Map.Missing(SitePages.All, SiteTargets.All).Count;
|
||||
var mapState = missing == 0 ? "tutte le voci compilate" : $"{missing.ToString(CultureInfo.InvariantCulture)} voci vuote o assenti";
|
||||
return
|
||||
[
|
||||
$"Vocabolario dei lettori per «{Site}»: {VocabularyFile.Origin}, {vocabularyState}.",
|
||||
$"Mappa dei bersagli per «{Site}»: {MapFile.Origin}, {mapState}.",
|
||||
Blocked.Count == 0
|
||||
? "Con questa configurazione tutte le ricette possono girare."
|
||||
: $"Con questa configurazione non possono girare {Blocked.Count.ToString(CultureInfo.InvariantCulture)} ricette su {all.ToString(CultureInfo.InvariantCulture)}: {Names(Blocked)}.",
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A copy in the Data folder that hides a better embedded file: a vocabulary still «ipotesi» while the embedded one
|
||||
/// is «confermato», or a map that leaves recipes unable to run that the embedded one lets run. A stale copy would
|
||||
/// otherwise keep the new files of an update from ever being used.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Warnings
|
||||
{
|
||||
get
|
||||
{
|
||||
var warnings = new List<string>();
|
||||
if (VocabularyFile.IsOverride && EmbeddedVocabulary is { } embedded
|
||||
&& Vocabulary.Status == VocabularyStatus.Hypothesis && embedded.Status == VocabularyStatus.Confirmed)
|
||||
{
|
||||
warnings.Add($"Il vocabolario dei lettori in {VocabularyFile.OverridePath} è ancora un'ipotesi, mentre quello incorporato in Febe è confermato: la copia nella cartella dei dati nasconde quello nuovo. Toglila (o aggiornala) e riavvia Febe.");
|
||||
}
|
||||
|
||||
if (MapFile.IsOverride && EmbeddedMap is { } embeddedMap)
|
||||
{
|
||||
var hidden = MissingFrom(Map).Except(MissingFrom(embeddedMap)).ToList();
|
||||
if (hidden.Count > 0)
|
||||
{
|
||||
warnings.Add($"La mappa dei bersagli in {MapFile.OverridePath} lascia ferme ricette che con quella incorporata in Febe potrebbero girare ({Names(hidden)}): la copia nella cartella dei dati nasconde quella nuova. Toglila (o aggiornala) e riavvia Febe.");
|
||||
}
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes what was loaded for <paramref name="site"/>: <paramref name="vocabulary"/> and <paramref name="map"/>
|
||||
/// as the pipeline loaded them (their <c>Source</c> tells a Data-folder copy from the embedded file). The text of a
|
||||
/// copy is read again from its path for the fingerprint.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">A copy in the Data folder cannot be read any more.</exception>
|
||||
public static CollectionConfiguration Describe(string site, ReaderVocabulary vocabulary, SiteMap map)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(site);
|
||||
ArgumentNullException.ThrowIfNull(vocabulary);
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
var vocabularyFile = LoadedFile($"lettori.{site}.json", vocabulary.Source);
|
||||
var mapFile = LoadedFile($"bersagli.{site}.json", map.Source);
|
||||
var embeddedVocabulary = vocabularyFile.IsOverride ? Try(() => ReaderVocabulary.LoadEmbedded(vocabularyFile.Name)) : vocabulary;
|
||||
var embeddedMap = mapFile.IsOverride ? Try(() => SiteMap.LoadEmbedded(mapFile.Name)) : map;
|
||||
return new CollectionConfiguration(site, vocabulary, map, vocabularyFile, mapFile, embeddedVocabulary, embeddedMap);
|
||||
}
|
||||
|
||||
/// <summary>The recipes a map and a vocabulary do not let run, by the same rule as the runner's.</summary>
|
||||
public static IReadOnlyList<RecipeKind> BlockedBy(SiteMap map, ReaderVocabulary vocabulary)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
ArgumentNullException.ThrowIfNull(vocabulary);
|
||||
return vocabulary.IsUsable ? MissingFrom(map) : Enum.GetValues<RecipeKind>();
|
||||
}
|
||||
|
||||
/// <summary>The recipes whose pages or targets the map lacks, whatever the vocabulary.</summary>
|
||||
private static RecipeKind[] MissingFrom(SiteMap map) =>
|
||||
[.. Enum.GetValues<RecipeKind>().Where(kind =>
|
||||
{
|
||||
var (pages, targets) = RecipeRunner.Requirements(kind);
|
||||
return map.Missing(pages, targets).Count > 0;
|
||||
})];
|
||||
|
||||
private static CollectionConfigurationFile LoadedFile(string name, string? source)
|
||||
{
|
||||
if (source is { Length: > 0 } path && !string.Equals(path, name, StringComparison.Ordinal))
|
||||
{
|
||||
return new CollectionConfigurationFile(name, path, File.ReadAllText(path));
|
||||
}
|
||||
|
||||
return new CollectionConfigurationFile(name, null, SiteMap.ReadEmbeddedText(name));
|
||||
}
|
||||
|
||||
private static T? Try<T>(Func<T> load)
|
||||
where T : class
|
||||
{
|
||||
try
|
||||
{
|
||||
return load();
|
||||
}
|
||||
catch (Exception ex) when (ex is FileNotFoundException or InvalidDataException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string FingerprintOf(string site, CollectionConfigurationFile vocabulary, CollectionConfigurationFile map)
|
||||
{
|
||||
static string Normalized(string text) => text.Replace("\r\n", "\n", StringComparison.Ordinal);
|
||||
var text = string.Join('\n', site, vocabulary.Name, Normalized(vocabulary.Text), map.Name, Normalized(map.Text));
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
|
||||
}
|
||||
|
||||
private static string Names(IEnumerable<RecipeKind> kinds) => string.Join(", ", kinds.Select(RecipeRunner.Name));
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// Which responses of the page carry data worth reading (spec §6.2), decided from what the browser declares about
|
||||
/// them, never from the address.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Instagram serves its GraphQL data (<c>/graphql/query</c>, <c>/api/graphql</c>) as <c>text/javascript</c>, and only
|
||||
/// the REST answers (<c>/api/v1/...</c>) as <c>application/json</c> (HAR of Alberto's browser, 21 October 2026). A
|
||||
/// JavaScript type counts only when the page itself fetched it (XHR, Fetch): script files are never parsed.
|
||||
/// </remarks>
|
||||
public static partial class DataResponses
|
||||
{
|
||||
/// <summary>Largest page document whose embedded data is read.</summary>
|
||||
public const int MaxDocumentChars = 16 * 1024 * 1024;
|
||||
|
||||
private static readonly JsonDocumentOptions BlockOptions = new() { MaxDepth = 256 };
|
||||
|
||||
/// <summary>True for a body worth parsing as JSON data.</summary>
|
||||
/// <param name="mimeType">Declared MIME type, without parameters.</param>
|
||||
/// <param name="resourceType">Browser resource type (Document, XHR, Fetch, Script...), when known.</param>
|
||||
public static bool IsData(string mimeType, string? resourceType)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mimeType);
|
||||
if (mimeType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return mimeType.Contains("javascript", StringComparison.OrdinalIgnoreCase)
|
||||
&& resourceType is not null
|
||||
&& (resourceType.Equals("XHR", StringComparison.OrdinalIgnoreCase) || resourceType.Equals("Fetch", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>True for an HTML document of the main frame: the data it embeds is read too (<see cref="EmbeddedJsonBlocks"/>).</summary>
|
||||
public static bool IsPageDocument(string mimeType, bool isMainFrameDocument) =>
|
||||
isMainFrameDocument && mimeType.Equals("text/html", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// The JSON blocks a page embeds in <c><script type="application/json"></c> elements, one parsed document per
|
||||
/// block, in document order; none when there is none. Blocks that are not valid JSON are left out.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Single-page sites put the data of the first screen in the document itself and fetch only the following pages:
|
||||
/// without this, the first page of a profile opened by address would arrive «empty». The reader recognizes the data by
|
||||
/// shape wherever it sits inside a block (spec §6.4).
|
||||
/// <para>
|
||||
/// Every block is an answer of its own and is read on its own, like a response: joined to the others, the
|
||||
/// pagination of one block (collections that say «has_next_page» of themselves, a post that says
|
||||
/// «more_available: false» of itself) would end up on the items of another and end a walk early. The blocks are
|
||||
/// parsed lazily, one per step of the enumeration: the caller disposes each before taking the next, so a large
|
||||
/// document never has all its blocks in memory at once.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static IEnumerable<JsonDocument> EmbeddedJsonBlocks(string html)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(html);
|
||||
return html.Length > MaxDocumentChars ? [] : Blocks(html);
|
||||
}
|
||||
|
||||
private static IEnumerable<JsonDocument> Blocks(string html)
|
||||
{
|
||||
for (var match = NextBlock(html, previous: null); match is not null; match = NextBlock(html, match))
|
||||
{
|
||||
var body = match.Groups["body"];
|
||||
if (TryParse(html.AsMemory(body.Index, body.Length)) is { } block)
|
||||
{
|
||||
yield return block;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The block element after <paramref name="previous"/> (the first one when null), or null at the end.</summary>
|
||||
private static Match? NextBlock(string html, Match? previous)
|
||||
{
|
||||
try
|
||||
{
|
||||
var match = previous is null ? JsonScript().Match(html) : previous.NextMatch();
|
||||
return match.Success ? match : null;
|
||||
}
|
||||
catch (RegexMatchTimeoutException)
|
||||
{
|
||||
// A pathological document: the blocks found so far have been given, the rest is left out.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonDocument? TryParse(ReadOnlyMemory<char> text)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonDocument.Parse(text, BlockOptions);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException)
|
||||
{
|
||||
// Not JSON, or too deep; ArgumentException: text that is not valid UTF-16 (a lone surrogate). Left out.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex("""<script\b[^>]*?\btype\s*=\s*["']?application/json["']?[^>]*>(?<body>.*?)</script\s*>""", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 5000)]
|
||||
private static partial Regex JsonScript();
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Collection.Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// What <see cref="DiagnosticLog.ReadAll"/> found: the traces, oldest first, how many lines were damaged, and how many
|
||||
/// day files could not be opened or read at all (held by another program, a read error of the disk, no permission).
|
||||
/// </summary>
|
||||
public sealed record DiagnosticLogContents(IReadOnlyList<SessionTrace> Traces, int DamagedLines, int UnreadableFiles = 0);
|
||||
|
||||
/// <summary>
|
||||
/// The finished traces of the diagnostic report (issue #39), one JSON line each, in
|
||||
/// <c>Dati/diagnostica/sessioni-AAAA-MM-GG.jsonl</c> by local day of the start of the trace. Kept
|
||||
/// <see cref="DefaultDays"/> days: older files of its own folder (and only those, by their name) are deleted when a
|
||||
/// line is written or the log is read. Each line is written whole and flushed; a damaged line (a stop in the middle
|
||||
/// of a write) is skipped and counted when reading, and so is a file that cannot be read. A session in progress also
|
||||
/// has lines of its own (its start, then checkpoints): when reading, a trace found more than once (same session and
|
||||
/// start) is kept once, the finished line over the ones in progress, else the last one. Thread-safe.
|
||||
/// </summary>
|
||||
public sealed class DiagnosticLog
|
||||
{
|
||||
/// <summary>Days kept, today included.</summary>
|
||||
public const int DefaultDays = 14;
|
||||
|
||||
private const string Prefix = "sessioni-";
|
||||
private const string Extension = ".jsonl";
|
||||
private const string DayFormat = "yyyy-MM-dd";
|
||||
|
||||
private readonly IClock _clock;
|
||||
private readonly Lock _gate = new();
|
||||
private DateOnly? _retentionDay;
|
||||
|
||||
public DiagnosticLog(string folder, IClock clock, int days = DefaultDays)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(days, 1);
|
||||
Folder = Path.GetFullPath(folder);
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
Days = days;
|
||||
}
|
||||
|
||||
public string Folder { get; }
|
||||
|
||||
public int Days { get; }
|
||||
|
||||
/// <summary>Name of the file of a local day.</summary>
|
||||
public static string FileNameFor(DateOnly day) => Prefix + day.ToString(DayFormat, CultureInfo.InvariantCulture) + Extension;
|
||||
|
||||
/// <summary>Appends one finished trace to the file of the local day of its start.</summary>
|
||||
public void Append(SessionTrace trace)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(trace);
|
||||
var line = JsonSerializer.Serialize(trace, DiagnosticsJsonContext.Default.SessionTrace);
|
||||
var bytes = Encoding.UTF8.GetBytes(line + "\n");
|
||||
var day = LocalCalendar.Today(trace.Start, _clock.LocalZone);
|
||||
lock (_gate)
|
||||
{
|
||||
Directory.CreateDirectory(Folder);
|
||||
ApplyRetention(force: false);
|
||||
using var stream = new FileStream(Path.Combine(Folder, FileNameFor(day)), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
|
||||
if (stream.Length > 0)
|
||||
{
|
||||
// A stop in the middle of a write leaves a line without its end: start on a new line, so that only
|
||||
// the damaged line is lost and not this one too.
|
||||
stream.Seek(-1, SeekOrigin.End);
|
||||
if (stream.ReadByte() != '\n')
|
||||
{
|
||||
stream.WriteByte((byte)'\n');
|
||||
}
|
||||
}
|
||||
|
||||
stream.Seek(0, SeekOrigin.End);
|
||||
stream.Write(bytes);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when a trace that started at <paramref name="start"/> is among the days kept.</summary>
|
||||
public bool Keeps(DateTimeOffset start) => LocalCalendar.Today(start, _clock.LocalZone) >= FirstDayKept();
|
||||
|
||||
/// <summary>
|
||||
/// Every trace of the days kept, oldest first, once each (see the class); damaged lines and unreadable files are
|
||||
/// skipped and counted.
|
||||
/// </summary>
|
||||
public DiagnosticLogContents ReadAll()
|
||||
{
|
||||
var traces = new List<SessionTrace>();
|
||||
var damaged = 0;
|
||||
var unreadable = 0;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!Directory.Exists(Folder))
|
||||
{
|
||||
return new DiagnosticLogContents([], 0);
|
||||
}
|
||||
|
||||
ApplyRetention(force: true);
|
||||
var first = FirstDayKept();
|
||||
foreach (var (day, path) in Files().Where(f => f.Day >= first).OrderBy(f => f.Day))
|
||||
{
|
||||
string[] lines;
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
lines = reader.ReadToEnd().Split('\n');
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// One file only: the others are still read, and the report says that one is missing.
|
||||
unreadable++;
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var raw in lines)
|
||||
{
|
||||
var line = raw.Trim();
|
||||
if (line.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (JsonSerializer.Deserialize(line, DiagnosticsJsonContext.Default.SessionTrace) is { } trace)
|
||||
{
|
||||
traces.Add(trace);
|
||||
}
|
||||
else
|
||||
{
|
||||
damaged++;
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
damaged++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new DiagnosticLogContents([.. Latest(traces).OrderBy(t => t.Start)], damaged, unreadable);
|
||||
}
|
||||
|
||||
/// <summary>One trace per session and start: the finished one if there is one, else the last line written.</summary>
|
||||
internal static IEnumerable<SessionTrace> Latest(IEnumerable<SessionTrace> inWriteOrder)
|
||||
{
|
||||
var kept = new Dictionary<(long?, DateTimeOffset), SessionTrace>();
|
||||
foreach (var trace in inWriteOrder)
|
||||
{
|
||||
var key = (trace.Session, trace.Start);
|
||||
if (!kept.TryGetValue(key, out var earlier) || !(trace.InProgress && !earlier.InProgress))
|
||||
{
|
||||
kept[key] = trace;
|
||||
}
|
||||
}
|
||||
|
||||
return kept.Values;
|
||||
}
|
||||
|
||||
private DateOnly FirstDayKept() => LocalCalendar.Today(_clock.Now, _clock.LocalZone).AddDays(-(Days - 1));
|
||||
|
||||
/// <summary>Deletes the files of days before the ones kept (once per day unless forced).</summary>
|
||||
private void ApplyRetention(bool force)
|
||||
{
|
||||
var today = LocalCalendar.Today(_clock.Now, _clock.LocalZone);
|
||||
if (!force && _retentionDay == today)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_retentionDay = today;
|
||||
var first = FirstDayKept();
|
||||
foreach (var (day, path) in Files())
|
||||
{
|
||||
if (day < first)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Tried again at the next write or reading.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The files of this log in the folder, by the day in their name (other files are never touched).</summary>
|
||||
private IEnumerable<(DateOnly Day, string Path)> Files()
|
||||
{
|
||||
if (!Directory.Exists(Folder))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
foreach (var path in Directory.EnumerateFiles(Folder, Prefix + "*" + Extension))
|
||||
{
|
||||
var name = Path.GetFileName(path);
|
||||
var text = name[Prefix.Length..^Extension.Length];
|
||||
if (DateOnly.TryParseExact(text, DayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day))
|
||||
{
|
||||
yield return (day, path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Collection.Diagnostics;
|
||||
|
||||
/// <summary>The head of an exported report.</summary>
|
||||
/// <param name="Version">Febe's version (three numbers).</param>
|
||||
/// <param name="Edition">«docker» or «windows».</param>
|
||||
/// <param name="Created">When the report is written.</param>
|
||||
/// <param name="Zone">Alberto's time zone: the times of the report are written in it.</param>
|
||||
/// <param name="Days">Days the log keeps.</param>
|
||||
/// <param name="DamagedLines">Lines of the log that could not be read («righeRovinate»).</param>
|
||||
/// <param name="RecorderFaults">Errors the recorder swallowed, failed writes among them («erroriRegistratore»).</param>
|
||||
/// <param name="UnreadableFiles">Day files of the log that could not be read («fileIlleggibili»).</param>
|
||||
/// <param name="UnfinishedSessions">Sessions Febe stopped without closing, a crash or a kill («sessioniSenzaFine»).</param>
|
||||
public sealed record DiagnosticReportHeader(
|
||||
string Version,
|
||||
string Edition,
|
||||
DateTimeOffset Created,
|
||||
TimeZoneInfo Zone,
|
||||
int Days = DiagnosticLog.DefaultDays,
|
||||
int DamagedLines = 0,
|
||||
int RecorderFaults = 0,
|
||||
int UnreadableFiles = 0,
|
||||
int UnfinishedSessions = 0);
|
||||
|
||||
/// <summary>
|
||||
/// The file Alberto sends after a live test that went wrong (issue #39, «Esporta il rapporto di diagnostica»):
|
||||
/// UTF-8 JSON without BOM, indented, with the traces of the engine sessions and of the days outside sessions. Like
|
||||
/// the traces, it holds no data value: no address, user name, cookie, body or free text.
|
||||
/// </summary>
|
||||
public static partial class DiagnosticReport
|
||||
{
|
||||
/// <summary>The value of «rapporto».</summary>
|
||||
public const string Title = "diagnostica della raccolta";
|
||||
|
||||
/// <summary>Name of the exported file for the local day of <paramref name="now"/>.</summary>
|
||||
public static string FileName(DateTimeOffset now, TimeZoneInfo zone) =>
|
||||
$"febe-diagnostica-{LocalCalendar.Today(now, zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json";
|
||||
|
||||
/// <summary>Writes the report to <paramref name="stream"/> (left open).</summary>
|
||||
/// <exception cref="InvalidOperationException">Debug builds only: the text holds «://» or «@», which no reduction lets through.</exception>
|
||||
public static void Write(Stream stream, IReadOnlyList<SessionTrace> traces, DiagnosticReportHeader header)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
ArgumentNullException.ThrowIfNull(traces);
|
||||
ArgumentNullException.ThrowIfNull(header);
|
||||
var zone = header.Zone;
|
||||
using var buffer = new MemoryStream();
|
||||
using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Indented = true }))
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
writer.WriteString("rapporto", Title);
|
||||
writer.WriteString("versione", Safe(header.Version));
|
||||
writer.WriteString("edizione", Safe(header.Edition));
|
||||
writer.WriteString("creato", Local(header.Created, zone));
|
||||
writer.WriteString("fuso", Safe(ZoneName(zone)));
|
||||
writer.WriteNumber("giorni", header.Days);
|
||||
|
||||
// Not zero: the report is not the whole story (lines of the log lost, writes or readings that failed, day
|
||||
// files that could not be read, sessions cut short by a crash).
|
||||
writer.WriteNumber("righeRovinate", Math.Max(0, header.DamagedLines));
|
||||
writer.WriteNumber("erroriRegistratore", Math.Max(0, header.RecorderFaults));
|
||||
writer.WriteNumber("fileIlleggibili", Math.Max(0, header.UnreadableFiles));
|
||||
writer.WriteNumber("sessioniSenzaFine", Math.Max(0, header.UnfinishedSessions));
|
||||
WriteTraces(writer, "sessioni", traces.Where(t => t.Session is not null), zone);
|
||||
WriteTraces(writer, "fuoriSessione", traces.Where(t => t.Session is null), zone);
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
var text = Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length);
|
||||
if (text.Contains("://", StringComparison.Ordinal) || text.Contains('@', StringComparison.Ordinal))
|
||||
{
|
||||
throw new InvalidOperationException("Il rapporto di diagnostica contiene un indirizzo o un nome: una riduzione non ha funzionato.");
|
||||
}
|
||||
#endif
|
||||
|
||||
buffer.Position = 0;
|
||||
buffer.CopyTo(stream);
|
||||
stream.WriteByte((byte)'\n');
|
||||
}
|
||||
|
||||
private static void WriteTraces(Utf8JsonWriter writer, string name, IEnumerable<SessionTrace> traces, TimeZoneInfo zone)
|
||||
{
|
||||
writer.WriteStartArray(name);
|
||||
foreach (var trace in traces.OrderBy(t => t.Start))
|
||||
{
|
||||
JsonSerializer.Serialize(writer, InZone(trace, zone), DiagnosticsJsonContext.Default.SessionTrace);
|
||||
}
|
||||
|
||||
writer.WriteEndArray();
|
||||
}
|
||||
|
||||
/// <summary>The same trace with its times written in Alberto's zone (same instants, local offset).</summary>
|
||||
private static SessionTrace InZone(SessionTrace trace, TimeZoneInfo zone) => trace with
|
||||
{
|
||||
Start = Local(trace.Start, zone),
|
||||
End = trace.End is { } end ? Local(end, zone) : null,
|
||||
Pages = [.. trace.Pages.Select(p => p with { At = Local(p.At, zone) })],
|
||||
Recipes = [.. trace.Recipes.Select(r => r with { At = Local(r.At, zone) })],
|
||||
Signals = [.. trace.Signals.Select(s => s with { At = Local(s.At, zone) })],
|
||||
};
|
||||
|
||||
private static DateTimeOffset Local(DateTimeOffset instant, TimeZoneInfo zone) => TimeZoneInfo.ConvertTime(instant, zone);
|
||||
|
||||
/// <summary>
|
||||
/// The IANA name of the zone («Europe/Rome»), also on Windows, whose own names have spaces («W. Europe Standard
|
||||
/// Time»), the one of the computer's region when the Windows name covers several («Europe/Rome» rather than
|
||||
/// «Europe/Berlin» in Italy); the Windows name with its spaces as underscores when there is no IANA one.
|
||||
/// </summary>
|
||||
internal static string ZoneName(TimeZoneInfo zone)
|
||||
{
|
||||
string? region = null;
|
||||
try
|
||||
{
|
||||
region = RegionInfo.CurrentRegion.TwoLetterISORegionName;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// No region (invariant culture): the zone's main IANA name.
|
||||
}
|
||||
|
||||
if (region is { Length: 2 } && TimeZoneInfo.TryConvertWindowsIdToIanaId(zone.Id, region, out var regional))
|
||||
{
|
||||
return regional;
|
||||
}
|
||||
|
||||
return TimeZoneInfo.TryConvertWindowsIdToIanaId(zone.Id, out var iana) ? iana : zone.Id.Replace(' ', '_');
|
||||
}
|
||||
|
||||
private static string Safe(string? text) => text is not null && SafeText().IsMatch(text) ? text : CollectionDiagnostics.Other;
|
||||
|
||||
[GeneratedRegex("^[A-Za-z0-9_./+-]{1,64}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex SafeText();
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection.Diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// What one engine session did with the site, for the diagnostic report (issue #39), or what happened outside any
|
||||
/// session on one local day (<see cref="Session"/> null: Alberto at the browser, downloads between sessions).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It holds no data value by construction: only enums, codes from closed lists (signal codes, page and target names
|
||||
/// of the site map), counts, sizes, times and address patterns where every segment that is not a word of the site
|
||||
/// is <c>{numero}</c> or <c>{testo}</c>. Never addresses, user names, bodies, cookies or free text.
|
||||
/// </remarks>
|
||||
public sealed record SessionTrace
|
||||
{
|
||||
/// <summary>The engine session; null for the bucket outside sessions.</summary>
|
||||
public long? Session { get; init; }
|
||||
|
||||
public DateTimeOffset Start { get; init; }
|
||||
|
||||
public DateTimeOffset? End { get; init; }
|
||||
|
||||
public SessionOutcome? Outcome { get; init; }
|
||||
|
||||
public SessionStopCause? StopCause { get; init; }
|
||||
|
||||
/// <summary>The recipe status that stopped the session early, when one did.</summary>
|
||||
public RecipeStatus? StoppedBy { get; init; }
|
||||
|
||||
/// <summary>The speed factor of the session (spec §7.7), two decimals.</summary>
|
||||
public double? Mood { get; init; }
|
||||
|
||||
/// <summary>True for a session still running when the trace was taken (or when Febe stopped).</summary>
|
||||
public bool InProgress { get; init; }
|
||||
|
||||
/// <summary>Pages the recipes opened, in order.</summary>
|
||||
public IReadOnlyList<PageVisit> Pages { get; init; } = [];
|
||||
|
||||
/// <summary>Main-frame navigations (also the ones the engine did not ask for), counted by pattern.</summary>
|
||||
public IReadOnlyList<NavigationGroup> Navigations { get; init; } = [];
|
||||
|
||||
/// <summary>Responses the page received, counted by kind, with sizes and what the readers did with them.</summary>
|
||||
public IReadOnlyList<ResponseGroup> Responses { get; init; } = [];
|
||||
|
||||
/// <summary>Distinct key structures of responses the readers did not recognize (strict: no key that could be data).</summary>
|
||||
public IReadOnlyList<UnknownShape> UnknownShapes { get; init; } = [];
|
||||
|
||||
/// <summary>Verdicts of the recipe steps: «riconosciuto», «vuoto», «sconosciuto».</summary>
|
||||
public IReadOnlyList<VerdictCount> Steps { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<TargetCount> Targets { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<RecipeLine> Recipes { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<SignalLine> Signals { get; init; } = [];
|
||||
|
||||
/// <summary>Refusals of the Governor.</summary>
|
||||
public IReadOnlyList<DenialCount> Denials { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<QueuedFiles> FilesQueued { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<DownloadGroup> Downloads { get; init; } = [];
|
||||
|
||||
/// <summary>Bytes of the files downloaded (what crossed the network), when the queue said.</summary>
|
||||
public long DownloadedBytes { get; init; }
|
||||
|
||||
/// <summary>Items not kept because a list was full: counted, never dropped silently.</summary>
|
||||
public TraceOverflow Overflow { get; init; } = new();
|
||||
}
|
||||
|
||||
/// <summary>A page a recipe opened: the name in the site map and its shape, never the address.</summary>
|
||||
public sealed record PageVisit(DateTimeOffset At, string Page, string? Pattern, bool Ok);
|
||||
|
||||
/// <summary>Main-frame navigations with the same pattern.</summary>
|
||||
public sealed record NavigationGroup(HostKind HostKind, string? Page, string Pattern, bool SameDocument, int Count);
|
||||
|
||||
/// <summary>Responses with the same host kind, pattern, resource type, MIME type and status class.</summary>
|
||||
/// <param name="Count">Responses seen.</param>
|
||||
/// <param name="Bytes">Sum of what crossed the network.</param>
|
||||
/// <param name="MaxBytes">Largest single response.</param>
|
||||
/// <param name="Recognized">Bodies (or blocks of a page) the readers recognized.</param>
|
||||
/// <param name="Empty">Bodies with no contents (an empty page or list).</param>
|
||||
/// <param name="Unrelated">Bodies that are not about contents (ignored).</param>
|
||||
/// <param name="Unrecognized">Bodies with a shape the readers do not know.</param>
|
||||
/// <param name="NotSite">Bodies of a host that is not the site (not read).</param>
|
||||
/// <param name="NotRead">Responses whose body is not data and is not read at all (images, scripts...).</param>
|
||||
/// <param name="Contents">Contents the readers found.</param>
|
||||
/// <param name="Profiles">Profiles the readers found.</param>
|
||||
/// <param name="Dropped">Bodies that never reached the readers, by reason.</param>
|
||||
public sealed record ResponseGroup(
|
||||
HostKind HostKind,
|
||||
string? Page,
|
||||
string Pattern,
|
||||
string? ResourceType,
|
||||
string Mime,
|
||||
string Status,
|
||||
int Count,
|
||||
long Bytes,
|
||||
long MaxBytes,
|
||||
int Recognized,
|
||||
int Empty,
|
||||
int Unrelated,
|
||||
int Unrecognized,
|
||||
int NotSite,
|
||||
int NotRead,
|
||||
int Contents,
|
||||
int Profiles,
|
||||
IReadOnlyList<DropCount> Dropped);
|
||||
|
||||
public sealed record DropCount(BodyDropReason Reason, int Count);
|
||||
|
||||
public sealed record UnknownShape(string Structure, string Pattern, int Count);
|
||||
|
||||
public sealed record VerdictCount(string Verdict, int Count);
|
||||
|
||||
public sealed record TargetCount(string Target, TargetCheckStatus Status, int Count);
|
||||
|
||||
public sealed record RecipeLine(DateTimeOffset At, RecipeKind Kind, RecipeStatus Status, string? Signal, int Actions, int NewEntries)
|
||||
{
|
||||
/// <summary>For a recipe that failed on an unexpected error: the type name of the exception, never its message.</summary>
|
||||
public string? Error { get; init; }
|
||||
}
|
||||
|
||||
public sealed record SignalLine(DateTimeOffset At, SignalLevel Level, string Code);
|
||||
|
||||
public sealed record DenialCount(ActionKind Action, DenialReason Reason, int Count);
|
||||
|
||||
/// <summary>Saves of contents read by the recipes: how many, and how many files they put in the download queue.</summary>
|
||||
/// <param name="Outcome">A <see cref="SaveOutcome"/> name, or «Completed» for a «Post singolo» completion.</param>
|
||||
public sealed record QueuedFiles(EntryKind Kind, string Outcome, int Saves, int Files, int Skipped);
|
||||
|
||||
public sealed record DownloadGroup(EntryKind Kind, DownloadStep Step, int Count, long Bytes)
|
||||
{
|
||||
/// <summary>Why a file failed or waits for another attempt (<see cref="DownloadCauses"/>), when the queue said.</summary>
|
||||
public string? Cause { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Items left out because their list reached its cap (<see cref="CollectionDiagnostics"/>).</summary>
|
||||
public sealed record TraceOverflow
|
||||
{
|
||||
public int Pages { get; init; }
|
||||
|
||||
public int Navigations { get; init; }
|
||||
|
||||
public int Responses { get; init; }
|
||||
|
||||
public int UnknownShapes { get; init; }
|
||||
|
||||
public int Signals { get; init; }
|
||||
|
||||
public int Recipes { get; init; }
|
||||
|
||||
/// <summary>Bodies forgotten while still waiting for their reading (too many responses at once).</summary>
|
||||
public int Requests { get; init; }
|
||||
|
||||
/// <summary>Sizes, readings or drops that arrived after their own trace was closed (counted in the trace open then).</summary>
|
||||
public int Late { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What there is to report, with what the report must say about itself.</summary>
|
||||
/// <param name="Traces">The traces, oldest first.</param>
|
||||
/// <param name="DamagedLines">Lines of the log that could not be read (a stop in the middle of a write).</param>
|
||||
/// <param name="RecorderFaults">Errors the recorder swallowed since Febe started (a failed write among them).</param>
|
||||
public sealed record DiagnosticCollection(IReadOnlyList<SessionTrace> Traces, int DamagedLines = 0, int RecorderFaults = 0)
|
||||
{
|
||||
/// <summary>Day files of the log that could not be opened or read: their sessions are missing.</summary>
|
||||
public int UnreadableFiles { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Sessions whose last line in the log is in progress, not running now and not closed by a shutdown: Febe stopped
|
||||
/// without closing them (a crash, a kill), and what they did after their last line is missing.
|
||||
/// </summary>
|
||||
public int UnfinishedSessions { get; init; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
UseStringEnumConverter = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[JsonSerializable(typeof(SessionTrace))]
|
||||
internal sealed partial class DiagnosticsJsonContext : JsonSerializerContext;
|
||||
@@ -353,6 +353,7 @@ public sealed class DownloadQueue
|
||||
{
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, "Indirizzo del file non valido.", _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Failed);
|
||||
Report(media, entry, DownloadStep.Failed, cause: DownloadCauses.BadAddress);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -382,33 +383,35 @@ public sealed class DownloadQueue
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case FetchOutcome.Completed:
|
||||
await IngestAsync(account, entry, media, temp, maxBytes, tally, ct).ConfigureAwait(false);
|
||||
await IngestAsync(account, entry, media, temp, maxBytes, result.BudgetBytes, tally, ct).ConfigureAwait(false);
|
||||
return;
|
||||
case FetchOutcome.TooLarge:
|
||||
var limit = maxBytes is { } m ? ItalianText.Number(Math.Max(1, m / (1024 * 1024))) : "?";
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, $"Video oltre il limite di {limit} MB impostato per l'account.", _clock.Now, ct).ConfigureAwait(false);
|
||||
_retryAt.TryRemove(media.Id, out _);
|
||||
tally.Add(ref tally.Skipped);
|
||||
Report(media, entry, DownloadStep.Skipped);
|
||||
Report(media, entry, DownloadStep.Skipped, result.BudgetBytes);
|
||||
return;
|
||||
case FetchOutcome.HttpError when result.HttpStatus is { } status && _options.ExpiredStatuses.Contains(status):
|
||||
await ExpiredAsync(entry, media, tally, singlePostQueued, ct).ConfigureAwait(false);
|
||||
await ExpiredAsync(entry, media, tally, singlePostQueued, result.BudgetBytes, ct).ConfigureAwait(false);
|
||||
return;
|
||||
case FetchOutcome.HostNotAllowed:
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, "L'indirizzo non è del CDN: non si scarica (specifica §6.5).", _clock.Now, ct).ConfigureAwait(false);
|
||||
_retryAt.TryRemove(media.Id, out _);
|
||||
tally.Add(ref tally.Failed);
|
||||
Report(media, entry, DownloadStep.Failed);
|
||||
Report(media, entry, DownloadStep.Failed, result.BudgetBytes, DownloadCauses.HostNotAllowed);
|
||||
return;
|
||||
case FetchOutcome.NetworkError when IsConnectionError(result.Error):
|
||||
// No connection at all (router restarting, cable out): every file would fail the same way.
|
||||
// No connection at all (router restarting, cable out): every file would fail the same way. Not the
|
||||
// file's fault (no attempt counted), but the report says why it is still waiting.
|
||||
PauseUntil(_clock.Now + _options.ConnectionPause, tally);
|
||||
Report(media, entry, DownloadStep.Retried, result.BudgetBytes, DownloadCauses.Connection);
|
||||
return;
|
||||
default:
|
||||
var error = result.HttpStatus is { } code
|
||||
? $"Il CDN ha risposto {code.ToString(CultureInfo.InvariantCulture)}."
|
||||
: $"Errore di rete durante lo scaricamento ({result.Error ?? "senza dettagli"}).";
|
||||
await RetryLaterAsync(entry, media, error, tally, ct).ConfigureAwait(false);
|
||||
await RetryLaterAsync(entry, media, error, tally, result.BudgetBytes, ct, DownloadCauses.Of(result.HttpStatus)).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -421,11 +424,12 @@ public sealed class DownloadQueue
|
||||
{
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, "Video oltre il limite impostato per l'account.", _clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Skipped);
|
||||
Report(media, entry, DownloadStep.Skipped);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
// Disk full or similar: the file waits for a later pass (nothing was written under the final name).
|
||||
await RetryLaterAsync(entry, media, $"Scrittura non riuscita: {ex.GetType().Name}.", tally, CancellationToken.None).ConfigureAwait(false);
|
||||
await RetryLaterAsync(entry, media, $"Scrittura non riuscita: {ex.GetType().Name}.", tally, null, CancellationToken.None, DownloadCauses.Write).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -455,14 +459,14 @@ public sealed class DownloadQueue
|
||||
/// A failure that may pass: the file waits for a later attempt, a little longer each time; after
|
||||
/// <see cref="DownloadOptions.MaxAttempts"/> failures it is «fallito».
|
||||
/// </summary>
|
||||
private async Task RetryLaterAsync(Entry entry, Media media, string error, Tally tally, CancellationToken ct)
|
||||
private async Task RetryLaterAsync(Entry entry, Media media, string error, Tally tally, long? bytes, CancellationToken ct, string? cause = null)
|
||||
{
|
||||
if (media.Attempts + 1 >= _options.MaxAttempts)
|
||||
{
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, error, _clock.Now, ct).ConfigureAwait(false);
|
||||
_retryAt.TryRemove(media.Id, out _);
|
||||
tally.Add(ref tally.Failed);
|
||||
Report(media, entry, DownloadStep.Failed);
|
||||
Report(media, entry, DownloadStep.Failed, bytes, cause);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -474,10 +478,12 @@ public sealed class DownloadQueue
|
||||
}
|
||||
|
||||
tally.Add(ref tally.Retried);
|
||||
Report(media, entry, DownloadStep.Retried, bytes, cause);
|
||||
}
|
||||
|
||||
private async Task IngestAsync(Account account, Entry entry, Media media, string temp, long? maxBytes, Tally tally, CancellationToken ct)
|
||||
private async Task IngestAsync(Account account, Entry entry, Media media, string temp, long? maxBytes, long fileBytes, Tally tally, CancellationToken ct)
|
||||
{
|
||||
var bytes = fileBytes;
|
||||
MemoryStream? cover = null;
|
||||
try
|
||||
{
|
||||
@@ -489,6 +495,7 @@ public sealed class DownloadQueue
|
||||
{
|
||||
await _budget.RecordAsync(fetched.BudgetBytes, account.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
tally.AddBytes(fetched.BudgetBytes);
|
||||
bytes += fetched.BudgetBytes;
|
||||
}
|
||||
|
||||
if (fetched.Outcome == FetchOutcome.HttpError && fetched.HttpStatus is { } status)
|
||||
@@ -526,13 +533,13 @@ public sealed class DownloadQueue
|
||||
if (saved.Outcome == MediaSaveOutcome.Stored)
|
||||
{
|
||||
tally.Add(ref tally.Stored);
|
||||
Report(media, entry, DownloadStep.Stored);
|
||||
Report(media, entry, DownloadStep.Stored, bytes);
|
||||
}
|
||||
else
|
||||
{
|
||||
await IdenticalAsync(entry, media, saved.Identical!, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Duplicates);
|
||||
Report(media, entry, DownloadStep.Duplicate);
|
||||
Report(media, entry, DownloadStep.Duplicate, bytes);
|
||||
}
|
||||
}
|
||||
finally
|
||||
@@ -582,7 +589,7 @@ public sealed class DownloadQueue
|
||||
/// A file whose renewed address is refused again and again ends «fallito» after
|
||||
/// <see cref="DownloadOptions.MaxAttempts"/> failures, instead of sending «Post singolo» to the site for ever.
|
||||
/// </summary>
|
||||
private async Task ExpiredAsync(Entry entry, Media media, Tally tally, ConcurrentDictionary<long, bool> singlePostQueued, CancellationToken ct)
|
||||
private async Task ExpiredAsync(Entry entry, Media media, Tally tally, ConcurrentDictionary<long, bool> singlePostQueued, long? bytes, CancellationToken ct)
|
||||
{
|
||||
_retryAt.TryRemove(media.Id, out _);
|
||||
if (entry.Kind != EntryKind.Story && media.Attempts + 1 >= _options.MaxAttempts)
|
||||
@@ -590,7 +597,7 @@ public sealed class DownloadQueue
|
||||
var attempts = ItalianText.Number(media.Attempts + 1);
|
||||
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, $"Indirizzo rifiutato anche dopo il rinnovo ({attempts} tentativi): il file resta «fallito».", _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Failed);
|
||||
Report(media, entry, DownloadStep.Failed);
|
||||
Report(media, entry, DownloadStep.Failed, bytes, DownloadCauses.RefusedAfterRenewal);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -604,7 +611,7 @@ public sealed class DownloadQueue
|
||||
};
|
||||
await _storage.Media.MarkFailedAsync(media.Id, entry.Kind == EntryKind.Story ? MediaState.Failed : MediaState.Expired, why, _clock.Now, ct).ConfigureAwait(false);
|
||||
tally.Add(ref tally.Expired);
|
||||
Report(media, entry, DownloadStep.Expired);
|
||||
Report(media, entry, DownloadStep.Expired, bytes);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -615,7 +622,7 @@ public sealed class DownloadQueue
|
||||
}
|
||||
|
||||
tally.Add(ref tally.Expired);
|
||||
Report(media, entry, DownloadStep.Expired);
|
||||
Report(media, entry, DownloadStep.Expired, bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -632,8 +639,8 @@ public sealed class DownloadQueue
|
||||
}
|
||||
}
|
||||
|
||||
private void Report(Media media, Entry entry, DownloadStep step) =>
|
||||
Progress?.Invoke(this, new DownloadProgress(media.Id, entry.Id, entry.AccountId, entry.Kind, step));
|
||||
private void Report(Media media, Entry entry, DownloadStep step, long? bytes = null, string? cause = null) =>
|
||||
Progress?.Invoke(this, new DownloadProgress(media.Id, entry.Id, entry.AccountId, entry.Kind, step, bytes) { Cause = cause });
|
||||
|
||||
/// <summary>The extension from the content (magic numbers), else from the kind of file.</summary>
|
||||
private static string Extension(string path, Media media)
|
||||
@@ -737,7 +744,44 @@ public enum DownloadStep
|
||||
Skipped,
|
||||
Expired,
|
||||
Failed,
|
||||
|
||||
/// <summary>Not settled: the file waits for a later attempt (a failure that may pass).</summary>
|
||||
Retried,
|
||||
}
|
||||
|
||||
/// <summary>Progress of the queue for the interface: identifiers only, never addresses.</summary>
|
||||
public sealed record DownloadProgress(long MediaId, long EntryId, long AccountId, EntryKind Kind, DownloadStep Step);
|
||||
/// <param name="Bytes">What crossed the network for this file (its cover included), when known.</param>
|
||||
public sealed record DownloadProgress(long MediaId, long EntryId, long AccountId, EntryKind Kind, DownloadStep Step, long? Bytes = null)
|
||||
{
|
||||
/// <summary>Why the file failed or waits for another attempt (<see cref="DownloadCauses"/>); null when it did not.</summary>
|
||||
public string? Cause { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why a file failed or waits for another attempt, for the diagnostic report (issue #39): a closed list of codes,
|
||||
/// never an address or the text of an error.
|
||||
/// </summary>
|
||||
public static class DownloadCauses
|
||||
{
|
||||
/// <summary>A network error that is not a missing connection (the connection pauses the queue instead).</summary>
|
||||
public const string Network = "rete";
|
||||
|
||||
/// <summary>No connection at all: the queue pauses, the file waits without an attempt counted.</summary>
|
||||
public const string Connection = "connessione";
|
||||
|
||||
/// <summary>The file could not be written (disk full or similar).</summary>
|
||||
public const string Write = "scrittura";
|
||||
|
||||
/// <summary>The address of the file is not valid.</summary>
|
||||
public const string BadAddress = "indirizzo-non-valido";
|
||||
|
||||
/// <summary>The address is not of the CDN (spec §6.5).</summary>
|
||||
public const string HostNotAllowed = "host-non-ammesso";
|
||||
|
||||
/// <summary>The renewed address was refused again, too many times.</summary>
|
||||
public const string RefusedAfterRenewal = "rifiutato-dopo-rinnovo";
|
||||
|
||||
/// <summary>«http-404», «http-503»...: the status the CDN answered; <see cref="Network"/> without one.</summary>
|
||||
public static string Of(int? httpStatus) =>
|
||||
httpStatus is >= 100 and < 600 ? "http-" + httpStatus.Value.ToString(CultureInfo.InvariantCulture) : Network;
|
||||
}
|
||||
@@ -73,8 +73,9 @@ public sealed class HostClassifier
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Instagram's public host names: the site and the two CDN families its pages load files from.
|
||||
/// Public knowledge, not response formats; still to be confirmed by the M0 probe.
|
||||
/// Instagram's public host names: the site and the two CDN families its pages load files from. In the HAR of
|
||||
/// 21 October 2026 the data came from www.instagram.com (logging from graph.instagram.com), the video files from
|
||||
/// scontent-*.cdninstagram.com and the scripts from static.cdninstagram.com; fbcdn.net is public knowledge.
|
||||
/// </summary>
|
||||
public static HostClassifier Instagram { get; } = new(
|
||||
["instagram.com"],
|
||||
|
||||
@@ -69,4 +69,61 @@ public interface IResponseObserver
|
||||
void OnResponse(ResponseDescriptor response);
|
||||
|
||||
void OnNavigation(NavigationDescriptor navigation);
|
||||
|
||||
/// <summary>
|
||||
/// The body of a data response announced by <see cref="OnResponse"/> will not reach the consumers: it failed to
|
||||
/// load, was too large, was not JSON after all (Instagram's «for (;;);» answers), or the page moved on. Observers
|
||||
/// that wait for bodies stop waiting for this one.
|
||||
/// </summary>
|
||||
void OnBodyDropped(string requestId)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The same as <see cref="OnBodyDropped(string)"/>, with the reason (for the diagnostic report, issue #39). The tap
|
||||
/// calls this one; by default it forwards to the overload without a reason.
|
||||
/// </summary>
|
||||
void OnBodyDropped(string requestId, BodyDropReason reason) => OnBodyDropped(requestId);
|
||||
|
||||
/// <summary>
|
||||
/// A response announced by <see cref="OnResponse"/> finished loading: <paramref name="encodedBytes"/> is what
|
||||
/// crossed the network (the browser's encodedDataLength). Called for every response, whether its body is read or not.
|
||||
/// </summary>
|
||||
void OnLoadingFinished(string requestId, long encodedBytes)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Why the body of a response did not reach the consumers (closed list: a report may show it).</summary>
|
||||
public enum BodyDropReason
|
||||
{
|
||||
/// <summary>Over the size the tap reads (memory guard).</summary>
|
||||
TooLarge,
|
||||
|
||||
/// <summary>The browser says the request failed.</summary>
|
||||
LoadingFailed,
|
||||
|
||||
/// <summary>The page moved to another document before the body finished.</summary>
|
||||
FrameNavigated,
|
||||
|
||||
/// <summary>The browser was restarted or reconnected.</summary>
|
||||
Reconnected,
|
||||
|
||||
/// <summary>Nobody was listening for bodies.</summary>
|
||||
NoConsumers,
|
||||
|
||||
/// <summary>The browser no longer had the body (evicted from its buffer) or gave none.</summary>
|
||||
Unavailable,
|
||||
|
||||
/// <summary>The body did not arrive in time.</summary>
|
||||
Timeout,
|
||||
|
||||
/// <summary>Declared as data, but not JSON after all.</summary>
|
||||
NotJson,
|
||||
|
||||
/// <summary>A page document without any embedded JSON block.</summary>
|
||||
NoJsonBlock,
|
||||
|
||||
/// <summary>An unexpected error while reading it.</summary>
|
||||
Unexpected,
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
namespace Febe.Core.Collection.Privacy;
|
||||
|
||||
/// <summary>
|
||||
/// Turns an address path into a pattern that names nobody (issue #34, issue #39): every segment that is not a known word
|
||||
/// of the site's addresses becomes <c>{numero}</c> or <c>{testo}</c>. Used by the request shapes of the probe and by the
|
||||
/// diagnostic report. A missing word only costs detail, never privacy.
|
||||
/// </summary>
|
||||
public static class PathPatterns
|
||||
{
|
||||
/// <summary>Written in place of a segment made only of digits.</summary>
|
||||
public const string Number = "{numero}";
|
||||
|
||||
/// <summary>Written in place of any other segment that is not a known word.</summary>
|
||||
public const string Text = "{testo}";
|
||||
|
||||
/// <summary>
|
||||
/// Path segments kept as they are: words of the site's addresses, the same for everyone. Anything else (user names,
|
||||
/// identifiers, codes) becomes <see cref="Number"/> or <see cref="Text"/>.
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> Known = new(StringComparer.Ordinal)
|
||||
{
|
||||
"api", "v1", "graphql", "graphql_www", "query", "ajax", "bulk-route-definitions", "navigation", "web", "users",
|
||||
"user", "web_profile_info", "usernameinfo", "info", "feed", "timeline", "reels_media", "reels_tray", "highlights",
|
||||
"highlights_tray", "friendships", "following", "followers", "show", "show_many", "search", "topsearch", "fbsearch",
|
||||
"web_search", "typeahead", "accounts_typeahead", "top_serp", "media", "comments", "usertags", "clips", "stories",
|
||||
"story", "tags", "sections", "discover", "explore", "chaining", "profile", "posts", "reels", "tagged", "saved",
|
||||
"qp", "batch_fetch_web", "logging_client_events", "direct_v2", "inbox", "has_new", "get_presence", "wwwgraphql",
|
||||
"ig", "bz", "web_info", "current_user", "user_info", "locations", "seen", "media_seen", "reel", "p", "accounts",
|
||||
"edit", "activity", "news", "inbox_v2", "notifications", "badge", "home", "graphql_query",
|
||||
|
||||
// Fixed roots of the site's own pages (verification, login, messages...): a stop that lands there must say so,
|
||||
// not «/{testo}/», and the site map must not take them for a profile (SiteMap.Classify).
|
||||
"challenge", "checkpoint", "direct", "login", "logout", "emails", "password", "reset", "two_factor", "onetap",
|
||||
"suspended", "consent", "settings", "help", "legal", "privacy", "terms", "about",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// File extensions a CDN or other address may show in a report: a closed list, so that the last part of a name
|
||||
/// with a dot («nome.cognome») never passes as an extension.
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> Extensions = new(StringComparer.Ordinal)
|
||||
{
|
||||
"jpg", "jpeg", "png", "webp", "heic", "gif", "avif", "mp4", "m4a", "m4v", "webm", "mov", "js", "css", "json",
|
||||
"woff", "woff2", "ttf", "ico", "svg", "html", "txt",
|
||||
};
|
||||
|
||||
/// <summary>The known words, the same for everyone.</summary>
|
||||
public static IReadOnlySet<string> KnownSegments => Known;
|
||||
|
||||
/// <summary>The extensions <see cref="ExtensionOf"/> may answer.</summary>
|
||||
public static IReadOnlySet<string> KnownExtensions => Extensions;
|
||||
|
||||
/// <summary>The path with each segment that is not a known word replaced by <c>{numero}</c> or <c>{testo}</c>.</summary>
|
||||
/// <remarks>Anything after «?» or «#» is dropped first: only a path is a path.</remarks>
|
||||
public static string Of(string path)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(path);
|
||||
var cut = path.IndexOfAny(['?', '#']);
|
||||
if (cut >= 0)
|
||||
{
|
||||
path = path[..cut];
|
||||
}
|
||||
|
||||
var segments = path.Split('/');
|
||||
for (var i = 0; i < segments.Length; i++)
|
||||
{
|
||||
var segment = segments[i];
|
||||
if (segment.Length == 0 || Known.Contains(segment))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
segments[i] = IsDigits(segment) ? Number : Text;
|
||||
}
|
||||
|
||||
return string.Join('/', segments);
|
||||
}
|
||||
|
||||
/// <summary>True for a word of the site kept by <see cref="Of"/>.</summary>
|
||||
public static bool IsKnownSegment(string segment) => Known.Contains(segment);
|
||||
|
||||
/// <summary>The extension of the last segment of <paramref name="path"/> (lower case, no dot) when it is on the closed list; otherwise null.</summary>
|
||||
public static string? ExtensionOf(string? path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var cut = path.IndexOfAny(['?', '#']);
|
||||
if (cut >= 0)
|
||||
{
|
||||
path = path[..cut];
|
||||
}
|
||||
|
||||
var last = path[(path.LastIndexOf('/') + 1)..];
|
||||
var dot = last.LastIndexOf('.');
|
||||
if (dot < 0 || dot == last.Length - 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var extension = last[(dot + 1)..].ToLowerInvariant();
|
||||
return Extensions.Contains(extension) ? extension : null;
|
||||
}
|
||||
|
||||
private static bool IsDigits(string segment)
|
||||
{
|
||||
foreach (var c in segment)
|
||||
{
|
||||
if (!char.IsAsciiDigit(c))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return segment.Length > 0;
|
||||
}
|
||||
}
|
||||
@@ -13,18 +13,69 @@ public static class KeyStructure
|
||||
public const int DefaultMaxLength = 600;
|
||||
private const int MaxDepth = 6;
|
||||
private const int MaxKeysPerObject = 24;
|
||||
private const int MaxCollectDepth = 256;
|
||||
private const int MaxCollectedValues = 100_000;
|
||||
private const int MaxMapCandidates = 64;
|
||||
private const int MaxElementsCompared = 32;
|
||||
|
||||
public static string Describe(JsonElement root, int maxLength = DefaultMaxLength)
|
||||
/// <summary>Fields that identify an account or an item: two siblings that both have one are entries of a map.</summary>
|
||||
private static readonly HashSet<string> IdentityFields = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
Append(sb, root, 0);
|
||||
if (sb.Length > maxLength)
|
||||
"pk", "pk_id", "id", "fbid", "fbid_v2", "strong_id__", "instagram_pk", "user_id", "userID", "username", "full_name",
|
||||
"profile_pic_url", "code",
|
||||
};
|
||||
|
||||
public static string Describe(JsonElement root, int maxLength = DefaultMaxLength) =>
|
||||
Write(root, LooksLikeIdentifier, mapEntries: false, maxLength);
|
||||
|
||||
/// <summary>
|
||||
/// The stricter description of the diagnostic report (issue #39), where not even a name may pass: a key is shown
|
||||
/// only when it is made of words of a closed list (<see cref="StructureWords.IsStructural"/>), and never when it
|
||||
/// equals, ignoring case, a string value found anywhere in the same body. Every other key becomes «#»: a user name
|
||||
/// («marta_92», «jerry»), a post code, a short token, an identifier, a key with a dot or a space.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Keys made of words of the list can still be names («the_artist», «street_style»), so two more rules apply, and
|
||||
/// under both only a field of the closed list (<see cref="StructureWords.IsFieldKey"/>: the keys of the reader
|
||||
/// vocabularies and of the cleaned samples, such as <c>user</c> and <c>owner</c> of a post) stays:
|
||||
/// <list type="bullet">
|
||||
/// <item>a key with a plain value (text, number, true or false, null) is a field or «#»: a map of counts or flags keyed
|
||||
/// by name never shows;</item>
|
||||
/// <item>the keys of a map are «#»: two or more keys of one object whose values are alike (both objects or both
|
||||
/// lists, and one of them empty, or both lists of plain values, or with at least half of their keys in common or a
|
||||
/// shared identity field such as <c>pk</c>), and in a list of two or more objects the keys of the first one that no
|
||||
/// other has (a list of maps with one entry each).</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public static string DescribeStrict(JsonElement root, int maxLength = DefaultMaxLength)
|
||||
{
|
||||
var values = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
CollectStrings(root, values, 0);
|
||||
return Write(root, key => !StructureWords.IsStructural(key) || values.Contains(key), mapEntries: true, maxLength);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when a key is data rather than structure: it looks like an identifier, or it has any character other than
|
||||
/// ASCII letters, digits, «_» and «-» (a user name with a dot, an address, a phrase). Shared with the sample sanitizer
|
||||
/// (spec §14.5) and the diagnostic report.
|
||||
/// </summary>
|
||||
public static bool IsDataKey(string key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
if (LooksLikeIdentifier(key))
|
||||
{
|
||||
sb.Length = Math.Max(0, maxLength - 1);
|
||||
sb.Append('…');
|
||||
return true;
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
foreach (var c in key)
|
||||
{
|
||||
if (!(char.IsAsciiLetterOrDigit(c) || c is '_' or '-'))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -70,7 +121,237 @@ public static class KeyStructure
|
||||
return others > 0 && digits >= 5; // e.g. «id:123456»
|
||||
}
|
||||
|
||||
private static void Append(StringBuilder sb, JsonElement element, int depth)
|
||||
private static string Write(JsonElement root, Func<string, bool> hidden, bool mapEntries, int maxLength)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
Append(sb, root, hidden, mapEntries, 0);
|
||||
if (sb.Length > maxLength)
|
||||
{
|
||||
sb.Length = Math.Max(0, maxLength - 1);
|
||||
sb.Append('…');
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>The string values of the body (keys excluded), for <see cref="DescribeStrict"/>.</summary>
|
||||
private static void CollectStrings(JsonElement element, HashSet<string> values, int depth)
|
||||
{
|
||||
if (depth > MaxCollectDepth || values.Count >= MaxCollectedValues)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
CollectStrings(property.Value, values, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
CollectStrings(item, values, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.String:
|
||||
if (element.GetString() is { Length: > 0 and <= 256 } text)
|
||||
{
|
||||
values.Add(text);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The keys of <paramref name="element"/> that the strict structure hides besides the ones its predicate already
|
||||
/// rejects (see <see cref="DescribeStrict"/>): keys with a plain value, entries of a map, and
|
||||
/// <paramref name="extra"/> (keys that only the first element of a list has), except the fields of the closed list.
|
||||
/// Null when there is none.
|
||||
/// </summary>
|
||||
private static HashSet<string>? MapEntries(JsonElement element, HashSet<string>? extra)
|
||||
{
|
||||
HashSet<string>? entries = null;
|
||||
void Hide(string key)
|
||||
{
|
||||
if (!StructureWords.IsFieldKey(key))
|
||||
{
|
||||
(entries ??= new HashSet<string>(StringComparer.Ordinal)).Add(key);
|
||||
}
|
||||
}
|
||||
|
||||
List<(string Key, Shape Shape)>? candidates = null;
|
||||
var many = false;
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
var shape = ShapeOf(property.Value);
|
||||
if (shape is null)
|
||||
{
|
||||
Hide(property.Name);
|
||||
}
|
||||
else if (many || (candidates?.Count ?? 0) >= MaxMapCandidates)
|
||||
{
|
||||
// So many objects or lists side by side are a map: no need to compare them.
|
||||
many = true;
|
||||
Hide(property.Name);
|
||||
}
|
||||
else
|
||||
{
|
||||
(candidates ??= []).Add((property.Name, shape));
|
||||
}
|
||||
}
|
||||
|
||||
if (candidates is { Count: >= 2 })
|
||||
{
|
||||
var alike = new bool[candidates.Count];
|
||||
for (var i = 0; i < candidates.Count; i++)
|
||||
{
|
||||
for (var j = i + 1; j < candidates.Count; j++)
|
||||
{
|
||||
if (many || Alike(candidates[i].Shape, candidates[j].Shape))
|
||||
{
|
||||
alike[i] = alike[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < candidates.Count; i++)
|
||||
{
|
||||
if (alike[i])
|
||||
{
|
||||
Hide(candidates[i].Key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (extra is not null)
|
||||
{
|
||||
foreach (var key in extra)
|
||||
{
|
||||
Hide(key);
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Two values of one object are alike (entries of a map): both objects or both lists, and one of them empty, or both
|
||||
/// lists of plain values, or both with keys (of the object, of the first element of the list) half in common or an
|
||||
/// identity field in common.
|
||||
/// </summary>
|
||||
private static bool Alike(Shape a, Shape b)
|
||||
{
|
||||
if (a.List != b.List)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a.Keys is null || b.Keys is null)
|
||||
{
|
||||
// A list of plain values is like an empty list or another list of plain values, never like a list of objects.
|
||||
return a.Keys is not { Count: > 0 } && b.Keys is not { Count: > 0 };
|
||||
}
|
||||
|
||||
if (a.Keys.Count == 0 || b.Keys.Count == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var common = 0;
|
||||
foreach (var key in a.Keys)
|
||||
{
|
||||
if (b.Keys.Contains(key))
|
||||
{
|
||||
if (IdentityFields.Contains(key))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
common++;
|
||||
}
|
||||
}
|
||||
|
||||
var union = a.Keys.Count + b.Keys.Count - common;
|
||||
return common * 2 >= union;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The keys of the first element of a list of two or more objects that no other element has (among the first
|
||||
/// <see cref="MaxElementsCompared"/>): in a list of maps with one entry each, the entries. Null when there is none.
|
||||
/// </summary>
|
||||
private static HashSet<string>? OnlyInFirst(JsonElement array)
|
||||
{
|
||||
HashSet<string>? first = null;
|
||||
var others = 0;
|
||||
var seen = 0;
|
||||
foreach (var item in array.EnumerateArray())
|
||||
{
|
||||
if (++seen > MaxElementsCompared)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (item.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (first is null)
|
||||
{
|
||||
first = KeysOf(item);
|
||||
continue;
|
||||
}
|
||||
|
||||
others++;
|
||||
foreach (var property in item.EnumerateObject())
|
||||
{
|
||||
first.Remove(property.Name);
|
||||
}
|
||||
}
|
||||
|
||||
return others > 0 && first is { Count: > 0 } ? first : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a value is, for the map rule: an object or a list (<paramref name="List"/>), with the keys of the object or of
|
||||
/// the first element of the list (empty: an empty object or list, or a list whose first element is an empty object;
|
||||
/// null: a list of plain values or of lists).
|
||||
/// </summary>
|
||||
private sealed record Shape(bool List, HashSet<string>? Keys);
|
||||
|
||||
/// <summary>The shape of a value; null for a plain value (text, number, true or false, null).</summary>
|
||||
private static Shape? ShapeOf(JsonElement value)
|
||||
{
|
||||
switch (value.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
return new Shape(false, KeysOf(value));
|
||||
case JsonValueKind.Array:
|
||||
using (var items = value.EnumerateArray())
|
||||
{
|
||||
if (!items.MoveNext())
|
||||
{
|
||||
return new Shape(true, []);
|
||||
}
|
||||
|
||||
return new Shape(true, items.Current.ValueKind == JsonValueKind.Object ? KeysOf(items.Current) : null);
|
||||
}
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static HashSet<string> KeysOf(JsonElement value) =>
|
||||
value.EnumerateObject().Select(p => p.Name).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
private static void Append(StringBuilder sb, JsonElement element, Func<string, bool> hidden, bool mapEntries, int depth, HashSet<string>? onlyInFirst = null)
|
||||
{
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
@@ -85,9 +366,10 @@ public static class KeyStructure
|
||||
var count = 0;
|
||||
var identifierKeys = 0;
|
||||
JsonElement? identifierSample = null;
|
||||
var entries = mapEntries ? MapEntries(element, onlyInFirst) : null;
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (LooksLikeIdentifier(property.Name))
|
||||
if (hidden(property.Name) || entries?.Contains(property.Name) == true)
|
||||
{
|
||||
identifierKeys++;
|
||||
identifierSample ??= property.Value;
|
||||
@@ -115,7 +397,7 @@ public static class KeyStructure
|
||||
if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
|
||||
{
|
||||
sb.Append(':');
|
||||
Append(sb, property.Value, depth + 1);
|
||||
Append(sb, property.Value, hidden, mapEntries, depth + 1);
|
||||
}
|
||||
|
||||
count++;
|
||||
@@ -132,7 +414,7 @@ public static class KeyStructure
|
||||
if (identifierSample is { ValueKind: JsonValueKind.Object or JsonValueKind.Array } sample)
|
||||
{
|
||||
sb.Append(':');
|
||||
Append(sb, sample, depth + 1);
|
||||
Append(sb, sample, hidden, mapEntries, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +432,8 @@ public static class KeyStructure
|
||||
{
|
||||
if (item.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
|
||||
{
|
||||
Append(sb, item, depth + 1);
|
||||
var extra = mapEntries && item.ValueKind == JsonValueKind.Object ? OnlyInFirst(element) : null;
|
||||
Append(sb, item, hidden, mapEntries, depth + 1, extra);
|
||||
}
|
||||
|
||||
break; // the first element stands for the others
|
||||
|
||||
@@ -127,6 +127,12 @@ public enum ReadShape
|
||||
|
||||
/// <summary>A shape the vocabulary does not describe: event «formato non riconosciuto» (spec §6.4).</summary>
|
||||
Unrecognized,
|
||||
|
||||
/// <summary>
|
||||
/// Nothing the vocabulary speaks about: none of its relevance keys appears anywhere (promotions, logging, a search
|
||||
/// box). Ignored: neither data, nor an empty page, nor an unknown shape (<see cref="ReaderVocabulary.Relevance"/>).
|
||||
/// </summary>
|
||||
Unrelated,
|
||||
}
|
||||
|
||||
/// <summary>Everything one response gave, detached from the JSON document (which is disposed right after).</summary>
|
||||
@@ -146,6 +152,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; }
|
||||
}
|
||||
@@ -136,6 +136,9 @@ public sealed record HighlightKeys
|
||||
|
||||
/// <summary>The contents of the collection, when the response carries them.</summary>
|
||||
public VocabularyKeys Items { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The cover image of the collection, read as a version.</summary>
|
||||
public VocabularyKeys Cover { get; init; } = VocabularyKeys.None;
|
||||
}
|
||||
|
||||
/// <summary>Keys of the pagination information that comes with a page of data.</summary>
|
||||
@@ -185,6 +188,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.
|
||||
@@ -316,9 +328,10 @@ public sealed record ReaderVocabulary
|
||||
Picture = K(p.Picture),
|
||||
LatestStoryAt = K(p.LatestStoryAt),
|
||||
},
|
||||
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items) },
|
||||
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items), Cover = K(h.Cover) },
|
||||
Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) },
|
||||
Viewer = K(file.Viewer),
|
||||
Relevance = [.. (file.Relevance?.Keys ?? []).Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k.Trim()).Distinct(StringComparer.Ordinal)],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -342,6 +355,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
|
||||
@@ -418,6 +440,8 @@ internal sealed class HighlightDto
|
||||
public List<string>? Owner { get; set; }
|
||||
|
||||
public List<string>? Items { get; set; }
|
||||
|
||||
public List<string>? Cover { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class PageDto
|
||||
|
||||
@@ -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))
|
||||
{
|
||||
@@ -128,6 +151,7 @@ public sealed class ShapeReader
|
||||
Id = id,
|
||||
Title = AsText(Get(_v.Highlight.Title, node)) ?? string.Empty,
|
||||
Owner = highlightOwner,
|
||||
Cover = _v.Highlight.Cover.TryGet(node, out var cover) ? ReadVersion(cover) : null,
|
||||
Items = walk.Contents.Skip(before).ToList(),
|
||||
Order = walk.Highlights.Count,
|
||||
});
|
||||
@@ -160,8 +184,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 +364,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 +541,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)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Collection.Privacy;
|
||||
|
||||
namespace Febe.Core.Collection.Readers;
|
||||
|
||||
/// <summary>
|
||||
/// The closed list of words a key may be made of to appear in the strict key structure of the diagnostic report
|
||||
/// (issue #39, <see cref="KeyStructure.DescribeStrict"/>). Every other key is written «#»: a user name, a post code or a
|
||||
/// short token used as a key never leaves the machine, even when the body does not repeat it as a value.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A key passes when it has only ASCII letters, digits, «_» and «-», does not look like an identifier, and every part
|
||||
/// between «_» and «-» is a word of the list (case ignored): <c>image_versions2</c>, <c>__typename</c>,
|
||||
/// <c>has_more_headload_comments</c>. The words come from the keys of the cleaned samples in <c>tests/Febe.Tests/campioni</c>
|
||||
/// (structure only: the sanitizer already replaced every key that is data), from the shipped reader vocabularies
|
||||
/// (<c>lettori.instagram.json</c>, <c>lettori.prova.json</c>) and from the words of the site's addresses
|
||||
/// (<see cref="PathPatterns.KnownSegments"/>). A missing word only costs detail («#»), never privacy.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A few words that are also first names, places or opaque codes (<see cref="CompoundOnly"/>) pass only inside a key
|
||||
/// that also has a word of the list (<c>next_max_id</c>), never alone (a user called «max») nor with one another
|
||||
/// (<c>max_mark</c>, two first names).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A name made only of words of the list («the_artist», «street_style») still passes this check, so the strict structure
|
||||
/// (<see cref="KeyStructure.DescribeStrict"/>) asks more of two kinds of keys. A key with a plain value (text, number,
|
||||
/// true or false, null) stays only when it is a field of the closed list (<see cref="IsFieldKey"/>): the entries of a
|
||||
/// map of counts or flags keyed by name never show. The entries of a map of objects or lists are found by their
|
||||
/// siblings (similar keys, a shared identity field such as <c>pk</c>, an empty value, lists of plain values, or a key
|
||||
/// that only the first element of a list has), and among them too only the fields of the closed list stay. A
|
||||
/// single such name used as the key of an object or a list, with no sibling alike and never repeated as a value in the
|
||||
/// body, is the residual risk of a closed list of words.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class StructureWords
|
||||
{
|
||||
private const string SampleWords = """
|
||||
a accessibility account achievements action activation active ad add additional address ads affiliate agent
|
||||
aggregated ai aigm all allow allowed alpha altezza altro and anonymous api app appearance appreciation archive
|
||||
are artist as asset associated at attachment attribute attributed attribution attributions audience audio author
|
||||
authors auto autodub automatically autore autosave available awaiting award background badge badges bandwidth
|
||||
barra base batch bbox be been behavior benefits best bestie besties bio biography bit blocked blocking bloks
|
||||
bookmarked boost boosted bottomsheet brand branded breaking broadcast broadcasts business button by cache camera
|
||||
can candidates canonical caption capture carousel category chaining challenge chat check city client clip clips
|
||||
club cluster coauthor code codecs collab collaborator collection color comment commenter commenting comments
|
||||
commerce commission community complete composer composition config configs connected connection consideration
|
||||
consumption container content contenuti contenuto context contextual control copertina count countdowns counts
|
||||
cover covered created creation creative creator cropped cropping crosspost crosspostable cta cursor custom cut
|
||||
cutout dash data debug decision default delayed deleted demotion deny derived details detected detection dettagli
|
||||
device did disable disabled discover display distribution dopo download downloads downstream durata duration
|
||||
eager earned edges edit edited editing educational effect effects elements eligibility eligible eligiblity
|
||||
embeds embodiment emojis enable enabled encoding end enforced enough entities entry entrypoint entrypoints
|
||||
errors estimated event exclusive expansion expiration expiring explicit explore extensions external face
|
||||
facepile failure fallback fan favorite fb fbid fbsearch featured feed feedback fetch fetching file filmati
|
||||
filter filtered filters final first fissato fitting flags floating flush follow followed follower followers
|
||||
following for formatted foto foundation frame free friction friendship from full gating gen genai geoblocked
|
||||
gif gifting graphql grid group guardian has hashtag hashtags have hd header headline headload height hidden
|
||||
hide high highlight highlights host hypercard id identifier ids ig igbio igids igtv image improvements in
|
||||
incoming indirizzo info inform infos initial initiate inline insert insights instagram integrity interaction
|
||||
interactive internal interop inventory invited invocation io is item items kb key label labels langs language
|
||||
largest larghezza lat latest length light like liked likers likes link linked links list live lng load locales
|
||||
location locations logging long longform main manifest manually marketplace mashed mashup mashups may media
|
||||
medias member memorialized mention merchandising message messaging meta metadata method mids mime module more
|
||||
ms music mute muted muting mutual name new news next node nome non nonmimicable note notes notice notices num
|
||||
number numero nux of on only open options organic original originality outgoing overlap overlay owner page
|
||||
pagina paid param parent parti partnership parts party path payload per photo pic picture pill pinned pivot
|
||||
pivots pk places play playback player playlist playlists point pos position post prefetch premium presets preview
|
||||
previous privacy private privately producer producers product production products professional profile profilo
|
||||
progressive project promo promotion promotions prompts pronouns pubblicato pubblicazioni public qualities
|
||||
quando questions quick quiet raccolta raccolte rank ranked ranking reaction reactions reason reattribution
|
||||
recommendation recs reel reels referral refresh regulated related remix remixes remixing remove rename render
|
||||
rendered reply report repost reposter representation representations request requesting require reshare reshared
|
||||
resolution response rest restore restricted restyle result results reusable reuse revamp review ring riservato
|
||||
risk risorsa risultati ritratto roll root rotation routing row save saved scade scans scroll scrubber search
|
||||
secondary seconds see seen segments seguiti seguito selector sequence server settings severity share shared
|
||||
sharing shop shopping short should show sigla size sizes sliders smart snippet social sort sound source spam
|
||||
spatial speed sponsor sprite spritesheet start starting stato status sticker stickers storia storie story street
|
||||
string strong style submission submitted submitters subscribe subscriber subscribers subtype successiva successivo
|
||||
suggested supervision surface tab tag tagged tagging tags taken tappable tappables teen template testo text the
|
||||
third threading thumbnail thumbnails time timeline timeout timer timestamp tipo tips title titolo to toggle
|
||||
token tool top topic topics topsearch total totali tracking translated translation translations transparency
|
||||
tray treatment trend trending trial type typename ufi ui ultima unavailable unicode unified unpublished unseen
|
||||
unviewable up upcoming upsell uri url urls us use user userid username users usertags utc v1 v2 variant verified
|
||||
version versione versions versions2 video view viewer viewers views visibile visibility visible visual voci
|
||||
wearable wearables weight welcome width with x xdt xdtuserdict xpost y you zip
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// Every key of the cleaned samples of <c>tests/Febe.Tests/campioni</c> (their data keys were already replaced by the
|
||||
/// sanitizer), frozen here because the samples do not ship with Febe: with the keys of the reader vocabularies, the
|
||||
/// closed list of fields (<see cref="IsFieldKey"/>).
|
||||
/// </summary>
|
||||
private const string SampleKeys = """
|
||||
__bbox __typename accessibility_caption account_badges account_type achievements_info action_type
|
||||
active_meta_verified_benefits additional_audio_info additional_audio_username additional_candidates
|
||||
address_street ai_agent_owner_username ai_agent_type ai_interactive_embodiment_attachment_style_info
|
||||
ai_label_info ai_topic_filters aigm_account_label_info all_previous_submitters
|
||||
all_video_dash_prefetch_representations allow_creator_to_rename altezza altro appearance_effect
|
||||
are_remixes_crosspostable asset_recommendation_info associated_clip_medias
|
||||
attributed_custom_audio_asset_id attribution_label_text attribution_user audience audio audio_asset_id
|
||||
audio_asset_start_time_in_ms audio_filter_infos audio_parts audio_parts_by_filter audio_ranking_info
|
||||
audio_reattribution_info audio_type auto_load_more_enabled autore autosave_to_exclusive_highlight
|
||||
bandwidth barra base_url basel_encoding_timeout best_audio_cluster_id bio_links biography
|
||||
biography_with_entities bit_flags blocking bloks_app_url bloks_sticker boost_unavailable_identifier
|
||||
boost_unavailable_reason boost_unavailable_reason_v2 boosted_status branded_content_tag_info
|
||||
breaking_content_info breaking_creator_info broadcasts camera_tool can_add_tag can_remix_be_shared_to_fb
|
||||
can_remix_be_shared_to_fb_expansion can_reply can_reshare can_see_insights_as_brand
|
||||
can_see_organic_insights can_see_quiet_post_attribution can_toggle_mashups_allowed
|
||||
can_view_more_preview_comments can_viewer_reshare can_viewer_save candidates caption caption_is_edited
|
||||
capture_type carousel_media carousel_media_count carousel_parent_id category challenge_info chiave
|
||||
city_name client_cache_key clips_attribution_info clips_connection clips_creation_entry_point
|
||||
clips_metadata clips_tab_pinned_user_ids coauthor_producer_can_see_organic_insights coauthor_producers
|
||||
code codecs collab_follow_button_info collaborator_edit_eligibility color_filters comment comment_count
|
||||
comment_cover_pos comment_filter_param comment_inform_treatment comment_likes_enabled
|
||||
commenting_disabled_for_viewer comments comments_disabled commerce_integrity_review_decision
|
||||
community_notes_info complete connected_member_count consumption_info content_appreciation_info
|
||||
content_type contenuti contenuto contextual_highlight_info copertina corpo cover_media created_at
|
||||
created_at_for_fb_app created_at_utc creation_tool_info creative_config
|
||||
creator_is_in_premium_reactions_alpha cropped_image_version crosspost_metadata cursor custom_list_info
|
||||
cutout_sticker_info dash_manifest data debug_link default deleted_reason
|
||||
derived_content_start_time_in_composition_in_ms descrittore detection_method dettagli device_timestamp
|
||||
did_report_as_spam disable_caption_and_comment disable_use_in_clips_client_cache display_artist
|
||||
display_labels display_labels_with_translations display_media_id display_uri dopo
|
||||
downstream_use_xpost_deny_reason durata duration_in_ms duration_selector_seconds edges effect_configs
|
||||
effect_filter_name effect_preview eligible_for_text_app_activation_badge eligible_insights_entrypoints
|
||||
eligible_promotions enable_media_notes_production enable_submission_friction enabled end end_cursor
|
||||
entities entry_point_container errors estimated_scans_sizes expiring_at explore extensions
|
||||
external_lynx_url external_media_info external_url face_effect_id facepile_top_likers failure_reason
|
||||
fallback fan_club_id fan_club_info fan_club_name fan_consideration_page_revamp_eligiblity
|
||||
fb_comment_count fb_comments fb_downstream_use_xpost_metadata fb_like_count fb_play_count fb_user_tags
|
||||
fbid fbid_v2 featured_label featured_products feed_demotion_control feed_post_reshare_disabled
|
||||
feed_recs_demotion_control fetch__XDTUserDict file_size_kb filmati filter_options filter_type
|
||||
first_frame fissato floating_context_item_type floating_context_items follow_hashtag_info followed_by
|
||||
follower_count following following_count formatted_clips_media_count formatted_mashups_count foto
|
||||
foundation_improvements_enabled friendship_status full_image_version full_name gating
|
||||
gen_ai_detection_method gen_ai_tool_info geoblocked_comment_notices group guardian_hypercard_content
|
||||
has_anonymous_profile_picture has_audio has_been_mashed_up has_besties_media has_chaining
|
||||
has_created_ssc has_delayed_metadata has_enough_subscribers_for_ssc
|
||||
has_high_risk_gen_ai_inform_treatment has_liked has_longform_media has_more_comments
|
||||
has_more_headload_comments has_more_headload_fb_comments has_next_page has_nonmimicable_additional_audio
|
||||
has_previous_page has_privately_liked has_profile_pic has_restyle_presets has_shared_to_fb
|
||||
has_story_archive has_tagged_users has_translation has_viewer_saved has_viewer_submitted_note
|
||||
has_views_fetching has_visible_media_notes hashtags hd_profile_pic_url_info hd_profile_pic_versions
|
||||
headline height hidden_likes_string_variant hide_creator_marketplace_badge hide_remixing
|
||||
hide_stickers_for_original_language hide_view_all_comment_entrypoint highlights horizon_attribution_info
|
||||
host id ig_artist ig_media_sharing_disabled ig_mention ig_play_count ig_quick_promotion_batch_fetch_root
|
||||
igbio_product igtv_first_frame image_versions2 in incoming_request indirizzo inform_module
|
||||
initial_representation_ids initiate_at_top inline_audio_label insert_new_comment_to_top instagram_pk
|
||||
integrity_review_decision interop_messaging_user_fbid inventory_source invited_coauthor_producers io
|
||||
is_active_on_text_post_app is_active_trial is_affiliate_commission_eligible is_ai_user
|
||||
is_audio_automatically_attributed is_auto_detected is_awaiting_distribution is_bestie is_bookmarked
|
||||
is_business is_cannes is_comments_gif_composer_enabled is_coppa_enforced is_covered
|
||||
is_created_by_media_owner is_creator_requesting_mashup is_cutout_sticker_allowed is_dash_eligible
|
||||
is_educational is_eligible_content_for_post_roll_ad is_eligible_for_audio_effects
|
||||
is_eligible_for_autodub is_eligible_for_autodub_upsell is_eligible_for_organic_eager_refresh
|
||||
is_eligible_for_poe is_eligible_for_poe_premium is_eligible_for_request_a_note is_eligible_for_rta
|
||||
is_eligible_for_vinyl_sticker is_embeds_disabled is_enabled is_explicit is_fan_club_gifting_eligible
|
||||
is_fan_club_promo_video is_fan_club_referral_eligible is_favorite is_fb_only is_feed_favorite
|
||||
is_feed_feedback_aggregated is_feedback_aggregated is_feta_guardian_user is_final is_free_trial_eligible
|
||||
is_guardian_user is_in_profile_grid is_internal_only is_light_weight_check
|
||||
is_light_weight_reuse_allowed_check is_longform_player_eligible is_manually_enabled is_memorialized
|
||||
is_meta_ai_invocation_blocked_by_author is_muting_reel is_open_to_public_submission
|
||||
is_organic_product_tagging_eligible is_original_audio_download_eligible is_paid_partnership
|
||||
is_photo_comments_composer_enabled_for_author is_pivot_page_available is_post_live_clips_media
|
||||
is_private is_professional_account is_public_chat_welcome_video is_quiet_post is_ranked_comment
|
||||
is_regulated_c18 is_reshare_of_text_post_app_media_in_ig is_restricted is_reuse_allowed
|
||||
is_reuse_disabled is_ring_creator is_seen is_shared_from_basel is_shared_to_fb is_short_drama
|
||||
is_social_ufi_disabled is_spatial_image is_story_edited is_third_party_downloads_eligible
|
||||
is_trending_in_clips is_unpublished is_verified is_visual_reply_commenter_notice_enabled
|
||||
is_xpost_from_fb items largest_public_bc_id larghezza lat latest_besties_reel_media latest_reel_media
|
||||
latest_wearables_reel_media_long like_and_view_counts_disabled like_count
|
||||
liked_by_media_owner_badge_enabled link link_text linked_fb_info linked_media_playlist_data
|
||||
live_broadcast_id live_broadcast_visibility lng location locations logging_info_token
|
||||
longform_clip_metadata longform_title magic_cut_end_time magic_cut_start_time
|
||||
main_feed_carousel_starting_media_id mashup_info mashup_type mashups_allowed
|
||||
mashups_allowed_for_carousel max_thumbnails_per_sprite may_have_template_info media
|
||||
media_attributions_data media_count media_cropping_info media_header_display media_id media_note
|
||||
media_notes media_overlay_info media_repost_count media_reposter_bottomsheet_enabled media_type
|
||||
media_ui_attributions_data media_ui_attributions_data_v2 merchandising_pill_info message
|
||||
meta_ai_suggested_prompts meta_verified_benefits_info mezql_token mids mime_type more_available
|
||||
music_asset_info music_canonical_id music_info music_metadata muted muting mutual_followers_count name
|
||||
node nome nome_visibile non_privacy_filtered_mashups_media_count note_submission_disabled
|
||||
num_earned_achievements num_results number_of_qualities numero nux_info oa_owner_is_music_artist
|
||||
organic_tracking_token original_audio_subtype original_audio_title original_height original_media
|
||||
original_media_id original_sound_info original_width originality_info outgoing_request
|
||||
overlap_duration_in_ms owner owner_id page_info pagina parti parti_totali path photo_of_you pk pk_id
|
||||
places play_count playback_resolution_csvqm playback_resolution_mos position premium_reaction_count
|
||||
preview preview_comments previous_trend_rank privacy_filtered_mashups_media_count private_reply_status
|
||||
product_type professional_clips_upsell_type profile_background_color profile_background_secondary_color
|
||||
profile_context_facepile_users profile_context_links_with_user_ids profile_grid_control_enabled
|
||||
profile_grid_thumbnail_fitting_style profile_pic_genai_tool_info profile_pic_id profile_pic_url profilo
|
||||
progressive_download_url progressive_identifier pronouns pubblicato pubblicazioni quando
|
||||
quick_response_emojis raccolta raccolte rank_token ranked_position reactions reel_media_background
|
||||
reel_media_seen_timestamp reel_type reels_media reels_on_the_rise_info regulated_news_in_locations
|
||||
related_ads_pivots_media_info remove_message_entrypoint rendered_width representation_id representations
|
||||
request_start_time_ms require reshare_count reshared_story_media_author result
|
||||
reusable_text_attribute_string reusable_text_info ring_creator_metadata riservato risorsa risultati
|
||||
ritratto rotation saved_collection_ids scade scans_profile scroll_behavior
|
||||
scrubber_spritesheet_info_candidates search_social_context search_social_context_snippet_type see_more
|
||||
seen seen_ranked_position segments seguiti seguito sequence_number server_metadata severity
|
||||
share_count_disabled share_enabled sharing_friction_info sharing_friction_payload shop_routing_user_id
|
||||
shopping_info short_drama_creator should_allow_audio_editing should_allow_restore
|
||||
should_have_inform_treatment should_have_sharing_friction should_mute_audio should_mute_audio_reason
|
||||
should_mute_audio_reason_type should_render_upsell should_request_ads
|
||||
should_show_author_pog_for_tagged_media_shared_to_profile_grid should_show_category
|
||||
should_show_playlists_in_profile_tab show_account_transparency_details show_achievements show_ring_award
|
||||
show_text_post_app_badge show_tips sigla smart_frame social_context social_context_facepile_users
|
||||
social_context_type social_context_users_count sort_options speed_selector sponsor_tags sprite_height
|
||||
sprite_urls sprite_width start start_cursor stato status sticker_data storie story_app_attribution
|
||||
story_bloks_stickers story_bloks_tappables story_countdowns story_cta story_feed_media story_hashtags
|
||||
story_link_stickers story_locations story_music_stickers story_questions story_sliders strong_id__
|
||||
subscribe_cta_visible subscriber_count subtype_name_for_REST__ successiva successivo supervision_info
|
||||
surface_nux_id taken_at tappable_elements teen_project_info template_info testo text
|
||||
text_post_app_badge_label text_post_app_is_private text_post_share_to_ig_story_stickers
|
||||
third_party_downloads_enabled threading_enabled thumbnail_duration thumbnail_height thumbnail_width
|
||||
thumbnails thumbnails_per_row time_at_flush_ms time_created timeline_pinned_user_ids
|
||||
timer_selector_seconds tipo title titolo top_likers total_clips_count total_thumbnail_num_per_sprite
|
||||
translated_langs_for_autodub transparency_label transparency_product transparency_product_enabled tray
|
||||
trend_rank tya_media_related_topics type ultima_storia unicode unified_feedback_enabled unseen_count
|
||||
unseen_wearables_media_igids unviewable_authors_infos upcoming_event url url_expiration_timestamp_us
|
||||
user userID user_activation_info user_id user_notes username users usertags valore versione
|
||||
video_dash_manifest video_duration video_id video_length video_sticker_locales video_versions view_count
|
||||
viewer viewer_count viewer_has_liked viewer_interaction_settings viewer_premium_reaction_asset_id
|
||||
viewers visibility visual_comment_reply_sticker_info voci wearable_attribution_info width x
|
||||
xdt_api__v1__discover__chaining xdt_api__v1__fbsearch__topsearch_connection
|
||||
xdt_api__v1__feed__reels_media xdt_api__v1__feed__reels_media__connection xdt_api__v1__feed__reels_tray
|
||||
xdt_api__v1__feed__user_timeline_graphql_connection xdt_api__v1__usertags__user_id__feed_connection
|
||||
xdt_mark_story_reel_seen xdt_viewer xpost_fb_creator_info y zip
|
||||
""";
|
||||
|
||||
private static readonly FrozenSet<string> CompoundOnlyWords = FrozenSet.Create(
|
||||
StringComparer.OrdinalIgnoreCase,
|
||||
"max", "mark", "basel", "cannes", "lynx", "feta", "poe", "drama", "magic", "rise", "vinyl", "horizon", "coppa",
|
||||
"csvqm", "tya", "rta", "ssc", "oa", "bc", "pog", "mezql", "c18", "mos");
|
||||
|
||||
private static readonly Lazy<Lists> Built = new(Build);
|
||||
|
||||
/// <summary>Words that pass only as a part of a key that also has a word of the list.</summary>
|
||||
public static IReadOnlySet<string> CompoundOnly => CompoundOnlyWords;
|
||||
|
||||
/// <summary>True for a word of the list (case ignored).</summary>
|
||||
public static bool IsWord(string word) => Built.Value.Words.Contains(word);
|
||||
|
||||
/// <summary>
|
||||
/// True for a whole key of the shipped reader vocabularies (<c>user</c>, <c>owner</c>, <c>image_versions2</c>), case
|
||||
/// ignored: the only keys the strict structure keeps among the entries of a map.
|
||||
/// </summary>
|
||||
public static bool IsKnownKey(string key) => Built.Value.Keys.Contains(key) && IsStructural(key);
|
||||
|
||||
/// <summary>
|
||||
/// True for a field of the closed list: a whole key of the reader vocabularies (<see cref="IsKnownKey"/>) or of the
|
||||
/// cleaned samples (<c>is_private</c>, <c>has_next_page</c>, <c>pubblicazioni</c>), case ignored, that is also
|
||||
/// structural. In the strict structure, a key with a plain value (text, number, true or false, null), and a key
|
||||
/// among the entries of a map, stays only when it is one of these.
|
||||
/// </summary>
|
||||
public static bool IsFieldKey(string key) =>
|
||||
(Built.Value.Keys.Contains(key) || Built.Value.SampleKeys.Contains(key)) && IsStructural(key);
|
||||
|
||||
/// <summary>True when <paramref name="key"/> may appear as it is in the strict key structure.</summary>
|
||||
public static bool IsStructural(string key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
if (key.Length == 0 || key.Length > 120 || KeyStructure.IsDataKey(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var parts = key.Split(['_', '-'], StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var words = Built.Value.Words;
|
||||
var listWord = false;
|
||||
foreach (var part in parts)
|
||||
{
|
||||
if (words.Contains(part))
|
||||
{
|
||||
listWord = true;
|
||||
}
|
||||
else if (!CompoundOnlyWords.Contains(part))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Compound-only words never stand on their own, nor together («max_mark»): at least one part is a word of the list.
|
||||
return listWord;
|
||||
}
|
||||
|
||||
private static Lists Build()
|
||||
{
|
||||
var words = new HashSet<string>(SampleWords.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries), StringComparer.OrdinalIgnoreCase);
|
||||
var keys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var segment in PathPatterns.KnownSegments)
|
||||
{
|
||||
AddParts(words, segment);
|
||||
}
|
||||
|
||||
foreach (var file in new[] { "lettori.instagram.json", "lettori.prova.json" })
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(SiteMap.ReadEmbeddedText(file));
|
||||
AddVocabulary(words, keys, document.RootElement, 0);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or IOException)
|
||||
{
|
||||
// The sample words are enough: a vocabulary only adds detail.
|
||||
}
|
||||
}
|
||||
|
||||
words.ExceptWith(CompoundOnlyWords);
|
||||
var sampleKeys = SampleKeys.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).ToFrozenSet(StringComparer.OrdinalIgnoreCase);
|
||||
return new Lists(words.ToFrozenSet(StringComparer.OrdinalIgnoreCase), keys.ToFrozenSet(StringComparer.OrdinalIgnoreCase), sampleKeys);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The key names of a vocabulary file: every string of its lists, split at «.» (whole keys) and then at «_» and «-»
|
||||
/// (words).
|
||||
/// </summary>
|
||||
private static void AddVocabulary(HashSet<string> words, HashSet<string> keys, JsonElement element, int depth)
|
||||
{
|
||||
if (depth > 8)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
AddVocabulary(words, keys, property.Value, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
if (item.ValueKind == JsonValueKind.String && item.GetString() is { } path)
|
||||
{
|
||||
foreach (var key in path.Split('.', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (!KeyStructure.IsDataKey(key))
|
||||
{
|
||||
keys.Add(key);
|
||||
AddParts(words, key);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
AddVocabulary(words, keys, item, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record Lists(FrozenSet<string> Words, FrozenSet<string> Keys, FrozenSet<string> SampleKeys);
|
||||
|
||||
private static void AddParts(HashSet<string> words, string key)
|
||||
{
|
||||
foreach (var part in key.Split(['_', '-'], StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
words.Add(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Readers;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
@@ -29,6 +30,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)
|
||||
{
|
||||
@@ -38,9 +40,30 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
|
||||
public ShapeReader Reader => _reader;
|
||||
|
||||
/// <summary>
|
||||
/// The recorder of the diagnostic report (issue #39), told what the readers did with every body, also the ones
|
||||
/// not kept (another host, unrelated); null: nothing is recorded.
|
||||
/// </summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
|
||||
/// <summary>How long a data response may stay «on its way» before it is forgotten (its body may never come).</summary>
|
||||
public TimeSpan PendingLifetime { get; init; } = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>
|
||||
/// Identifier of the connected account in the latest site answer that gave one (<see cref="ReadResult.ViewerId"/>),
|
||||
/// also an answer that is otherwise <see cref="ReadShape.Unrelated"/> and not kept.
|
||||
/// </summary>
|
||||
public string? ViewerId
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _viewerId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sequence number of the last read: pass it to <see cref="Since"/> to get what arrives after now.</summary>
|
||||
public long Mark()
|
||||
{
|
||||
@@ -135,7 +158,10 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Reads one body (also used by tests and the probe samples).</summary>
|
||||
/// <summary>
|
||||
/// Reads one body (also used by tests and the probe samples). Returns null, and keeps nothing, for responses that
|
||||
/// are not the site's or that are <see cref="ReadShape.Unrelated"/>.
|
||||
/// </summary>
|
||||
public CapturedRead? Accept(ResponseDescriptor response, JsonElement body)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
@@ -146,10 +172,27 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
|
||||
if (response.HostKind != HostKind.Site)
|
||||
{
|
||||
Observe(response, null, body);
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = _reader.Read(body);
|
||||
Observe(response, result, body);
|
||||
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);
|
||||
@@ -163,10 +206,32 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tells the diagnostics what the readers made of a body; for an unknown shape, its strict key structure, taken
|
||||
/// now, while the document is alive. Never a reason to fail the reading.
|
||||
/// </summary>
|
||||
private void Observe(ResponseDescriptor response, ReadResult? result, JsonElement body)
|
||||
{
|
||||
if (Diagnostics is not { } diagnostics)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var structure = result?.Shape == ReadShape.Unrecognized ? KeyStructure.DescribeStrict(body) : null;
|
||||
diagnostics.ReadObserved(response, result, structure);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Diagnostics are optional: the reading goes on as if they were not there.
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnResponse(ResponseDescriptor response)
|
||||
{
|
||||
if (response.HostKind == HostKind.Site
|
||||
&& response.MimeType.Contains("json", StringComparison.OrdinalIgnoreCase)
|
||||
&& DataResponses.IsData(response.MimeType, response.ResourceType)
|
||||
&& response.Status is >= 200 and < 600 && response.Status != 204)
|
||||
{
|
||||
lock (_gate)
|
||||
@@ -176,6 +241,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.Diagnostics;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
@@ -44,6 +45,9 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
|
||||
public IFebeStorage Storage => storage;
|
||||
|
||||
/// <summary>The recorder of the diagnostic report (issue #39): files put in the download queue. Null: not recorded.</summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// A profile seen in the data. The account is identified by its numeric id; when its name changed, a followed
|
||||
/// profile is renamed (folder kept, notice raised) and a profile that is not followed becomes «Non raggiungibile»
|
||||
@@ -138,22 +142,29 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
var (result, queued, skipped) = await SaveCoreAsync(account, item, kind, ct).ConfigureAwait(false);
|
||||
Diagnostics?.FilesQueued(sessionId, kind, queued, result.Outcome.ToString(), skipped);
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task<(SaveResult Result, int Queued, int Skipped)> SaveCoreAsync(Account account, ContentItem item, EntryKind kind, CancellationToken ct)
|
||||
{
|
||||
if (!Wants(account, kind))
|
||||
{
|
||||
return new SaveResult(SaveOutcome.Excluded, null);
|
||||
return (new SaveResult(SaveOutcome.Excluded, null), 0, 0);
|
||||
}
|
||||
|
||||
var known = await storage.Entries.FindAsync(account.Id, kind, item.Id, ct).ConfigureAwait(false);
|
||||
if (known is not null)
|
||||
{
|
||||
await RefreshFilesAsync(known, item, fromHighlight: false, ct).ConfigureAwait(false);
|
||||
return new SaveResult(SaveOutcome.Known, known);
|
||||
return (new SaveResult(SaveOutcome.Known, known), 0, 0);
|
||||
}
|
||||
|
||||
if (kind is EntryKind.Post or EntryKind.Tagged
|
||||
&& account.Limits.Depth == HistoryDepth.FromDate && account.Limits.FromDate is { } from && item.TakenAt < from)
|
||||
{
|
||||
return new SaveResult(SaveOutcome.Excluded, null);
|
||||
return (new SaveResult(SaveOutcome.Excluded, null), 0, 0);
|
||||
}
|
||||
|
||||
if (kind != EntryKind.ProfilePicture
|
||||
@@ -166,7 +177,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
Caption = imported.Caption ?? item.Caption,
|
||||
};
|
||||
await storage.Entries.UpdateAsync(enriched, ct).ConfigureAwait(false);
|
||||
return new SaveResult(SaveOutcome.Enriched, enriched);
|
||||
return (new SaveResult(SaveOutcome.Enriched, enriched), 0, 0);
|
||||
}
|
||||
|
||||
var now = clock.Now;
|
||||
@@ -175,7 +186,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
var added = await storage.Entries.AddAsync(entry, media, ct).ConfigureAwait(false);
|
||||
if (!added.Created)
|
||||
{
|
||||
return new SaveResult(SaveOutcome.Known, added.Stored.Entry);
|
||||
return (new SaveResult(SaveOutcome.Known, added.Stored.Entry), 0, 0);
|
||||
}
|
||||
|
||||
if (!item.IsComplete && kind is EntryKind.Post or EntryKind.Tagged)
|
||||
@@ -183,7 +194,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
await QueueSinglePostAsync(added.Stored.Entry, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new SaveResult(SaveOutcome.Created, added.Stored.Entry);
|
||||
return (new SaveResult(SaveOutcome.Created, added.Stored.Entry), media.Count(m => m.State == MediaState.ToDownload), media.Count(m => m.State == MediaState.Skipped));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -201,6 +212,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
var added = await storage.Entries.AddAsync(picture.Entry, [picture.Media], ct).ConfigureAwait(false);
|
||||
if (added.Created)
|
||||
{
|
||||
Diagnostics?.FilesQueued(null, EntryKind.ProfilePicture, picture.Media.State == MediaState.ToDownload ? 1 : 0, nameof(SaveOutcome.Created));
|
||||
return new SaveResult(SaveOutcome.Created, added.Stored.Entry);
|
||||
}
|
||||
|
||||
@@ -259,6 +271,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
}
|
||||
}
|
||||
|
||||
Diagnostics?.FilesQueued(null, entry.Kind, changed, CollectionDiagnostics.CompletedOutcome);
|
||||
if ((entry.Code is null && item.Code is not null) || (entry.Caption is null && item.Caption is not null))
|
||||
{
|
||||
var latest = await storage.Entries.GetAsync(entry.Id, ct).ConfigureAwait(false) ?? entry;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
@@ -9,6 +10,9 @@ namespace Febe.Core.Collection.Recipes;
|
||||
internal sealed class RecipeStopException(RecipeStatus status, string message) : Exception(message)
|
||||
{
|
||||
public RecipeStatus Status { get; } = status;
|
||||
|
||||
/// <summary>For a failure on an unexpected error: the type name of that exception (diagnostic report, never the message).</summary>
|
||||
public string? ErrorType { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -96,7 +100,19 @@ internal sealed class RecipeRun : IDisposable
|
||||
public async Task<PageLoad> OpenAsync(string page, IReadOnlyDictionary<string, string>? values = null)
|
||||
{
|
||||
var path = Env.SiteMap.BuildPath(page, values);
|
||||
var load = await Env.Driver.OpenAsync(path, Ct).ConfigureAwait(false);
|
||||
PageLoad load;
|
||||
try
|
||||
{
|
||||
load = await Env.Driver.OpenAsync(path, Ct).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Env.Diagnostics?.PageOpened(Session.SessionId, page, ok: false);
|
||||
throw;
|
||||
}
|
||||
|
||||
// The page NAME of the site map, never the path: it holds the user name or the code.
|
||||
Env.Diagnostics?.PageOpened(Session.SessionId, page, load.Succeeded);
|
||||
ThrowIfSignal();
|
||||
if (!load.Succeeded)
|
||||
{
|
||||
@@ -114,6 +130,7 @@ internal sealed class RecipeRun : IDisposable
|
||||
{
|
||||
ThrowIfSignal();
|
||||
var result = await Env.Driver.ClickAsync(target, parameters, Ct).ConfigureAwait(false);
|
||||
Env.Diagnostics?.TargetClicked(Session.SessionId, target, result.Status);
|
||||
if (!result.Found)
|
||||
{
|
||||
ThrowIfSignal();
|
||||
@@ -167,6 +184,7 @@ internal sealed class RecipeRun : IDisposable
|
||||
{
|
||||
if (reads.Any(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)))
|
||||
{
|
||||
Env.Diagnostics?.StepJudged(Session.SessionId, CollectionDiagnostics.VerdictRecognized);
|
||||
_signals.ObserveNonEmptyPage();
|
||||
return true;
|
||||
}
|
||||
@@ -174,10 +192,12 @@ internal sealed class RecipeRun : IDisposable
|
||||
var unknown = reads.Where(r => r.Result.Shape == ReadShape.Unrecognized && r.Result.KeyStructure is not null).Select(r => r.Result.KeyStructure!).Distinct().ToList();
|
||||
if (unknown.Count > 0)
|
||||
{
|
||||
Env.Diagnostics?.StepJudged(Session.SessionId, CollectionDiagnostics.VerdictUnknown);
|
||||
UnknownShapes.AddRange(unknown);
|
||||
throw Stop(RecipeStatus.UnrecognizedFormat, "La risposta del sito ha una forma che i lettori non riconoscono.");
|
||||
}
|
||||
|
||||
Env.Diagnostics?.StepJudged(Session.SessionId, CollectionDiagnostics.VerdictEmpty);
|
||||
_signals.ObserveEmptyPage(where);
|
||||
ThrowIfSignal();
|
||||
return false;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
@@ -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,384 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Watches a viewer that shows <paramref name="opened"/>: reads the item shown from the address of the page, waits
|
||||
/// the time of §7.7, asks a StoryView permit before each «next» (and after the fact when the viewer moved on by
|
||||
/// itself) and closes the viewer after the last item of <paramref name="owner"/>, or as soon as it shows something
|
||||
/// else. On any stop other than a signal the viewer is closed first. Returns the identifiers shown, in order.
|
||||
/// Watches a viewer that shows <paramref name="opened"/>: on each item it first asks the StoryView permit for the
|
||||
/// item after it (before it can come on screen, by a click or by itself), then waits the time of §7.7, and closes
|
||||
/// the viewer after the last item of <paramref name="owner"/>, or as soon as it shows something else. The item
|
||||
/// shown is read from the address when the address carries it (<see cref="FollowAddressAsync"/>), otherwise counted
|
||||
/// (<see cref="FollowCountAsync"/>). On any stop other than a signal, an unexpected error included, the viewer is
|
||||
/// closed first; a viewer that stays open stops the run as a target not found. A cancellation leaves the page as it
|
||||
/// is. Returns the identifiers shown, in order, each under its permit.
|
||||
/// </summary>
|
||||
private async Task<ViewerResult> WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, IReadOnlyDictionary<string, string> opened)
|
||||
private async Task<ViewerResult> WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, ViewerOpening opened)
|
||||
{
|
||||
var shown = new List<string>();
|
||||
var counted = new HashSet<string>(StringComparer.Ordinal);
|
||||
var pendingPermit = true; // asked before the click that opened the viewer
|
||||
var position = opened;
|
||||
var stuck = 0;
|
||||
var viewer = new ViewerWatch(viewerPage, ownerKey, owner, account, mark);
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
try
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!string.Equals(position[ownerKey], owner, StringComparison.OrdinalIgnoreCase))
|
||||
if (!opened.Position.ContainsKey(ownerKey))
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
await Writer.EventAsync(
|
||||
"visualizzatore-altro-account",
|
||||
viewerPage == SitePages.StoryViewer
|
||||
? $"Dopo le storie di {account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano."
|
||||
: $"Il visualizzatore è passato a un'altra raccolta di {account.Username}: chiuso senza salvarla.",
|
||||
EventSeverity.Warning,
|
||||
account.Id,
|
||||
run.Session.SessionId,
|
||||
run.Ct).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, null);
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, $"La forma dell'indirizzo «{viewerPage}» nella mappa {Env.SiteMap.Source ?? Env.SiteMap.Site} non dice di chi è il visualizzatore: manca «{{{ownerKey}}}».");
|
||||
}
|
||||
|
||||
var id = position["id"];
|
||||
if (counted.Add(id))
|
||||
if (opened.Position.ContainsKey(ItemKey))
|
||||
{
|
||||
if (!pendingPermit)
|
||||
{
|
||||
// The viewer moved on by itself: this item was shown without asking first; ask now.
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
pendingPermit = false;
|
||||
shown.Add(id);
|
||||
await FollowAddressAsync(run, viewer, opened.Position, shown).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await FollowCountAsync(run, viewer, opened, shown).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The list of the account arrives with the viewer (H4): it tells which item is the last one.
|
||||
var list = await ViewerListAsync(run, mark, viewerPage, owner, account).ConfigureAwait(false);
|
||||
var item = list.FirstOrDefault(i => i.Id == id);
|
||||
var video = item?.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration;
|
||||
await Env.Driver.WaitAsync(StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier), run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return new ViewerResult(shown, null); // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!SamePosition(current, position))
|
||||
{
|
||||
position = current; // it moved on by itself while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
var index = list.FindIndex(i => i.Id == id);
|
||||
if (list.Count > 0 && index == list.Count - 1)
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, null);
|
||||
}
|
||||
|
||||
if (!pendingPermit)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
pendingPermit = true;
|
||||
}
|
||||
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
var next = await WaitForViewerAsync(run, viewerPage, previous: current).ConfigureAwait(false);
|
||||
if (next is null)
|
||||
{
|
||||
return new ViewerResult(shown, null); // closed after the last item
|
||||
}
|
||||
|
||||
if (SamePosition(next, current))
|
||||
{
|
||||
if (++stuck >= 2)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti.");
|
||||
}
|
||||
|
||||
continue; // the click went unnoticed: watch a little more and try again
|
||||
}
|
||||
|
||||
stuck = 0;
|
||||
position = next;
|
||||
return new ViewerResult(shown, null);
|
||||
}
|
||||
}
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
if (stop.Status != RecipeStatus.StoppedBySignal)
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
// Leave no viewer open: it would move on by itself to other accounts. After a signal the page stays as it is.
|
||||
try
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
}
|
||||
catch (RecipeStopException)
|
||||
{
|
||||
}
|
||||
var stillOpen = stop.Status == RecipeStatus.StoppedBySignal ? null : await TryCloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, Worse(stop, stillOpen));
|
||||
}
|
||||
|
||||
return new ViewerResult(shown, stop);
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Not even an unexpected error leaves the viewer open; what was shown until then is saved all the same.
|
||||
var stillOpen = await TryCloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
var failure = new RecipeStopException(RecipeStatus.Failed, $"Errore imprevisto in «{Name(run.Request.Kind)}» ({ex.GetType().Name}): {ex.Message}") { ErrorType = ex.GetType().Name };
|
||||
return new ViewerResult(shown, Worse(failure, stillOpen));
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException cancelled)
|
||||
{
|
||||
// A pause, the session closed by a signal, Alberto taking the browser: the page is left as it is, what was
|
||||
// shown under its permit is saved all the same, then the cancellation goes on.
|
||||
return new ViewerResult(shown, null, ExceptionDispatchInfo.Capture(cancelled));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a viewer showed, and why it stopped early (the caller saves what was shown, then stops).</summary>
|
||||
private sealed record ViewerResult(List<string> Shown, RecipeStopException? Stop);
|
||||
/// <summary>
|
||||
/// Follows a viewer whose address carries the item shown (the test site: «/storie/{username}/{id}/»): every
|
||||
/// position is read from the address, so an item the viewer skipped or showed by itself is known for what it is.
|
||||
/// The permit asked on an item covers the next one, also when it comes by itself; an item that comes by itself
|
||||
/// after what the list gave as the last one had no permit: the viewer is closed and it is not saved.
|
||||
/// </summary>
|
||||
private async Task FollowAddressAsync(RecipeRun run, ViewerWatch viewer, IReadOnlyDictionary<string, string> opened, List<string> shown)
|
||||
{
|
||||
var counted = new HashSet<string>(StringComparer.Ordinal);
|
||||
var permitted = true; // asked before the click that opened the viewer: for the first item on screen
|
||||
var position = opened;
|
||||
var stuck = 0;
|
||||
while (true)
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!viewer.ShowsOwner(position))
|
||||
{
|
||||
await LeaveOtherOwnerAsync(run, viewer).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var id = position[ItemKey];
|
||||
if (counted.Add(id))
|
||||
{
|
||||
if (!permitted)
|
||||
{
|
||||
await CloseEarlyAsync(run, viewer, viewer.Page == SitePages.StoryViewer
|
||||
? $"Il visualizzatore è andato avanti da solo dopo quella che per la pagina era l'ultima storia di {viewer.Account.Username}: chiuso, la storia in più non si salva."
|
||||
: $"Il visualizzatore è andato avanti da solo dopo quello che per la pagina era l'ultimo contenuto della raccolta di {viewer.Account.Username}: chiuso, il contenuto in più non si salva.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
permitted = false;
|
||||
shown.Add(id);
|
||||
}
|
||||
|
||||
var since = Env.Clock.Now;
|
||||
|
||||
// The list of the account arrives with the viewer (H4): it tells which item is the last one.
|
||||
var list = await ViewerListAsync(run, viewer).ConfigureAwait(false);
|
||||
var index = list.FindIndex(i => i.Id == id);
|
||||
var last = list.Count > 0 && index == list.Count - 1;
|
||||
if (!last && !permitted)
|
||||
{
|
||||
// The permit for the item after this one, before it can come on screen.
|
||||
await run.PermitAsync(ActionKind.StoryView, viewer.Account.Id).ConfigureAwait(false);
|
||||
permitted = true;
|
||||
}
|
||||
|
||||
await WatchAsync(run, index < 0 ? null : VideoDuration(list[index]), since, latest: null).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return; // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!SamePosition(current, position))
|
||||
{
|
||||
position = current; // it moved on by itself while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
if (last)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
var next = await WaitForViewerAsync(run, viewer.Page, previous: current).ConfigureAwait(false);
|
||||
if (next is null)
|
||||
{
|
||||
return; // closed after the last item
|
||||
}
|
||||
|
||||
if (SamePosition(next, current))
|
||||
{
|
||||
if (++stuck >= 2)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti.");
|
||||
}
|
||||
|
||||
continue; // the click went unnoticed: watch a little more and try again
|
||||
}
|
||||
|
||||
stuck = 0;
|
||||
position = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Follows a viewer whose address does not say which item is shown: Instagram's highlight viewer stays on
|
||||
/// «/stories/highlights/{id}/» from one item to the next (HAR of 21/10/2026). The items are counted against the
|
||||
/// list the page received for the owner: the first one shown is the first of the list, and each click on «next»
|
||||
/// moves one on. A move the viewer makes by itself cannot be seen, so it is never counted: a video, which moves the
|
||||
/// viewer on when it ends, is left before then (<see cref="VideoClickLead"/>), and when that is no longer possible
|
||||
/// (the Governor's wait for the permit took its time) the viewer is closed without clicking «next», the items after
|
||||
/// it not saved. A photo is never taken as over, because how long the site keeps it is not in the data: should the
|
||||
/// viewer leave one by itself, the count falls behind and its last «next» takes the viewer to another collection,
|
||||
/// where it is closed. A click the page ignores would put the count ahead: nothing in the address or in the data
|
||||
/// tells it yet (to be measured live).
|
||||
/// </summary>
|
||||
private async Task FollowCountAsync(RecipeRun run, ViewerWatch viewer, ViewerOpening opened, List<string> shown)
|
||||
{
|
||||
var position = opened.Position;
|
||||
var index = 0;
|
||||
var appearedAfter = opened.ClickedAt; // the item at «index» did not come on screen before this
|
||||
while (true)
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!viewer.ShowsOwner(position))
|
||||
{
|
||||
await LeaveOtherOwnerAsync(run, viewer).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var since = Env.Clock.Now;
|
||||
var list = await ViewerListAsync(run, viewer).ConfigureAwait(false);
|
||||
if (index >= list.Count)
|
||||
{
|
||||
// The page described nothing (more) for this owner: which item is on screen cannot be told.
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// On screen under the permit asked before it could come: before opening, or on the item before it.
|
||||
var item = list[index];
|
||||
if (!shown.Contains(item.Id, StringComparer.Ordinal))
|
||||
{
|
||||
shown.Add(item.Id);
|
||||
}
|
||||
|
||||
var last = index == list.Count - 1;
|
||||
var video = VideoDuration(item);
|
||||
DateTimeOffset? leaveBy = video is { } duration && duration > TimeSpan.Zero
|
||||
? appearedAfter + duration - TimeSpan.FromTicks((long)(VideoClickLead.Ticks * Env.Driver.WaitMultiplier))
|
||||
: null;
|
||||
if (!last)
|
||||
{
|
||||
// The permit for the item after this one, before it can come on screen; asked only while the viewer
|
||||
// surely has not moved on by itself, and the item still has to be left in time once it is granted.
|
||||
if (!Passed(leaveBy))
|
||||
{
|
||||
await run.PermitAsync(ActionKind.StoryView, viewer.Account.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Passed(leaveBy))
|
||||
{
|
||||
await CloseEarlyAsync(run, viewer, viewer.Page == SitePages.StoryViewer
|
||||
? $"Una storia video di {viewer.Account.Username} poteva essere già finita, con il visualizzatore andato avanti da solo: chiuso senza cliccare «avanti», le storie successive non si salvano questa volta."
|
||||
: $"Un video della raccolta di {viewer.Account.Username} poteva essere già finito, con il visualizzatore andato avanti da solo: chiuso senza cliccare «avanti», i contenuti successivi non si salvano questa volta.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await WatchAsync(run, video, since, leaveBy).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return; // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!viewer.ShowsOwner(current))
|
||||
{
|
||||
position = current; // it moved on by itself to another owner while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
if (last)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var pressedAfter = Env.Clock.Now;
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
index++;
|
||||
appearedAfter = pressedAfter;
|
||||
position = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (position is null)
|
||||
{
|
||||
return; // the viewer closed: the item after was not shown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True once <paramref name="moment"/> has come (never for none).</summary>
|
||||
private bool Passed(DateTimeOffset? moment) => moment is { } end && Env.Clock.Now >= end;
|
||||
|
||||
/// <summary>
|
||||
/// Waits the time of §7.7 on an item on screen since <paramref name="since"/>: what the recipe waited meanwhile (the
|
||||
/// Governor's spacing before the permit for the next item) is part of it. Never past <paramref name="latest"/>.
|
||||
/// </summary>
|
||||
private async Task WatchAsync(RecipeRun run, TimeSpan? video, DateTimeOffset since, DateTimeOffset? latest)
|
||||
{
|
||||
var until = since + StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier);
|
||||
if (latest is { } end && end < until)
|
||||
{
|
||||
until = end;
|
||||
}
|
||||
|
||||
var wait = until - Env.Clock.Now;
|
||||
if (wait > TimeSpan.Zero)
|
||||
{
|
||||
await Env.Driver.WaitAsync(wait, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static TimeSpan? VideoDuration(ContentItem item) => item.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration;
|
||||
|
||||
/// <summary>The viewer went on to another account or collection: closed, and the event recorded.</summary>
|
||||
private async Task LeaveOtherOwnerAsync(RecipeRun run, ViewerWatch viewer)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
await Writer.EventAsync(
|
||||
"visualizzatore-altro-account",
|
||||
viewer.Page == SitePages.StoryViewer
|
||||
? $"Dopo le storie di {viewer.Account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano."
|
||||
: $"Il visualizzatore è passato a un'altra raccolta di {viewer.Account.Username}: chiuso senza salvarla.",
|
||||
EventSeverity.Warning,
|
||||
viewer.Account.Id,
|
||||
run.Session.SessionId,
|
||||
run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The viewer may be on an item not shown under a permit, or not known: closed before the end, without clicking
|
||||
/// «next», and the event recorded. What it may show now is not saved.
|
||||
/// </summary>
|
||||
private async Task CloseEarlyAsync(RecipeRun run, ViewerWatch viewer, string why)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
await Writer.EventAsync("visualizzatore-chiuso-prima", why, EventSeverity.Info, viewer.Account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the viewer on the way out of a stop, unless a signal says to leave the page as it is; never throws, but
|
||||
/// for a cancellation. Returns why the viewer may still be open (it did not close with its command), otherwise null.
|
||||
/// </summary>
|
||||
private async Task<RecipeStopException?> TryCloseViewerAsync(RecipeRun run, string viewerPage)
|
||||
{
|
||||
try
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
// After a signal the page stays as it is; otherwise the command was not found or the viewer did not close.
|
||||
return stop.Status == RecipeStatus.TargetNotFound ? stop : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Whether it closed is not known (the browser may be gone): the stop being reported is the first one.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The stop to report: a viewer left open outranks a milder first stop, as a target not found, which makes the
|
||||
/// session stop and put the page at rest.
|
||||
/// </summary>
|
||||
private static RecipeStopException Worse(RecipeStopException first, RecipeStopException? stillOpen) =>
|
||||
stillOpen is null || first.Status == RecipeStatus.TargetNotFound
|
||||
? first
|
||||
: RecipeRun.Stop(RecipeStatus.TargetNotFound, $"{first.Message} {stillOpen.Message}");
|
||||
|
||||
/// <summary>The address a viewer opened on, and when the click that opened it started.</summary>
|
||||
private sealed record ViewerOpening(IReadOnlyDictionary<string, string> Position, DateTimeOffset ClickedAt);
|
||||
|
||||
/// <summary>
|
||||
/// What a viewer showed, and why it stopped early: a stop, or a cancellation. The caller saves what was shown, then
|
||||
/// goes on with the stop (<see cref="ThrowIfStopped"/>).
|
||||
/// </summary>
|
||||
private sealed record ViewerResult(List<string> Shown, RecipeStopException? Stop, ExceptionDispatchInfo? Cancelled = null)
|
||||
{
|
||||
/// <summary>The token to store what was shown with: stopped early, the run's own may be cancelled already, or a moment later (storage only).</summary>
|
||||
public CancellationToken StoreToken(RecipeRun run) => Stop is null && Cancelled is null ? run.Ct : CancellationToken.None;
|
||||
|
||||
/// <summary>Goes on with the cancellation or the stop, once what was shown is stored.</summary>
|
||||
public void ThrowIfStopped()
|
||||
{
|
||||
Cancelled?.Throw();
|
||||
if (Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A viewer being watched: its page, the placeholder of its owner in the address, the owner, the account, the mark of its data.</summary>
|
||||
private sealed record ViewerWatch(string Page, string OwnerKey, string Owner, Account Account, long Mark)
|
||||
{
|
||||
/// <summary>True when the address still shows the owner watched (an account, or a collection).</summary>
|
||||
public bool ShowsOwner(IReadOnlyDictionary<string, string> position) =>
|
||||
position.TryGetValue(OwnerKey, out var shown) && string.Equals(shown, Owner, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static bool SamePosition(IReadOnlyDictionary<string, string> a, IReadOnlyDictionary<string, string> b) =>
|
||||
a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var v) && string.Equals(v, p.Value, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The items of the viewer for the owner, as received (waits for them the first time).</summary>
|
||||
private async Task<List<ContentItem>> ViewerListAsync(RecipeRun run, long mark, string viewerPage, string owner, Account account)
|
||||
/// <summary>
|
||||
/// The items of the viewer for the owner, as received (waits for them the first time). The stories of an account are
|
||||
/// only what looks like a story (it expires and is in no collection): a post of the account arriving meanwhile (the
|
||||
/// grid comes in an answer of its own, also after the viewer opened) would hide which story is the last one, or,
|
||||
/// counted by position, move every position after it.
|
||||
/// </summary>
|
||||
private async Task<List<ContentItem>> ViewerListAsync(RecipeRun run, ViewerWatch viewer)
|
||||
{
|
||||
Func<ContentItem, bool> belongs = viewerPage == SitePages.StoryViewer
|
||||
? c => IsOwnedBy(c, account)
|
||||
: c => c.HighlightId == owner;
|
||||
var present = Contents(Env.Capture.Since(mark), belongs);
|
||||
Func<ContentItem, bool> belongs = viewer.Page == SitePages.StoryViewer
|
||||
? c => IsOwnedBy(c, viewer.Account) && c.ExpiresAt is not null && c.HighlightId is null
|
||||
: c => InCollection(c, viewer.Owner);
|
||||
var present = Contents(Env.Capture.Since(viewer.Mark), belongs);
|
||||
if (present.Count > 0)
|
||||
{
|
||||
return present;
|
||||
}
|
||||
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Any(belongs)).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(viewer.Mark, r => r.Contents.Any(belongs)).ConfigureAwait(false);
|
||||
run.Judge(reads, r => r.Contents.Any(belongs), null);
|
||||
return Contents(reads, belongs);
|
||||
}
|
||||
@@ -383,10 +664,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 +690,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 +725,18 @@ public sealed partial class RecipeRunner
|
||||
|
||||
private static ProfileInfo? ProfileIn(ReadResult result, Account account) =>
|
||||
result.Profiles.FirstOrDefault(p => (account.InstagramId is { } id && p.Id == id) || string.Equals(p.Username, account.Username, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The profile of the account, or one of its collections: what says that its profile page arrived.</summary>
|
||||
private static bool OwnProfileOrCollectionsIn(ReadResult result, Account account) =>
|
||||
ProfileIn(result, account) is not null || result.Highlights.Any(h => IsHighlightOf(h, account));
|
||||
|
||||
/// <summary>A collection of the account: its owner is the account, or the answer does not say whose it is.</summary>
|
||||
private static bool IsHighlightOf(HighlightInfo highlight, Account account) =>
|
||||
highlight.Owner is not { } owner
|
||||
|| (account.InstagramId is { } id && owner.Id == id)
|
||||
|| string.Equals(owner.Username, account.Username, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>An item received inside collection <paramref name="highlightId"/> (both in the form of the address).</summary>
|
||||
private static bool InCollection(ContentItem item, string highlightId) =>
|
||||
item.HighlightId is { } id && string.Equals(ShapeReader.HighlightId(id), highlightId, StringComparison.Ordinal);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
@@ -40,6 +41,9 @@ public sealed record RecipeEnvironment
|
||||
public ICircuitBreaker? Breaker { get; init; }
|
||||
|
||||
public RecipeOptions Options { get; init; } = new();
|
||||
|
||||
/// <summary>The recorder of the diagnostic report (issue #39). Null: nothing is recorded.</summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -50,18 +54,20 @@ public sealed record RecipeEnvironment
|
||||
/// Common rules: the Governor is asked before every counted action and a refusal stops the recipe in order; a stop
|
||||
/// signal stops it where it is and leaves the page as it is; a missing target stops it with a report, never with
|
||||
/// coordinates; an unknown response shape stops it with <see cref="RecipeStatus.UnrecognizedFormat"/> and an event
|
||||
/// that carries only the key structure. Recipes refuse to run on a site whose map or reader vocabulary is still a
|
||||
/// skeleton (the first Instagram files, to be filled after M0).
|
||||
/// that carries only the key structure. A recipe refuses to run, as <see cref="RecipeStatus.NotConfigured"/>, while the
|
||||
/// site's map lacks a page or target it needs or the reader vocabulary is not usable (Instagram's targets, H11).
|
||||
/// </remarks>
|
||||
public sealed partial class RecipeRunner : IRecipeRunner
|
||||
{
|
||||
private readonly Lock _refusalsGate = new();
|
||||
private readonly HashSet<RecipeKind> _refusalsReported = [];
|
||||
private long? _sessionId;
|
||||
private RecipeKind? _lastKind;
|
||||
|
||||
public RecipeRunner(RecipeEnvironment environment)
|
||||
{
|
||||
Env = environment ?? throw new ArgumentNullException(nameof(environment));
|
||||
Writer = new CollectionWriter(environment.Storage, environment.Clock);
|
||||
Writer = new CollectionWriter(environment.Storage, environment.Clock) { Diagnostics = environment.Diagnostics };
|
||||
}
|
||||
|
||||
public RecipeEnvironment Env { get; }
|
||||
@@ -83,15 +89,19 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
_ => kind.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>Pages and targets a recipe cannot work without.</summary>
|
||||
/// <summary>
|
||||
/// Pages and targets a recipe cannot work without. «profile-not-found» is not among them: it is looked up only when
|
||||
/// the map sets it, and without it a profile that does not exist gives no data, judged like any page that arrives
|
||||
/// empty.
|
||||
/// </summary>
|
||||
public static (IReadOnlyList<string> Pages, IReadOnlyList<string> Targets) Requirements(RecipeKind kind) => kind switch
|
||||
{
|
||||
RecipeKind.FollowingSweep => ([SitePages.Home], []),
|
||||
RecipeKind.AccountStories => ([SitePages.Profile, SitePages.StoryViewer], [SiteTargets.ProfileStoryRing, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
|
||||
RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], [SiteTargets.ProfileNotFound]),
|
||||
RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], []),
|
||||
RecipeKind.Highlight => ([SitePages.Profile, SitePages.HighlightViewer], [SiteTargets.ProfileHighlight, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
|
||||
RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabTagged]),
|
||||
RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabReels]),
|
||||
RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileTabTagged]),
|
||||
RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileTabReels]),
|
||||
RecipeKind.SinglePost => ([SitePages.Post], []),
|
||||
RecipeKind.FollowingList => ([SitePages.Following], []),
|
||||
_ => ([], []),
|
||||
@@ -112,24 +122,29 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
ArgumentNullException.ThrowIfNull(session);
|
||||
var name = Name(request.Kind);
|
||||
|
||||
var (pages, targets) = Requirements(request.Kind);
|
||||
var missing = Env.SiteMap.Missing(pages, targets);
|
||||
if (missing.Count > 0)
|
||||
// A map or a vocabulary that lacks what the recipe needs is a state of the configuration, not a failure of the
|
||||
// recipe: nothing is done, nothing counts towards suspension, and it is said once per recipe and process (the
|
||||
// engine stops planning it, NotConfiguredReason).
|
||||
if (Refusal(request.Kind) is { } refusal)
|
||||
{
|
||||
var message = $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}). Va completata con i campioni della sonda di M0 (ipotesi H11).";
|
||||
await Writer.EventAsync("mappa-incompleta", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
return new RecipeOutcome(RecipeStatus.TargetNotFound, 0, 0, message);
|
||||
}
|
||||
bool first;
|
||||
lock (_refusalsGate)
|
||||
{
|
||||
first = _refusalsReported.Add(request.Kind);
|
||||
}
|
||||
|
||||
if (Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable)
|
||||
{
|
||||
var message = $"«{name}» non può girare: {unusable}";
|
||||
await Writer.EventAsync("lettori-incompleti", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
return new RecipeOutcome(RecipeStatus.UnrecognizedFormat, 0, 0, message);
|
||||
if (first)
|
||||
{
|
||||
await Writer.EventAsync(refusal.Code, refusal.Message + SessionComposer.NotConfiguredTail, EventSeverity.Warning, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Env.Diagnostics?.RecipeEnded(session.SessionId, request.Kind, RecipeStatus.NotConfigured, null, 0, 0);
|
||||
return new RecipeOutcome(RecipeStatus.NotConfigured, 0, 0, refusal.Message);
|
||||
}
|
||||
|
||||
if (Env.Breaker is { } breaker && !breaker.State.AllowsSiteActions)
|
||||
{
|
||||
Env.Diagnostics?.RecipeEnded(session.SessionId, request.Kind, RecipeStatus.Denied, breaker.State.LastSignal?.Code, 0, 0);
|
||||
return new RecipeOutcome(RecipeStatus.Denied, 0, 0, "L'interruttore è aperto: nessuna azione verso il sito.");
|
||||
}
|
||||
|
||||
@@ -143,6 +158,7 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
using var run = new RecipeRun(this, request, session, ct);
|
||||
RecipeStatus status;
|
||||
string? text = null;
|
||||
string? errorType = null;
|
||||
try
|
||||
{
|
||||
await CheckSessionCookieAsync(run).ConfigureAwait(false);
|
||||
@@ -164,6 +180,7 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
{
|
||||
status = stop.Status;
|
||||
text = stop.Message;
|
||||
errorType = stop.ErrorType;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
@@ -180,6 +197,7 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
{
|
||||
status = RecipeStatus.Failed;
|
||||
text = $"Errore imprevisto in «{name}» ({ex.GetType().Name}): {ex.Message}";
|
||||
errorType = ex.GetType().Name;
|
||||
}
|
||||
|
||||
if (run.Signal is { } signal && status is not (RecipeStatus.StoppedBySignal or RecipeStatus.Cancelled))
|
||||
@@ -197,6 +215,17 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
// The timeline is a convenience: failing to write it never changes how the recipe ended.
|
||||
}
|
||||
|
||||
// The report takes the status and the code of the signal, never the message (it may name an account). A recipe
|
||||
// cancelled because the breaker stopped (a signal reported straight to it, like the session cookie lost) gets
|
||||
// the breaker's code too.
|
||||
var breakerState = Env.Breaker?.State;
|
||||
var signalCode = run.Signal?.Code ?? status switch
|
||||
{
|
||||
RecipeStatus.StoppedBySignal => breakerState?.LastSignal?.Code,
|
||||
RecipeStatus.Cancelled when breakerState is { AllowsSiteActions: false } => breakerState.LastSignal?.Code,
|
||||
_ => null,
|
||||
};
|
||||
Env.Diagnostics?.RecipeEnded(session.SessionId, request.Kind, status, signalCode, run.Actions, run.NewEntries, status == RecipeStatus.Failed ? errorType : null);
|
||||
_lastKind = request.Kind;
|
||||
return new RecipeOutcome(status, run.Actions, run.NewEntries, text)
|
||||
{
|
||||
@@ -206,6 +235,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.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Core.Collection.Privacy;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
@@ -31,10 +32,13 @@ public static class SitePages
|
||||
/// <summary>The same list resuming after {cursor} (optional).</summary>
|
||||
public const string FollowingFrom = "followingFrom";
|
||||
|
||||
/// <summary>Shape of the address of the story viewer: {username} and {id} of the story shown.</summary>
|
||||
/// <summary>Shape of the address of the story viewer: {username}, and {id} of the story shown when the address carries it.</summary>
|
||||
public const string StoryViewer = "storyViewer";
|
||||
|
||||
/// <summary>Shape of the address of the highlight viewer: {highlight} and {id} of the item shown.</summary>
|
||||
/// <summary>
|
||||
/// Shape of the address of the highlight viewer: {highlight}, and {id} of the item shown when the address carries it
|
||||
/// (Instagram's does not: «/stories/highlights/{highlight}/» stays the same from item to item).
|
||||
/// </summary>
|
||||
public const string HighlightViewer = "highlightViewer";
|
||||
|
||||
public static IReadOnlyList<string> All { get; } =
|
||||
@@ -82,6 +86,11 @@ public sealed partial class SiteMap
|
||||
private readonly Dictionary<string, string> _pages;
|
||||
private readonly HashSet<string> _configuredTargets;
|
||||
private readonly HashSet<string> _knownTargets;
|
||||
private readonly IReadOnlyList<(string Name, Regex Shape)> _classifier;
|
||||
private readonly HashSet<string> _literals;
|
||||
|
||||
/// <summary>The fixed words and the placeholder names of the shipped maps (the only ones a report may show).</summary>
|
||||
private static readonly Lazy<(HashSet<string> Words, HashSet<string> Placeholders)> Shipped = new(LoadShippedWords);
|
||||
|
||||
public SiteMap(string site, IReadOnlyDictionary<string, string?> pages, IEnumerable<string> configuredTargets, IEnumerable<string> knownTargets, string? source = null)
|
||||
{
|
||||
@@ -90,6 +99,20 @@ public sealed partial class SiteMap
|
||||
_pages = pages.Where(p => !string.IsNullOrWhiteSpace(p.Value)).ToDictionary(p => p.Key, p => p.Value!.Trim(), StringComparer.Ordinal);
|
||||
_configuredTargets = new HashSet<string>(configuredTargets, StringComparer.Ordinal);
|
||||
_knownTargets = new HashSet<string>(knownTargets, StringComparer.Ordinal);
|
||||
|
||||
// More literal segments first (the highlight viewer before the story viewer, whose {username} would take
|
||||
// «highlights»), shapes without a query before the same shape with one, then the order of SitePages.All: a page
|
||||
// made only of placeholders (the profile, «/{username}/») comes after every page with a word of its own.
|
||||
_classifier = [.. _pages
|
||||
.Select(p => (Name: p.Key, Pattern: p.Value, Shape: p.Value.Split('?')[0]))
|
||||
.OrderByDescending(p => LiteralSegments(p.Shape))
|
||||
.ThenBy(p => p.Pattern.Contains('?', StringComparison.Ordinal) ? 1 : 0)
|
||||
.ThenBy(p => IndexOfPage(p.Name))
|
||||
.ThenBy(p => p.Name, StringComparer.Ordinal)
|
||||
.Select(p => (p.Name, new Regex(ShapeRegex(p.Shape, out _), RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(100))))];
|
||||
_literals = new HashSet<string>(
|
||||
_pages.Values.SelectMany(v => v.Split('?')[0].Split('/', StringSplitOptions.RemoveEmptyEntries)).Where(segment => !Placeholder().IsMatch(segment)),
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public string Site { get; }
|
||||
@@ -141,26 +164,8 @@ public sealed partial class SiteMap
|
||||
return null;
|
||||
}
|
||||
|
||||
var shape = pattern.Split('?')[0];
|
||||
var names = new List<string>();
|
||||
var regex = new StringBuilder("^");
|
||||
var last = 0;
|
||||
foreach (Match m in Placeholder().Matches(shape))
|
||||
{
|
||||
regex.Append(Regex.Escape(shape[last..m.Index]));
|
||||
regex.Append("([^/]+)");
|
||||
names.Add(m.Groups[1].Value);
|
||||
last = m.Index + m.Length;
|
||||
}
|
||||
|
||||
regex.Append(Regex.Escape(shape[last..]));
|
||||
if (!shape.EndsWith('/'))
|
||||
{
|
||||
regex.Append("/?");
|
||||
}
|
||||
|
||||
regex.Append('$');
|
||||
var match = Regex.Match(path, regex.ToString(), RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(100));
|
||||
var regex = ShapeRegex(pattern.Split('?')[0], out var names);
|
||||
var match = Regex.Match(path, regex, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(100));
|
||||
if (!match.Success)
|
||||
{
|
||||
return null;
|
||||
@@ -175,10 +180,79 @@ public sealed partial class SiteMap
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which page of the map an address path has the shape of, or null when none (data endpoints, pages the map does not
|
||||
/// know). Pages with more words of their own are tried first, so «/stories/highlights/1/» is the highlight viewer
|
||||
/// and not the story viewer of someone called «highlights»; the profile, made only of a placeholder, comes last.
|
||||
/// A placeholder never takes a fixed word of the site (<see cref="PathPatterns.IsKnownSegment"/>) or of a map:
|
||||
/// «/challenge/», «/explore/», «/reels/» are not profiles. Only the page NAME comes out: never the values (issue #39).
|
||||
/// </summary>
|
||||
public string? Classify(string? path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var (name, shape) in _classifier)
|
||||
{
|
||||
try
|
||||
{
|
||||
var match = shape.Match(path);
|
||||
if (match.Success && !TakesAWord(match))
|
||||
{
|
||||
return name;
|
||||
}
|
||||
}
|
||||
catch (RegexMatchTimeoutException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The shape of the address of page <paramref name="name"/> for a report: without its query, with its
|
||||
/// {placeholders} and no value (e.g. «/{username}/»); null when the page is not set. A map may come from Alberto's
|
||||
/// data folder, so the shape is reduced like any path: only the fixed words of the site and of the shipped maps
|
||||
/// and their placeholders stay, any other segment becomes {numero} or {testo} («/alberto.rossi/following/» written
|
||||
/// in place of «/{username}/following/» gives «/{testo}/following/»).
|
||||
/// </summary>
|
||||
public string? PatternOf(string name) =>
|
||||
_pages.TryGetValue(name, out var pattern) ? ReportShape(pattern.Split('?')[0]) : null;
|
||||
|
||||
/// <summary>A page shape reduced for a report (<see cref="PatternOf"/>).</summary>
|
||||
public static string ReportShape(string shape)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(shape);
|
||||
var (words, placeholders) = Shipped.Value;
|
||||
var segments = shape.Split('/');
|
||||
for (var i = 0; i < segments.Length; i++)
|
||||
{
|
||||
var segment = segments[i];
|
||||
if (segment.Length == 0 || PathPatterns.IsKnownSegment(segment) || words.Contains(segment))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var whole = Placeholder().Match(segment);
|
||||
if (whole.Success && whole.Length == segment.Length && placeholders.Contains(whole.Groups[1].Value))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
segments[i] = PathPatterns.Of("/" + segment)[1..];
|
||||
}
|
||||
|
||||
return string.Join('/', segments);
|
||||
}
|
||||
|
||||
/// <summary>The target map of the local test site (embedded <c>bersagli.prova.json</c>).</summary>
|
||||
public static SiteMap LoadTestSite() => LoadEmbedded("bersagli.prova.json");
|
||||
|
||||
/// <summary>The Instagram skeleton (embedded <c>bersagli.instagram.json</c>): every entry is still unset (H11).</summary>
|
||||
/// <summary>The Instagram map (embedded <c>bersagli.instagram.json</c>): the pages seen in real traffic, targets still unset (H11).</summary>
|
||||
public static SiteMap LoadInstagram() => LoadEmbedded("bersagli.instagram.json");
|
||||
|
||||
public static SiteMap LoadOrEmbedded(string? path, string embeddedName) =>
|
||||
@@ -258,6 +332,85 @@ public sealed partial class SiteMap
|
||||
}
|
||||
}
|
||||
|
||||
private static string ShapeRegex(string shape, out List<string> names)
|
||||
{
|
||||
names = [];
|
||||
var regex = new StringBuilder("^");
|
||||
var last = 0;
|
||||
foreach (Match m in Placeholder().Matches(shape))
|
||||
{
|
||||
regex.Append(Regex.Escape(shape[last..m.Index]));
|
||||
regex.Append("([^/]+)");
|
||||
names.Add(m.Groups[1].Value);
|
||||
last = m.Index + m.Length;
|
||||
}
|
||||
|
||||
regex.Append(Regex.Escape(shape[last..]));
|
||||
if (!shape.EndsWith('/'))
|
||||
{
|
||||
regex.Append("/?");
|
||||
}
|
||||
|
||||
regex.Append('$');
|
||||
return regex.ToString();
|
||||
}
|
||||
|
||||
/// <summary>True when a placeholder of the match took a fixed word of the site or of a map (not a value, so not this page).</summary>
|
||||
private bool TakesAWord(Match match)
|
||||
{
|
||||
var shippedWords = Shipped.Value.Words;
|
||||
for (var i = 1; i < match.Groups.Count; i++)
|
||||
{
|
||||
var value = match.Groups[i].Value;
|
||||
if (PathPatterns.IsKnownSegment(value) || PathPatterns.IsKnownSegment(value.ToLowerInvariant())
|
||||
|| _literals.Contains(value) || shippedWords.Contains(value))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static (HashSet<string> Words, HashSet<string> Placeholders) LoadShippedWords()
|
||||
{
|
||||
var words = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var placeholders = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var file in new[] { "bersagli.instagram.json", "bersagli.prova.json" })
|
||||
{
|
||||
foreach (var pattern in LoadEmbedded(file)._pages.Values)
|
||||
{
|
||||
// The names of the values the recipes fill in, in the path or in the query («{cursor}»).
|
||||
placeholders.UnionWith(Placeholder().Matches(pattern).Select(m => m.Groups[1].Value));
|
||||
foreach (var segment in pattern.Split('?')[0].Split('/', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (!Placeholder().IsMatch(segment))
|
||||
{
|
||||
words.Add(segment);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (words, placeholders);
|
||||
}
|
||||
|
||||
private static int LiteralSegments(string shape) =>
|
||||
shape.Split('/', StringSplitOptions.RemoveEmptyEntries).Count(segment => !Placeholder().IsMatch(segment));
|
||||
|
||||
private static int IndexOfPage(string name)
|
||||
{
|
||||
for (var i = 0; i < SitePages.All.Count; i++)
|
||||
{
|
||||
if (SitePages.All[i] == name)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return int.MaxValue;
|
||||
}
|
||||
|
||||
private static bool IsConfigured(JsonElement target)
|
||||
{
|
||||
foreach (var key in new[] { "role", "name", "href" })
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"note": "SCHELETRO della prima versione (specifica §6.3, ipotesi H11). Elenca solo le pagine e i bersagli di cui le ricette hanno bisogno, tutti VUOTI: si compilano con i campioni della sonda di M0 (docs/prove-dal-vivo.md, docs/sonda/esito.md). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.",
|
||||
"note": "Mappa di Instagram, aggiornata il 25 ottobre 2026 (specifica §6.3). PAGINE: compilate solo quelle che hanno una prova reale nel file HAR del browser di Alberto del 21 ottobre 2026, cioè i modelli di indirizzo che Instagram stesso manda al browser (/ajax/bulk-route-definitions/) e i percorsi del Referer delle richieste fatte dalla pagina: home, profile, post, storyViewer, highlightViewer. Restano vuote, senza prove: following e followingFrom (quindi «Elenco dei seguiti» non gira), profileFrom, reelsFrom e taggedFrom (facoltative). Le parti facoltative dei modelli di Instagram ({?tab}, {?initial_media_id}) non si scrivono: qui ogni segnaposto vale esattamente un segmento. BERSAGLI: tutti ancora VUOTI (ipotesi H11). Il HAR aveva solo risposte Fetch/XHR: nessun documento e nessun attributo degli elementi (ruoli, nomi accessibili, collegamenti). Si compilano con docs/prove-dal-vivo.md, parte A bis (tools/bersagli/raccogli-bersagli.js). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.",
|
||||
"pages": {
|
||||
"home": { "path": "", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti." },
|
||||
"profile": { "path": "", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}." },
|
||||
"profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Se resta vuota lo storico riprende scorrendo." },
|
||||
"reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel." },
|
||||
"taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati." },
|
||||
"post": { "path": "", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code}." },
|
||||
"following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}." },
|
||||
"followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa." },
|
||||
"storyViewer": { "path": "", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata." },
|
||||
"highlightViewer": { "path": "", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} e {id}." }
|
||||
"home": { "path": "/", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti. Prova: modello «/» (PolarisFeedRoute) nelle definizioni delle pagine. Che cosa arrivi caricandola (H1) non è nel HAR e resta da provare." },
|
||||
"profile": { "path": "/{username}/", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}. Prova: modello /{username}/{?tab}/{?view_type}/{?igshid}/ (PolarisProfilePostsTabRoute), senza le parti facoltative. I valori di {?tab} non si vedono nel campione." },
|
||||
"profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Nessuna prova di un indirizzo del genere: resta vuota e lo storico riprende scorrendo." },
|
||||
"reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel. Nessuna prova: la scheda non è nel campione." },
|
||||
"taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati. Nessuna prova: la scheda non è nel campione." },
|
||||
"post": { "path": "/p/{code}/", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code} (11 caratteri). Prova: il percorso /p/{code}/ nel Referer delle richieste della pagina di un post. Instagram usa anche /{username}/reel/{code}/ (modello /{username}/{permalink_key}/{shortcode}/): Febe apre la forma /p/." },
|
||||
"following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}. Nessuna prova nel campione: resta vuota e «Elenco dei seguiti» non gira finché non arriva (parte A bis)." },
|
||||
"followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa. Nessuna prova." },
|
||||
"storyViewer": { "path": "/stories/{username}/{id}/", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata. Prova: modello /stories/{username}/{?initial_media_id}/ (PolarisStoriesV3Route). DA CONFERMARE che l'indirizzo segua ogni storia (l'{id} cambia a ogni avanzamento) e che porti l'{id} fin dall'apertura: senza {id} questa forma non corrisponde e la ricetta si ferma dicendo che il visualizzatore non si è aperto. Anche /stories/highlights/<cifre>/ ha questa forma, con username «highlights»: per le Storie di un account è «un altro account» e il visualizzatore si chiude; la ricetta delle raccolte legge solo highlightViewer." },
|
||||
"highlightViewer": { "path": "/stories/highlights/{highlight}/", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} sono le 17 cifre dell'identificativo (nei dati «highlight:<cifre>», ridotto alle cifre dal lettore). Prova: il Referer delle richieste fatte guardando una raccolta e il modello /stories/highlights/{highlight_reel_id}/ (PolarisStoriesV3HighlightsRoute). Non c'è l'{id} del contenuto mostrato: l'indirizzo resta lo stesso mentre si guarda, quindi la posizione nella raccolta non si legge dall'indirizzo." }
|
||||
},
|
||||
"targets": {
|
||||
"home-story": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Voce della barra delle storie per un account ({username})." },
|
||||
|
||||
@@ -1,51 +1,56 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"status": "ipotesi",
|
||||
"note": "IPOTESI, DA CONFERMARE CON I CAMPIONI DI M0 (specifica §6.4, regola 10). Contiene solo gli indizi che la specifica stessa elenca in §6.4 (pk, code, taken_at, image_versions2.candidates, video_versions, carousel_media); ogni altro concetto è vuoto e si compila sui campioni ripuliti della sonda. Finché lo stato è «ipotesi» o manca un concetto necessario, le ricette si rifiutano di girare su Instagram.",
|
||||
"status": "confermato",
|
||||
"note": "Vocabolario dei lettori per Instagram, compilato il 25 ottobre 2026 sulle risposte reali che il browser di Alberto ha ricevuto il 21 ottobre (file HAR) e completato il 12 novembre con quelle del secondo HAR (scheda del profilo, post del profilo, raccolte del profilo, storie), ripulite con «febe-sonda ripulisci» e conservate in tests/Febe.Tests/campioni/instagram (regola 10). Ogni concetto dice da quali campioni viene; quelli senza riscontro restano vuoti o sono segnati come indizio. I dati di storie e raccolte arrivano come «text/javascript», non come JSON dichiarato: la cattura li legge lo stesso (DataResponses). «viewer»: xdt_viewer.user, visto in raccolta-in-evidenza, descrive l'account collegato con il solo identificativo, senza nome; nel blocco incorporato nella pagina iniziale (vassoio-storie, 12 novembre) ha anche username e profile_pic_url, e il lettore lo legge come Viewer (H10, da provare con la raccolta vera).",
|
||||
"content": {
|
||||
"note": "Indizi di §6.4: chiavi viste in passato, non uno schema. Ipotesi, da confermare con i campioni di M0.",
|
||||
"note": "Un contenuto (XDTMediaDict): post, reel, storia o contenuto di una raccolta. Visti in post-video (/api/v1/media/…/info/), raccolta-in-evidenza, raccolta-pagina-successiva, post-del-profilo (reel e serie) e storie-di-un-profilo. Le griglie delle schede Reel e Con tag (reel-del-profilo, con-tag) sono anteprime senza taken_at né video_versions: non sono contenuti, il contenuto intero arriva da post-del-profilo o da /api/v1/media/…/info/. «user» dei contenuti di una storia ha solo l'identificativo, senza nome: l'autore si eredita dalla raccolta o dalla serie di storie che li contiene. La didascalia è un oggetto con il testo in «text». Serie (carousel_media, media_type 8): i figli sono contenuti con le loro image_versions2 e video_versions, visti in post-del-profilo (6 foto) e serie-con-video (20 figli, uno video).",
|
||||
"id": ["pk"],
|
||||
"code": ["code"],
|
||||
"takenAt": ["taken_at"],
|
||||
"caption": [],
|
||||
"caption": ["caption.text"],
|
||||
"images": ["image_versions2.candidates"],
|
||||
"videos": ["video_versions"],
|
||||
"children": ["carousel_media"],
|
||||
"childCount": [],
|
||||
"owner": [],
|
||||
"childCount": ["carousel_media_count"],
|
||||
"owner": ["user", "owner"],
|
||||
"pinned": [],
|
||||
"expiresAt": [],
|
||||
"duration": []
|
||||
"expiresAt": ["expiring_at"],
|
||||
"duration": ["video_duration"]
|
||||
},
|
||||
"version": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H5).",
|
||||
"url": [],
|
||||
"width": [],
|
||||
"height": [],
|
||||
"note": "Una versione: candidates di image_versions2 (url, width, height, da 10 a 14 per contenuto) e video_versions (type 101, 102, 103 e url; dimensioni solo nei post, non nelle storie). Se il video ha l'audio lo dice il contenuto (has_audio), non la versione: hasAudio resta vuoto e ogni versione conta come file completo (H5 da confermare scaricando).",
|
||||
"url": ["url"],
|
||||
"width": ["width"],
|
||||
"height": ["height"],
|
||||
"hasAudio": []
|
||||
},
|
||||
"profile": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H10).",
|
||||
"id": [],
|
||||
"username": [],
|
||||
"displayName": [],
|
||||
"isPrivate": [],
|
||||
"isFollowed": [],
|
||||
"postCount": [],
|
||||
"picture": [],
|
||||
"latestStoryAt": []
|
||||
"note": "Un profilo (XDTUserDict): visto come autore di un post (user, owner), come proprietario di una raccolta, nella ricerca e nei profili suggeriti. friendship_status.following dice se Alberto lo segue; latest_reel_media è la data dell'ultima storia; media_count, il numero dei post, compare solo nella scheda del profilo (scheda-profilo, PolarisProfilePageContentQuery). Nel vassoio delle storie (vassoio-storie, incorporato nella pagina iniziale) ogni voce ha l'utente con nome e foto ma senza nome per esteso.",
|
||||
"id": ["pk", "id"],
|
||||
"username": ["username"],
|
||||
"displayName": ["full_name"],
|
||||
"isPrivate": ["is_private"],
|
||||
"isFollowed": ["friendship_status.following"],
|
||||
"postCount": ["media_count"],
|
||||
"picture": ["hd_profile_pic_url_info", "hd_profile_pic_versions", "profile_pic_url"],
|
||||
"latestStoryAt": ["latest_reel_media"]
|
||||
},
|
||||
"highlight": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H9).",
|
||||
"id": [],
|
||||
"title": [],
|
||||
"owner": [],
|
||||
"items": []
|
||||
"note": "Una raccolta in evidenza (XDTReelDict con reel_type highlight_reel): id «highlight:<numero>», title, user e i contenuti in items. Vista in raccolta-in-evidenza e raccolta-pagina-successiva. L'elenco delle raccolte di un profilo (raccolte-del-profilo, PolarisProfileStoryHighlightsTrayContentQuery) ha id, title, user e la copertina in cover_media.cropped_image_version, senza contenuti.",
|
||||
"id": ["id"],
|
||||
"title": ["title"],
|
||||
"owner": ["user"],
|
||||
"items": ["items"],
|
||||
"cover": ["cover_media.cropped_image_version"]
|
||||
},
|
||||
"page": {
|
||||
"note": "Da compilare con i campioni di M0 (H3).",
|
||||
"hasMore": [],
|
||||
"cursor": []
|
||||
"note": "page_info delle connessioni GraphQL (has_next_page, end_cursor) e more_available delle risposte REST. Visti in raccolta-in-evidenza e post-video.",
|
||||
"hasMore": ["has_next_page", "more_available"],
|
||||
"cursor": ["end_cursor"]
|
||||
},
|
||||
"viewer": []
|
||||
"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)
|
||||
{
|
||||
@@ -579,12 +627,15 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
}
|
||||
|
||||
s.Runtime.CurrentSession = context;
|
||||
s.Diagnostics?.SessionStarted(record.Id, start, mood);
|
||||
s.Runtime.HadSessionSinceStart = true;
|
||||
Volatile.Write(ref _manualWaiting, false);
|
||||
s.Runtime.NextSessionAt = null;
|
||||
s.Events.Publish(EngineNotificationKind.StateChanged);
|
||||
|
||||
var outcome = SessionOutcome.Completed;
|
||||
var cause = SessionStopCause.WorkDone;
|
||||
SessionSummary? summary = null;
|
||||
var interrupted = false;
|
||||
try
|
||||
{
|
||||
@@ -594,25 +645,37 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
sessionCts.Cancel();
|
||||
}
|
||||
|
||||
var summary = await _composer.RunAsync(context, outsideWindowTask, sessionCts.Token).ConfigureAwait(false);
|
||||
summary = await _composer.RunAsync(context, outsideWindowTask, sessionCts.Token).ConfigureAwait(false);
|
||||
if (summary.StoppedEarly || !s.Breaker.State.AllowsSiteActions || s.Runtime.IsPaused || s.Runtime.UserIsDriving)
|
||||
{
|
||||
outcome = StopOutcome();
|
||||
cause = ct.IsCancellationRequested ? SessionStopCause.Shutdown : StopCause(summary);
|
||||
}
|
||||
else
|
||||
{
|
||||
// A shutdown between two recipes leaves the composer as if its work were done: say what it was.
|
||||
cause = ct.IsCancellationRequested ? SessionStopCause.Shutdown
|
||||
: s.Clock.Now >= plannedEnd ? SessionStopCause.PlannedEnd
|
||||
: summary.BudgetsExhausted ? SessionStopCause.BudgetsExhausted
|
||||
: SessionStopCause.WorkDone;
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
outcome = StopOutcome();
|
||||
cause = StopCause(null);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
outcome = SessionOutcome.Interrupted;
|
||||
cause = SessionStopCause.Shutdown;
|
||||
interrupted = true;
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
outcome = SessionOutcome.Failed;
|
||||
cause = SessionStopCause.Failed;
|
||||
await s.Events.WriteAsync(
|
||||
EventSeverity.Error,
|
||||
EngineEventCodes.RecipeFailed,
|
||||
@@ -629,10 +692,29 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
|
||||
s.Runtime.CurrentSession = null;
|
||||
s.Runtime.Activity = null;
|
||||
await EndSessionAsync(record, context, outcome, outsideWindowTask, interrupted).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await EndSessionAsync(record, context, outcome, outsideWindowTask, interrupted).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
s.Diagnostics?.SessionEnded(record.Id, s.Clock.Now, outcome, cause, summary?.StoppedEarlyBy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why a session that did not reach its natural end stopped (diagnostic report): an open breaker first, then the
|
||||
/// pause, then Alberto at the browser, then a recipe outcome; anything else is a cancellation. A shutdown of Febe
|
||||
/// (the loop's token cancelled) is checked by the caller first: a real recipe returns «Cancelled» instead of throwing.
|
||||
/// </summary>
|
||||
private SessionStopCause StopCause(SessionSummary? summary) =>
|
||||
!_s.Breaker.State.AllowsSiteActions ? SessionStopCause.BreakerOpen
|
||||
: _s.Runtime.IsPaused ? SessionStopCause.Paused
|
||||
: _s.Runtime.UserIsDriving ? SessionStopCause.UserDriving
|
||||
: summary?.StoppedEarly == true ? SessionStopCause.StoppedEarly
|
||||
: SessionStopCause.Cancelled;
|
||||
|
||||
private async Task EndSessionAsync(SessionRecord record, SessionContext context, SessionOutcome outcome, EngineTask? outsideWindowTask, bool interrupted)
|
||||
{
|
||||
var s = _s;
|
||||
@@ -796,6 +878,10 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
|
||||
private void OnBreakerChanged(object? sender, BreakerState state)
|
||||
{
|
||||
// The diagnostic report records the signal that stopped the breaker, also one the detector never saw (the
|
||||
// session cookie lost, reported by the connection): a logout must not look like any other stop.
|
||||
_s.Diagnostics?.BreakerChanged(state);
|
||||
|
||||
// Signals arrive on capture threads: the engine is never run inline on them (it may need the browser to answer).
|
||||
// The composer also checks the breaker before every recipe, so the session stops at once either way.
|
||||
CancellationTokenSource? session = null;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
@@ -64,6 +65,12 @@ public sealed class EngineServices
|
||||
/// <summary>Current engine and caution settings.</summary>
|
||||
public EngineSettings Settings { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The recorder of the diagnostic report (issue #39): told when sessions start and end, and why. Null: nothing is
|
||||
/// recorded. Set by the composition before the engine starts.
|
||||
/// </summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Loads settings, pause flag, gradual-start origin and breaker state from the database. When the gradual start has
|
||||
/// no origin yet (first run after the first connection) it starts now.
|
||||
|
||||
@@ -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))
|
||||
{
|
||||
@@ -833,6 +985,7 @@ internal sealed class SessionComposer
|
||||
else if (recheck.Reason is DenialReason.BreakerOpen or DenialReason.OutsideActiveWindow or DenialReason.Paused or DenialReason.UserIsDriving)
|
||||
{
|
||||
state.Stop = true;
|
||||
state.StopStatus ??= outcome.Status;
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -850,6 +1003,7 @@ internal sealed class SessionComposer
|
||||
}
|
||||
|
||||
state.Stop = true;
|
||||
state.StopStatus ??= outcome.Status;
|
||||
break;
|
||||
|
||||
case RecipeStatus.TargetNotFound:
|
||||
@@ -861,6 +1015,7 @@ internal sealed class SessionComposer
|
||||
await RecordRecipeFailureAsync(kind, account, EngineEventCodes.TargetNotFound,
|
||||
$"Non trovo nella pagina ciò che serve per {RecipeName(kind)}{Of(account)}: mi fermo e lo segnalo, senza cliccare a caso.", now).ConfigureAwait(false);
|
||||
state.Stop = true;
|
||||
state.StopStatus ??= outcome.Status;
|
||||
break;
|
||||
|
||||
case RecipeStatus.UnrecognizedFormat:
|
||||
@@ -875,6 +1030,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 +1130,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 +1340,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);
|
||||
@@ -1206,6 +1383,9 @@ internal sealed class SessionComposer
|
||||
|
||||
public bool Stop { get; set; }
|
||||
|
||||
/// <summary>The recipe status that first set <see cref="Stop"/>, when a recipe did (diagnostic report).</summary>
|
||||
public RecipeStatus? StopStatus { get; set; }
|
||||
|
||||
public int Recipes { get; set; }
|
||||
|
||||
/// <summary>Next story check planned by the last visit of a profile not followed.</summary>
|
||||
@@ -1214,9 +1394,20 @@ internal sealed class SessionComposer
|
||||
/// <summary>Set while the stories of a visit run: their next check is the visit's.</summary>
|
||||
public DateTimeOffset? PendingStoriesNext { get; set; }
|
||||
|
||||
public SessionSummary Summary() => new(Recipes, Stop);
|
||||
public SessionSummary Summary() => new(Recipes, Stop)
|
||||
{
|
||||
StoppedEarlyBy = StopStatus,
|
||||
BudgetsExhausted = Exhausted.Count > 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a session did, for its row and its timeline line.</summary>
|
||||
internal sealed record SessionSummary(int Recipes, bool StoppedEarly);
|
||||
internal sealed record SessionSummary(int Recipes, bool StoppedEarly)
|
||||
{
|
||||
/// <summary>The recipe status that stopped the session early, when a recipe did (diagnostic report, issue #39).</summary>
|
||||
public RecipeStatus? StoppedEarlyBy { get; init; }
|
||||
|
||||
/// <summary>Some budget categories were used up during the session and their work skipped.</summary>
|
||||
public bool BudgetsExhausted { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
namespace Febe.Core.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Why an engine session ended (issue #39, diagnostic report). Finer than <see cref="Domain.SessionOutcome"/>, which
|
||||
/// puts most of these under «Stopped»; computed by <see cref="EngineHost"/> from what it already looks at, and never
|
||||
/// stored in the database.
|
||||
/// </summary>
|
||||
public enum SessionStopCause
|
||||
{
|
||||
/// <summary>The planned length of the session was reached.</summary>
|
||||
PlannedEnd,
|
||||
|
||||
/// <summary>Nothing else to do before the planned end.</summary>
|
||||
WorkDone,
|
||||
|
||||
/// <summary>Ended before the planned end with some budget categories used up (their work was skipped).</summary>
|
||||
BudgetsExhausted,
|
||||
|
||||
/// <summary>A recipe outcome stopped the session (see the recipe status that did).</summary>
|
||||
StoppedEarly,
|
||||
|
||||
/// <summary>The circuit breaker was open: a stop signal of spec §7.6.</summary>
|
||||
BreakerOpen,
|
||||
|
||||
/// <summary>Alberto paused the engine.</summary>
|
||||
Paused,
|
||||
|
||||
/// <summary>Alberto took the browser.</summary>
|
||||
UserDriving,
|
||||
|
||||
/// <summary>Cancelled for another reason.</summary>
|
||||
Cancelled,
|
||||
|
||||
/// <summary>Febe was shutting down.</summary>
|
||||
Shutdown,
|
||||
|
||||
/// <summary>An unexpected error closed the session.</summary>
|
||||
Failed,
|
||||
}
|
||||
@@ -128,6 +128,9 @@ public sealed record DataFolderLayout
|
||||
/// <summary>Dati/registro: rotating logs.</summary>
|
||||
public string Logs => Path.Combine(Root, "registro");
|
||||
|
||||
/// <summary>Dati/diagnostica: the traces of the diagnostic report, two weeks (issue #39).</summary>
|
||||
public string Diagnostics => Path.Combine(Root, "diagnostica");
|
||||
|
||||
/// <summary>Dati/segnali.json.</summary>
|
||||
public string SignalsFile => Path.Combine(Root, "segnali.json");
|
||||
}
|
||||
@@ -3,7 +3,7 @@ using Febe.Core.Storage;
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Settings of the library (spec §4.7, mockup 08): the library folder, the two naming schemes and whether the file
|
||||
/// Settings of the library (spec §4.7, mockup 08): the library folder, the three naming schemes and whether the file
|
||||
/// modification time is set to the publication time. Stored in the <c>setting</c> table.
|
||||
/// </summary>
|
||||
public sealed record LibrarySettings(string LibraryRoot, LibraryNaming Naming, bool SetFileTimeToPublication = true)
|
||||
@@ -18,12 +18,16 @@ public sealed record LibrarySettings(string LibraryRoot, LibraryNaming Naming, b
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(defaultLibraryRoot);
|
||||
var values = await store.GetAllAsync(ct).ConfigureAwait(false);
|
||||
var root = values.GetValueOrDefault(SettingKeys.LibraryRoot);
|
||||
var general = NamingScheme.Validate(values.GetValueOrDefault(SettingKeys.NamingScheme) ?? NamingScheme.DefaultGeneral, forHighlights: false);
|
||||
var highlight = NamingScheme.Validate(values.GetValueOrDefault(SettingKeys.HighlightNamingScheme) ?? NamingScheme.DefaultHighlight, forHighlights: true);
|
||||
NamingScheme Scheme(string key, NamingSchemeUse use) =>
|
||||
NamingScheme.Validate(values.GetValueOrDefault(key) ?? NamingScheme.Default(use).Text, use).Scheme ?? NamingScheme.Default(use);
|
||||
|
||||
var setTime = !values.TryGetValue(SettingKeys.SetFileTimeToPublication, out var text) || !bool.TryParse(text, out var parsed) || parsed;
|
||||
return new LibrarySettings(
|
||||
string.IsNullOrWhiteSpace(root) ? defaultLibraryRoot : root,
|
||||
new LibraryNaming(general.Scheme ?? NamingScheme.General, highlight.Scheme ?? NamingScheme.Highlight),
|
||||
new LibraryNaming(
|
||||
Scheme(SettingKeys.NamingScheme, NamingSchemeUse.General),
|
||||
Scheme(SettingKeys.HighlightNamingScheme, NamingSchemeUse.Highlight),
|
||||
Scheme(SettingKeys.ProfilePictureNamingScheme, NamingSchemeUse.ProfilePicture)),
|
||||
setTime);
|
||||
}
|
||||
|
||||
@@ -37,6 +41,7 @@ public sealed record LibrarySettings(string LibraryRoot, LibraryNaming Naming, b
|
||||
[SettingKeys.LibraryRoot] = LibraryRoot,
|
||||
[SettingKeys.NamingScheme] = Naming.General.Text,
|
||||
[SettingKeys.HighlightNamingScheme] = Naming.Highlight.Text,
|
||||
[SettingKeys.ProfilePictureNamingScheme] = Naming.ProfilePicture.Text,
|
||||
[SettingKeys.SetFileTimeToPublication] = SetFileTimeToPublication ? "true" : "false",
|
||||
},
|
||||
ct);
|
||||
|
||||
@@ -9,7 +9,7 @@ public sealed record NamingPreviewFile(string Name, MediaKind Kind);
|
||||
public sealed record NamingPreviewFolder(IReadOnlyList<string> Path, IReadOnlyList<NamingPreviewFile> Files);
|
||||
|
||||
/// <summary>
|
||||
/// The «Risultato» tree of the settings screen (mockup 08): an account folder with sample files rendered by the two
|
||||
/// The «Risultato» tree of the settings screen (mockup 08): an account folder with sample files rendered by the three
|
||||
/// schemes. The interface shows each folder path joined by « \ ».
|
||||
/// </summary>
|
||||
public sealed record NamingPreview(
|
||||
@@ -21,21 +21,25 @@ public sealed record NamingPreview(
|
||||
public bool IsValid => Errors.Count == 0;
|
||||
|
||||
/// <summary>
|
||||
/// Renders three sample files — a post photo (second of a series), a story video and a highlight photo — with the
|
||||
/// given schemes. Sample times are local times in <paramref name="zone"/>, so the preview reads the same anywhere.
|
||||
/// Renders four sample files — a post photo (second of a series), a story video, a highlight photo and a profile
|
||||
/// picture — with the given schemes. Sample times are local times in <paramref name="zone"/>, so the preview reads
|
||||
/// the same anywhere. Each error and warning starts with the name of its scheme (<see cref="Prefix"/>).
|
||||
/// </summary>
|
||||
public static NamingPreview Build(string? generalScheme, string? highlightScheme, TimeZoneInfo zone, string sampleAccount = "nome.utente")
|
||||
public static NamingPreview Build(string? generalScheme, string? highlightScheme, string? profilePictureScheme, TimeZoneInfo zone, string sampleAccount = "nome.utente")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(sampleAccount);
|
||||
var general = NamingScheme.Validate(generalScheme, forHighlights: false);
|
||||
var highlight = NamingScheme.Validate(highlightScheme, forHighlights: true);
|
||||
var errors = general.Errors.Select(e => "Schema: " + e)
|
||||
.Concat(highlight.Errors.Select(e => "Schema per le raccolte in evidenza: " + e))
|
||||
.ToList();
|
||||
var warnings = general.Warnings.Select(e => "Schema: " + e)
|
||||
.Concat(highlight.Warnings.Select(e => "Schema per le raccolte in evidenza: " + e))
|
||||
.ToList();
|
||||
var general = NamingScheme.Validate(generalScheme, NamingSchemeUse.General);
|
||||
var highlight = NamingScheme.Validate(highlightScheme, NamingSchemeUse.Highlight);
|
||||
var profile = NamingScheme.Validate(profilePictureScheme, NamingSchemeUse.ProfilePicture);
|
||||
(NamingSchemeValidation Validation, string Prefix)[] all =
|
||||
[
|
||||
(general, Prefix(NamingSchemeUse.General)),
|
||||
(highlight, Prefix(NamingSchemeUse.Highlight)),
|
||||
(profile, Prefix(NamingSchemeUse.ProfilePicture)),
|
||||
];
|
||||
var errors = all.SelectMany(s => s.Validation.Errors.Select(e => s.Prefix + e)).ToList();
|
||||
var warnings = all.SelectMany(s => s.Validation.Warnings.Select(e => s.Prefix + e)).ToList();
|
||||
|
||||
var folders = new List<NamingPreviewFolder>();
|
||||
void Add(NamingScheme scheme, EntryKind kind, DateTime local, string code, int n, MediaKind media, string? collection)
|
||||
@@ -73,6 +77,22 @@ public sealed record NamingPreview(
|
||||
Add(h, EntryKind.Highlight, new DateTime(2025, 8, 2, 10, 11, 12), "3391207", 1, MediaKind.Photo, "Estate 2025");
|
||||
}
|
||||
|
||||
if (profile.Scheme is { } p)
|
||||
{
|
||||
Add(p, EntryKind.ProfilePicture, new DateTime(2026, 9, 30, 21, 4, 33), "a3f9c2e1", 1, MediaKind.Photo, null);
|
||||
}
|
||||
|
||||
return new NamingPreview(WindowsFileNames.SanitizeSegment(sampleAccount), folders, errors, warnings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The start of the errors and warnings of a scheme («Schema: », «Schema per le raccolte in evidenza: », «Schema
|
||||
/// per le foto del profilo: »): the settings screen uses it to mark the field in error.
|
||||
/// </summary>
|
||||
public static string Prefix(NamingSchemeUse use) => use switch
|
||||
{
|
||||
NamingSchemeUse.Highlight => "Schema per le raccolte in evidenza: ",
|
||||
NamingSchemeUse.ProfilePicture => "Schema per le foto del profilo: ",
|
||||
_ => "Schema: ",
|
||||
};
|
||||
}
|
||||
@@ -9,7 +9,8 @@ namespace Febe.Core.Library;
|
||||
/// <para>
|
||||
/// A backslash (or a slash) separates folders on every operating system. Placeholders: <c>account</c>, <c>tipo</c>,
|
||||
/// <c>anno</c>, <c>mese</c>, <c>data</c>, <c>ora</c>, <c>codice</c>, <c>n</c>, <c>raccolta</c> (only in the scheme of
|
||||
/// highlight collections). Dates and times are in Alberto's time zone: <c>data</c> is yyyy-MM-dd and <c>ora</c> is
|
||||
/// highlight collections). There are three schemes (<see cref="NamingSchemeUse"/>): general, highlight collections and
|
||||
/// profile pictures, so that each of the last two keeps its own folder whatever the general scheme says. Dates and times are in Alberto's time zone: <c>data</c> is yyyy-MM-dd and <c>ora</c> is
|
||||
/// HH-mm-ss. The file extension is added to the last segment.
|
||||
/// </para>
|
||||
/// <para>
|
||||
@@ -23,33 +24,57 @@ public sealed class NamingScheme
|
||||
|
||||
public const string DefaultHighlight = @"{account}\evidenza\{raccolta}\{data}_{ora}_{codice}_{n}";
|
||||
|
||||
/// <summary>
|
||||
/// Profile pictures: few per account, so no year folder. <c>{codice}</c> is the start of the SHA-256 (spec §4.3);
|
||||
/// <c>{n}</c> is always 1, kept so that the names read like the others and the import recognizes them.
|
||||
/// </summary>
|
||||
public const string DefaultProfilePicture = @"{account}\profilo\{data}_{ora}_{codice}_{n}";
|
||||
|
||||
/// <summary>Placeholders accepted, in the order shown in the interface.</summary>
|
||||
public static IReadOnlyList<string> Placeholders { get; } = ["account", "tipo", "anno", "mese", "data", "ora", "codice", "n", "raccolta"];
|
||||
|
||||
private readonly IReadOnlyList<IReadOnlyList<Token>> _segments;
|
||||
|
||||
private NamingScheme(string text, bool forHighlights, IReadOnlyList<IReadOnlyList<Token>> segments)
|
||||
private NamingScheme(string text, NamingSchemeUse use, IReadOnlyList<IReadOnlyList<Token>> segments)
|
||||
{
|
||||
Text = text;
|
||||
ForHighlights = forHighlights;
|
||||
Use = use;
|
||||
_segments = segments;
|
||||
}
|
||||
|
||||
/// <summary>The scheme as written.</summary>
|
||||
public string Text { get; }
|
||||
|
||||
/// <summary>Which files the scheme names.</summary>
|
||||
public NamingSchemeUse Use { get; }
|
||||
|
||||
/// <summary>True for the scheme of highlight collections (accepts <c>{raccolta}</c>).</summary>
|
||||
public bool ForHighlights { get; }
|
||||
public bool ForHighlights => Use == NamingSchemeUse.Highlight;
|
||||
|
||||
public static NamingScheme General { get; } = Parse(DefaultGeneral, forHighlights: false);
|
||||
public static NamingScheme General { get; } = Parse(DefaultGeneral, NamingSchemeUse.General);
|
||||
|
||||
public static NamingScheme Highlight { get; } = Parse(DefaultHighlight, forHighlights: true);
|
||||
public static NamingScheme Highlight { get; } = Parse(DefaultHighlight, NamingSchemeUse.Highlight);
|
||||
|
||||
/// <summary>Parses a scheme. </summary>
|
||||
/// <exception cref="FormatException">The scheme is not valid; the message (Italian) says why.</exception>
|
||||
public static NamingScheme Parse(string text, bool forHighlights)
|
||||
public static NamingScheme ProfilePicture { get; } = Parse(DefaultProfilePicture, NamingSchemeUse.ProfilePicture);
|
||||
|
||||
/// <summary>The default scheme for a use.</summary>
|
||||
public static NamingScheme Default(NamingSchemeUse use) => use switch
|
||||
{
|
||||
var validation = Validate(text, forHighlights);
|
||||
NamingSchemeUse.Highlight => Highlight,
|
||||
NamingSchemeUse.ProfilePicture => ProfilePicture,
|
||||
_ => General,
|
||||
};
|
||||
|
||||
/// <summary>Parses the general scheme or the one of highlight collections.</summary>
|
||||
/// <exception cref="FormatException">The scheme is not valid; the message (Italian) says why.</exception>
|
||||
public static NamingScheme Parse(string text, bool forHighlights) =>
|
||||
Parse(text, forHighlights ? NamingSchemeUse.Highlight : NamingSchemeUse.General);
|
||||
|
||||
/// <summary>Parses a scheme.</summary>
|
||||
/// <exception cref="FormatException">The scheme is not valid; the message (Italian) says why.</exception>
|
||||
public static NamingScheme Parse(string text, NamingSchemeUse use)
|
||||
{
|
||||
var validation = Validate(text, use);
|
||||
if (!validation.IsValid)
|
||||
{
|
||||
throw new FormatException(validation.Errors[0]);
|
||||
@@ -58,8 +83,12 @@ public sealed class NamingScheme
|
||||
return validation.Scheme!;
|
||||
}
|
||||
|
||||
/// <summary>Checks the general scheme or the one of highlight collections.</summary>
|
||||
public static NamingSchemeValidation Validate(string? text, bool forHighlights) =>
|
||||
Validate(text, forHighlights ? NamingSchemeUse.Highlight : NamingSchemeUse.General);
|
||||
|
||||
/// <summary>Checks a scheme for the settings screen: errors block saving, warnings are shown.</summary>
|
||||
public static NamingSchemeValidation Validate(string? text, bool forHighlights)
|
||||
public static NamingSchemeValidation Validate(string? text, NamingSchemeUse use)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
var warnings = new List<string>();
|
||||
@@ -90,7 +119,7 @@ public sealed class NamingScheme
|
||||
{
|
||||
errors.Add($"Segnaposto sconosciuto: {{{token.Value}}}. Quelli ammessi sono: {string.Join(", ", Placeholders)}.");
|
||||
}
|
||||
else if (token.Value == "raccolta" && !forHighlights)
|
||||
else if (token.Value == "raccolta" && use != NamingSchemeUse.Highlight)
|
||||
{
|
||||
errors.Add("{raccolta} si usa solo nello schema per le raccolte in evidenza.");
|
||||
}
|
||||
@@ -110,7 +139,15 @@ public sealed class NamingScheme
|
||||
segments.RemoveAt(0);
|
||||
}
|
||||
|
||||
if (!used.Contains("codice") && !used.Contains("n"))
|
||||
if (use == NamingSchemeUse.ProfilePicture)
|
||||
{
|
||||
// One file per picture: {n} is always 1, and {codice} (the start of the SHA-256) tells the pictures apart.
|
||||
if (!used.Contains("codice"))
|
||||
{
|
||||
warnings.Add("Senza {codice} due foto del profilo possono avere lo stesso nome: Febe aggiunge un numero per distinguerle.");
|
||||
}
|
||||
}
|
||||
else if (!used.Contains("codice") && !used.Contains("n"))
|
||||
{
|
||||
warnings.Add("Senza {codice} e {n} più file possono avere lo stesso nome: Febe aggiunge un numero per distinguerli.");
|
||||
}
|
||||
@@ -119,12 +156,12 @@ public sealed class NamingScheme
|
||||
warnings.Add("Senza {n} i file di un post con più foto o video hanno lo stesso nome: Febe aggiunge un numero per distinguerli.");
|
||||
}
|
||||
|
||||
if (forHighlights && !used.Contains("raccolta"))
|
||||
if (use == NamingSchemeUse.Highlight && !used.Contains("raccolta"))
|
||||
{
|
||||
warnings.Add("Senza {raccolta} i contenuti delle diverse raccolte finiscono nella stessa cartella.");
|
||||
}
|
||||
|
||||
return new NamingSchemeValidation(new NamingScheme(text.Trim(), forHighlights, segments), [], warnings);
|
||||
return new NamingSchemeValidation(new NamingScheme(text.Trim(), use, segments), [], warnings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -241,7 +278,20 @@ public sealed class NamingScheme
|
||||
private readonly record struct Token(bool IsPlaceholder, string Value);
|
||||
}
|
||||
|
||||
/// <summary>Result of <see cref="NamingScheme.Validate"/>.</summary>
|
||||
/// <summary>Which files a naming scheme names (spec §4.7).</summary>
|
||||
public enum NamingSchemeUse
|
||||
{
|
||||
/// <summary>Posts, stories and tagged posts.</summary>
|
||||
General,
|
||||
|
||||
/// <summary>Contents of highlight collections (accepts <c>{raccolta}</c>).</summary>
|
||||
Highlight,
|
||||
|
||||
/// <summary>Profile pictures.</summary>
|
||||
ProfilePicture,
|
||||
}
|
||||
|
||||
/// <summary>Result of <see cref="NamingScheme.Validate(string?, NamingSchemeUse)"/>.</summary>
|
||||
public sealed record NamingSchemeValidation(NamingScheme? Scheme, IReadOnlyList<string> Errors, IReadOnlyList<string> Warnings)
|
||||
{
|
||||
public bool IsValid => Scheme is not null && Errors.Count == 0;
|
||||
@@ -272,11 +322,16 @@ public sealed record NamingValues(
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The two configurable schemes (spec §4.7): general and for highlight collections.</summary>
|
||||
public sealed record LibraryNaming(NamingScheme General, NamingScheme Highlight)
|
||||
/// <summary>The three configurable schemes (spec §4.7): general, highlight collections and profile pictures.</summary>
|
||||
public sealed record LibraryNaming(NamingScheme General, NamingScheme Highlight, NamingScheme ProfilePicture)
|
||||
{
|
||||
public static LibraryNaming Default { get; } = new(NamingScheme.General, NamingScheme.Highlight);
|
||||
public static LibraryNaming Default { get; } = new(NamingScheme.General, NamingScheme.Highlight, NamingScheme.ProfilePicture);
|
||||
|
||||
/// <summary>The scheme that applies to an entry kind.</summary>
|
||||
public NamingScheme For(EntryKind kind) => kind == EntryKind.Highlight ? Highlight : General;
|
||||
public NamingScheme For(EntryKind kind) => kind switch
|
||||
{
|
||||
EntryKind.Highlight => Highlight,
|
||||
EntryKind.ProfilePicture => ProfilePicture,
|
||||
_ => General,
|
||||
};
|
||||
}
|
||||
@@ -28,6 +28,9 @@ public static class SettingKeys
|
||||
/// <summary>Naming scheme for highlight collections.</summary>
|
||||
public const string HighlightNamingScheme = "libreria.schema-evidenza";
|
||||
|
||||
/// <summary>Naming scheme for profile pictures.</summary>
|
||||
public const string ProfilePictureNamingScheme = "libreria.schema-profilo";
|
||||
|
||||
/// <summary>«Imposta la data del file a quella di pubblicazione» (true/false).</summary>
|
||||
public const string SetFileTimeToPublication = "libreria.data-file-pubblicazione";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Febe.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the commands that <see cref="Sql.Command"/> creates on this thread while a read runs, and disposes them when the
|
||||
/// read ends. Reads build their commands inline (<c>c.Command(...).ExecuteReader()</c>); left to the garbage collector,
|
||||
/// a command keeps its SQLite statement alive until the finalizer runs, so the connection closed by
|
||||
/// <see cref="FebeDatabase.DisposeAsync"/> would only really close then, keeping the files open (#46).
|
||||
/// </summary>
|
||||
internal sealed class CommandScope : IDisposable
|
||||
{
|
||||
[ThreadStatic]
|
||||
private static CommandScope? t_current;
|
||||
|
||||
private readonly CommandScope? _outer;
|
||||
private readonly List<SqliteCommand> _commands = [];
|
||||
|
||||
private CommandScope(CommandScope? outer) => _outer = outer;
|
||||
|
||||
/// <summary>Starts tracking the commands created on this thread until the scope is disposed.</summary>
|
||||
public static CommandScope Begin() => t_current = new CommandScope(t_current);
|
||||
|
||||
/// <summary>Adds <paramref name="command"/> to the open scope of this thread, if any.</summary>
|
||||
public static void Track(SqliteCommand command) => t_current?._commands.Add(command);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
t_current = _outer;
|
||||
foreach (var command in _commands)
|
||||
{
|
||||
command.Dispose();
|
||||
}
|
||||
|
||||
_commands.Clear();
|
||||
}
|
||||
}
|
||||
@@ -118,16 +118,16 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
|
||||
try
|
||||
{
|
||||
connection.Open();
|
||||
var mode = connection.Command("PRAGMA journal_mode = WAL").ExecuteScalar() as string;
|
||||
var mode = connection.Scalar("PRAGMA journal_mode = WAL") as string;
|
||||
if (!string.Equals(mode, "wal", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new DatabaseMigrationException(
|
||||
$"Febe non riesce a mettere il database in modalità WAL (modalità attuale: {mode}). La cartella dei dati deve stare su un disco locale.");
|
||||
}
|
||||
|
||||
connection.Command("PRAGMA synchronous = NORMAL").ExecuteNonQuery();
|
||||
connection.Command($"PRAGMA busy_timeout = {BusyTimeoutMs}").ExecuteNonQuery();
|
||||
connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery();
|
||||
connection.Execute("PRAGMA synchronous = NORMAL");
|
||||
connection.Execute($"PRAGMA busy_timeout = {BusyTimeoutMs}");
|
||||
connection.Execute("PRAGMA foreign_keys = ON");
|
||||
var version = MigrationRunner.Apply(connection, migrations);
|
||||
return new FebeDatabase(path, connection, readConnectionString, version);
|
||||
}
|
||||
@@ -155,6 +155,7 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
|
||||
try
|
||||
{
|
||||
using var connection = OpenReadConnection();
|
||||
using var commands = CommandScope.Begin(); // disposed first: the connection then really closes
|
||||
return Task.FromResult(work(connection));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
@@ -184,7 +185,8 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
|
||||
connection =>
|
||||
{
|
||||
// VACUUM INTO reads a consistent snapshot; it works on a read-only connection and does not block the writer.
|
||||
connection.Command("VACUUM INTO @destination").With("@destination", destination).ExecuteNonQuery();
|
||||
using var vacuum = connection.Command("VACUUM INTO @destination").With("@destination", destination);
|
||||
vacuum.ExecuteNonQuery();
|
||||
return true;
|
||||
},
|
||||
ct);
|
||||
@@ -210,9 +212,17 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
|
||||
}
|
||||
|
||||
Writer.Dispose();
|
||||
|
||||
// The idle read connections close first, so the writer is the last connection: only the writer can checkpoint
|
||||
// and delete febe.sqlite-wal and -shm when it closes (a read-only connection leaves them behind).
|
||||
using (var pooled = new SqliteConnection(_readConnectionString))
|
||||
{
|
||||
SqliteConnection.ClearPool(pooled);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_writerConnection.Command("PRAGMA wal_checkpoint(TRUNCATE)").ExecuteNonQuery();
|
||||
_writerConnection.Execute("PRAGMA wal_checkpoint(TRUNCATE)");
|
||||
}
|
||||
catch (SqliteException)
|
||||
{
|
||||
@@ -220,11 +230,6 @@ public sealed class FebeDatabase : IFebeStorage, IDatabaseMaintenance
|
||||
}
|
||||
|
||||
_writerConnection.Dispose();
|
||||
using (var pooled = new SqliteConnection(_readConnectionString))
|
||||
{
|
||||
SqliteConnection.ClearPool(pooled);
|
||||
}
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,7 @@ internal static partial class MigrationRunner
|
||||
}
|
||||
|
||||
public static int GetVersion(SqliteConnection connection) =>
|
||||
(int)connection.Command("PRAGMA user_version").ScalarInt64();
|
||||
Convert.ToInt32(connection.Scalar("PRAGMA user_version"), CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>Applies the pending migrations. Returns the resulting version.</summary>
|
||||
public static int Apply(SqliteConnection connection, IReadOnlyList<Migration> migrations)
|
||||
@@ -97,7 +97,7 @@ internal static partial class MigrationRunner
|
||||
}
|
||||
|
||||
// Table rebuilds in later migrations need foreign keys off; they are checked before each commit instead.
|
||||
connection.Command("PRAGMA foreign_keys = OFF").ExecuteNonQuery();
|
||||
connection.Execute("PRAGMA foreign_keys = OFF");
|
||||
try
|
||||
{
|
||||
foreach (var migration in migrations.Where(m => m.Version > current))
|
||||
@@ -105,8 +105,9 @@ internal static partial class MigrationRunner
|
||||
using var transaction = connection.BeginTransaction(deferred: false);
|
||||
try
|
||||
{
|
||||
connection.Command(migration.Sql, transaction).ExecuteNonQuery();
|
||||
using (var check = connection.Command("PRAGMA foreign_key_check", transaction).ExecuteReader())
|
||||
connection.Execute(migration.Sql, transaction);
|
||||
using (var checkCommand = connection.Command("PRAGMA foreign_key_check", transaction))
|
||||
using (var check = checkCommand.ExecuteReader())
|
||||
{
|
||||
if (check.Read())
|
||||
{
|
||||
@@ -115,8 +116,7 @@ internal static partial class MigrationRunner
|
||||
}
|
||||
}
|
||||
|
||||
connection.Command(string.Create(CultureInfo.InvariantCulture, $"PRAGMA user_version = {migration.Version}"), transaction)
|
||||
.ExecuteNonQuery();
|
||||
connection.Execute(string.Create(CultureInfo.InvariantCulture, $"PRAGMA user_version = {migration.Version}"), transaction);
|
||||
transaction.Commit();
|
||||
}
|
||||
catch (Exception ex) when (ex is SqliteException or DatabaseMigrationException)
|
||||
@@ -130,7 +130,7 @@ internal static partial class MigrationRunner
|
||||
}
|
||||
finally
|
||||
{
|
||||
connection.Command("PRAGMA foreign_keys = ON").ExecuteNonQuery();
|
||||
connection.Execute("PRAGMA foreign_keys = ON");
|
||||
}
|
||||
|
||||
return GetVersion(connection);
|
||||
|
||||
@@ -75,9 +75,28 @@ internal static class Sql
|
||||
var command = connection.CreateCommand();
|
||||
command.CommandText = sql;
|
||||
command.Transaction = transaction;
|
||||
CommandScope.Track(command);
|
||||
return command;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs a statement and disposes its command at once. A command left to the garbage collector keeps its SQLite
|
||||
/// statement alive until the finalizer runs, and a connection closed meanwhile only closes then: the WAL and its
|
||||
/// handles outlive <see cref="FebeDatabase.DisposeAsync"/> (#46).
|
||||
/// </summary>
|
||||
public static int Execute(this SqliteConnection connection, string sql, SqliteTransaction? transaction = null)
|
||||
{
|
||||
using var command = connection.Command(sql, transaction);
|
||||
return command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
/// <summary>Runs a query for one value and disposes its command at once (see <see cref="Execute"/>).</summary>
|
||||
public static object? Scalar(this SqliteConnection connection, string sql)
|
||||
{
|
||||
using var command = connection.Command(sql);
|
||||
return command.ExecuteScalar();
|
||||
}
|
||||
|
||||
/// <summary>Sets a parameter, adding it the first time: a prepared command can be run again with new values.</summary>
|
||||
public static SqliteCommand With(this SqliteCommand command, string name, object? value)
|
||||
{
|
||||
|
||||
@@ -221,14 +221,21 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore
|
||||
}
|
||||
}
|
||||
|
||||
var bytes = c.Command("""
|
||||
SELECT COALESCE(SUM(m.bytes), 0) FROM media m JOIN entry e ON e.id = m.entry_id
|
||||
WHERE e.account_id = @a AND m.state IN ('Downloaded', 'Imported')
|
||||
""").With("@a", accountId).ScalarInt64();
|
||||
var pending = c.Command("""
|
||||
SELECT COUNT(*) FROM media m JOIN entry e ON e.id = m.entry_id
|
||||
WHERE e.account_id = @a AND m.state IN ('ToDownload', 'Expired')
|
||||
""").With("@a", accountId).ScalarInt64();
|
||||
// One pass over the account's files, driven from its entries (CROSS JOIN keeps entry as the outer loop):
|
||||
// without ANALYZE statistics SQLite otherwise starts from the media state index and reads the files of
|
||||
// the whole library for one account's card (#46).
|
||||
long bytes, pending;
|
||||
using (var r = c.Command("""
|
||||
SELECT COALESCE(SUM(CASE WHEN m.state IN ('Downloaded', 'Imported') THEN m.bytes END), 0),
|
||||
COALESCE(SUM(m.state IN ('ToDownload', 'Expired')), 0)
|
||||
FROM entry e CROSS JOIN media m ON m.entry_id = e.id
|
||||
WHERE e.account_id = @a
|
||||
""").With("@a", accountId).ExecuteReader())
|
||||
{
|
||||
r.Read();
|
||||
bytes = r.GetInt64(0);
|
||||
pending = r.GetInt64(1);
|
||||
}
|
||||
var collections = c.Command("SELECT COUNT(*) FROM highlight WHERE account_id = @a AND removed_at IS NULL")
|
||||
.With("@a", accountId).ScalarInt64();
|
||||
|
||||
|
||||
@@ -2,9 +2,11 @@ using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Web.Demo;
|
||||
using Febe.Web.Engine;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -14,13 +16,20 @@ namespace Febe.Web.Api;
|
||||
|
||||
/// <summary>
|
||||
/// What the Attività page needs beside the engine snapshot (spec §7.6, §7.9, mockups 06 and 11): the history of the
|
||||
/// stops, the still frame of the browser, the probable duplicates waiting for Alberto.
|
||||
/// stops, the still frame of the browser, the probable duplicates waiting for Alberto, the diagnostic report.
|
||||
/// </summary>
|
||||
public static class ActivityApi
|
||||
{
|
||||
/// <summary>Days of stops shown by the page.</summary>
|
||||
public const int HistoryDays = 14;
|
||||
|
||||
/// <summary>
|
||||
/// «Esporta il rapporto di diagnostica» (issue #39, spec §7.9): the traces of the engine sessions of the last two
|
||||
/// weeks as a JSON file to send, with no data value in it. Also answered with a configuration problem, where the
|
||||
/// engine never started and the report is empty.
|
||||
/// </summary>
|
||||
public const string DiagnosticsPath = "/api/engine/diagnostica";
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapGet("/api/engine/incidents", async (IIncidentHistory history, IClock clock, CancellationToken ct) =>
|
||||
@@ -56,8 +65,37 @@ public static class ActivityApi
|
||||
var import = await storage.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct).ConfigureAwait(false);
|
||||
return ApiHttp.Json(new DuplicateCountsDto(download, import), FebeJsonContext.Default.DuplicateCountsDto);
|
||||
});
|
||||
|
||||
endpoints.MapGet(DiagnosticsPath, async (HttpContext context, IDiagnosticSource source, FebeWebOptions options, IClock clock, CancellationToken ct) =>
|
||||
{
|
||||
var gathered = await source.GatherAsync(ct).ConfigureAwait(false);
|
||||
var now = clock.Now;
|
||||
var zone = clock.LocalZone;
|
||||
var edition = options.Demo ? DemoRequest.Edition(context) ?? FebeEdition.Desktop : options.Edition;
|
||||
|
||||
// Written whole before answering: a failure becomes an error message, never half a file.
|
||||
using var buffer = new MemoryStream();
|
||||
DiagnosticReport.Write(
|
||||
buffer,
|
||||
gathered.Traces,
|
||||
new DiagnosticReportHeader(
|
||||
options.Version,
|
||||
EditionName(edition),
|
||||
now,
|
||||
zone,
|
||||
DamagedLines: gathered.DamagedLines,
|
||||
RecorderFaults: gathered.RecorderFaults,
|
||||
UnreadableFiles: gathered.UnreadableFiles,
|
||||
UnfinishedSessions: gathered.UnfinishedSessions));
|
||||
context.Response.Headers.ContentDisposition = $"attachment; filename=\"{DiagnosticReport.FileName(now, zone)}\"";
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
return Results.Bytes(buffer.ToArray(), "application/json; charset=utf-8");
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The «edizione» of the diagnostic report.</summary>
|
||||
public static string EditionName(FebeEdition edition) => edition == FebeEdition.Desktop ? "windows" : "docker";
|
||||
|
||||
public static async Task<IncidentListDto> IncidentsAsync(IIncidentHistory history, IClock clock, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(history);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ public sealed record NamingPreviewFileDto(string Name, string Kind);
|
||||
|
||||
public sealed record NamingPreviewFolderDto(IReadOnlyList<string> Path, IReadOnlyList<NamingPreviewFileDto> Files);
|
||||
|
||||
/// <summary>The «Risultato» tree of mockup 08 and the problems of the two schemes.</summary>
|
||||
/// <summary>The «Risultato» tree of mockup 08 and the problems of the three schemes.</summary>
|
||||
public sealed record NamingPreviewDto(string AccountFolder, IReadOnlyList<NamingPreviewFolderDto> Folders, IReadOnlyList<string> Errors, IReadOnlyList<string> Warnings);
|
||||
|
||||
/// <summary>Impostazioni, Generali (mockup 08).</summary>
|
||||
@@ -71,8 +71,10 @@ public sealed record GeneralSettingsDto(
|
||||
bool CanChangeDataFolder,
|
||||
string NamingScheme,
|
||||
string HighlightScheme,
|
||||
string ProfilePictureScheme,
|
||||
string DefaultNamingScheme,
|
||||
string DefaultHighlightScheme,
|
||||
string DefaultProfilePictureScheme,
|
||||
IReadOnlyList<string> Placeholders,
|
||||
bool SetFileTime,
|
||||
NamingPreviewDto Preview,
|
||||
@@ -80,10 +82,14 @@ public sealed record GeneralSettingsDto(
|
||||
bool KeepInTray,
|
||||
string Language);
|
||||
|
||||
/// <summary>Saves Impostazioni, Generali. A null <see cref="LibraryFolder"/> keeps the library folder.</summary>
|
||||
public sealed record GeneralSettingsRequest(string? LibraryFolder, string NamingScheme, string HighlightScheme, bool SetFileTime, bool? Autostart, bool? KeepInTray);
|
||||
/// <summary>
|
||||
/// Saves Impostazioni, Generali. A null <see cref="LibraryFolder"/> keeps the library folder; a null
|
||||
/// <see cref="ProfilePictureScheme"/> keeps the scheme of profile pictures.
|
||||
/// </summary>
|
||||
public sealed record GeneralSettingsRequest(string? LibraryFolder, string NamingScheme, string HighlightScheme, bool SetFileTime, bool? Autostart, bool? KeepInTray, string? ProfilePictureScheme = null);
|
||||
|
||||
public sealed record NamingRequest(string? NamingScheme, string? HighlightScheme);
|
||||
/// <summary>The schemes to preview; a null <see cref="ProfilePictureScheme"/> stands for the default one.</summary>
|
||||
public sealed record NamingRequest(string? NamingScheme, string? HighlightScheme, string? ProfilePictureScheme = null);
|
||||
|
||||
/// <summary><see cref="Which"/>: library or data.</summary>
|
||||
public sealed record PickFolderRequest(string Which);
|
||||
|
||||
@@ -38,8 +38,14 @@ public static class SettingsApi
|
||||
{
|
||||
var d = Deps.From(services);
|
||||
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.GeneralSettingsRequest).ConfigureAwait(false);
|
||||
var general = Validate(NamingScheme.Validate(body.NamingScheme, forHighlights: false), "Schema");
|
||||
var highlight = Validate(NamingScheme.Validate(body.HighlightScheme, forHighlights: true), "Schema per le raccolte in evidenza");
|
||||
var general = Validate(NamingScheme.Validate(body.NamingScheme, NamingSchemeUse.General), NamingSchemeUse.General);
|
||||
var highlight = Validate(NamingScheme.Validate(body.HighlightScheme, NamingSchemeUse.Highlight), NamingSchemeUse.Highlight);
|
||||
|
||||
// A request without the scheme of profile pictures keeps the stored one.
|
||||
var profile = body.ProfilePictureScheme is { } profileText
|
||||
? Validate(NamingScheme.Validate(profileText, NamingSchemeUse.ProfilePicture), NamingSchemeUse.ProfilePicture)
|
||||
: (await LibrarySettings.LoadAsync(d.Storage.Settings, d.Library.Layout.Root, ct).ConfigureAwait(false)).Naming.ProfilePicture;
|
||||
var naming = new LibraryNaming(general, highlight, profile);
|
||||
var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock);
|
||||
var root = d.Library.Layout.Root;
|
||||
if (!string.IsNullOrWhiteSpace(body.LibraryFolder) && !SamePath(body.LibraryFolder, root))
|
||||
@@ -52,7 +58,7 @@ public static class SettingsApi
|
||||
root = await ChangeLibraryRootAsync(d, body.LibraryFolder, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await new LibrarySettings(root, new LibraryNaming(general, highlight), body.SetFileTime).SaveAsync(d.Storage.Settings, ct).ConfigureAwait(false);
|
||||
await new LibrarySettings(root, naming, body.SetFileTime).SaveAsync(d.Storage.Settings, ct).ConfigureAwait(false);
|
||||
if (caps.Autostart && body.Autostart is { } autostart)
|
||||
{
|
||||
await d.Shell.SetAutostartAsync(autostart, ct).ConfigureAwait(false);
|
||||
@@ -67,7 +73,7 @@ public static class SettingsApi
|
||||
if (d.Services.GetService(typeof(Febe.Core.Library.LibraryIngest)) is Febe.Core.Library.LibraryIngest ingest)
|
||||
{
|
||||
// The scheme and a new library folder (desktop) hold for the next downloads, without a restart.
|
||||
ingest.Apply(new LibraryNaming(general, highlight), body.SetFileTime);
|
||||
ingest.Apply(naming, body.SetFileTime);
|
||||
ingest.UseLayout(d.Library.Layout);
|
||||
}
|
||||
d.Changes.Publish(new LibraryChange(d.Clock.Now, null, "settings"));
|
||||
@@ -78,7 +84,8 @@ public static class SettingsApi
|
||||
{
|
||||
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.NamingRequest).ConfigureAwait(false);
|
||||
var sample = await SampleAccountAsync(storage, ct).ConfigureAwait(false);
|
||||
return ApiHttp.Json(Preview(NamingPreview.Build(body.NamingScheme, body.HighlightScheme, clock.LocalZone, sample)), FebeJsonContext.Default.NamingPreviewDto);
|
||||
var profile = body.ProfilePictureScheme ?? NamingScheme.DefaultProfilePicture;
|
||||
return ApiHttp.Json(Preview(NamingPreview.Build(body.NamingScheme, body.HighlightScheme, profile, clock.LocalZone, sample)), FebeJsonContext.Default.NamingPreviewDto);
|
||||
});
|
||||
|
||||
endpoints.MapPost("/api/settings/pick-folder", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
|
||||
@@ -268,11 +275,13 @@ public static class SettingsApi
|
||||
!caps.FoldersReadOnly && (dataChange?.CanChange ?? false),
|
||||
settings.Naming.General.Text,
|
||||
settings.Naming.Highlight.Text,
|
||||
settings.Naming.ProfilePicture.Text,
|
||||
NamingScheme.DefaultGeneral,
|
||||
NamingScheme.DefaultHighlight,
|
||||
NamingScheme.DefaultProfilePicture,
|
||||
NamingScheme.Placeholders,
|
||||
settings.SetFileTimeToPublication,
|
||||
Preview(NamingPreview.Build(settings.Naming.General.Text, settings.Naming.Highlight.Text, d.Clock.LocalZone, sample)),
|
||||
Preview(NamingPreview.Build(settings.Naming.General.Text, settings.Naming.Highlight.Text, settings.Naming.ProfilePicture.Text, d.Clock.LocalZone, sample)),
|
||||
autostart,
|
||||
tray,
|
||||
"it");
|
||||
@@ -297,14 +306,14 @@ public static class SettingsApi
|
||||
?? "nome.utente";
|
||||
}
|
||||
|
||||
private static NamingScheme Validate(NamingSchemeValidation validation, string name)
|
||||
private static NamingScheme Validate(NamingSchemeValidation validation, NamingSchemeUse use)
|
||||
{
|
||||
if (validation.IsValid)
|
||||
{
|
||||
return validation.Scheme!;
|
||||
}
|
||||
|
||||
throw new BadRequestException(string.Join(" ", validation.Errors.Select(e => $"{name}: {e}")));
|
||||
throw new BadRequestException(string.Join(" ", validation.Errors.Select(e => NamingPreview.Prefix(use) + e)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -44,9 +44,13 @@ public static class HealthEndpoint
|
||||
/// </summary>
|
||||
public sealed class ConfigurationGateMiddleware(RequestDelegate next, IConfigurationProblems problems)
|
||||
{
|
||||
/// <summary>API addresses still answered while there is a problem.</summary>
|
||||
/// <summary>
|
||||
/// API addresses still answered while there is a problem. The diagnostic report is among them, so that its address
|
||||
/// never answers with an error: it holds no data value, and with a configuration problem it is empty (the engine
|
||||
/// never started, nothing was recorded).
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> AllowedApi =
|
||||
["/api/capabilities", "/api/preferences", "/api/accesso", "/api/uscita", "/api/engine", "/api/eventi"];
|
||||
["/api/capabilities", "/api/preferences", "/api/accesso", "/api/uscita", "/api/engine", "/api/eventi", ActivityApi.DiagnosticsPath];
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Privacy;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Web.Engine;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Febe.Web.Demo;
|
||||
|
||||
/// <summary>
|
||||
/// The diagnostic report of the demo (issue #39): today's sessions of <see cref="DemoWorld"/> told as traces, with
|
||||
/// counts that follow the session numbers. It follows the scene: «sessione» adds the session in progress, «fermo» ends
|
||||
/// the last session with the verification (signal <c>challenge-url</c>, breaker open), «scollegato» and «errore» have
|
||||
/// nothing (the engine never ran). Like the real report, it holds no name: patterns come from the site map and from
|
||||
/// <see cref="PathPatterns"/>, every other value from a closed list.
|
||||
/// </summary>
|
||||
public sealed class DemoDiagnosticSource(IHttpContextAccessor accessor, DemoWorld world, IClock clock) : IDiagnosticSource
|
||||
{
|
||||
/// <summary>The verification of the scene «fermo» (spec §7.6, <c>segnali.json</c>).</summary>
|
||||
public const string ChallengeCode = "challenge-url";
|
||||
|
||||
private const string Json = "application/json";
|
||||
private const string Html = "text/html";
|
||||
|
||||
private static readonly SiteMap Map = SiteMap.LoadInstagram();
|
||||
|
||||
public Task<IReadOnlyList<SessionTrace>> ListAsync(CancellationToken ct) =>
|
||||
Task.FromResult(Build(DemoRequest.Scene(accessor.HttpContext), clock.Now));
|
||||
|
||||
/// <summary>The traces of a scene at <paramref name="now"/>, oldest first.</summary>
|
||||
public IReadOnlyList<SessionTrace> Build(DemoScene scene, DateTimeOffset now)
|
||||
{
|
||||
if (scene is DemoScene.Disconnected or DemoScene.Error)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var sessions = world.Today.Where(s => s.End <= now).ToList();
|
||||
var traces = new List<SessionTrace>();
|
||||
for (var i = 0; i < sessions.Count; i++)
|
||||
{
|
||||
var stopped = scene == DemoScene.Stopped && i == sessions.Count - 1;
|
||||
traces.Add(Trace(i + 1, sessions[i], stopped ? Ending.Stopped : Ending.Finished, i));
|
||||
}
|
||||
|
||||
if (scene == DemoScene.Session)
|
||||
{
|
||||
traces.Add(Trace(sessions.Count + 1, DemoEngine.CurrentSession(now), Ending.InProgress, sessions.Count));
|
||||
}
|
||||
|
||||
if (sessions.Count > 0 && scene != DemoScene.Stopped)
|
||||
{
|
||||
traces.Add(Outside(sessions[0].End + TimeSpan.FromMinutes(3), sessions));
|
||||
}
|
||||
|
||||
return [.. traces.OrderBy(t => t.Start)];
|
||||
}
|
||||
|
||||
private enum Ending
|
||||
{
|
||||
Finished,
|
||||
Stopped,
|
||||
InProgress,
|
||||
}
|
||||
|
||||
private static SessionTrace Trace(long id, DemoSession s, Ending ending, int index)
|
||||
{
|
||||
var profiles = Math.Max(1, s.ProfilesOpened);
|
||||
var storyAccounts = s.StoriesViewed == 0 ? 0 : Math.Clamp(s.StoriesViewed / 3, 1, profiles + 2);
|
||||
var stories = Math.Min(s.NewEntries, s.StoriesViewed);
|
||||
var posts = s.NewEntries - stories;
|
||||
var storyBytes = s.NewEntries == 0 ? 0 : s.Bytes * stories / s.NewEntries;
|
||||
var stopped = ending == Ending.Stopped;
|
||||
|
||||
// Pages, spread over the session: the home, the profiles, the stories viewers.
|
||||
var names = new List<string> { SitePages.Home };
|
||||
names.AddRange(Enumerable.Repeat(SitePages.Profile, profiles));
|
||||
names.AddRange(Enumerable.Repeat(SitePages.StoryViewer, storyAccounts));
|
||||
var step = (s.End - s.Start) / (names.Count + 1);
|
||||
var pages = names.Select((name, i) => new PageVisit(s.Start + (step * (i + 1)), name, Map.PatternOf(name), true)).ToList();
|
||||
|
||||
var navigations = new List<NavigationGroup>
|
||||
{
|
||||
new(HostKind.Site, SitePages.Home, Pattern(SitePages.Home), false, 1),
|
||||
new(HostKind.Site, SitePages.Profile, Pattern(SitePages.Profile), false, profiles),
|
||||
};
|
||||
if (storyAccounts > 0)
|
||||
{
|
||||
navigations.Add(new(HostKind.Site, SitePages.StoryViewer, Pattern(SitePages.StoryViewer), true, s.StoriesViewed));
|
||||
}
|
||||
|
||||
var dataCalls = (profiles * 3) + s.HistoryPages + 4;
|
||||
var images = s.StoriesViewed + (profiles * 12);
|
||||
var videos = s.StoriesViewed / 2;
|
||||
var responses = new List<ResponseGroup>
|
||||
{
|
||||
Group(HostKind.Site, SitePages.Home, Pattern(SitePages.Home), "Document", Html, 1, 412_000) with { Recognized = 1, Contents = 6 },
|
||||
Group(HostKind.Site, SitePages.Profile, Pattern(SitePages.Profile), "Document", Html, profiles, 388_000) with { Recognized = profiles, Profiles = profiles },
|
||||
Group(HostKind.Site, null, PathPatterns.Of("/graphql/query"), "Fetch", Json, dataCalls, 24_000) with
|
||||
{
|
||||
Recognized = profiles + s.HistoryPages,
|
||||
Empty = profiles / 4,
|
||||
Unrelated = dataCalls - profiles - s.HistoryPages - (profiles / 4),
|
||||
Contents = posts,
|
||||
Profiles = profiles,
|
||||
},
|
||||
Group(HostKind.Site, null, PathPatterns.Of("/ajax/bulk-route-definitions/"), "Fetch", Json, profiles + 2, 3_000) with { Unrelated = profiles + 2 },
|
||||
Group(HostKind.Cdn, null, "cdn *.jpg", "Image", "image/jpeg", images, 140_000) with { NotRead = images },
|
||||
Group(HostKind.Other, null, CollectionDiagnostics.Other + " *.js", "Script", "application/javascript", 14, 220_000) with { NotRead = 14 },
|
||||
};
|
||||
if (storyAccounts > 0)
|
||||
{
|
||||
responses.Add(Group(HostKind.Site, null, PathPatterns.Of("/api/v1/feed/reels_media/"), "XHR", Json, storyAccounts, 36_000) with
|
||||
{
|
||||
Recognized = storyAccounts,
|
||||
Contents = s.StoriesViewed,
|
||||
});
|
||||
}
|
||||
|
||||
if (videos > 0)
|
||||
{
|
||||
responses.Add(Group(HostKind.Cdn, null, "cdn *.mp4", "Media", "video/mp4", videos, 2_400_000) with { NotRead = videos });
|
||||
}
|
||||
|
||||
var recipes = new List<RecipeLine> { new(s.Start + step, RecipeKind.FollowingSweep, RecipeStatus.Completed, null, 2 + storyAccounts, Math.Min(2, posts)) };
|
||||
recipes.AddRange(Enumerable.Range(0, storyAccounts).Select(i => new RecipeLine(
|
||||
s.Start + (step * (2 + profiles + i)), RecipeKind.AccountStories, RecipeStatus.Completed, null, 3, i == 0 ? stories : 0)));
|
||||
recipes.AddRange(Enumerable.Range(0, profiles).Select(i => new RecipeLine(
|
||||
s.Start + (step * (2 + i)), RecipeKind.ProfileCheck, RecipeStatus.Completed, null, 1, i == 0 ? Math.Max(0, posts - 2) : 0)));
|
||||
var signals = new List<SignalLine>();
|
||||
if (stopped)
|
||||
{
|
||||
// The last profile check met the verification page: stopped there, nothing after it.
|
||||
var at = s.End - TimeSpan.FromSeconds(40);
|
||||
var last = recipes.FindLastIndex(r => r.Kind == RecipeKind.ProfileCheck);
|
||||
recipes[last] = recipes[last] with { At = at, Status = RecipeStatus.StoppedBySignal, Signal = ChallengeCode, NewEntries = 0 };
|
||||
signals.Add(new SignalLine(at, SignalLevel.Challenge, ChallengeCode));
|
||||
pages.Add(new PageVisit(at, SitePages.Profile, Map.PatternOf(SitePages.Profile), false));
|
||||
navigations.Add(new(HostKind.Site, null, PathPatterns.Of("/challenge/"), false, 1));
|
||||
responses.Add(Group(HostKind.Site, null, PathPatterns.Of("/challenge/"), "Document", Html, 1, 96_000) with { Unrelated = 1 });
|
||||
}
|
||||
|
||||
var steps = new List<VerdictCount>
|
||||
{
|
||||
new(CollectionDiagnostics.VerdictRecognized, 1 + profiles + storyAccounts + s.HistoryPages),
|
||||
};
|
||||
if (profiles >= 4)
|
||||
{
|
||||
steps.Add(new(CollectionDiagnostics.VerdictEmpty, profiles / 4));
|
||||
}
|
||||
|
||||
var targets = new List<TargetCount>();
|
||||
if (storyAccounts > 0)
|
||||
{
|
||||
targets.Add(new(SiteTargets.HomeStory, TargetCheckStatus.Clicked, storyAccounts));
|
||||
targets.Add(new(SiteTargets.ViewerNext, TargetCheckStatus.Clicked, Math.Max(0, s.StoriesViewed - storyAccounts)));
|
||||
targets.Add(new(SiteTargets.ViewerClose, TargetCheckStatus.Clicked, storyAccounts));
|
||||
}
|
||||
|
||||
var queued = new List<QueuedFiles>();
|
||||
var downloads = new List<DownloadGroup>();
|
||||
if (stories > 0)
|
||||
{
|
||||
queued.Add(new(EntryKind.Story, nameof(SaveOutcome.Created), stories, stories, 0));
|
||||
downloads.Add(new(EntryKind.Story, DownloadStep.Stored, stories, storyBytes));
|
||||
}
|
||||
|
||||
if (posts > 0)
|
||||
{
|
||||
queued.Add(new(EntryKind.Post, nameof(SaveOutcome.Created), posts, posts + (posts / 3), 0));
|
||||
downloads.Add(new(EntryKind.Post, DownloadStep.Stored, posts + (posts / 3), s.Bytes - storyBytes));
|
||||
}
|
||||
|
||||
queued.Add(new(EntryKind.Post, nameof(SaveOutcome.Known), profiles * 2, 0, 0));
|
||||
|
||||
return new SessionTrace
|
||||
{
|
||||
Session = id,
|
||||
Start = s.Start,
|
||||
End = ending == Ending.InProgress ? null : s.End,
|
||||
Outcome = ending switch
|
||||
{
|
||||
Ending.Stopped => SessionOutcome.Stopped,
|
||||
Ending.InProgress => SessionOutcome.Running,
|
||||
_ => SessionOutcome.Completed,
|
||||
},
|
||||
StopCause = ending switch
|
||||
{
|
||||
Ending.Stopped => SessionStopCause.BreakerOpen,
|
||||
Ending.InProgress => null,
|
||||
_ => index % 3 == 2 ? SessionStopCause.WorkDone : SessionStopCause.PlannedEnd,
|
||||
},
|
||||
Mood = Math.Round(0.85 + (0.05 * (index % 4)), 2),
|
||||
InProgress = ending == Ending.InProgress,
|
||||
Pages = pages,
|
||||
Navigations = navigations,
|
||||
Responses = responses,
|
||||
Steps = steps,
|
||||
Targets = targets,
|
||||
Recipes = recipes,
|
||||
Signals = signals,
|
||||
FilesQueued = queued,
|
||||
Downloads = downloads,
|
||||
DownloadedBytes = s.Bytes,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Today outside the sessions: files of the queue settled between two sessions.</summary>
|
||||
private static SessionTrace Outside(DateTimeOffset start, IReadOnlyList<DemoSession> sessions)
|
||||
{
|
||||
var files = Math.Clamp(sessions.Sum(s => s.NewEntries) / 6, 1, 12);
|
||||
return new SessionTrace
|
||||
{
|
||||
Session = null,
|
||||
Start = start,
|
||||
InProgress = true,
|
||||
Downloads =
|
||||
[
|
||||
new(EntryKind.Post, DownloadStep.Stored, files, files * 1_900_000L),
|
||||
new(EntryKind.Story, DownloadStep.Duplicate, 1, 0),
|
||||
],
|
||||
DownloadedBytes = files * 1_900_000L,
|
||||
};
|
||||
}
|
||||
|
||||
private static string Pattern(string page) => Map.PatternOf(page) ?? PathPatterns.Text;
|
||||
|
||||
private static ResponseGroup Group(HostKind host, string? page, string pattern, string resourceType, string mime, int count, long average) =>
|
||||
new(host, page, pattern, resourceType, mime, "2xx", count, count * average, average + (average / 10), 0, 0, 0, 0, 0, 0, 0, 0, []);
|
||||
}
|
||||
@@ -30,6 +30,10 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
|
||||
return sessions.Count > 0 ? sessions[^1].End - TimeSpan.FromSeconds(40) : now - TimeSpan.FromMinutes(25);
|
||||
}
|
||||
|
||||
/// <summary>The session in progress of the scene «sessione»: started two and a half minutes ago.</summary>
|
||||
public static DemoSession CurrentSession(DateTimeOffset now) =>
|
||||
new(now - TimeSpan.FromMinutes(2.5), now, 2, 6, 0, 18_000_000, 2);
|
||||
|
||||
public async Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default)
|
||||
{
|
||||
var scene = CurrentScene;
|
||||
@@ -40,9 +44,7 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
|
||||
var inWindow = now >= world.WindowStart && now < world.WindowEnd;
|
||||
var sessions = scene is DemoScene.Disconnected or DemoScene.Error ? [] : world.Today.Where(s => s.End <= now).ToList();
|
||||
var stopAt = StopInstant(now);
|
||||
var current = scene == DemoScene.Session
|
||||
? new DemoSession(now - TimeSpan.FromMinutes(2.5), now, 2, 6, 0, 18_000_000, 2)
|
||||
: null;
|
||||
var current = scene == DemoScene.Session ? CurrentSession(now) : null;
|
||||
var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false);
|
||||
var marta = accounts.FirstOrDefault(a => a.Username == "marta.demo")?.Username ?? world.MineUsername;
|
||||
|
||||
|
||||
@@ -99,6 +99,7 @@ public sealed class DemoHost : IAsyncDisposable
|
||||
services.AddSingleton<IConnectionService, DemoConnectionService>();
|
||||
services.AddSingleton<IBrowserPreview, DemoBrowserPreview>();
|
||||
services.AddSingleton<IIncidentHistory, DemoIncidentHistory>();
|
||||
services.AddSingleton<IDiagnosticSource, DemoDiagnosticSource>();
|
||||
services.AddSingleton<IDataFolderChange, DemoDataFolderChange>();
|
||||
services.AddSingleton(demoImport);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
|
||||
namespace Febe.Web.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// The traces of the diagnostic report (issue #39) for «Esporta il rapporto di diagnostica» in Attività: the finished
|
||||
/// ones of the last two weeks and the ones in progress, oldest first. They hold no data value
|
||||
/// (<see cref="SessionTrace"/>).
|
||||
/// </summary>
|
||||
public interface IDiagnosticSource
|
||||
{
|
||||
Task<IReadOnlyList<SessionTrace>> ListAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// The traces with what the report must say about itself (damaged lines of the log, errors of the recorder). By
|
||||
/// default the traces of <see cref="ListAsync"/> with nothing lost.
|
||||
/// </summary>
|
||||
async Task<DiagnosticCollection> GatherAsync(CancellationToken ct) =>
|
||||
new(await ListAsync(ct).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
/// <summary>The traces of the recorder of the running Febe (its log in <c>Dati/diagnostica</c>, and what is open).</summary>
|
||||
public sealed class RecordedDiagnosticSource(CollectionDiagnostics diagnostics) : IDiagnosticSource
|
||||
{
|
||||
public Task<IReadOnlyList<SessionTrace>> ListAsync(CancellationToken ct) =>
|
||||
Task.Run(diagnostics.Collect, ct);
|
||||
|
||||
public Task<DiagnosticCollection> GatherAsync(CancellationToken ct) =>
|
||||
Task.Run(diagnostics.Gather, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The default when the composition registers no recorder (tests, a start with a configuration problem, where the
|
||||
/// engine never started): nothing was recorded, so the report has empty lists.
|
||||
/// </summary>
|
||||
public sealed class NoDiagnosticSource : IDiagnosticSource
|
||||
{
|
||||
public Task<IReadOnlyList<SessionTrace>> ListAsync(CancellationToken ct) =>
|
||||
Task.FromResult<IReadOnlyList<SessionTrace>>([]);
|
||||
}
|
||||
@@ -67,6 +67,7 @@ public static class FebeWeb
|
||||
services.TryAddSingleton<IConfigurationProblems, NoConfigurationProblems>();
|
||||
services.TryAddSingleton<IConnectionService, UnavailableConnectionService>();
|
||||
services.TryAddSingleton<IBrowserPreview, NoBrowserPreview>();
|
||||
services.TryAddSingleton<IDiagnosticSource, NoDiagnosticSource>();
|
||||
services.TryAddSingleton<IIncidentHistory>(sp => new StoredIncidentHistory(sp.GetRequiredService<IFebeStorage>()));
|
||||
services.TryAddSingleton<IAlertTestSender, NoTelegramSender>();
|
||||
services.TryAddSingleton<IDataFolderChange, FixedDataFolder>();
|
||||
|
||||
@@ -13,7 +13,7 @@ Qui sotto le convenzioni per chi continua il lavoro (composizione di Server e De
|
||||
| `Hosting/` | `EmbeddedWwwroot`: `IFileProvider` sulle risorse incorporate `wwwroot/…` (o su una cartella, per sviluppo) |
|
||||
| `Security/` | Controlli di §13.1: Host, Origin, gettone del desktop, password e blocco della veste Docker, intestazioni |
|
||||
| `Api/` | Endpoint minimi, DTO (`Dtos.cs`), contesto JSON generato (`FebeJsonContext`), conversioni (`ApiMapping`) |
|
||||
| `Engine/` | `IEngineControl` (comandi al motore), `EngineHostControl`, `OfflineEngine` (nessun motore), `BrowserUseTracker`, `IEngineSettingsControl` (limiti al motore), `IBrowserPreview` (anteprima), `IIncidentHistory` (incidenti) |
|
||||
| `Engine/` | `IEngineControl` (comandi al motore), `EngineHostControl`, `OfflineEngine` (nessun motore), `BrowserUseTracker`, `IEngineSettingsControl` (limiti al motore), `IBrowserPreview` (anteprima), `IIncidentHistory` (incidenti), `IDiagnosticSource` (rapporto di diagnostica) |
|
||||
| `Library/` | `FebeLibrary` (archivio + disposizione, `HashIndex`, `DownloadDuplicates`), `LibraryChanges`, esportazione CSV, collegamenti a Instagram, nomi utente, `IDataFolderChange`, `FolderSizes`, `RebuildJob` |
|
||||
| `Connection/` | Contratto condiviso con il lato server del collegamento: `IConnectionService`, `IConfigurationProblems`, `PROTOCOLLO.md` (vista remota `/api/vista`); `UnavailableConnectionService` è il ripiego |
|
||||
| `Import/` | `ImportHub`: l'`ImportService` registrato dalla composizione, oppure uno costruito sulla libreria |
|
||||
@@ -68,6 +68,7 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri
|
||||
| `IEngineSettingsControl` | `StoredEngineSettingsControl`: salva le impostazioni del motore nell'archivio | `new EngineHostSettingsControl(engineHost)`: le applica anche al motore che gira |
|
||||
| `IBrowserPreview` | `NoBrowserPreview` (nessuna anteprima) | Chi ha il browser: `GetLatestAsync` restituisce l'ultima schermata JPEG (`BrowserFrame`) con l'indirizzo |
|
||||
| `IIncidentHistory` | `StoredIncidentHistory` (dall'archivio) | Di solito nessuno |
|
||||
| `IDiagnosticSource` (`Engine/DiagnosticSource.cs`) | `NoDiagnosticSource`: niente registrato, il rapporto ha gli elenchi vuoti (prove, avvio con un problema di configurazione) | `Febe.App`: `RecordedDiagnosticSource` sul registratore `CollectionDiagnostics` (registro in `Dati/diagnostica`, 14 giorni, e sessioni in corso); dimostrazione: `DemoDiagnosticSource`, secondo la scena |
|
||||
| `IAlertTestSender` (Core) | `NoTelegramSender`: nessun messaggio parte (dimostrazione, prove), la risposta lo dice | La composizione (`Febe.App`, le due vesti): `TelegramAlertChannel` (Core, `Alerts/Telegram.cs`), lo stesso canale che usa `AlertService` |
|
||||
| `IDataFolderChange` | `FixedDataFolder`: la cartella dei dati non si cambia dall'interfaccia | Desktop: `DesktopDataFolderChange` registra la scelta e `DataFolderMove` sposta la cartella al prossimo avvio, con copia verificata (SHA-256) |
|
||||
| `ImportService` (Core) | `ImportHub` ne costruisce uno sulla libreria (Docker: solo sotto `FebeWebOptions.ImportRoot`, di serie `/importa`; desktop: qualsiasi cartella) | La composizione, se vuole opzioni diverse (ffmpeg, cartella sorgente) |
|
||||
@@ -119,6 +120,7 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
|
||||
| `GET /api/engine/incidents` | Incidenti degli ultimi 14 giorni (rallentamenti, verifiche, arresti), con un consiglio dopo 3 rallentamenti in 7 giorni |
|
||||
| `POST /api/engine/recipes/{ricetta}/resume` | «Riattiva» una ricetta sospesa dopo tre problemi di fila (`IEngineControl.ResumeRecipeAsync`: metodo con un'implementazione predefinita che risponde «non era sospesa», così le altre implementazioni non cambiano). Attività mostra le ricette sospese da `snapshot.suspendedRecipes` |
|
||||
| `GET /api/alerts` | Avvisi degli ultimi 14 giorni (§13.3, sezione «Avvisi» di Attività): righe della cronologia con i codici di `AlertCatalog.Codes`, compresi gli avvisi non arrivati |
|
||||
| `GET /api/engine/diagnostica` | «Esporta il rapporto di diagnostica» (issue #39, §7.9): file JSON `febe-diagnostica-aaaa-mm-gg.json` (giorno locale) in allegato, `no-store`, UTF-8 senza BOM, da `DiagnosticReport.Write` con le tracce di `IDiagnosticSource`. Nessun valore dei dati: solo conteggi, misure, orari, codici da elenchi chiusi e forme degli indirizzi. In testa `righeRovinate`, `erroriRegistratore`, `fileIlleggibili` e `sessioniSenzaFine` (`IDiagnosticSource.GatherAsync`). Risponde anche con un problema di configurazione (`ConfigurationGateMiddleware.AllowedApi`), con gli elenchi vuoti: il motore non è partito |
|
||||
| `GET /api/browser/preview`, `GET /api/browser/preview/frame` | Anteprima del browser in Attività: indirizzo e immagine JPEG (`no-store`, 404 se non c'è) |
|
||||
| `GET /api/duplicates/count`, `GET /api/duplicates?after=`, `POST /api/duplicates/{pairId}` (`{ decision, applyToAll }`) | Doppioni dopo uno scaricamento (§9.5): `keepLarger`, `keepExisting`, `keepBoth`; niente si decide da solo |
|
||||
| `GET/PUT /api/settings/general`, `POST /api/settings/naming-preview`, `/pick-folder`, `/data-folder` | Cartelle (cambio della libreria solo desktop), schema dei nomi con anteprima, tema, avvio, area di notifica |
|
||||
@@ -197,7 +199,7 @@ Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da
|
||||
- `text.js`: `t('chiave.sotto', { n, … })` (forme `singolare|plurale` scelte da `n`), `number` (punti delle migliaia),
|
||||
`decimal`, `bytes`, `duration`, `around` («verso le 15:30»), `ago` («2 ore fa»), `dayName`.
|
||||
- `api.js`: `api(percorso, { method, body, signal, raw })` (lancia `ApiError` con il messaggio italiano del server),
|
||||
`download`, `withCarried`. I parametri `scena`, `veste`, `tema` della dimostrazione restano negli indirizzi interni e
|
||||
`download(percorso, corpo, nomeDiRiserva)` (POST con il corpo; GET con corpo `null`), `withCarried`. I parametri `scena`, `veste`, `tema` della dimostrazione restano negli indirizzi interni e
|
||||
viaggiano verso l'API (intestazioni `X-Febe-Scena`, `X-Febe-Veste`).
|
||||
- `engine.js`: `onEngine`, `onLibrary`, `refreshEngine`. In dimostrazione niente SSE: si chiede il motore ogni 30 s
|
||||
(così le schermate senza finestra finiscono).
|
||||
@@ -230,8 +232,8 @@ scrive mai nella libreria vera e non usa la rete.
|
||||
di configurazione); tema: `?tema=chiaro|scuro`; veste: `?veste=desktop|windows|docker`.
|
||||
- Indirizzi diretti: `/account?dialogo=aggiungi`, `/account/3/impostazioni`, `/account/2?tipo=storie`,
|
||||
`/importa?passo=3` (revisione di un'importazione già analizzata), `/doppioni`, `/impostazioni/collegamento?scena=scollegato&veste=docker`.
|
||||
- Seconda parte (`Demo/DemoPart2.cs`, `Demo/DemoImport.cs`): collegamento, anteprima del browser e incidenti secondo la
|
||||
scena; tre doppioni dopo uno scaricamento; una sorgente da importare generata in `importa/Backup del vecchio disco`
|
||||
- Seconda parte (`Demo/DemoPart2.cs`, `Demo/DemoImport.cs`, `Demo/DemoDiagnostics.cs`): collegamento, anteprima del
|
||||
browser, incidenti e rapporto di diagnostica secondo la scena; tre doppioni dopo uno scaricamento; una sorgente da importare generata in `importa/Backup del vecchio disco`
|
||||
(copie identiche, varianti, cartelle senza account, file non riconosciuti) e già analizzata all'avvio.
|
||||
- I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i
|
||||
conti tornino.
|
||||
|
||||
@@ -104,9 +104,12 @@ export function eventsUrl() {
|
||||
return withCarried('/api/eventi');
|
||||
}
|
||||
|
||||
/** Downloads an answer as a file (CSV export). */
|
||||
/**
|
||||
* Downloads an answer as a file: a POST with the body (CSV export), or a GET when the body is null (diagnostic report).
|
||||
* Through api(), so the carried scene and shell travel with it.
|
||||
*/
|
||||
export async function download(path, body, fallbackName) {
|
||||
const response = await api(path, { method: 'POST', body, raw: true });
|
||||
const response = await api(path, body === null ? { raw: true } : { method: 'POST', body, raw: true });
|
||||
const blob = await response.blob();
|
||||
const disposition = response.headers.get('Content-Disposition') || '';
|
||||
const match = /filename="?([^";]+)"?/.exec(disposition);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// ones that are not stops, like a backfill completed or a disk almost full). It updates by itself from the event
|
||||
// stream (the demo asks every 30 seconds). The red strip of a stop is drawn by the page frame.
|
||||
|
||||
import { api, withCarried } from '../core/api.js';
|
||||
import { api, download, withCarried } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { dotOf, refreshEngine } from '../core/engine.js';
|
||||
import { openBrowser } from '../core/shell.js';
|
||||
@@ -97,7 +97,39 @@ function drawActions(page, state) {
|
||||
: h('button.btn', {
|
||||
type: 'button', onclick: pause, disabled: ['Off', 'NotConnected'].includes(s.mode), 'aria-label': t('attivita.pausa'),
|
||||
}, icon('pause'), h('span.testo-btn', t('attivita.pausa')));
|
||||
page.actions(first, h('button.btn', { type: 'button', onclick: openBrowser, 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))));
|
||||
page.actions(
|
||||
first,
|
||||
h('button.btn', { type: 'button', onclick: openBrowser, 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))),
|
||||
diagnosticsButton(),
|
||||
);
|
||||
}
|
||||
|
||||
// True while a report is being exported. The title row is rebuilt at every engine update, so the button of the click
|
||||
// may be gone by the end: the flag, not the button, says whether an export is running.
|
||||
let exporting = false;
|
||||
|
||||
/** «Diagnostica»: the report of the last two weeks of sessions, with no name in it, to send after a test gone wrong (#39). */
|
||||
function diagnosticsButton() {
|
||||
const button = h('button.btn', {
|
||||
type: 'button', title: t('attivita.esportaDiagnostica'), 'aria-label': t('attivita.esportaDiagnostica'), disabled: exporting,
|
||||
}, icon('file-down'), h('span.testo-btn', t('attivita.diagnostica')));
|
||||
button.onclick = async () => {
|
||||
if (exporting) return;
|
||||
exporting = true;
|
||||
button.disabled = true;
|
||||
try {
|
||||
await download('/api/engine/diagnostica', null, 'febe-diagnostica.json');
|
||||
toast(t('attivita.diagnosticaEsportata'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
exporting = false;
|
||||
// The button on the page now, which may not be this one.
|
||||
for (const shown of document.querySelectorAll('[data-diagnostica]')) shown.disabled = false;
|
||||
}
|
||||
};
|
||||
button.dataset.diagnostica = '';
|
||||
return button;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- now
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Impostazioni, Generali (mockup 08, spec §4.7, §10.5, §12): the Libreria and Dati folders with «Cambia…» (desktop:
|
||||
// native picker; Docker: read-only with the note), free and used space; the two naming schemes with the live «Risultato»
|
||||
// native picker; Docker: read-only with the note), free and used space; the three naming schemes with the live «Risultato»
|
||||
// tree, the placeholders and the errors; «Imposta la data del file a quella di pubblicazione»; theme and language;
|
||||
// the «Avvio» block on Windows only.
|
||||
|
||||
@@ -12,9 +12,10 @@ import { guardChanges, heading } from './settings.js';
|
||||
|
||||
export default async function general(page, box) {
|
||||
let data = await api('/api/settings/general', { signal: page.signal });
|
||||
let saved = { naming: data.namingScheme, highlight: data.highlightScheme, setFileTime: data.setFileTime };
|
||||
const stored = (d) => ({ naming: d.namingScheme, highlight: d.highlightScheme, profile: d.profilePictureScheme, setFileTime: d.setFileTime });
|
||||
let saved = stored(data);
|
||||
const form = { ...saved };
|
||||
const dirty = () => form.naming !== saved.naming || form.highlight !== saved.highlight || form.setFileTime !== saved.setFileTime;
|
||||
const dirty = () => Object.keys(saved).some((key) => form[key] !== saved[key]);
|
||||
guardChanges(page, dirty);
|
||||
|
||||
// ------------------------------------------------------------------------------------------- folders
|
||||
@@ -86,6 +87,7 @@ export default async function general(page, box) {
|
||||
libraryFolder: null,
|
||||
namingScheme: withForm ? form.naming : saved.naming,
|
||||
highlightScheme: withForm ? form.highlight : saved.highlight,
|
||||
profilePictureScheme: withForm ? form.profile : saved.profile,
|
||||
setFileTime: withForm ? form.setFileTime : saved.setFileTime,
|
||||
autostart: null,
|
||||
keepInTray: null,
|
||||
@@ -93,7 +95,7 @@ export default async function general(page, box) {
|
||||
};
|
||||
try {
|
||||
data = await api('/api/settings/general', { method: 'PUT', body });
|
||||
saved = { naming: data.namingScheme, highlight: data.highlightScheme, setFileTime: data.setFileTime };
|
||||
saved = stored(data);
|
||||
if (withForm) Object.assign(form, saved);
|
||||
drawFolders();
|
||||
drawSaveBar();
|
||||
@@ -108,16 +110,20 @@ export default async function general(page, box) {
|
||||
// ------------------------------------------------------------------------------------------- naming
|
||||
const naming = h('input.dati', { type: 'text', value: form.naming, id: 'schema', spellcheck: 'false', autocomplete: 'off' });
|
||||
const highlight = h('input.dati', { type: 'text', value: form.highlight, id: 'schema-evidenza', spellcheck: 'false', autocomplete: 'off' });
|
||||
const profile = h('input.dati', { type: 'text', value: form.profile, id: 'schema-profilo', spellcheck: 'false', autocomplete: 'off' });
|
||||
const namingField = h('label.campo', naming);
|
||||
const highlightField = h('label.campo', highlight);
|
||||
const profileField = h('label.campo', profile);
|
||||
const problems = h('div.problemi-schema', { 'aria-live': 'polite' });
|
||||
const tree = h('div.albero.pannello', { 'aria-label': t('impostazioni.generali.risultato') });
|
||||
const setTime = checkbox({ checked: form.setFileTime, label: t('impostazioni.generali.dataFile'), onchange: (v) => { form.setFileTime = v; drawSaveBar(); } });
|
||||
|
||||
function drawTree(preview) {
|
||||
const errors = preview.errors || [];
|
||||
// Each error starts with the name of its scheme (NamingPreview.Prefix).
|
||||
namingField.classList.toggle('errore', errors.some((e) => e.startsWith('Schema:')));
|
||||
highlightField.classList.toggle('errore', errors.some((e) => !e.startsWith('Schema:')));
|
||||
highlightField.classList.toggle('errore', errors.some((e) => e.startsWith('Schema per le raccolte in evidenza:')));
|
||||
profileField.classList.toggle('errore', errors.some((e) => e.startsWith('Schema per le foto del profilo:')));
|
||||
fill(problems,
|
||||
errors.map((e) => h('p.errore-testo', icon('octagon-alert', 'xs'), ' ', e)),
|
||||
(preview.warnings || []).map((w) => h('p.avviso-testo', icon('triangle-alert', 'xs'), ' ', w)));
|
||||
@@ -131,7 +137,7 @@ export default async function general(page, box) {
|
||||
|
||||
const refresh = later(async () => {
|
||||
try {
|
||||
drawTree(await api('/api/settings/naming-preview', { method: 'POST', body: { namingScheme: form.naming, highlightScheme: form.highlight }, signal: page.signal }));
|
||||
drawTree(await api('/api/settings/naming-preview', { method: 'POST', body: { namingScheme: form.naming, highlightScheme: form.highlight, profilePictureScheme: form.profile }, signal: page.signal }));
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') showError(error);
|
||||
}
|
||||
@@ -139,6 +145,7 @@ export default async function general(page, box) {
|
||||
page.onLeave(() => refresh.cancel());
|
||||
naming.addEventListener('input', () => { form.naming = naming.value; drawSaveBar(); refresh(); });
|
||||
highlight.addEventListener('input', () => { form.highlight = highlight.value; drawSaveBar(); refresh(); });
|
||||
profile.addEventListener('input', () => { form.profile = profile.value; drawSaveBar(); refresh(); });
|
||||
|
||||
// ------------------------------------------------------------------------------------------- save bar
|
||||
function drawSaveBar() {
|
||||
@@ -157,6 +164,7 @@ export default async function general(page, box) {
|
||||
Object.assign(form, saved);
|
||||
naming.value = form.naming;
|
||||
highlight.value = form.highlight;
|
||||
profile.value = form.profile;
|
||||
setTime.input.checked = form.setFileTime;
|
||||
drawSaveBar();
|
||||
refresh();
|
||||
@@ -197,6 +205,7 @@ export default async function general(page, box) {
|
||||
h('div.colonna-nomi',
|
||||
h('label.etichetta', { for: 'schema' }, t('impostazioni.generali.schema')), namingField,
|
||||
h('label.etichetta', { for: 'schema-evidenza' }, t('impostazioni.generali.schemaEvidenza')), highlightField,
|
||||
h('label.etichetta', { for: 'schema-profilo' }, t('impostazioni.generali.schemaProfilo')), profileField,
|
||||
h('p.aiuto.segnaposto', t('impostazioni.generali.segnaposto', { elenco: data.placeholders.join(', ') })),
|
||||
problems,
|
||||
h('div.data-file', setTime)),
|
||||
|
||||