Unione dell'ondata 4 (interfaccia parte 2, server reale e Docker): impostazioni del motore, anteprima del browser e schema dei nomi collegati al server reale; decisioni consolidate
verifica / prove (push) Successful in 18m40s
verifica / prove (push) Successful in 18m40s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
39 files changed
+6228
-12
No files matched your search
@@ -0,0 +1,15 @@
|
||||
# Contesto di «docker build -f docker/Dockerfile .»: solo ciò che serve a compilare e provare.
|
||||
**/bin/
|
||||
**/obj/
|
||||
**/out/
|
||||
**/*.trx
|
||||
**/TestResults/
|
||||
.git
|
||||
.gitea
|
||||
.claude
|
||||
.vs
|
||||
.vscode
|
||||
.idea
|
||||
docs/
|
||||
**/*.user
|
||||
**/node_modules/
|
||||
@@ -0,0 +1,125 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
#
|
||||
# Febe — immagine per il server di casa (specifica §11).
|
||||
#
|
||||
# docker build -f docker/Dockerfile \
|
||||
# --build-arg VERSION=0.1.0 --build-arg GIT_COMMIT=$(git rev-parse --short=12 HEAD) \
|
||||
# -t gitea.encke-hake.ts.net/alby96/febe:0.1.0 .
|
||||
#
|
||||
# Stadi:
|
||||
# build restore e compilazione di tutta la soluzione con gli avvisi come errori;
|
||||
# test tutte le prove: un'immagine con prove rosse non esiste. Qui non ci sono Chromium né Xvfb, quindi le prove
|
||||
# con il browser vero risultano «inconcludenti» (saltate) e girano solo dove ci sono (CI, sviluppo);
|
||||
# publish Febe.Server autosufficiente per linux-x64: nell'immagine non serve il runtime .NET;
|
||||
# runtime Debian stabile ridotta (trixie-slim) con Chromium della distribuzione, Xvfb, ffmpeg, ICU, caratteri
|
||||
# (anche emoji), certificati, fusi orari, lingua italiana; tini come processo 1; setpriv per PUID/PGID.
|
||||
#
|
||||
# Vedi docs/docker.md per volumi, variabili, porte, sandbox, salute e aggiornamento.
|
||||
|
||||
ARG DOTNET_VERSION=10.0
|
||||
|
||||
# ─────────────────────────────────────────────────────────────── build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS build
|
||||
WORKDIR /src
|
||||
ENV DOTNET_NOLOGO=1 DOTNET_CLI_TELEMETRY_OPTOUT=1
|
||||
|
||||
# Prima i file di progetto: il restore resta in cache finché non cambiano.
|
||||
COPY Directory.Build.props Directory.Packages.props Febe.slnx ./
|
||||
COPY src/Febe.Core/Febe.Core.csproj src/Febe.Core/
|
||||
COPY src/Febe.Data/Febe.Data.csproj src/Febe.Data/
|
||||
COPY src/Febe.Browser/Febe.Browser.csproj src/Febe.Browser/
|
||||
COPY src/Febe.Web/Febe.Web.csproj src/Febe.Web/
|
||||
COPY src/Febe.Server/Febe.Server.csproj src/Febe.Server/
|
||||
COPY src/Febe.Desktop/Febe.Desktop.csproj src/Febe.Desktop/
|
||||
COPY tests/Febe.Tests/Febe.Tests.csproj tests/Febe.Tests/
|
||||
COPY tools/Febe.Sonda/Febe.Sonda.csproj tools/Febe.Sonda/
|
||||
COPY tools/Febe.SitoDiProva/Febe.SitoDiProva.csproj tools/Febe.SitoDiProva/
|
||||
RUN dotnet restore Febe.slnx \
|
||||
&& dotnet restore src/Febe.Server/Febe.Server.csproj -r linux-x64
|
||||
|
||||
COPY . .
|
||||
ARG GIT_COMMIT=n/d
|
||||
RUN dotnet build Febe.slnx -c Release --no-restore -nologo -warnaserror -p:SourceRevisionId=${GIT_COMMIT}
|
||||
|
||||
# ─────────────────────────────────────────────────────────────── test
|
||||
FROM build AS test
|
||||
RUN dotnet test tests/Febe.Tests -c Release --no-build --nologo \
|
||||
&& touch /tmp/prove-verdi
|
||||
|
||||
# ─────────────────────────────────────────────────────────────── publish
|
||||
FROM build AS publish
|
||||
ARG GIT_COMMIT=n/d
|
||||
# La pubblicazione parte solo con le prove verdi.
|
||||
COPY --from=test /tmp/prove-verdi /tmp/prove-verdi
|
||||
RUN dotnet publish src/Febe.Server/Febe.Server.csproj -c Release -r linux-x64 --self-contained true \
|
||||
-nologo -p:SourceRevisionId=${GIT_COMMIT} -p:DebugType=none -o /app \
|
||||
&& test -x /app/febe
|
||||
|
||||
# ─────────────────────────────────────────────────────────────── runtime
|
||||
FROM debian:trixie-slim AS runtime
|
||||
ARG VERSION=dev
|
||||
ARG GIT_COMMIT=n/d
|
||||
|
||||
LABEL org.opencontainers.image.title="Febe" \
|
||||
org.opencontainers.image.description="Archivio personale di foto, video e storie da Instagram: un browser vero, a ritmo umano, e una libreria sul server di casa." \
|
||||
org.opencontainers.image.version="${VERSION}" \
|
||||
org.opencontainers.image.revision="${GIT_COMMIT}" \
|
||||
org.opencontainers.image.authors="Alberto Balbo" \
|
||||
org.opencontainers.image.source="https://gitea.encke-hake.ts.net/Alby96/Febe" \
|
||||
org.opencontainers.image.url="https://gitea.encke-hake.ts.net/Alby96/Febe"
|
||||
|
||||
# Chromium della distribuzione con le sue lingue, il display virtuale, ffmpeg (miniature dei video importati), ICU e
|
||||
# le librerie del runtime .NET autosufficiente, caratteri di sistema con le emoji, certificati, fusi orari, la lingua
|
||||
# italiana generata, tini come processo 1 (raccoglie i processi di Chromium), setpriv (util-linux) per PUID/PGID.
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
chromium chromium-l10n \
|
||||
xvfb \
|
||||
ffmpeg \
|
||||
libicu76 libssl3t64 libstdc++6 libgcc-s1 zlib1g \
|
||||
fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \
|
||||
ca-certificates tzdata locales \
|
||||
tini util-linux passwd \
|
||||
&& sed -i 's/^# *\(it_IT.UTF-8 UTF-8\)/\1/' /etc/locale.gen \
|
||||
&& locale-gen \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Criteri di Chromium: niente salvataggio delle password né compilazione automatica (nel profilo resta solo la sessione).
|
||||
COPY docker/chromium/febe.json /etc/chromium/policies/managed/febe.json
|
||||
# Il profilo seccomp dedicato (quello di Docker più clone/unshare per la sandbox di Chromium): l'avvio lo copia in
|
||||
# /dati/seccomp.json, così sul server c'è sempre la versione di questa immagine (docs/docker.md, «Sandbox»).
|
||||
COPY docker/chromium/seccomp.json /usr/share/febe/seccomp.json
|
||||
|
||||
COPY --from=publish /app /app
|
||||
COPY docker/entrypoint.sh /usr/local/bin/febe-avvio
|
||||
RUN sed -i 's/\r$//' /usr/local/bin/febe-avvio \
|
||||
&& chmod 0755 /usr/local/bin/febe-avvio \
|
||||
&& mkdir -p /dati /libreria /importa
|
||||
|
||||
ENV LANG=it_IT.UTF-8 \
|
||||
TZ=Europe/Rome \
|
||||
PUID=99 \
|
||||
PGID=100 \
|
||||
FEBE_PORTA=8480 \
|
||||
FEBE_CHROMIUM=/usr/bin/chromium \
|
||||
DOTNET_NOLOGO=1 \
|
||||
DOTNET_gcServer=0
|
||||
|
||||
WORKDIR /app
|
||||
VOLUME ["/dati", "/libreria", "/importa"]
|
||||
|
||||
# Solo la porta dell'interfaccia. La porta di debug del browser ascolta su 127.0.0.1 dentro il contenitore e non si
|
||||
# pubblica mai.
|
||||
EXPOSE 8480
|
||||
|
||||
# /salute risponde «ok» o «problema» (password mancante, /dati non scrivibile o in rete). Nell'immagine non c'è curl:
|
||||
# la sonda è il programma stesso.
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||||
CMD ["/app/febe", "--controllo-salute"]
|
||||
|
||||
# tini è il processo 1: inoltra SIGTERM a Febe (che ferma il motore, poi Chromium con SIGINT, poi Xvfb) e raccoglie i
|
||||
# processi figli di Chromium rimasti orfani.
|
||||
STOPSIGNAL SIGTERM
|
||||
ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/febe-avvio"]
|
||||
CMD ["/app/febe"]
|
||||
@@ -0,0 +1,25 @@
|
||||
# File di Chromium per l'immagine Docker
|
||||
|
||||
| File | Dove finisce | A che cosa serve |
|
||||
|---|---|---|
|
||||
| `febe.json` | `/etc/chromium/policies/managed/febe.json` | Criteri del browser: niente salvataggio delle password (`PasswordManagerEnabled`), niente controllo delle password trapelate (`PasswordLeakDetectionEnabled`), niente compilazione automatica di indirizzi e carte (`AutofillAddressEnabled`, `AutofillCreditCardEnabled`). Nel profilo resta solo la sessione (specifica §6.1, §11) |
|
||||
| `seccomp.json` | `/usr/share/febe/seccomp.json`, copiato a ogni avvio in `/dati/seccomp.json` | Profilo seccomp dedicato da indicare con `--security-opt seccomp=…` (vedi `docs/docker.md`, «Sandbox») |
|
||||
|
||||
`seccomp.json` è il profilo predefinito di Docker (`moby/profiles`, ramo `main`, `seccomp/default.json`, licenza
|
||||
Apache 2.0) con **una sola regola in più**, in fondo all'elenco: `clone` e `unshare` ammessi anche senza
|
||||
`CAP_SYS_ADMIN`. Servono alla sandbox di Chromium per creare i suoi spazi dei nomi utente, PID e rete. Tutto il resto
|
||||
del filtro di Docker resta com'è.
|
||||
|
||||
Prova del 13 ottobre 2026, in un contenitore come utente 1000 (Docker 29.8, profilo `builtin`, nucleo 6.18). Il
|
||||
Chromium provato è quello dell'ambiente di sviluppo (build di Playwright, librerie dell'host montate in sola lettura),
|
||||
non quello di Debian, perché da qui i pacchetti Debian non si scaricano: il meccanismo della sandbox è lo stesso, ma
|
||||
la prova con l'immagine vera va rifatta sul server (`chrome://sandbox` dalla vista remota).
|
||||
|
||||
| Impostazione | Esito |
|
||||
|---|---|
|
||||
| profilo predefinito di Docker | Chromium non parte: `No usable sandbox!` |
|
||||
| `seccomp.json` di questa cartella | `chrome://sandbox`: «You are adequately sandboxed» (spazi dei nomi, PID, rete, Seccomp-BPF sì); `navigator.webdriver` falso, `it-IT`, `Europe/Rome` |
|
||||
| `seccomp=unconfined` | come sopra, ma senza nessun filtro di Docker |
|
||||
|
||||
Per aggiornarlo: prendere il `default.json` della versione di Docker in uso e riaggiungere la regola
|
||||
`{"names": ["clone", "unshare"], "action": "SCMP_ACT_ALLOW"}`.
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"PasswordManagerEnabled": false,
|
||||
"PasswordLeakDetectionEnabled": false,
|
||||
"AutofillAddressEnabled": false,
|
||||
"AutofillCreditCardEnabled": false
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,50 @@
|
||||
# Febe con Docker Compose: esempio (specifica §11, docs/docker.md).
|
||||
#
|
||||
# FEBE_PASSWORD='una frase lunga' docker compose -f docker/compose.yml up -d
|
||||
# → http://<server>:8480/ (Impostazioni ▸ Collegamento ▸ «Accedi a Instagram» dalla vista remota)
|
||||
#
|
||||
# Per costruire l'immagine in locale invece di scaricarla, togli il commento a «build».
|
||||
# Su Unraid usa invece il modello docker/unraid/febe.xml.
|
||||
#
|
||||
# Mai esporre la porta su Internet: solo rete di casa, oppure una VPN o un proxy con HTTPS davanti.
|
||||
|
||||
services:
|
||||
febe:
|
||||
image: gitea.encke-hake.ts.net/alby96/febe:latest
|
||||
# build:
|
||||
# context: ..
|
||||
# dockerfile: docker/Dockerfile
|
||||
# args:
|
||||
# VERSION: ${VERSION:-dev}
|
||||
# GIT_COMMIT: ${GIT_COMMIT:-n/d}
|
||||
container_name: febe
|
||||
# tini è già nell'immagine come processo 1: «init: true» non serve.
|
||||
restart: unless-stopped
|
||||
# Febe ferma il motore, poi Chromium con SIGINT (la sessione resta nel profilo), poi Xvfb.
|
||||
stop_grace_period: 30s
|
||||
# La sandbox di Chromium crea spazi dei nomi utente, che il profilo seccomp predefinito di Docker vieta (provato:
|
||||
# «No usable sandbox»). Questo profilo è quello di Docker più clone/unshare: la sandbox del browser resta attiva
|
||||
# e il resto del filtro di Docker pure. Vedi docs/docker.md, «Sandbox».
|
||||
security_opt:
|
||||
- seccomp=./chromium/seccomp.json
|
||||
ports:
|
||||
# Solo la porta dell'interfaccia. La porta di debug del browser resta dentro il contenitore, su 127.0.0.1.
|
||||
- "8480:8480"
|
||||
volumes:
|
||||
# Disco locale del server: database, profilo del browser con la sessione di Instagram, miniature, copie, registro.
|
||||
- ${FEBE_DATI:-/srv/febe/dati}:/dati
|
||||
# Foto e video: può stare anche su una condivisione.
|
||||
- ${FEBE_LIBRERIA:-/srv/febe/libreria}:/libreria
|
||||
# Cartelle da importare, sempre in sola lettura.
|
||||
- ${FEBE_IMPORTA:-/srv/febe/importa}:/importa:ro
|
||||
environment:
|
||||
FEBE_PASSWORD: ${FEBE_PASSWORD:?Imposta FEBE_PASSWORD, la password dell interfaccia}
|
||||
TZ: Europe/Rome
|
||||
LANG: it_IT.UTF-8
|
||||
PUID: "1000"
|
||||
PGID: "1000"
|
||||
# Facoltative:
|
||||
# FEBE_HOST: "tower.local,192.168.1.10" # nomi con cui raggiungi l'interfaccia (gli altri sono rifiutati)
|
||||
# FEBE_PROXY_FIDATO: "1" # dietro un proxy con HTTPS che passa X-Forwarded-Host
|
||||
# FEBE_SENZA_SANDBOX: "1" # solo se Chromium non parte: vedi docs/docker.md, «Sandbox»
|
||||
# Chromium usa /tmp invece della memoria condivisa (--disable-dev-shm-usage): shm_size non serve.
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#!/bin/sh
|
||||
# Febe: avvio del contenitore (specifica §11).
|
||||
#
|
||||
# Fa solo tre cose e poi cede il posto al server:
|
||||
# 1. crea, se mancano, il gruppo PGID e l'utente PUID (su Unraid 99 e 100, «nobody:users»);
|
||||
# 2. rende /dati di quell'utente (la prima volta, o se PUID/PGID sono cambiati) e prepara /dati/home;
|
||||
# 3. exec del server con setpriv, come quell'utente: il server avvia e sorveglia da sé Xvfb e Chromium.
|
||||
# Nessun ciclo di sorveglianza qui: è il lavoro di Febe.Server (niente script di shell che facciano da supervisore).
|
||||
# /libreria non si cambia mai ricorsivamente (sono le foto di Alberto); /importa è in sola lettura e non si tocca.
|
||||
# Se /dati non si può sistemare (disco di rete, permessi) si parte lo stesso: è Febe a spiegare il problema nella sua
|
||||
# pagina, invece di un contenitore che si riavvia senza dire perché.
|
||||
set -eu
|
||||
|
||||
PUID="${PUID:-99}"
|
||||
PGID="${PGID:-100}"
|
||||
|
||||
# Già avviato come utente normale (docker run --user ...): niente da cambiare.
|
||||
if [ "$(id -u)" != "0" ]; then
|
||||
exec "$@"
|
||||
fi
|
||||
|
||||
if [ "${PUID}" = "0" ]; then
|
||||
echo "Febe: PUID=0 non è ammesso. Il browser di Febe non gira come root: indica l'utente dei file (su Unraid PUID=99, PGID=100)." >&2
|
||||
exit 64
|
||||
fi
|
||||
|
||||
if ! getent group "${PGID}" >/dev/null 2>&1; then
|
||||
groupadd -g "${PGID}" febe
|
||||
fi
|
||||
|
||||
if ! getent passwd "${PUID}" >/dev/null 2>&1; then
|
||||
useradd -o -u "${PUID}" -g "${PGID}" -M -d /dati/home -s /usr/sbin/nologin febe
|
||||
fi
|
||||
|
||||
if mkdir -p /dati 2>/dev/null; then
|
||||
if [ "$(stat -c '%u:%g' /dati)" != "${PUID}:${PGID}" ]; then
|
||||
echo "Febe: assegno /dati a ${PUID}:${PGID}."
|
||||
chown -R "${PUID}:${PGID}" /dati 2>/dev/null || echo "Febe: non riesco ad assegnare /dati a ${PUID}:${PGID}." >&2
|
||||
fi
|
||||
chmod 0750 /dati 2>/dev/null || true
|
||||
if mkdir -p /dati/home 2>/dev/null; then
|
||||
chown "${PUID}:${PGID}" /dati/home 2>/dev/null || true
|
||||
chmod 0700 /dati/home 2>/dev/null || true
|
||||
fi
|
||||
# Il profilo seccomp della sandbox di Chromium, aggiornato a ogni avvio: è il file che «--security-opt seccomp=»
|
||||
# indica sul server (su Unraid /mnt/user/appdata/febe/seccomp.json). Docker lo legge alla creazione del contenitore.
|
||||
if [ -f /usr/share/febe/seccomp.json ]; then
|
||||
cp /usr/share/febe/seccomp.json /dati/seccomp.json 2>/dev/null && chmod 0644 /dati/seccomp.json 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
# Una cartella della libreria appena creata da Docker appartiene a root: solo quella, senza ricorsione.
|
||||
if [ -d /libreria ] && [ "$(stat -c '%u' /libreria)" = "0" ]; then
|
||||
chown "${PUID}:${PGID}" /libreria 2>/dev/null || true
|
||||
fi
|
||||
|
||||
export HOME=/dati/home
|
||||
echo "Febe: avvio come utente ${PUID}, gruppo ${PGID}, fuso ${TZ:-Europe/Rome}, lingua ${LANG:-it_IT.UTF-8}."
|
||||
exec setpriv --reuid="${PUID}" --regid="${PGID}" --init-groups "$@"
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.8 KiB |
@@ -0,0 +1,35 @@
|
||||
<?xml version="1.0"?>
|
||||
<Container version="2">
|
||||
<Name>Febe</Name>
|
||||
<Repository>gitea.encke-hake.ts.net/alby96/febe:latest</Repository>
|
||||
<Registry>https://gitea.encke-hake.ts.net/Alby96/-/packages/container/febe</Registry>
|
||||
<Network>bridge</Network>
|
||||
<MyIP/>
|
||||
<Shell>bash</Shell>
|
||||
<Privileged>false</Privileged>
|
||||
<Support>https://gitea.encke-hake.ts.net/Alby96/Febe/issues</Support>
|
||||
<Project>https://gitea.encke-hake.ts.net/Alby96/Febe</Project>
|
||||
<Overview>Febe: archivio personale di foto, video e storie da Instagram. Un browser vero (Chromium su un display virtuale) visita i profili a ritmo umano, con tetti giornalieri, e salva cio' che la pagina riceve in una libreria di file sul server. Si accede una volta sola, a mano, dalla vista remota della pagina Impostazioni, Collegamento: password e codici passano dal server senza essere registrati, quindi l'interfaccia non va mai esposta su Internet senza una VPN o un proxy con HTTPS. La cartella /dati contiene la sessione di Instagram: chi ha /dati, o una sua copia, ha la sessione. Non usare il contenitore e Febe per Windows sullo stesso account. Unica variabile obbligatoria: la password dell'interfaccia. Guida: docs/docker.md nel repository.</Overview>
|
||||
<Category>Backup: MediaApp:Photos</Category>
|
||||
<WebUI>http://[IP]:[PORT:8480]/</WebUI>
|
||||
<TemplateURL>https://gitea.encke-hake.ts.net/Alby96/Febe/raw/branch/main/docker/unraid/febe.xml</TemplateURL>
|
||||
<Icon>https://gitea.encke-hake.ts.net/Alby96/Febe/raw/branch/main/docker/unraid/febe.png</Icon>
|
||||
<ExtraParams>--restart=unless-stopped --stop-timeout 30 --security-opt seccomp=/mnt/user/appdata/febe/seccomp.json</ExtraParams>
|
||||
<PostArgs/>
|
||||
<CPUset/>
|
||||
<DateInstalled/>
|
||||
<DonateText/>
|
||||
<DonateLink/>
|
||||
<Requires>Prima della prima installazione, dal terminale di Unraid: mkdir -p /mnt/user/appdata/febe && wget -O /mnt/user/appdata/febe/seccomp.json https://gitea.encke-hake.ts.net/Alby96/Febe/raw/branch/main/docker/chromium/seccomp.json (profilo seccomp per la sandbox di Chromium, indicato in ExtraParams; poi lo aggiorna il contenitore da solo). Spiegazione in docs/docker.md, «Sandbox».</Requires>
|
||||
|
||||
<Config Name="Porta dell'interfaccia" Target="8480" Default="8480" Mode="tcp" Description="Porta dell'interfaccia web (http://IP:porta/). E' l'unica porta da pubblicare: quella di debug del browser resta dentro il contenitore." Type="Port" Display="always" Required="true" Mask="false">8480</Config>
|
||||
<Config Name="Dati (/dati)" Target="/dati" Default="/mnt/user/appdata/febe" Mode="rw" Description="Database, profilo del browser con la sessione di Instagram, miniature, copie giornaliere del database, registro. Deve stare su un disco locale: la cartella delle applicazioni sul disco di cache. Mai una condivisione di rete." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/appdata/febe</Config>
|
||||
<Config Name="Libreria (/libreria)" Target="/libreria" Default="/mnt/user/Febe" Mode="rw" Description="Dove finiscono foto e video, una cartella per account. Puo' stare anche su una condivisione. Febe non cancella e non sostituisce mai un file da solo." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/Febe</Config>
|
||||
<Config Name="Da importare (/importa)" Target="/importa" Default="/mnt/user/Febe-importa" Mode="ro" Description="Cartelle con foto e video che hai gia', da importare dalla pagina Importa. Sempre in sola lettura: Febe copia, non tocca gli originali." Type="Path" Display="always" Required="false" Mask="false">/mnt/user/Febe-importa</Config>
|
||||
<Config Name="Password dell'interfaccia" Target="FEBE_PASSWORD" Default="" Mode="" Description="Obbligatoria. Senza password Febe mostra solo una pagina che spiega il problema: il motore e il browser non partono. Usa una frase lunga che non usi altrove (non quella di Instagram)." Type="Variable" Display="always" Required="true" Mask="true"></Config>
|
||||
<Config Name="TZ" Target="TZ" Default="Europe/Rome" Mode="" Description="Fuso orario: orari dei nomi dei file, fascia oraria del motore e fuso dichiarato dal browser." Type="Variable" Display="advanced" Required="false" Mask="false">Europe/Rome</Config>
|
||||
<Config Name="PUID" Target="PUID" Default="99" Mode="" Description="Utente dei file (su Unraid 99, nobody). Il browser non gira mai come root." Type="Variable" Display="advanced" Required="false" Mask="false">99</Config>
|
||||
<Config Name="PGID" Target="PGID" Default="100" Mode="" Description="Gruppo dei file (su Unraid 100, users)." Type="Variable" Display="advanced" Required="false" Mask="false">100</Config>
|
||||
<Config Name="FEBE_HOST" Target="FEBE_HOST" Default="" Mode="" Description="Facoltativa: i nomi con cui raggiungi l'interfaccia, separati da virgole (per esempio tower.local,192.168.1.10). Se la imposti, gli altri nomi vengono rifiutati." Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
|
||||
<Config Name="FEBE_SENZA_SANDBOX" Target="FEBE_SENZA_SANDBOX" Default="" Mode="" Description="Lasciala vuota. Mettila a 1 solo se il registro dice che Chromium non parte per la sandbox: e' un compromesso, spiegato in docs/docker.md." Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
|
||||
</Container>
|
||||
@@ -111,3 +111,34 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-10-13 | CSV con `;`, UTF-8 con BOM, CRLF, date locali, durate con la virgola, apostrofo davanti a = + - @ | Excel in italiano; nessuna formula da un nome di file |
|
||||
| 2026-10-13 | Analisi a gruppi di 64 file, lettura in parallelo (fino a 4), confronto e salvataggio in ordine; foto fino a 64 MB lette una volta sola | «Primo incontrato» stabile e un solo passaggio sul disco |
|
||||
| 2026-10-13 | Un lavoro d'importazione alla volta; eventi «importazione-analizzata», «importazione-completata», «account-solo-archivio» | Il disco è il collo di bottiglia; cronologia in Attività |
|
||||
| 2026-10-13 | `CapabilitiesDto` riceve un nuovo campo posizionale finale `Problems` | serve alla pagina di errore di configurazione; è un cambio di firma pubblica di un DTO: chi lo costruisce a mano deve passare il valore. |
|
||||
| 2026-10-13 | `POST /api/connection/begin` non segna il browser come usato; lo segna `finish` | «Riprendi» dopo una verifica deve accendersi solo quando Alberto ha finito nel browser, non appena lo apre. |
|
||||
| 2026-10-13 | Ripieghi `TryAdd` per tutto ciò che non è di questo lavoro (collegamento, anteprima, invio Telegram, cambio cartella dati) | interfaccia e prove funzionano già; la composizione sostituisce i pezzi senza toccare Febe.Web. |
|
||||
| 2026-10-13 | `ImportHub` costruisce un `ImportService` sulla libreria se la composizione non ne registra uno; in Docker solo sotto `FebeWebOptions.ImportRoot` (`/importa`) | Importa funziona subito in tutte e due le vesti, nei limiti di §9.1. |
|
||||
| 2026-10-13 | In Limiti e comportamento gli orari sono campi di testo a 24 ore | il selettore d'ora del browser mostra AM/PM secondo la lingua del sistema. |
|
||||
| 2026-10-13 | Scartare un doppione dopo uno scaricamento avviene solo su scelta esplicita: il file scartato si ricorda e non si riscarica | regola 11, la libreria non decide da sola. |
|
||||
| 2026-10-13 | Cambiando la cartella della libreria (desktop), gli account con cartella già esistente restano fissati al vecchio percorso | nessun file si sposta da solo; i nuovi account vanno nella cartella nuova. |
|
||||
| 2026-10-13 | Il gettone Telegram non torna mai all'interfaccia (solo `telegramTokenSet`) e un campo vuoto lo lascia com'è | §13.3 e regola 10. |
|
||||
| 2026-10-13 | La ricostruzione del database chiede di scrivere «ricostruisci» ed è rifiutata durante un'importazione | operazione pesante (§8.5). |
|
||||
| 2026-10-13 | `/salute` non fatto qui | appartiene al lavoro Server/Docker; evita due rotte uguali. |
|
||||
| 2026-10-13 | Nella dimostrazione «In coda» è ordinata per orario | come il mockup 06; il motore vero dà il suo ordine. |
|
||||
| 2026-10-13 | `ApiErrorMiddleware` toglie « (Parameter 'x')» dai messaggi | gli errori arrivano all'interfaccia in italiano pulito. |
|
||||
| 2026-10-13 | «Fai una copia adesso» sostituisce la copia di oggi | una copia al giorno, se ne tengono 7. |
|
||||
| 2026-10-13 | Server reale come comando predefinito di `febe`; password solo da `FEBE_PASSWORD`, mai da riga di comando | Le righe di comando sono leggibili da altri processi |
|
||||
| 2026-10-13 | Problema di configurazione: solo interfaccia su un database temporaneo, gate API 503, nessun browser né motore, nulla scritto in `/dati` | §8.2, §11: la vista remota mai raggiungibile senza password |
|
||||
| 2026-10-13 | Senza password il middleware lascia passare solo pagina d'errore, file, `capabilities`, `preferences`, `/salute` | Prima rispondeva 503 a tutto e la pagina d'errore non poteva comparire |
|
||||
| 2026-10-13 | Profilo seccomp dedicato (predefinito di Docker + `clone`/`unshare`) in compose e nel modello Unraid; `FEBE_SENZA_SANDBOX` solo come compromesso esplicito | S5 misurata: col profilo predefinito «No usable sandbox», col dedicato sandbox completa |
|
||||
| 2026-10-13 | Il profilo seccomp si copia a ogni avvio in `/dati/seccomp.json`; Unraid lo chiede in ExtraParams, con il primo scaricamento indicato in `Requires` | Docker legge il profilo alla creazione del contenitore |
|
||||
| 2026-10-13 | Criteri di Chromium: oltre ai tre richiesti, anche `PasswordLeakDetectionEnabled: false` | Nessun trattamento della password di Instagram dal browser |
|
||||
| 2026-10-13 | `HEALTHCHECK` con `febe --controllo-salute`, niente curl | Nessun pacchetto in più |
|
||||
| 2026-10-13 | tini come processo 1; entrypoint minimo con `setpriv`; `PUID=0` rifiutato | §11: Febe.Server sorveglia Xvfb e Chromium, utente non root |
|
||||
| 2026-10-13 | La porta di debug resta 9222 su 127.0.0.1; `HOME` di Chromium in `/dati/home`; variabili di proxy tolte all'ambiente del browser | §6.1, regola 2 |
|
||||
| 2026-10-13 | Lock `Singleton*` del profilo e lock X orfani tolti prima di ogni avvio | Dopo la ricreazione del contenitore il nome host cambia e Chromium rifiuterebbe il profilo con un dialogo invisibile |
|
||||
| 2026-10-13 | «Scollega» riavvia sul posto lo stesso `ChromiumProcessHost` (`RestartAsync`) | Sessione CDP, cattura e coda degli scaricamenti restano agganciate |
|
||||
| 2026-10-13 | Vista remota: «indietro» con `Page.navigate` all'indirizzo precedente tenuto in memoria; una vista alla volta, la più recente vince | Nessun comando di cronologia fra quelli ammessi |
|
||||
| 2026-10-13 | `FEBE_HOST` facoltativa (più i nomi loopback); vuota significa qualunque nome; `FEBE_PROXY_FIDATO` per un proxy HTTPS | Difesa in più contro il DNS rebinding senza rompere l'uso in LAN |
|
||||
| 2026-10-13 | Registro: un file al giorno, 14 giorni, 20 MB al giorno, indirizzi tolti | §8.2, §13.2 |
|
||||
| 2026-10-13 | Copia del database all'avvio e poi ogni giorno alle 3:20 locali | Fuori dalla fascia di ogni profilo |
|
||||
| 2026-10-13 | Modalità di sviluppo `--sito-di-prova` (solo indirizzi locali), `--accesso-di-prova`, `--prima-sessione` | Composizione vera senza Instagram (regola 1) |
|
||||
| 2026-10-13 | Prove d'insieme: orologio compresso 10× e fuso `Etc/GMT±n` dove è mezzogiorno | Motore sempre in fascia, a qualunque ora giri la prova |
|
||||
| 2026-10-13 | Il server reale registra `EngineHostSettingsControl`, un'anteprima vera del browser (`Page.captureScreenshot` al più ogni 4 s, niente sulla pagina vuota) e l'acquisizione della libreria, che riceve subito il nuovo schema dei nomi (`LibraryIngest.Apply`) | Raccordo fra interfaccia parte 2 e composizione del server: i limiti arrivano al motore in esecuzione e lo schema vale per i prossimi file senza riavvio (§4.7) |
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
# Febe in Docker (e su Unraid)
|
||||
|
||||
La veste Docker di Febe (specifica §11): un solo contenitore con l'interfaccia web, il motore, un Chromium vero su un
|
||||
display virtuale (Xvfb) e la libreria su disco. Si usa dal browser di casa; il browser di Febe si vede e si usa dalla
|
||||
**vista remota** della pagina Impostazioni ▸ Collegamento.
|
||||
|
||||
> **Prima di tutto.** Scaricare con un programma è contro le condizioni d'uso di Instagram. Febe va piano per ridurre il
|
||||
> rischio per l'account (ritmo umano, tetti, fermo al primo segnale), ma non può azzerarlo.
|
||||
|
||||
## Che cosa c'è nell'immagine
|
||||
|
||||
- Debian stabile ridotta (`debian:trixie-slim`). Su Ubuntu il pacchetto Chromium è uno snap e nei contenitori non funziona.
|
||||
- Febe pubblicato **autosufficiente** per `linux-x64`: nell'immagine non c'è il runtime .NET.
|
||||
- `chromium` e `chromium-l10n`, `xvfb`, `ffmpeg` (miniature dei video importati), ICU, caratteri di sistema con le emoji
|
||||
(`fonts-noto-color-emoji`, `fonts-liberation`, `fonts-dejavu-core`), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata.
|
||||
- `tini` come processo 1 (inoltra lo stop a Febe e raccoglie i processi di Chromium rimasti orfani) e `setpriv` per
|
||||
scendere all'utente `PUID`/`PGID`. Nessuno script fa da supervisore: è Febe ad avviare e riavviare Xvfb e Chromium.
|
||||
- Un file di criteri di Chromium (`/etc/chromium/policies/managed/febe.json`) che spegne il salvataggio delle password e
|
||||
la compilazione automatica: con l'archivio di base finirebbero in chiaro nel profilo. Nel profilo resta solo la sessione.
|
||||
- L'immagine si costruisce solo con le prove verdi: la compilazione e tutte le prove girano dentro la costruzione
|
||||
(quelle con il browser vero lì si saltano da sole, perché nello stadio di compilazione non ci sono Chromium e Xvfb;
|
||||
girano nella CI e in sviluppo).
|
||||
|
||||
## Volumi
|
||||
|
||||
| Volume | Uso | Dove metterlo |
|
||||
|---|---|---|
|
||||
| `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei, `seccomp.json` | Su un **disco locale** del server. Su Unraid: `/mnt/user/appdata/febe` (la cartella delle applicazioni sul disco di cache). Mai una condivisione di rete: SQLite e il profilo del browser lì si rovinano, e Febe si rifiuta di partire |
|
||||
| `/libreria` | Foto e video, una cartella per account, con `_febe.jsonl` | Dove vuoi, anche su una condivisione. Febe non cancella e non sostituisce mai un file da solo |
|
||||
| `/importa` | Cartelle da importare (pagina Importa) | **Sempre in sola lettura** (`:ro`): Febe copia, gli originali non si toccano |
|
||||
|
||||
## Variabili
|
||||
|
||||
| Variabile | Significato | Predefinito |
|
||||
|---|---|---|
|
||||
| `FEBE_PASSWORD` | Password dell'interfaccia. **Obbligatoria**: senza, il motore e il browser non partono e l'interfaccia mostra solo la pagina che spiega il problema | nessuno |
|
||||
| `FEBE_PORTA` | Porta dell'interfaccia dentro il contenitore | 8480 |
|
||||
| `TZ` | Fuso orario: fascia del motore, date nei nomi dei file, fuso dichiarato dal browser | Europe/Rome |
|
||||
| `LANG` | Lingua del contenitore e quindi del browser | it_IT.UTF-8 |
|
||||
| `PUID`, `PGID` | Utente e gruppo con cui gira Febe e di cui sono i file | 99, 100 (Unraid) |
|
||||
| `FEBE_HOST` | Facoltativa: i nomi con cui raggiungi l'interfaccia, separati da virgole (`tower.local,192.168.1.10`). Se c'è, ogni altro nome è rifiutato (oltre a 127.0.0.1 per il controllo di salute) | qualunque nome |
|
||||
| `FEBE_PROXY_FIDATO` | `1` se davanti c'è un proxy con HTTPS che passa `X-Forwarded-Host`: il controllo dell'origine usa quel nome | spenta |
|
||||
| `FEBE_SENZA_SANDBOX` | `1` avvia Chromium con `--no-sandbox`: è il compromesso descritto sotto, da usare solo se il profilo seccomp non si può usare | spenta |
|
||||
| `FEBE_CHROMIUM`, `FEBE_PORTA_DEBUG`, `FEBE_DISPLAY` | Avanzate: eseguibile di Chromium, porta di debug (sempre su 127.0.0.1), display di Xvfb | `/usr/bin/chromium`, 9222, `:99` |
|
||||
|
||||
La password dell'interfaccia non si passa mai sulla riga di comando e non finisce nei registri.
|
||||
|
||||
## Porte
|
||||
|
||||
Si pubblica **solo** la porta dell'interfaccia (8480). La porta di debug del browser (9222) ascolta solo su `127.0.0.1`
|
||||
dentro il contenitore: non va mai pubblicata, e Febe si rifiuta di usare il browser se la trova aperta altrove.
|
||||
|
||||
## Utente: PUID e PGID
|
||||
|
||||
L'avvio crea, se mancano, il gruppo `PGID` e l'utente `PUID`, assegna `/dati` a quell'utente (la prima volta, o quando
|
||||
cambi PUID/PGID: allora anche il contenuto) e passa a quell'utente con `setpriv`. `/libreria` non viene mai cambiata
|
||||
ricorsivamente: se Febe non riesce a scriverci, il registro lo dice. Febe **non gira come root**: con `PUID=0` il
|
||||
contenitore si ferma con un messaggio.
|
||||
|
||||
## Sandbox di Chromium (S5)
|
||||
|
||||
Esito della prova del 13 ottobre 2026 (dettagli in `docker/chromium/LEGGIMI.md`):
|
||||
|
||||
- come utente normale, **fuori** da Docker, la sandbox di Chromium parte da sola (spazi dei nomi utente);
|
||||
- **dentro** Docker, con il profilo seccomp predefinito, Chromium non parte affatto: `No usable sandbox!`. Il profilo
|
||||
di Docker vieta la creazione di spazi dei nomi utente a chi non ha `CAP_SYS_ADMIN`;
|
||||
- con il **profilo seccomp dedicato** di Febe (`docker/chromium/seccomp.json`: quello di Docker più `clone` e
|
||||
`unshare`) la sandbox è completa (`chrome://sandbox`: «You are adequately sandboxed») e il resto del filtro di Docker
|
||||
resta attivo. **È l'impostazione consigliata**, già scritta in `compose.yml` e nel modello di Unraid.
|
||||
|
||||
L'avvio del contenitore copia il profilo in `/dati/seccomp.json` a ogni partenza, così sul server c'è sempre la versione
|
||||
dell'immagine; Docker però lo legge quando **crea** il contenitore, quindi la prima volta il file va messo a mano
|
||||
(vedi Unraid, sotto).
|
||||
|
||||
Se il profilo dedicato non si può usare, le alternative sono due, in quest'ordine:
|
||||
|
||||
1. `--security-opt seccomp=unconfined`: la sandbox di Chromium resta attiva, ma il contenitore perde tutto il filtro
|
||||
seccomp di Docker.
|
||||
2. `FEBE_SENZA_SANDBOX=1`: Chromium parte con `--no-sandbox`. **È un compromesso**: una pagina che sfruttasse un
|
||||
difetto del browser non troverebbe la sandbox di Chromium a fermarla, solo i limiti del contenitore. Si accetta
|
||||
soltanto perché quel browser visita esclusivamente Instagram, e solo se le due strade sopra non sono possibili.
|
||||
Chromium mostra anche una barra d'avviso in alto, che toglie circa 50 pixel alla pagina.
|
||||
|
||||
Febe non sceglie da solo: se Chromium non parte, il registro dice perché e rimanda a questa sezione.
|
||||
|
||||
## Sicurezza: da leggere prima di installare
|
||||
|
||||
- **Mai esporre l'interfaccia su Internet** senza una VPN (per esempio WireGuard o Tailscale) o un proxy con HTTPS
|
||||
davanti. Dalla vista remota passa **la password di Instagram**: in Docker tasti, password e codici di Alberto
|
||||
attraversano la rete di casa e la memoria del server per arrivare al browser di Febe. Non vengono registrati né
|
||||
conservati, ma su HTTP in chiaro sono leggibili da chi sta sulla stessa rete.
|
||||
- **Chi ha `/dati`, o una sua copia, ha la sessione di Instagram.** Vale anche per le copie di sicurezza della cartella
|
||||
delle applicazioni (per esempio il plugin di backup di Unraid): trattale come una password.
|
||||
- **Contenitore e Febe per Windows non vanno usati insieme sullo stesso account.** Un account, un motore: due Febe che
|
||||
raccolgono con lo stesso account sommano le visite e raddoppiano il rischio.
|
||||
- La sessione nasce e resta nel browser del contenitore: i cookie non si copiano da un'altra macchina.
|
||||
- L'interfaccia è protetta da password (cookie di sessione `HttpOnly`, `SameSite=Strict`, blocco dopo tentativi
|
||||
ripetuti); ogni comando e l'apertura della vista remota controllano che la richiesta arrivi dall'interfaccia stessa.
|
||||
|
||||
## Installazione su Unraid
|
||||
|
||||
1. Dal terminale di Unraid, **una volta sola**, metti il profilo seccomp dove il modello lo cerca:
|
||||
|
||||
```sh
|
||||
mkdir -p /mnt/user/appdata/febe
|
||||
wget -O /mnt/user/appdata/febe/seccomp.json \
|
||||
https://gitea.encke-hake.ts.net/Alby96/Febe/raw/branch/main/docker/chromium/seccomp.json
|
||||
```
|
||||
|
||||
2. Il registro di Gitea dell'immagine è `gitea.encke-hake.ts.net/alby96/febe` (lo stesso host su cui la pubblica il
|
||||
rilascio). Se Unraid non riesce a scaricarla, accedi al registro dal terminale (`docker login gitea.encke-hake.ts.net`).
|
||||
3. Docker ▸ Aggiungi contenitore ▸ modello da `docker/unraid/febe.xml` (o dall'indirizzo del modello). Controlla:
|
||||
- porta 8480;
|
||||
- `/dati` su `/mnt/user/appdata/febe` (disco di cache);
|
||||
- `/libreria` dove vuoi le foto; `/importa` in sola lettura;
|
||||
- **password dell'interfaccia** (obbligatoria, nascosta);
|
||||
- `TZ`, `PUID` 99, `PGID` 100 tra le impostazioni avanzate;
|
||||
- in «Extra Parameters»: `--restart=unless-stopped --stop-timeout 30 --security-opt seccomp=/mnt/user/appdata/febe/seccomp.json`.
|
||||
4. Apri `http://<IP di Unraid>:8480/`, entra con la password, vai in Impostazioni ▸ Collegamento ▸ «Accedi a
|
||||
Instagram»: la vista remota mostra la vera pagina di accesso; scrivi tu nome utente, password ed eventuale codice,
|
||||
poi «Ho finito». Febe comincia qualche minuto dopo, con l'avvio graduale.
|
||||
5. Il collegamento sopravvive ai riavvii: la sessione resta nel profilo del browser in `/dati/browser`.
|
||||
|
||||
## Docker Compose
|
||||
|
||||
`docker/compose.yml` è un esempio pronto: immagine, porta, volumi (con `/importa` in sola lettura), variabili, profilo
|
||||
seccomp con percorso relativo al file, `restart: unless-stopped`, 30 secondi per fermarsi. `init: true` non serve
|
||||
(c'è già `tini`) e nemmeno `shm_size` (Chromium usa `/tmp` al posto della memoria condivisa).
|
||||
|
||||
```sh
|
||||
FEBE_PASSWORD='una frase lunga' docker compose -f docker/compose.yml up -d
|
||||
```
|
||||
|
||||
## Salute
|
||||
|
||||
`GET /salute` risponde senza password `{"stato":"ok"}` (200) oppure `{"stato":"problema"}` (503) quando un problema di
|
||||
configurazione ferma Febe (password mancante, `/dati` non scrivibile o su un disco di rete). L'immagine ha un
|
||||
`HEALTHCHECK` che lo chiede ogni 30 secondi con il programma stesso (`/app/febe --controllo-salute`: nell'immagine non
|
||||
c'è curl). Unraid mostra lo stato accanto al contenitore; da terminale: `docker inspect --format '{{.State.Health.Status}}' febe`.
|
||||
|
||||
## Problemi comuni
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|---|---|
|
||||
| L'interfaccia mostra solo una pagina «Manca la password dell'interfaccia» | Imposta `FEBE_PASSWORD` e riavvia il contenitore |
|
||||
| «La cartella dei dati è su un disco di rete» o «non può scrivere» | Collega `/dati` a una cartella su un disco locale (su Unraid l'appdata sul disco di cache) e controlla PUID/PGID |
|
||||
| Nel registro: «Il browser non parte… No usable sandbox» | Manca il profilo seccomp: vedi «Sandbox» sopra |
|
||||
| Unraid non crea il contenitore: «opening seccomp profile … no such file» | Manca `/mnt/user/appdata/febe/seccomp.json`: passo 1 dell'installazione |
|
||||
| La porta è occupata | Cambia la porta pubblicata (o `FEBE_PORTA`) |
|
||||
|
||||
Il registro di Febe è in `/dati/registro/febe-AAAA-MM-GG.log` e nell'output del contenitore (`docker logs febe`).
|
||||
Contiene azioni ed esiti, nomi utente sì; mai password, cookie, tasti, didascalie, corpi delle risposte né indirizzi
|
||||
firmati del CDN.
|
||||
|
||||
## Arresto e aggiornamento
|
||||
|
||||
- Allo stop (`docker stop`, aggiornamento, riavvio di Unraid) Febe chiude la vista remota, ferma il motore (la sessione
|
||||
in corso si chiude), poi Chromium con SIGINT, così la sessione di Instagram è scritta nel profilo, poi Xvfb. Lascia 30
|
||||
secondi (`--stop-timeout 30`, `stop_grace_period: 30s`); di solito ne bastano pochi.
|
||||
- **Aggiornare**: scarica la nuova immagine e ricrea il contenitore (su Unraid «Force update» o «Check for updates»).
|
||||
`/dati` e `/libreria` restano; il database si aggiorna da solo all'avvio (migrazioni numerate, in una transazione).
|
||||
Per sicurezza, prima di un aggiornamento importante puoi copiare a mano `/dati/febe.sqlite` a contenitore fermo.
|
||||
- Copie del database: una al giorno in `/dati/copie/febe-AAAA-MM-GG.sqlite`, sette giorni. Per tornare indietro:
|
||||
ferma il contenitore, sostituisci `/dati/febe.sqlite` con una copia, riavvia. Se il database va perso, la pagina
|
||||
Impostazioni ▸ Dati lo ricostruisce dalla libreria (`_febe.jsonl`) senza riscaricare nulla.
|
||||
|
||||
## Sviluppo senza Docker
|
||||
|
||||
Il server si avvia anche fuori dal contenitore, contro il sito di prova locale invece di Instagram (regola 1: mai
|
||||
Instagram dalle prove):
|
||||
|
||||
```sh
|
||||
dotnet run --project tools/Febe.SitoDiProva -- --porta 8481 --porta-cdn 8482
|
||||
FEBE_PASSWORD=prova dotnet run --project src/Febe.Server -- \
|
||||
--dati /tmp/febe/dati --libreria /tmp/febe/libreria --importa /tmp/febe/importa --ascolta 127.0.0.1 \
|
||||
--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 5
|
||||
```
|
||||
|
||||
- `--sito-di-prova` accetta solo indirizzi di questo computer; il «CDN» è `127.0.0.2` sulla porta successiva, oppure
|
||||
`--cdn-di-prova`. Mappe dei bersagli, lettori e segnali diventano quelli del sito di prova (`*.prova.json`).
|
||||
- `--accesso-di-prova` apre il sito una volta all'avvio, così il suo cookie di sessione esiste come dopo un accesso.
|
||||
- `--prima-sessione N` fa partire la prima sessione dopo N secondi invece di 2–10 minuti.
|
||||
- Come root servono `--senza-sandbox` (Chromium lo pretende) e, se Chromium non è nel `PATH`, `FEBE_CHROMIUM`.
|
||||
- Prova d'insieme automatica: `dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Server"`.
|
||||
@@ -123,6 +123,20 @@ public static class Keyboard
|
||||
public static Task KeyUpAsync(ICdpSession cdp, KeyStroke key, CancellationToken ct = default) =>
|
||||
cdp.SendAsync("Input.dispatchKeyEvent", Build("keyUp", key), ct);
|
||||
|
||||
/// <summary>
|
||||
/// Inserts text without key codes (<c>Input.dispatchKeyEvent</c> of type «char»): composed characters of the
|
||||
/// remote view, such as «è» typed with a dead key. Never logged.
|
||||
/// </summary>
|
||||
public static Task CharAsync(ICdpSession cdp, string text, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(cdp);
|
||||
ArgumentException.ThrowIfNullOrEmpty(text);
|
||||
return cdp.SendAsync(
|
||||
"Input.dispatchKeyEvent",
|
||||
new JsonObject { ["type"] = "char", ["text"] = text, ["unmodifiedText"] = text },
|
||||
ct);
|
||||
}
|
||||
|
||||
/// <summary>Presses and releases one key, with a human hold time when a clock is given.</summary>
|
||||
public static async Task PressAsync(ICdpSession cdp, KeyStroke key, IClock? clock = null, IRandomSource? random = null, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -27,12 +27,14 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
private readonly IBrowserLog _log;
|
||||
private readonly ReconnectingCdpSession _session = new();
|
||||
private readonly SemaphoreSlim _connectLock = new(1, 1);
|
||||
private readonly SemaphoreSlim _restartLock = new(1, 1);
|
||||
// Not disposed on purpose: background reconnection may still read its token; it holds no timer or handle.
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private SupervisedProcess? _supervisor;
|
||||
private CdpClient? _client;
|
||||
private BrowserOptions? _options;
|
||||
private int _stopping;
|
||||
private int _restarting;
|
||||
|
||||
public ChromiumProcessHost(ChromiumLaunchOptions? launch = null, IClock? clock = null, IBrowserLog? log = null)
|
||||
{
|
||||
@@ -62,6 +64,9 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
|
||||
public event EventHandler<SupervisedState>? StateChanged;
|
||||
|
||||
/// <summary>True while a page connection is attached (commands can be sent).</summary>
|
||||
public bool IsAttached => _session.IsAttached;
|
||||
|
||||
public async Task StartAsync(BrowserOptions options, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
@@ -70,6 +75,47 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
throw new InvalidOperationException("Il browser è già avviato.");
|
||||
}
|
||||
|
||||
await StartCoreAsync(options, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops the browser (SIGINT, so the profile is written to disk), runs <paramref name="whileStopped"/> — «Scollega»
|
||||
/// deletes the profile there — and starts it again with the same options. <see cref="Cdp"/> stays the same object:
|
||||
/// subscriptions survive and <see cref="ICdpConnectionEvents.Reconnected"/> is raised once the new browser is
|
||||
/// connected.
|
||||
/// </summary>
|
||||
public async Task RestartAsync(Action? whileStopped, CancellationToken ct)
|
||||
{
|
||||
var options = _options ?? throw new InvalidOperationException("Il browser non è mai partito.");
|
||||
if (Volatile.Read(ref _stopping) == 1)
|
||||
{
|
||||
throw new InvalidOperationException("Il browser si sta fermando.");
|
||||
}
|
||||
|
||||
await _restartLock.WaitAsync(ct).ConfigureAwait(false);
|
||||
Interlocked.Exchange(ref _restarting, 1);
|
||||
try
|
||||
{
|
||||
if (_supervisor is { } current)
|
||||
{
|
||||
await DropClientAsync().ConfigureAwait(false);
|
||||
await current.StopAsync(StopGrace).ConfigureAwait(false);
|
||||
_supervisor = null;
|
||||
_log.Info("Chromium è fermo per un nuovo avvio.");
|
||||
}
|
||||
|
||||
whileStopped?.Invoke();
|
||||
await StartCoreAsync(options, ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref _restarting, 0);
|
||||
_restartLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StartCoreAsync(BrowserOptions options, CancellationToken ct)
|
||||
{
|
||||
var executable = ChromiumCommandLine.FindExecutable(options.ExecutablePath)
|
||||
?? throw new FileNotFoundException("Chromium non è installato o non si trova (si può indicare con FEBE_CHROMIUM).");
|
||||
var arguments = ChromiumCommandLine.Build(options, _launch);
|
||||
@@ -131,10 +177,20 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
}
|
||||
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
await DropClientAsync().ConfigureAwait(false);
|
||||
if (_supervisor is { } supervisor)
|
||||
|
||||
// A restart in progress («Scollega») finishes first, so that no browser is left running behind the stop.
|
||||
await _restartLock.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await supervisor.StopAsync(StopGrace).ConfigureAwait(false);
|
||||
await DropClientAsync().ConfigureAwait(false);
|
||||
if (_supervisor is { } supervisor)
|
||||
{
|
||||
await supervisor.StopAsync(StopGrace).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_restartLock.Release();
|
||||
}
|
||||
|
||||
_log.Info("Chromium è fermo.");
|
||||
@@ -248,7 +304,7 @@ public sealed class ChromiumProcessHost : IBrowserHost
|
||||
|
||||
private void OnClientDisconnected(object? sender, Exception? reason)
|
||||
{
|
||||
if (Volatile.Read(ref _stopping) == 1 || !ReferenceEquals(sender, Volatile.Read(ref _client)))
|
||||
if (Volatile.Read(ref _stopping) == 1 || Volatile.Read(ref _restarting) == 1 || !ReferenceEquals(sender, Volatile.Read(ref _client)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -167,6 +167,13 @@ public sealed class RemoteViewSession : IAsyncDisposable
|
||||
return e.Down ? Keyboard.KeyDownAsync(_cdp, e.Key, ct) : Keyboard.KeyUpAsync(_cdp, e.Key, ct);
|
||||
}
|
||||
|
||||
/// <summary>Inserts composed text (a «char» event without key codes). Never logged.</summary>
|
||||
public Task CharAsync(string text, CancellationToken ct = default)
|
||||
{
|
||||
EnsureActive();
|
||||
return Keyboard.CharAsync(_cdp, text, ct);
|
||||
}
|
||||
|
||||
/// <summary>Opens an address chosen by Alberto (e.g. the login page from the connection page).</summary>
|
||||
public Task<NavigationResult> NavigateAsync(string url, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -88,6 +88,19 @@ public sealed class LibraryIngest(
|
||||
SafeFileWriter? writer = null)
|
||||
{
|
||||
private readonly SafeFileWriter _writer = writer ?? new SafeFileWriter(layout.MaxPathLength);
|
||||
private volatile LibraryNaming _naming = naming;
|
||||
private volatile bool _setFileTimeToPublication = setFileTimeToPublication;
|
||||
|
||||
/// <summary>
|
||||
/// Applies new naming schemes and the file-time choice from the settings page. They hold for the next files only:
|
||||
/// files already saved are never renamed (spec §4.7).
|
||||
/// </summary>
|
||||
public void Apply(LibraryNaming newNaming, bool newSetFileTimeToPublication)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(newNaming);
|
||||
_naming = newNaming;
|
||||
_setFileTimeToPublication = newSetFileTimeToPublication;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores one file of an entry already recorded in the database (<paramref name="media"/> must have its key).
|
||||
@@ -121,7 +134,7 @@ public sealed class LibraryIngest(
|
||||
}
|
||||
|
||||
var folder = layout.AccountFolder(account);
|
||||
var scheme = naming.For(entry.Kind);
|
||||
var scheme = _naming.For(entry.Kind);
|
||||
var zone = clock.LocalZone;
|
||||
var provisional = content.FixedRelativePath is { } fixedPath
|
||||
? LibraryLayout.ToStored(fixedPath)
|
||||
@@ -153,7 +166,7 @@ public sealed class LibraryIngest(
|
||||
},
|
||||
new SafeWriteOptions
|
||||
{
|
||||
LastWriteTime = setFileTimeToPublication ? entry.PublishedAt : null,
|
||||
LastWriteTime = _setFileTimeToPublication ? entry.PublishedAt : null,
|
||||
MaxBytes = content.MaxBytes,
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Gestures;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
/// <summary>
|
||||
/// The remote view over the real Chromium (spec §4.1, §11, PROTOCOLLO.md): a <see cref="RemoteViewSession"/> per open
|
||||
/// view, which holds the «Alberto is driving» lease while it is open, so the engine is still. One view at a time: a
|
||||
/// view opened in another tab replaces the older one. Keys go to the browser and nowhere else.
|
||||
/// </summary>
|
||||
internal sealed class BrowserRemoteViewHost(BrowserSupervisor browser, BrowserUseTracker tracker, IClock clock, ServerLog log) : IRemoteViewHost
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private BrowserRemoteViewConnection? _current;
|
||||
private bool _shuttingDown;
|
||||
|
||||
public async Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
|
||||
{
|
||||
if (!browser.IsAvailable)
|
||||
{
|
||||
throw new RemoteViewUnavailableException(browser.LastError is { } error
|
||||
? "Il browser di Febe non è in funzione: " + error
|
||||
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
|
||||
}
|
||||
|
||||
BrowserRemoteViewConnection? previous;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_shuttingDown)
|
||||
{
|
||||
throw new RemoteViewUnavailableException("Febe si sta fermando.");
|
||||
}
|
||||
|
||||
previous = _current;
|
||||
_current = null;
|
||||
}
|
||||
|
||||
if (previous is not null)
|
||||
{
|
||||
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var connection = new BrowserRemoteViewConnection(this, browser, tracker, clock);
|
||||
try
|
||||
{
|
||||
await connection.StartAsync(browser.BrowserOptions.WindowWidth, browser.BrowserOptions.WindowHeight, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
||||
{
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
throw new RemoteViewUnavailableException("Il browser di Febe non risponde: riprova fra qualche secondo.", ex);
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
_current = connection;
|
||||
}
|
||||
|
||||
log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
|
||||
return connection;
|
||||
}
|
||||
|
||||
/// <summary>Febe is stopping: the open view is closed with a reason the page can show.</summary>
|
||||
public async Task ShutdownAsync()
|
||||
{
|
||||
BrowserRemoteViewConnection? current;
|
||||
lock (_gate)
|
||||
{
|
||||
_shuttingDown = true;
|
||||
current = _current;
|
||||
_current = null;
|
||||
}
|
||||
|
||||
if (current is not null)
|
||||
{
|
||||
await current.EndAsync(RemoteViewEnd.ShuttingDown).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
internal void Closed(BrowserRemoteViewConnection connection)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (ReferenceEquals(_current, connection))
|
||||
{
|
||||
_current = null;
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("vista", "Vista remota chiusa.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One open remote view on the real browser.</summary>
|
||||
internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
{
|
||||
private readonly BrowserRemoteViewHost _owner;
|
||||
private readonly BrowserSupervisor _browser;
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
private readonly IClock _clock;
|
||||
private readonly RemoteViewSession _session;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Queue<RemoteViewMeta> _meta = new();
|
||||
private readonly SemaphoreSlim _signal = new(0, int.MaxValue);
|
||||
private readonly CancellationTokenSource _ended = new();
|
||||
private readonly List<IDisposable> _subscriptions = [];
|
||||
|
||||
// Full addresses of this view, for «back»: kept in memory only, never logged and never sent (the page gets them
|
||||
// without query string).
|
||||
private readonly List<string> _history = [];
|
||||
private ScreencastFrame? _pendingFrame;
|
||||
private string? _mainFrameId;
|
||||
private string _url = "about:blank";
|
||||
private int _width;
|
||||
private int _height;
|
||||
private int _disposed;
|
||||
private bool _used;
|
||||
|
||||
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, BrowserSupervisor browser, BrowserUseTracker tracker, IClock clock)
|
||||
{
|
||||
_owner = owner;
|
||||
_browser = browser;
|
||||
_tracker = tracker;
|
||||
_clock = clock;
|
||||
_session = new RemoteViewSession(browser.Host.Cdp, browser.Host.UserDriving);
|
||||
}
|
||||
|
||||
public RemoteViewEnd? Ended { get; private set; }
|
||||
|
||||
private ICdpSession Cdp => _browser.Host.Cdp;
|
||||
|
||||
public async Task StartAsync(int width, int height, CancellationToken ct)
|
||||
{
|
||||
_width = width;
|
||||
_height = height;
|
||||
_subscriptions.Add(Cdp.On("Page.frameNavigated", OnFrameNavigated));
|
||||
_subscriptions.Add(Cdp.On("Page.navigatedWithinDocument", OnNavigatedWithinDocument));
|
||||
var tree = await Cdp.SendAsync("Page.getFrameTree", null, ct).ConfigureAwait(false);
|
||||
var frame = tree.GetProperty("frameTree").GetProperty("frame");
|
||||
_mainFrameId = frame.GetProperty("id").GetString();
|
||||
var url = frame.TryGetProperty("url", out var u) ? u.GetString() ?? string.Empty : string.Empty;
|
||||
lock (_gate)
|
||||
{
|
||||
_history.Add(url);
|
||||
_url = WithoutQuery(url);
|
||||
_meta.Enqueue(new RemoteViewMeta(_width, _height, _url));
|
||||
}
|
||||
|
||||
_signal.Release();
|
||||
_session.Screencast.FrameReceived += OnFrame;
|
||||
await _session.StartAsync(new ScreencastOptions(Quality: 70, MaxWidth: width, MaxHeight: height), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<RemoteViewOutput> ReadAsync([EnumeratorCancellation] CancellationToken ct)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _ended.Token);
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _signal.WaitAsync(linked.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
RemoteViewMeta? meta = null;
|
||||
ScreencastFrame? frame = null;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_meta.Count > 0)
|
||||
{
|
||||
meta = _meta.Dequeue();
|
||||
}
|
||||
else
|
||||
{
|
||||
frame = _pendingFrame;
|
||||
_pendingFrame = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (meta is not null)
|
||||
{
|
||||
yield return meta;
|
||||
}
|
||||
else if (frame is not null)
|
||||
{
|
||||
yield return new RemoteViewFrame(frame.Jpeg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Task MouseAsync(RemoteViewMouse input, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
if (_session.Screencast.LastFrame is null)
|
||||
{
|
||||
return Task.CompletedTask; // no frame yet: nothing on screen to point at
|
||||
}
|
||||
|
||||
MarkUsed();
|
||||
var action = input.Action switch
|
||||
{
|
||||
RemoteViewMouseAction.Down => RemoteMouseAction.Down,
|
||||
RemoteViewMouseAction.Up => RemoteMouseAction.Up,
|
||||
RemoteViewMouseAction.Wheel => RemoteMouseAction.Wheel,
|
||||
_ => RemoteMouseAction.Move,
|
||||
};
|
||||
var button = input.Button switch
|
||||
{
|
||||
RemoteViewButton.Left => RemoteMouseButton.Left,
|
||||
RemoteViewButton.Middle => RemoteMouseButton.Middle,
|
||||
RemoteViewButton.Right => RemoteMouseButton.Right,
|
||||
_ => RemoteMouseButton.None,
|
||||
};
|
||||
return _session.MouseAsync(new RemoteMouseEvent(action, input.X, input.Y, button, input.ClickCount, input.DeltaX, input.DeltaY), ct);
|
||||
}
|
||||
|
||||
public Task KeyAsync(RemoteViewKey input, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
MarkUsed();
|
||||
if (input.Action == RemoteViewKeyAction.Char)
|
||||
{
|
||||
return _session.CharAsync(input.Text!, ct);
|
||||
}
|
||||
|
||||
return _session.KeyAsync(new RemoteKeyEvent(input.Action == RemoteViewKeyAction.Down, RemoteKeys.ToStroke(input)), ct);
|
||||
}
|
||||
|
||||
public async Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct)
|
||||
{
|
||||
MarkUsed();
|
||||
string? target;
|
||||
lock (_gate)
|
||||
{
|
||||
if (action == RemoteViewNavigation.Back)
|
||||
{
|
||||
if (_history.Count < 2)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_history.RemoveAt(_history.Count - 1);
|
||||
target = _history[^1];
|
||||
}
|
||||
else
|
||||
{
|
||||
target = _history.Count > 0 ? _history[^1] : null;
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(target))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Alberto's own navigation while he drives (rule 7): not an engine action, no Governor.
|
||||
await _session.NavigateAsync(target, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Ends the view from the server side (another tab, shutdown): the page is told why.</summary>
|
||||
public async Task EndAsync(RemoteViewEnd reason)
|
||||
{
|
||||
Ended ??= reason;
|
||||
await DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Ended ??= RemoteViewEnd.BrowserStopped;
|
||||
await _ended.CancelAsync().ConfigureAwait(false);
|
||||
_session.Screencast.FrameReceived -= OnFrame;
|
||||
foreach (var subscription in _subscriptions)
|
||||
{
|
||||
subscription.Dispose();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _session.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or OperationCanceledException)
|
||||
{
|
||||
// The browser is gone: the lease is released anyway.
|
||||
}
|
||||
|
||||
_owner.Closed(this);
|
||||
}
|
||||
|
||||
private void MarkUsed()
|
||||
{
|
||||
if (!_used)
|
||||
{
|
||||
_used = true;
|
||||
_tracker.MarkUsed(_clock.Now);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnFrame(object? sender, ScreencastFrame frame)
|
||||
{
|
||||
var width = (int)Math.Round(frame.DeviceWidth);
|
||||
var height = (int)Math.Round(frame.DeviceHeight);
|
||||
lock (_gate)
|
||||
{
|
||||
if (width > 0 && height > 0 && (width != _width || height != _height))
|
||||
{
|
||||
_width = width;
|
||||
_height = height;
|
||||
_meta.Enqueue(new RemoteViewMeta(width, height, _url));
|
||||
_signal.Release();
|
||||
}
|
||||
|
||||
var hadPending = _pendingFrame is not null;
|
||||
_pendingFrame = frame;
|
||||
if (hadPending)
|
||||
{
|
||||
return; // the older frame is replaced: the reader is behind
|
||||
}
|
||||
}
|
||||
|
||||
_signal.Release();
|
||||
}
|
||||
|
||||
private void OnFrameNavigated(JsonElement e)
|
||||
{
|
||||
if (!e.TryGetProperty("frame", out var frame) || frame.TryGetProperty("parentId", out _))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (frame.TryGetProperty("id", out var id) && id.GetString() is { } frameId)
|
||||
{
|
||||
_mainFrameId = frameId; // a new main frame after a browser restart
|
||||
}
|
||||
|
||||
Navigated(frame.TryGetProperty("url", out var u) ? u.GetString() : null);
|
||||
}
|
||||
|
||||
private void OnNavigatedWithinDocument(JsonElement e)
|
||||
{
|
||||
if (e.TryGetProperty("frameId", out var id) && id.GetString() is { } frameId && frameId == _mainFrameId)
|
||||
{
|
||||
Navigated(e.TryGetProperty("url", out var u) ? u.GetString() : null);
|
||||
}
|
||||
}
|
||||
|
||||
private void Navigated(string? url)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (_history.Count == 0 || _history[^1] != url)
|
||||
{
|
||||
_history.Add(url);
|
||||
if (_history.Count > 50)
|
||||
{
|
||||
_history.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
var shown = WithoutQuery(url);
|
||||
if (shown == _url)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_url = shown;
|
||||
_meta.Enqueue(new RemoteViewMeta(_width, _height, shown));
|
||||
}
|
||||
|
||||
_signal.Release();
|
||||
}
|
||||
|
||||
/// <summary>The address without query string or fragment (they may carry tokens).</summary>
|
||||
internal static string WithoutQuery(string url)
|
||||
{
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
|
||||
{
|
||||
var cut = url.IndexOfAny(['?', '#']);
|
||||
return cut < 0 ? url : url[..cut];
|
||||
}
|
||||
|
||||
return uri.Scheme is "http" or "https" ? uri.GetLeftPart(UriPartial.Path) : uri.GetLeftPart(UriPartial.Scheme) + uri.AbsolutePath;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Turns the DOM key of the page into what <c>Input.dispatchKeyEvent</c> needs (virtual key codes).</summary>
|
||||
internal static class RemoteKeys
|
||||
{
|
||||
private static readonly Dictionary<string, int> Named = new(StringComparer.Ordinal)
|
||||
{
|
||||
["Backspace"] = 8, ["Tab"] = 9, ["Enter"] = 13, ["Shift"] = 16, ["Control"] = 17, ["Alt"] = 18, ["Pause"] = 19,
|
||||
["CapsLock"] = 20, ["Escape"] = 27, [" "] = 32, ["PageUp"] = 33, ["PageDown"] = 34, ["End"] = 35, ["Home"] = 36,
|
||||
["ArrowLeft"] = 37, ["ArrowUp"] = 38, ["ArrowRight"] = 39, ["ArrowDown"] = 40, ["Insert"] = 45, ["Delete"] = 46,
|
||||
["Meta"] = 91, ["ContextMenu"] = 93,
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, int> Codes = new(StringComparer.Ordinal)
|
||||
{
|
||||
["Space"] = 32, ["Semicolon"] = 186, ["Equal"] = 187, ["Comma"] = 188, ["Minus"] = 189, ["Period"] = 190,
|
||||
["Slash"] = 191, ["Backquote"] = 192, ["BracketLeft"] = 219, ["Backslash"] = 220, ["BracketRight"] = 221,
|
||||
["Quote"] = 222, ["IntlBackslash"] = 226, ["NumpadEnter"] = 13,
|
||||
};
|
||||
|
||||
public static KeyStroke ToStroke(RemoteViewKey key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
var code = key.Code;
|
||||
var keyCode = 0;
|
||||
if (Named.TryGetValue(key.Key, out var named))
|
||||
{
|
||||
keyCode = named;
|
||||
}
|
||||
else if (code.Length == 4 && code.StartsWith("Key", StringComparison.Ordinal) && code[3] is >= 'A' and <= 'Z')
|
||||
{
|
||||
keyCode = code[3];
|
||||
}
|
||||
else if (code.Length == 6 && code.StartsWith("Digit", StringComparison.Ordinal) && code[5] is >= '0' and <= '9')
|
||||
{
|
||||
keyCode = code[5];
|
||||
}
|
||||
else if (code.Length == 7 && code.StartsWith("Numpad", StringComparison.Ordinal) && code[6] is >= '0' and <= '9')
|
||||
{
|
||||
keyCode = 96 + (code[6] - '0');
|
||||
}
|
||||
else if (code.Length is 2 or 3 && code[0] == 'F' && int.TryParse(code.AsSpan(1), out var f) && f is >= 1 and <= 12)
|
||||
{
|
||||
keyCode = 111 + f;
|
||||
}
|
||||
else if (Codes.TryGetValue(code, out var byCode))
|
||||
{
|
||||
keyCode = byCode;
|
||||
}
|
||||
else if (key.Key.Length == 1 && char.ToUpperInvariant(key.Key[0]) is var c && c is >= 'A' and <= 'Z' or >= '0' and <= '9')
|
||||
{
|
||||
keyCode = c;
|
||||
}
|
||||
|
||||
// Enter must carry its text, or forms are not submitted.
|
||||
var text = key.Text ?? (key.Key == "Enter" ? "\r" : null);
|
||||
return new KeyStroke(key.Key, code, keyCode, (KeyModifiers)(key.Modifiers & 15), text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
using System.Globalization;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Xvfb and Chromium of the Docker edition (spec §5, §6.1, §11): started by Febe.Server itself, never by a shell
|
||||
/// script. A start that fails (Chromium missing, sandbox refused, port taken) is retried with a growing wait; once
|
||||
/// running, the supervisors of <see cref="XvfbProcess"/> and <see cref="ChromiumProcessHost"/> restart what crashes.
|
||||
/// </summary>
|
||||
internal sealed class BrowserSupervisor : IAsyncDisposable
|
||||
{
|
||||
private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)];
|
||||
|
||||
private readonly ServerOptions _options;
|
||||
private readonly IClock _clock;
|
||||
private readonly ServerLog _log;
|
||||
private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private XvfbProcess? _xvfb;
|
||||
private volatile bool _started;
|
||||
private volatile string? _lastError;
|
||||
|
||||
public BrowserSupervisor(ServerOptions options, string profileDirectory, string homeDirectory, IClock clock, ServerLog log)
|
||||
{
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
|
||||
// Processes start, time out and restart in wall-clock time, whatever clock the engine runs on.
|
||||
_clock = new SystemClock(clock.LocalZone);
|
||||
ProfileDirectory = Path.GetFullPath(profileDirectory);
|
||||
HomeDirectory = Path.GetFullPath(homeDirectory);
|
||||
Host = new ChromiumProcessHost(options.LaunchOptions(HomeDirectory), _clock, log.ForBrowser());
|
||||
BrowserOptions = new BrowserOptions(
|
||||
ProfileDirectory,
|
||||
options.WindowWidth,
|
||||
options.WindowHeight,
|
||||
options.DebugPort,
|
||||
options.ChromiumPath,
|
||||
UsesXvfb ? options.Display : null);
|
||||
}
|
||||
|
||||
/// <summary>The browser: stable for the whole life of the server (a «Scollega» restarts it in place).</summary>
|
||||
public ChromiumProcessHost Host { get; }
|
||||
|
||||
public BrowserOptions BrowserOptions { get; }
|
||||
|
||||
/// <summary>Dati/browser: holds the Instagram session.</summary>
|
||||
public string ProfileDirectory { get; }
|
||||
|
||||
/// <summary>HOME of the browser process (certificate database, font cache).</summary>
|
||||
public string HomeDirectory { get; }
|
||||
|
||||
/// <summary>Linux needs the virtual display; elsewhere (development on Windows) the browser opens a normal window.</summary>
|
||||
public static bool UsesXvfb => OperatingSystem.IsLinux();
|
||||
|
||||
/// <summary>True when the browser runs and a page connection is attached.</summary>
|
||||
public bool IsAvailable => _started && Host.IsAttached;
|
||||
|
||||
/// <summary>Completes when the browser started the first time.</summary>
|
||||
public Task Ready => _ready.Task;
|
||||
|
||||
/// <summary>Why the last start failed, in Italian (for the log and the connection status); null when running.</summary>
|
||||
public string? LastError => _lastError;
|
||||
|
||||
public bool UserIsDriving => Host.UserIsDriving;
|
||||
|
||||
/// <summary>Starts Xvfb and Chromium, retrying until it works or <paramref name="ct"/> is cancelled.</summary>
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
for (var attempt = 0; !ct.IsCancellationRequested; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await StartOnceAsync(ct).ConfigureAwait(false);
|
||||
_started = true;
|
||||
_lastError = null;
|
||||
_ready.TrySetResult();
|
||||
_log.Info("browser", $"Browser pronto: finestra {_options.WindowWidth.ToString(CultureInfo.InvariantCulture)}×{_options.WindowHeight.ToString(CultureInfo.InvariantCulture)}, porta di debug {_options.DebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1{(_options.NoSandbox ? ", senza sandbox (FEBE_SENZA_SANDBOX)" : string.Empty)}.");
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_lastError = Explain(ex);
|
||||
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
|
||||
_log.Error("browser", $"Il browser non parte: {_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
|
||||
|
||||
// A failed start leaves nothing running in the host (it can be started again); Xvfb, if it started, stays.
|
||||
try
|
||||
{
|
||||
await _clock.Delay(wait, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Scollega» (spec §4.1): stops Chromium (SIGINT, so it closes cleanly), deletes the profile folder with the
|
||||
/// Instagram session, and starts the browser again with an empty profile.
|
||||
/// </summary>
|
||||
public async Task RestartWithEmptyProfileAsync(CancellationToken ct)
|
||||
{
|
||||
if (!_started)
|
||||
{
|
||||
DeleteProfile();
|
||||
return;
|
||||
}
|
||||
|
||||
await Host.RestartAsync(DeleteProfile, ct).ConfigureAwait(false);
|
||||
_log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto.");
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await StopProcessesAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task StartOnceAsync(CancellationToken ct)
|
||||
{
|
||||
Directory.CreateDirectory(HomeDirectory);
|
||||
if (UsesXvfb && _xvfb is null)
|
||||
{
|
||||
RemoveStaleDisplayLock(_options.Display);
|
||||
var xvfb = new XvfbProcess(_options.Display, _options.WindowWidth, _options.WindowHeight, clock: _clock, log: _log.ForBrowser());
|
||||
await xvfb.StartAsync(ct).ConfigureAwait(false);
|
||||
_xvfb = xvfb;
|
||||
}
|
||||
|
||||
RemoveStaleProfileLocks(ProfileDirectory);
|
||||
await Host.StartAsync(BrowserOptions, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task StopProcessesAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await Host.StopAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or IOException)
|
||||
{
|
||||
}
|
||||
|
||||
if (_xvfb is { } xvfb)
|
||||
{
|
||||
_xvfb = null;
|
||||
await xvfb.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void DeleteProfile()
|
||||
{
|
||||
if (Directory.Exists(ProfileDirectory))
|
||||
{
|
||||
Directory.Delete(ProfileDirectory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Chromium's «profile in use on another computer» lock: after the container is recreated the host name changes and
|
||||
/// Chromium would refuse the profile with a dialog nobody sees. Only Febe starts this browser, and it is not running
|
||||
/// now, so the lock files are stale by definition.
|
||||
/// </summary>
|
||||
internal static void RemoveStaleProfileLocks(string profileDirectory)
|
||||
{
|
||||
foreach (var name in new[] { "SingletonLock", "SingletonSocket", "SingletonCookie" })
|
||||
{
|
||||
var path = Path.Combine(profileDirectory, name);
|
||||
try
|
||||
{
|
||||
if (File.Exists(path) || new FileInfo(path).LinkTarget is not null)
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A display lock left by an Xvfb of an earlier run of the same container (restart after a crash): its process
|
||||
/// number may now belong to another process, so a lock whose owner is not an Xvfb is removed.
|
||||
/// </summary>
|
||||
internal static void RemoveStaleDisplayLock(string display)
|
||||
{
|
||||
if (!OperatingSystem.IsLinux() || !int.TryParse(display.AsSpan(1), NumberStyles.None, CultureInfo.InvariantCulture, out var number))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var id = number.ToString(CultureInfo.InvariantCulture);
|
||||
var lockFile = $"/tmp/.X{id}-lock";
|
||||
try
|
||||
{
|
||||
if (!File.Exists(lockFile))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var owner = int.TryParse(File.ReadAllText(lockFile).Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var pid) ? pid : 0;
|
||||
var comm = owner > 0 && File.Exists($"/proc/{owner.ToString(CultureInfo.InvariantCulture)}/comm")
|
||||
? File.ReadAllText($"/proc/{owner.ToString(CultureInfo.InvariantCulture)}/comm").Trim()
|
||||
: string.Empty;
|
||||
if (comm.Equals("Xvfb", StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
File.Delete(lockFile);
|
||||
var socket = $"/tmp/.X11-unix/X{id}";
|
||||
if (File.Exists(socket))
|
||||
{
|
||||
File.Delete(socket);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static string Explain(Exception ex) => ex switch
|
||||
{
|
||||
FileNotFoundException => ex.Message,
|
||||
PlatformNotSupportedException => ex.Message,
|
||||
TimeoutException => ex.Message,
|
||||
InvalidOperationException when ex.Message.Contains("sandbox", StringComparison.OrdinalIgnoreCase) =>
|
||||
ex.Message + " Se il registro parla della sandbox, vedi docs/docker.md: profilo seccomp oppure FEBE_SENZA_SANDBOX=1.",
|
||||
_ => $"{ex.GetType().Name}: {ex.Message}",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
/// <summary>
|
||||
/// The recipe runner of the engine before the browser exists: the engine and its monitor are built at start-up (the
|
||||
/// interface shows them at once), the collection pipeline only when Chromium is up. The engine loop is started after
|
||||
/// <see cref="Target"/> is set, so a recipe never runs without it.
|
||||
/// </summary>
|
||||
internal sealed class DeferredRecipeRunner : IRecipeRunner
|
||||
{
|
||||
private volatile IRecipeRunner? _target;
|
||||
|
||||
/// <summary>The real runner (the collection pipeline's), once the browser is up.</summary>
|
||||
public IRecipeRunner? Target
|
||||
{
|
||||
get => _target;
|
||||
set => _target = value;
|
||||
}
|
||||
|
||||
public Task<RecipeOutcome> RunAsync(RecipeRequest request, ISessionContext session, CancellationToken ct) =>
|
||||
_target is { } target
|
||||
? target.RunAsync(request, session, ct)
|
||||
: Task.FromResult(new RecipeOutcome(RecipeStatus.Cancelled, 0, 0, "Il browser non è ancora pronto."));
|
||||
|
||||
public Task RestAsync(CancellationToken ct) => _target?.RestAsync(ct) ?? Task.CompletedTask;
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
using System.Globalization;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Import;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Data;
|
||||
using Febe.Web;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
using Febe.Web.Library;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
/// <summary>Things tests (and only tests) replace in the composition.</summary>
|
||||
internal sealed record ServerHooks
|
||||
{
|
||||
public IClock? Clock { get; init; }
|
||||
|
||||
public IRandomSource? Random { get; init; }
|
||||
|
||||
/// <summary>The Data folder check (tests inject a mount table with a network share).</summary>
|
||||
public DataFolderCheck? DataFolderCheck { get; init; }
|
||||
|
||||
public TextWriter? Console { get; init; }
|
||||
|
||||
/// <summary>How long the web host waits for open requests (events, remote view) when stopping.</summary>
|
||||
public TimeSpan ShutdownTimeout { get; init; } = TimeSpan.FromSeconds(3);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The real composition of the Docker edition (spec §5, §11, milestone M5). Start-up checks first: with a problem
|
||||
/// (password missing, Data folder not writable or on a network share) neither the engine nor the browser start, and
|
||||
/// the interface shows only the page that explains it. Otherwise: database, library, thumbnails, perceptual hashes,
|
||||
/// import, daily backup, Xvfb and Chromium, the collection pipeline, the download queue and the engine, behind the
|
||||
/// password-protected interface. Disposing stops everything in order (engine, downloads, browser with SIGINT, Xvfb).
|
||||
/// </summary>
|
||||
internal sealed class FebeServer : IAsyncDisposable
|
||||
{
|
||||
private readonly ServerOptions _options;
|
||||
private readonly ServerLog _log;
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly List<Task> _background = [];
|
||||
private readonly List<IDisposable> _disposables = [];
|
||||
private readonly List<Action> _unsubscribe = [];
|
||||
private string? _temporaryFolder;
|
||||
private int _disposed;
|
||||
|
||||
private FebeServer(ServerOptions options, ServerLog log, IClock clock, IReadOnlyList<ConfigurationProblem> problems)
|
||||
{
|
||||
_options = options;
|
||||
_log = log;
|
||||
Clock = clock;
|
||||
Problems = problems;
|
||||
}
|
||||
|
||||
public IClock Clock { get; }
|
||||
|
||||
public IReadOnlyList<ConfigurationProblem> Problems { get; }
|
||||
|
||||
public WebApplication Web { get; private set; } = null!;
|
||||
|
||||
/// <summary>Where the interface answers (with 127.0.0.1 in place of «any address»).</summary>
|
||||
public Uri Address { get; private set; } = null!;
|
||||
|
||||
public FebeDatabase Database { get; private set; } = null!;
|
||||
|
||||
public DataFolderLayout? Data { get; private set; }
|
||||
|
||||
public LibraryLayout? Library { get; private set; }
|
||||
|
||||
public BrowserSupervisor? Browser { get; private set; }
|
||||
|
||||
public ServerConnectionService? Connection { get; private set; }
|
||||
|
||||
public BrowserRemoteViewHost? RemoteView { get; private set; }
|
||||
|
||||
public EngineHost? Engine { get; private set; }
|
||||
|
||||
public CollectionPipeline? Pipeline { get; private set; }
|
||||
|
||||
public ImportService? Import { get; private set; }
|
||||
|
||||
public PerceptualHashIndex? HashIndex { get; private set; }
|
||||
|
||||
/// <summary>Completes when browser, pipeline and engine are running (never, with a configuration problem).</summary>
|
||||
public Task Running => _running.Task;
|
||||
|
||||
private readonly TaskCompletionSource _running = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public static async Task<FebeServer> StartAsync(ServerOptions options, ServerHooks? hooks = null, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
hooks ??= new ServerHooks();
|
||||
var clock = hooks.Clock ?? new SystemClock(options.Zone);
|
||||
var problems = StartupChecks.Run(options, hooks.DataFolderCheck);
|
||||
var logFolder = problems.Count == 0 ? new DataFolderLayout(options.DataFolder).Logs : null;
|
||||
var log = new ServerLog(logFolder, hooks.Console ?? System.Console.Out, clock);
|
||||
var server = new FebeServer(options, log, clock, problems);
|
||||
try
|
||||
{
|
||||
foreach (var warning in options.Warnings)
|
||||
{
|
||||
log.Warn("avvio", warning);
|
||||
}
|
||||
|
||||
if (problems.Count > 0)
|
||||
{
|
||||
await server.StartWithProblemsAsync(hooks, ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await server.StartNormallyAsync(hooks, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return server;
|
||||
}
|
||||
catch
|
||||
{
|
||||
await server.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A configuration problem: only the interface, on an empty temporary database, behind the configuration gate. No
|
||||
/// engine, no browser, nothing written in the Data folder.
|
||||
/// </summary>
|
||||
private async Task StartWithProblemsAsync(ServerHooks hooks, CancellationToken ct)
|
||||
{
|
||||
foreach (var problem in Problems)
|
||||
{
|
||||
_log.Error("avvio", $"{problem.Title}. {problem.Remedy}");
|
||||
}
|
||||
|
||||
_log.Error("avvio", "Il motore e il browser non partono finché il problema non è risolto: l'interfaccia mostra solo la pagina che lo spiega.");
|
||||
_temporaryFolder = Path.Combine(Path.GetTempPath(), "febe-problema-" + Guid.NewGuid().ToString("N")[..10]);
|
||||
Database = await FebeDatabase.OpenAsync(Path.Combine(_temporaryFolder, "dati"), ct).ConfigureAwait(false);
|
||||
var data = new DataFolderLayout(Path.Combine(_temporaryFolder, "dati"));
|
||||
var layout = new LibraryLayout(Path.Combine(_temporaryFolder, "libreria"));
|
||||
var library = new FebeLibrary(Database, data, layout, Clock);
|
||||
|
||||
// The same services as a normal start, on the empty temporary database, so that every endpoint can be built;
|
||||
// the configuration gate answers 503 before any of them runs.
|
||||
Import = new ImportService(new ImportEnvironment
|
||||
{
|
||||
Storage = Database,
|
||||
Layout = layout,
|
||||
Journal = new AccountJournal(Clock),
|
||||
Clock = Clock,
|
||||
Sources = ImportSourceOptions.Docker(Path.Combine(_temporaryFolder, "importa")),
|
||||
DataFolder = data.Root,
|
||||
});
|
||||
await StartWebAsync(hooks, services =>
|
||||
{
|
||||
services.AddSingleton<IFebeStorage>(Database);
|
||||
services.AddSingleton(library);
|
||||
services.AddSingleton<IClock>(Clock);
|
||||
services.AddSingleton(Import);
|
||||
services.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
|
||||
services.AddSingleton<IConfigurationProblems>(new StartupProblems(Problems));
|
||||
services.AddSingleton<IConnectionService>(new UnavailableConnectionService(Problems));
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task StartNormallyAsync(ServerHooks hooks, CancellationToken ct)
|
||||
{
|
||||
var o = _options;
|
||||
var random = hooks.Random ?? new SystemRandom();
|
||||
var data = new DataFolderLayout(o.DataFolder);
|
||||
Data = data;
|
||||
_log.Info("avvio", $"Febe {typeof(FebeServer).Assembly.GetName().Version?.ToString(3)}: dati in {data.Root}, libreria in {Path.GetFullPath(o.LibraryFolder)}, importazioni da {Path.GetFullPath(o.ImportFolder)}, fuso {o.ZoneId}, lingua {o.Language}.");
|
||||
if (o.TestSite is not null)
|
||||
{
|
||||
_log.Warn("avvio", $"Modalità di sviluppo: il browser lavora sul sito di prova {o.TestSite.Authority}, non su Instagram.");
|
||||
}
|
||||
|
||||
// Database and library.
|
||||
Database = await FebeDatabase.OpenAsync(data.Root, ct).ConfigureAwait(false);
|
||||
var settings = await LibrarySettings.LoadAsync(Database.Settings, o.LibraryFolder, ct).ConfigureAwait(false);
|
||||
var layout = new LibraryLayout(o.LibraryFolder);
|
||||
Library = layout;
|
||||
TryCreateFolder(layout.Root, "libreria");
|
||||
var thumbnails = new ThumbnailStore(data.Thumbnails);
|
||||
var hashes = new PerceptualHashIndex();
|
||||
hashes.Load(await Database.Media.LoadPerceptualHashesAsync(ct).ConfigureAwait(false));
|
||||
HashIndex = hashes;
|
||||
var journal = new AccountJournal(Clock);
|
||||
var ingest = new LibraryIngest(Database, layout, settings.Naming, journal, Clock, thumbnails, hashes, settings.SetFileTimeToPublication);
|
||||
var library = new FebeLibrary(Database, data, layout, Clock, hashes);
|
||||
var staging = Path.Combine(data.Root, "temporanei");
|
||||
|
||||
// Import (spec §9): sources under /importa, read-only; what was running when Febe stopped becomes «interrotto».
|
||||
Import = new ImportService(new ImportEnvironment
|
||||
{
|
||||
Storage = Database,
|
||||
Layout = layout,
|
||||
Naming = settings.Naming,
|
||||
Journal = journal,
|
||||
Clock = Clock,
|
||||
Thumbnails = thumbnails,
|
||||
HashIndex = hashes,
|
||||
Frames = VideoFrameExtractor.TryCreate(),
|
||||
VideoProbe = FfprobeVideoMetadataProbe.TryCreate(),
|
||||
SetFileTimeToPublication = settings.SetFileTimeToPublication,
|
||||
Sources = ImportSourceOptions.Docker(Path.GetFullPath(o.ImportFolder)),
|
||||
DataFolder = data.Root,
|
||||
});
|
||||
var recovered = await Import.RecoverAsync(ct).ConfigureAwait(false);
|
||||
if (recovered > 0)
|
||||
{
|
||||
_log.Info("importazione", $"{recovered.ToString(CultureInfo.InvariantCulture)} importazioni interrotte dall'arresto precedente: si riprendono dalla pagina Importa.");
|
||||
}
|
||||
|
||||
// Browser, connection, remote view, engine. The engine loop starts only once the browser is up.
|
||||
var tracker = new BrowserUseTracker();
|
||||
var browser = new BrowserSupervisor(o, data.BrowserProfile, Path.Combine(data.Root, "home"), Clock, _log);
|
||||
Browser = browser;
|
||||
var connection = new ServerConnectionService(browser, Database, tracker, Clock, _log, o.LoginUrl, o.Site.SessionCookie);
|
||||
Connection = connection;
|
||||
RemoteView = new BrowserRemoteViewHost(browser, tracker, Clock, _log);
|
||||
var engineOptions = o.FirstSessionDelay is { } delay
|
||||
? EngineOptions.Default with { StartupDelayMin = delay, StartupDelayMax = delay }
|
||||
: EngineOptions.Default;
|
||||
var services = await EngineServices.CreateAsync(
|
||||
Database,
|
||||
Clock,
|
||||
random,
|
||||
engineOptions,
|
||||
userIsDriving: () => browser.UserIsDriving,
|
||||
isConnected: () => connection.IsConnected == true,
|
||||
ct: ct).ConfigureAwait(false);
|
||||
var runner = new DeferredRecipeRunner();
|
||||
var engine = new EngineHost(services, runner);
|
||||
Engine = engine;
|
||||
connection.AttachEngine(engine);
|
||||
browser.Host.UserDriving.Changed += (_, _) => engine.NotifyUserDrivingChanged();
|
||||
|
||||
await StartWebAsync(hooks, s =>
|
||||
{
|
||||
s.AddSingleton<IFebeStorage>(Database);
|
||||
s.AddSingleton(library);
|
||||
s.AddSingleton<IClock>(Clock);
|
||||
s.AddSingleton(tracker);
|
||||
s.AddSingleton(engine.Monitor);
|
||||
s.AddSingleton<IEngineControl>(new EngineHostControl(engine));
|
||||
s.AddSingleton<IConnectionService>(connection);
|
||||
s.AddSingleton<IRemoteViewHost>(RemoteView);
|
||||
s.AddSingleton<IEngineSettingsControl>(new EngineHostSettingsControl(engine));
|
||||
s.AddSingleton(ingest);
|
||||
s.AddSingleton<IBrowserPreview>(new ServerBrowserPreview(browser, Clock));
|
||||
s.AddSingleton<IConfigurationProblems>(new StartupProblems([]));
|
||||
s.AddSingleton(Import);
|
||||
s.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
// 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));
|
||||
}
|
||||
|
||||
private async Task StartWebAsync(ServerHooks hooks, Action<IServiceCollection> register)
|
||||
{
|
||||
var web = FebeWebHost.Build(
|
||||
_options.WebOptions(),
|
||||
new FebeListen(_options.ListenAddress, _options.Port),
|
||||
services =>
|
||||
{
|
||||
register(services);
|
||||
services.Configure<HostOptions>(h => h.ShutdownTimeout = hooks.ShutdownTimeout);
|
||||
},
|
||||
logging => logging.AddProvider(_log.ForAspNet()));
|
||||
try
|
||||
{
|
||||
await web.StartAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await web.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
|
||||
Web = web;
|
||||
Address = FebeWebHost.BoundAddress(web);
|
||||
_log.Info("avvio", $"Interfaccia sulla porta {Address.Port.ToString(CultureInfo.InvariantCulture)}{(Problems.Count > 0 ? " (solo la pagina del problema)" : string.Empty)}.");
|
||||
}
|
||||
|
||||
/// <summary>Xvfb and Chromium, then the pipeline, the downloads, the connection check and the engine.</summary>
|
||||
private async Task BringUpBrowserAsync(LibraryIngest ingest, string staging, EngineServices services, EngineHost engine, DeferredRecipeRunner runner, CancellationToken ct)
|
||||
{
|
||||
var browser = Browser!;
|
||||
await browser.RunAsync(ct).ConfigureAwait(false);
|
||||
if (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var o = _options;
|
||||
Pipeline = await CollectionPipeline.StartAsync(
|
||||
new CollectionPipelineOptions
|
||||
{
|
||||
Cdp = browser.Host.Cdp,
|
||||
Site = o.Site,
|
||||
Storage = Database,
|
||||
Ingest = ingest,
|
||||
Governor = services.Governor,
|
||||
Budget = services.Governor,
|
||||
DataBudget = services.Governor,
|
||||
Breaker = services.Breaker,
|
||||
Clock = Clock,
|
||||
Random = services.Random,
|
||||
StagingFolder = staging,
|
||||
ConfigFolder = Data!.Root,
|
||||
Pace = services.Settings.Pace,
|
||||
UserIsDriving = () => browser.UserIsDriving,
|
||||
Log = _log.ForBrowser(),
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
runner.Target = Pipeline.Runner;
|
||||
var changes = Web.Services.GetRequiredService<LibraryChanges>();
|
||||
_disposables.Add(changes.Attach(Pipeline.Downloads, Clock));
|
||||
_background.Add(Task.Run(() => DownloadLoopAsync(Pipeline.Downloads, ct), CancellationToken.None));
|
||||
|
||||
// Every finished recipe may have queued files: the queue looks at once instead of at its next idle poll.
|
||||
var downloads = Pipeline.Downloads;
|
||||
void WakeDownloads(object? sender, EngineNotification n)
|
||||
{
|
||||
if (n.Event?.Code.StartsWith("ricetta.", StringComparison.Ordinal) == true)
|
||||
{
|
||||
downloads.Wake();
|
||||
}
|
||||
}
|
||||
|
||||
services.Events.Notified += WakeDownloads;
|
||||
_unsubscribe.Add(() => services.Events.Notified -= WakeDownloads);
|
||||
|
||||
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
|
||||
if (o.TestSiteAutoLogin && Connection.IsConnected != true)
|
||||
{
|
||||
await TestSiteLoginAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_background.Add(Task.Run(() => Connection.RunAsync(ct), CancellationToken.None));
|
||||
await engine.StartAsync(ct).ConfigureAwait(false);
|
||||
_log.Info("motore", Connection.IsConnected == true
|
||||
? "Motore avviato: il browser è collegato."
|
||||
: "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»).");
|
||||
_running.TrySetResult();
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Error("avvio", "La raccolta non è partita.", ex);
|
||||
_running.TrySetException(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.
|
||||
/// </summary>
|
||||
private async Task TestSiteLoginAsync(CancellationToken ct)
|
||||
{
|
||||
var host = Browser!.Host;
|
||||
await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(host.Cdp, _options.LoginUrl, ct).ConfigureAwait(false);
|
||||
await Febe.Browser.Cdp.CdpPageExtensions.WaitForLoadAsync(host.Cdp, Clock, TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
|
||||
await host.RestAsync(ct).ConfigureAwait(false);
|
||||
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
|
||||
_log.Info("collegamento", "Sito di prova: accesso automatico fatto.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The download queue runs all the time (spec §6.5): it talks only to the CDN, so it goes on during a stop of the
|
||||
/// breaker. An error (browser restarting) ends a pass, never the loop.
|
||||
/// </summary>
|
||||
private async Task DownloadLoopAsync(DownloadQueue queue, CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await queue.RunAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Warn("scaricamenti", "Scaricamenti interrotti: riprendo fra 30 secondi.", ex);
|
||||
try
|
||||
{
|
||||
await Clock.Delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The daily copy of the database (spec §8.5): at start-up if today's is missing, then once a day.</summary>
|
||||
private async Task BackupLoopAsync(DailyBackup backup, CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await backup.RunAsync(ct).ConfigureAwait(false);
|
||||
if (result.Created is { } created)
|
||||
{
|
||||
_log.Info("copie", $"Copia del database del giorno fatta ({Febe.Core.Engine.ItalianText.Bytes(created.Bytes)}); copie tenute: {backup.List().Count.ToString(CultureInfo.InvariantCulture)}.");
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Error("copie", "Copia del database non riuscita: riprovo fra un'ora.", ex);
|
||||
try
|
||||
{
|
||||
await Clock.Delay(TimeSpan.FromHours(1), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Clock.Delay(UntilNextBackup(Clock.Now, Clock.LocalZone), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The next copy: a few minutes after local midnight (03:20, outside the active window of every profile).</summary>
|
||||
internal static TimeSpan UntilNextBackup(DateTimeOffset now, TimeZoneInfo zone)
|
||||
{
|
||||
var tomorrow = LocalCalendar.Today(now, zone).AddDays(1);
|
||||
var target = LocalCalendar.StartOfDay(tomorrow, zone) + TimeSpan.FromMinutes(200);
|
||||
var wait = target - now;
|
||||
return wait < TimeSpan.FromMinutes(1) ? TimeSpan.FromMinutes(1) : wait;
|
||||
}
|
||||
|
||||
/// <summary>Temporary files left by an interrupted run (only <c>.febe-*.part</c>: never a library file, rule 12).</summary>
|
||||
private async Task CleanTemporaryFilesAsync(string staging, LibraryLayout layout, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var removed = SafeFileWriter.CleanupTemporaryFiles(staging, recursive: false);
|
||||
removed += SafeFileWriter.CleanupTemporaryFiles(layout.Root);
|
||||
var root = Path.TrimEndingDirectorySeparator(layout.Root) + Path.DirectorySeparatorChar;
|
||||
foreach (var account in await Database.Accounts.ListAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
var folder = layout.AccountFolder(account);
|
||||
if (!(folder + Path.DirectorySeparatorChar).StartsWith(root, StringComparison.Ordinal))
|
||||
{
|
||||
removed += SafeFileWriter.CleanupTemporaryFiles(folder);
|
||||
}
|
||||
}
|
||||
|
||||
if (removed > 0)
|
||||
{
|
||||
_log.Info("libreria", $"Tolti {removed.ToString(CultureInfo.InvariantCulture)} file temporanei lasciati da un arresto precedente.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or OperationCanceledException)
|
||||
{
|
||||
_log.Warn("libreria", "Pulizia dei file temporanei non completata.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void TryCreateFolder(string folder, string what)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
_log.Error("avvio", $"La cartella della {what} ({folder}) non si può creare: i file scaricati non avranno dove andare.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stops everything in order: remote view, interface, engine, downloads, import, pipeline, browser, database.</summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_log.Info("arresto", "Arresto in corso.");
|
||||
if (RemoteView is { } view)
|
||||
{
|
||||
await Quietly(view.ShutdownAsync).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Web is { } web)
|
||||
{
|
||||
await Quietly(() => web.StopAsync()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Engine is { } engine)
|
||||
{
|
||||
await Quietly(() => engine.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
foreach (var task in _background.ToArray())
|
||||
{
|
||||
await Quietly(() => task).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var disposable in _disposables)
|
||||
{
|
||||
disposable.Dispose();
|
||||
}
|
||||
|
||||
foreach (var unsubscribe in _unsubscribe)
|
||||
{
|
||||
unsubscribe();
|
||||
}
|
||||
|
||||
if (Import is { } import)
|
||||
{
|
||||
await Quietly(() => import.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Pipeline is { } pipeline)
|
||||
{
|
||||
await Quietly(() => pipeline.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Connection is { } connection)
|
||||
{
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Browser is { } browser)
|
||||
{
|
||||
// Chromium with SIGINT, so that the session is written to the profile (decisions, S3); then Xvfb.
|
||||
await Quietly(() => browser.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Web is { } app)
|
||||
{
|
||||
await Quietly(() => app.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Database is { } database)
|
||||
{
|
||||
await Quietly(() => database.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (_temporaryFolder is { } temporary)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(temporary, recursive: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
_log.Info("arresto", "Febe è fermo.");
|
||||
_log.Dispose();
|
||||
_lifetime.Dispose();
|
||||
}
|
||||
|
||||
private async Task Quietly(Func<Task> step)
|
||||
{
|
||||
try
|
||||
{
|
||||
await step().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
if (ex is not OperationCanceledException)
|
||||
{
|
||||
_log.Warn("arresto", "Un passo dell'arresto non è riuscito.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// Composition root for Linux and Docker. Filled in by milestones M3–M5.
|
||||
// Composition root for Linux and Docker (spec §5, §11).
|
||||
using Febe.Server;
|
||||
|
||||
Console.OutputEncoding = System.Text.Encoding.UTF8;
|
||||
@@ -13,6 +13,16 @@ if (DemoCommand.Matches(args))
|
||||
return await DemoCommand.RunAsync(args, Console.Out, Console.Error);
|
||||
}
|
||||
|
||||
Console.WriteLine("Febe");
|
||||
Console.WriteLine("Comandi: --demo (interfaccia con dati dimostrativi), --simula 30g --profilo prudente (simulazione del motore).");
|
||||
return 0;
|
||||
if (HealthCheckCommand.Matches(args))
|
||||
{
|
||||
return await HealthCheckCommand.RunAsync(Environment.GetEnvironmentVariable, Console.Out);
|
||||
}
|
||||
|
||||
if (args.Any(a => a is "--aiuto" or "--help" or "-h"))
|
||||
{
|
||||
Console.WriteLine(ServerCommand.Usage);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Default: the real server (Docker edition).
|
||||
return await ServerCommand.RunAsync(args, Console.Out, Console.Error);
|
||||
@@ -0,0 +1,56 @@
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Preview of the browser for the Attività page (mockup 06): one still frame taken with Page.captureScreenshot when the
|
||||
/// page asks, at most every few seconds. Reading what the browser shows is not an action toward the site. On the empty
|
||||
/// rest page there is nothing to show.
|
||||
/// </summary>
|
||||
internal sealed class ServerBrowserPreview(BrowserSupervisor browser, IClock clock) : IBrowserPreview
|
||||
{
|
||||
private static readonly TimeSpan MinimumAge = TimeSpan.FromSeconds(4);
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private BrowserFrame? _last;
|
||||
|
||||
public async Task<BrowserFrame?> GetLatestAsync(CancellationToken ct)
|
||||
{
|
||||
if (!browser.IsAvailable)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var now = clock.Now;
|
||||
if (_last is { } cached && now - cached.At < MinimumAge)
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
|
||||
var url = await browser.Host.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
|
||||
if (string.IsNullOrEmpty(url) || url.StartsWith("about:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_last = null;
|
||||
return null;
|
||||
}
|
||||
|
||||
var jpeg = await PagePreview.CaptureAsync(browser.Host.Cdp, ct: ct).ConfigureAwait(false);
|
||||
_last = new BrowserFrame(jpeg, BrowserRemoteViewConnection.WithoutQuery(url), now);
|
||||
return _last;
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or KeyNotFoundException or InvalidOperationException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
/// <summary>
|
||||
/// The real server (default when neither <c>--demo</c> nor <c>--simula</c> is given): the Docker edition with the
|
||||
/// browser, the engine and the password-protected interface. Stops cleanly on SIGTERM (<c>docker stop</c>) and Ctrl+C.
|
||||
/// Exit code 0 after a clean stop, 1 when the interface cannot start, 2 for a wrong command line.
|
||||
/// </summary>
|
||||
internal static class ServerCommand
|
||||
{
|
||||
public const string Usage =
|
||||
"Uso: febe [--dati /dati] [--libreria /libreria] [--importa /importa] [--porta 8480] [--ascolta 0.0.0.0]\n"
|
||||
+ " [--porta-debug 9222] [--display :99] [--chromium percorso] [--senza-sandbox]\n"
|
||||
+ " [--sito-di-prova http://127.0.0.1:8481 [--cdn-di-prova http://127.0.0.2:8482] [--accesso-di-prova]] [--prima-sessione secondi]\n"
|
||||
+ "Variabili: FEBE_PASSWORD (obbligatoria), FEBE_PORTA, TZ, LANG, FEBE_HOST, FEBE_PROXY_FIDATO, FEBE_SENZA_SANDBOX, FEBE_CHROMIUM.\n"
|
||||
+ "Altri comandi: --demo, --simula 30g --profilo prudente, --controllo-salute.";
|
||||
|
||||
public static async Task<int> RunAsync(string[] args, TextWriter output, TextWriter error)
|
||||
{
|
||||
if (!ServerOptions.TryParse(args, Environment.GetEnvironmentVariable, out var options, out var problem))
|
||||
{
|
||||
await error.WriteLineAsync(problem).ConfigureAwait(false);
|
||||
await error.WriteLineAsync(Usage).ConfigureAwait(false);
|
||||
return 2;
|
||||
}
|
||||
|
||||
using var stop = new CancellationTokenSource();
|
||||
ConsoleCancelEventHandler onCancel = (_, e) =>
|
||||
{
|
||||
e.Cancel = true;
|
||||
stop.Cancel();
|
||||
};
|
||||
Console.CancelKeyPress += onCancel;
|
||||
using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, context =>
|
||||
{
|
||||
context.Cancel = true;
|
||||
stop.Cancel();
|
||||
});
|
||||
try
|
||||
{
|
||||
FebeServer server;
|
||||
try
|
||||
{
|
||||
server = await FebeServer.StartAsync(options, new ServerHooks { Console = output }, stop.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (IOException ex) when (ex.Message.Contains("address", StringComparison.OrdinalIgnoreCase) || ex.InnerException is System.Net.Sockets.SocketException)
|
||||
{
|
||||
await error.WriteLineAsync($"La porta {options.Port} è già occupata: cambia FEBE_PORTA o ferma l'altro programma.").ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
catch (OperationCanceledException) when (stop.IsCancellationRequested)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
await using (server.ConfigureAwait(false))
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, stop.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.CancelKeyPress -= onCancel;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>--controllo-salute</c>: the Docker HEALTHCHECK. Asks <c>/salute</c> on 127.0.0.1 and exits 0 for «ok», 1 otherwise.
|
||||
/// The image has no curl: the program checks itself.
|
||||
/// </summary>
|
||||
internal static class HealthCheckCommand
|
||||
{
|
||||
public const string Flag = "--controllo-salute";
|
||||
|
||||
public static bool Matches(string[] args) => args.Any(a => string.Equals(a, Flag, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public static async Task<int> RunAsync(Func<string, string?> environment, TextWriter output)
|
||||
{
|
||||
var port = int.TryParse(environment("FEBE_PORTA"), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var p) && p is >= 1 and <= 65535
|
||||
? p
|
||||
: Febe.Web.FebeListen.DefaultPort;
|
||||
return await CheckAsync(new Uri($"http://127.0.0.1:{port}/salute"), output).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public static async Task<int> CheckAsync(Uri address, TextWriter output)
|
||||
{
|
||||
using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false })
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(8),
|
||||
};
|
||||
try
|
||||
{
|
||||
using var response = await client.GetAsync(address).ConfigureAwait(false);
|
||||
var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
await output.WriteLineAsync(body).ConfigureAwait(false);
|
||||
return response.IsSuccessStatusCode ? 0 : 1;
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
|
||||
{
|
||||
await output.WriteLineAsync("Febe non risponde.").ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
using System.Globalization;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Web.Api;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
/// <summary>
|
||||
/// The link to Instagram in the Docker edition (spec §4.1, PROTOCOLLO.md) over the real browser. «Collegato» means
|
||||
/// that the session cookie exists in the browser profile: only its existence is checked (<c>Network.getCookies</c>,
|
||||
/// names only), never its value. Opening the login page is Alberto's action, not the engine's (rule 7, last
|
||||
/// sentence): it happens only while he holds the «driving» lease and the engine is still.
|
||||
/// </summary>
|
||||
internal sealed class ServerConnectionService : IConnectionService, IAsyncDisposable
|
||||
{
|
||||
/// <summary>Setting written at the first connection ever (Unix ms): the gradual start begins only once.</summary>
|
||||
public const string FirstConnectionKey = "collegamento.primo";
|
||||
|
||||
/// <summary>A cookie check younger than this is reused by the status (the sidebar asks often).</summary>
|
||||
public static readonly TimeSpan CookieCacheLifetime = TimeSpan.FromSeconds(3);
|
||||
|
||||
/// <summary>How often the cookie is looked at in the background (outside sessions it is the only way to notice).</summary>
|
||||
public static readonly TimeSpan BackgroundCheck = TimeSpan.FromSeconds(30);
|
||||
|
||||
private readonly BrowserSupervisor _browser;
|
||||
private readonly IFebeStorage _storage;
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
private readonly IClock _clock;
|
||||
private readonly ServerLog _log;
|
||||
private readonly string _loginUrl;
|
||||
private readonly SessionCookieOptions _cookie;
|
||||
private readonly SemaphoreSlim _commands = new(1, 1);
|
||||
private readonly Lock _gate = new();
|
||||
private EngineHost? _engine;
|
||||
private IDisposable? _lease;
|
||||
private bool? _connected;
|
||||
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
|
||||
|
||||
public ServerConnectionService(BrowserSupervisor browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, ServerLog log, string loginUrl, SessionCookieOptions cookie)
|
||||
{
|
||||
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
|
||||
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
|
||||
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
_loginUrl = loginUrl ?? throw new ArgumentNullException(nameof(loginUrl));
|
||||
_cookie = cookie ?? throw new ArgumentNullException(nameof(cookie));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the browser holds the session, from the last check (null before the first one). The engine reads it
|
||||
/// on every turn (<see cref="EngineRuntime.IsConnected"/>): it never waits for the browser.
|
||||
/// </summary>
|
||||
public bool? IsConnected
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _connected;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hook for the readers (hypothesis H10): when the data of the page tell which account is connected, the composition
|
||||
/// marks it as «Tu» (<see cref="Account.IsMine"/>); the status shows that account. Raised after every change of the
|
||||
/// connection, so that whoever learns the account can look again.
|
||||
/// </summary>
|
||||
public event EventHandler<bool>? ConnectionChanged;
|
||||
|
||||
/// <summary>The engine, once it exists (it is built after the browser).</summary>
|
||||
public void AttachEngine(EngineHost engine) => _engine = engine ?? throw new ArgumentNullException(nameof(engine));
|
||||
|
||||
public async Task<ConnectionStatus> GetStatusAsync(CancellationToken ct)
|
||||
{
|
||||
var driving = _browser.UserIsDriving;
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
return new ConnectionStatus(ConnectionState.BrowserUnavailable, null, null, driving, null);
|
||||
}
|
||||
|
||||
var breaker = _engine?.Services.Breaker.State.Status;
|
||||
var state = breaker is BreakerStatus.Challenge or BreakerStatus.Disconnected
|
||||
? ConnectionState.VerificationRequired
|
||||
: await CheckAsync(force: false, ct).ConfigureAwait(false) == true ? ConnectionState.Connected : ConnectionState.NotConnected;
|
||||
|
||||
Account? mine = null;
|
||||
if (state != ConnectionState.NotConnected)
|
||||
{
|
||||
mine = await _storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
public async Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
|
||||
{
|
||||
EnsureBrowser();
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_lease ??= _browser.Host.UserDriving.Begin();
|
||||
}
|
||||
|
||||
_tracker.MarkUsed(_clock.Now);
|
||||
if (openLogin)
|
||||
{
|
||||
// The engine ends its session when the lease starts; wait for it before taking the page.
|
||||
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
|
||||
var result = await _browser.Host.Cdp.NavigateAsync(_loginUrl, ct).ConfigureAwait(false);
|
||||
_log.Info("collegamento", result.Succeeded
|
||||
? "Alberto usa il browser: pagina di accesso aperta."
|
||||
: "Alberto usa il browser: la pagina di accesso non si è aperta (errore di rete del browser).");
|
||||
}
|
||||
else
|
||||
{
|
||||
_log.Info("collegamento", "Alberto usa il browser.");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commands.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<FinishResult> FinishAsync(CancellationToken ct)
|
||||
{
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
ReleaseLease();
|
||||
return new FinishResult(false, "Il browser di Febe non è in funzione in questo momento, quindi Febe non può controllare il collegamento. Riprova fra qualche minuto; se il problema resta, guarda il registro.");
|
||||
}
|
||||
|
||||
var connected = await CheckAsync(force: true, ct).ConfigureAwait(false) == true;
|
||||
_tracker.MarkUsed(_clock.Now);
|
||||
var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false);
|
||||
await RestQuietlyAsync().ConfigureAwait(false);
|
||||
ReleaseLease();
|
||||
|
||||
var stopped = _engine?.Services.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected;
|
||||
string message;
|
||||
if (!connected)
|
||||
{
|
||||
message = "Febe non trova la sessione di Instagram nel browser: l'accesso non sembra completato. Riprova con «Accedi a Instagram» e premi «Ho finito» solo dopo aver visto la tua pagina iniziale.";
|
||||
}
|
||||
else if (stopped)
|
||||
{
|
||||
message = "Collegato. Febe è ancora fermo per la verifica o la disconnessione: premi «Riprendi» quando vuoi che ricominci.";
|
||||
}
|
||||
else if (first)
|
||||
{
|
||||
message = "Collegato a Instagram. Febe comincia fra qualche minuto, con calma: nei primi giorni i tetti sono ridotti (avvio graduale).";
|
||||
}
|
||||
else
|
||||
{
|
||||
message = "Collegato a Instagram. Febe riprende da solo alla prossima sessione.";
|
||||
}
|
||||
|
||||
_log.Info("collegamento", connected ? "«Ho finito»: sessione presente nel browser." : "«Ho finito»: sessione assente nel browser.");
|
||||
return new FinishResult(connected, message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commands.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task CancelAsync(CancellationToken ct)
|
||||
{
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_browser.IsAvailable)
|
||||
{
|
||||
await RestQuietlyAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
ReleaseLease();
|
||||
_log.Info("collegamento", "«Annulla»: il browser torna a riposo.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commands.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync(CancellationToken ct)
|
||||
{
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
var hold = _browser.Host.UserDriving.Begin();
|
||||
try
|
||||
{
|
||||
var engine = _engine;
|
||||
if (engine is not null)
|
||||
{
|
||||
await engine.StopAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _browser.RestartWithEmptyProfileAsync(ct).ConfigureAwait(false);
|
||||
SetConnected(false);
|
||||
if (engine is not null)
|
||||
{
|
||||
await engine.Services.Events.WriteAsync(
|
||||
EventSeverity.Info,
|
||||
"collegamento.scollegato",
|
||||
"Scollegato da te: il profilo del browser con la sessione di Instagram è stato cancellato.",
|
||||
ct: CancellationToken.None).ConfigureAwait(false);
|
||||
await engine.StartAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_log.Info("collegamento", "«Scollega»: motore fermo, profilo del browser cancellato, browser ripartito vuoto.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ReleaseLease();
|
||||
hold.Dispose();
|
||||
_commands.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks at the cookie now (outside the cache) and records the change. Used at start-up, by the background loop
|
||||
/// and after the test site's automatic login.
|
||||
/// </summary>
|
||||
public async Task<bool?> RefreshAsync(CancellationToken ct)
|
||||
{
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
return IsConnected;
|
||||
}
|
||||
|
||||
var connected = await CheckAsync(force: true, ct).ConfigureAwait(false);
|
||||
if (connected == true)
|
||||
{
|
||||
await MarkConnectedAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return connected;
|
||||
}
|
||||
|
||||
/// <summary>The background check of the cookie, every <see cref="BackgroundCheck"/>, until cancelled.</summary>
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _clock.Delay(BackgroundCheck, ct).ConfigureAwait(false);
|
||||
if (!_browser.UserIsDriving)
|
||||
{
|
||||
await RefreshAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or IOException)
|
||||
{
|
||||
// The browser is restarting: the next turn looks again.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
ReleaseLease();
|
||||
_commands.Dispose();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task<bool?> CheckAsync(bool force, CancellationToken ct)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!force && _connected is not null && _clock.Now - _checkedAt < CookieCacheLifetime)
|
||||
{
|
||||
return _connected;
|
||||
}
|
||||
}
|
||||
|
||||
bool has;
|
||||
try
|
||||
{
|
||||
has = await SessionCookieProbe.HasSessionCookieAsync(_browser.Host.Cdp, _cookie, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
||||
{
|
||||
return IsConnected;
|
||||
}
|
||||
|
||||
SetConnected(has);
|
||||
return has;
|
||||
}
|
||||
|
||||
private void SetConnected(bool connected)
|
||||
{
|
||||
bool changed;
|
||||
lock (_gate)
|
||||
{
|
||||
changed = _connected != connected;
|
||||
_connected = connected;
|
||||
_checkedAt = _clock.Now;
|
||||
}
|
||||
|
||||
if (changed)
|
||||
{
|
||||
_log.Info("collegamento", connected ? "Sessione presente nel browser: collegato." : "Nessuna sessione nel browser: non collegato.");
|
||||
|
||||
// Wakes the engine: it looks again whether it can work (it only cancels a session if Alberto is driving).
|
||||
_engine?.NotifyUserDrivingChanged();
|
||||
ConnectionChanged?.Invoke(this, connected);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The first connection ever starts the gradual start (spec §7.2). True when it was the first.</summary>
|
||||
private async Task<bool> MarkConnectedAsync(CancellationToken ct)
|
||||
{
|
||||
if (await _storage.Settings.GetInt64Async(FirstConnectionKey, ct).ConfigureAwait(false) is not null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var now = _clock.Now;
|
||||
await _storage.Settings.SetAsync(FirstConnectionKey, now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture), ct).ConfigureAwait(false);
|
||||
if (_engine is { } engine)
|
||||
{
|
||||
await engine.Services.NotifyFirstConnectionAsync(ct).ConfigureAwait(false);
|
||||
await engine.Services.Events.WriteAsync(
|
||||
EventSeverity.Info,
|
||||
"collegamento.primo",
|
||||
"Primo collegamento a Instagram: comincia l'avvio graduale.",
|
||||
ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_log.Info("collegamento", "Primo collegamento: comincia l'avvio graduale.");
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task WaitForSessionEndAsync(CancellationToken ct)
|
||||
{
|
||||
if (_engine is not { } engine)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var deadline = _clock.Now + TimeSpan.FromSeconds(15);
|
||||
while (engine.Services.Runtime.CurrentSession is not null && _clock.Now < deadline)
|
||||
{
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string?> CurrentUrlAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var url = await _browser.Host.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
|
||||
return BrowserRemoteViewConnection.WithoutQuery(url);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or KeyNotFoundException or InvalidOperationException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RestQuietlyAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _browser.Host.RestAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
||||
{
|
||||
// The browser is restarting: it starts on the rest page anyway.
|
||||
}
|
||||
}
|
||||
|
||||
private void ReleaseLease()
|
||||
{
|
||||
IDisposable? lease;
|
||||
lock (_gate)
|
||||
{
|
||||
lease = _lease;
|
||||
_lease = null;
|
||||
}
|
||||
|
||||
lease?.Dispose();
|
||||
}
|
||||
|
||||
private void EnsureBrowser()
|
||||
{
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
throw new BadRequestException(_browser.LastError is { } error
|
||||
? "Il browser di Febe non è in funzione: " + error
|
||||
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Browser.Diagnostics;
|
||||
using Febe.Core.Abstractions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
/// <summary>
|
||||
/// The log of the server (spec §8.2, §13.2): one file per local day in <c>Dati/registro</c>
|
||||
/// (<c>febe-AAAA-MM-GG.log</c>), kept fourteen days, at most 20 MB a day, and the same lines on the console
|
||||
/// (<c>docker logs</c>). Only actions and outcomes: every message passes through <see cref="Scrub"/>, which removes
|
||||
/// addresses (signed CDN addresses, tokens); exceptions are written as type and first line only. Passwords, cookies,
|
||||
/// keys and response bodies never reach this class.
|
||||
/// </summary>
|
||||
internal sealed partial class ServerLog : IDisposable
|
||||
{
|
||||
public const int DefaultKeepDays = 14;
|
||||
|
||||
public const long DefaultMaxBytesPerDay = 20L * 1024 * 1024;
|
||||
|
||||
private const string Prefix = "febe-";
|
||||
private const string Extension = ".log";
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
private readonly string? _folder;
|
||||
private readonly TextWriter? _console;
|
||||
private readonly IClock _clock;
|
||||
private readonly int _keepDays;
|
||||
private readonly long _maxBytesPerDay;
|
||||
private StreamWriter? _file;
|
||||
private DateOnly _day;
|
||||
private long _written;
|
||||
private bool _capped;
|
||||
private bool _disposed;
|
||||
|
||||
/// <param name="folder">Dati/registro; null writes to the console only (configuration problems, tests).</param>
|
||||
/// <param name="console">Console writer; null for none.</param>
|
||||
/// <param name="clock">Time of the lines and of the daily file.</param>
|
||||
/// <param name="keepDays">Days of files kept.</param>
|
||||
/// <param name="maxBytesPerDay">Above this the day's file stops growing (the console still gets the lines).</param>
|
||||
public ServerLog(string? folder, TextWriter? console, IClock clock, int keepDays = DefaultKeepDays, long maxBytesPerDay = DefaultMaxBytesPerDay)
|
||||
{
|
||||
_folder = folder is null ? null : Path.GetFullPath(folder);
|
||||
_console = console;
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_keepDays = Math.Max(1, keepDays);
|
||||
_maxBytesPerDay = maxBytesPerDay;
|
||||
}
|
||||
|
||||
/// <summary>Lowest level written to the console; the file gets everything from Information up.</summary>
|
||||
public LogLevel ConsoleLevel { get; init; } = LogLevel.Information;
|
||||
|
||||
/// <summary>The log folder, when there is one.</summary>
|
||||
public string? Folder => _folder;
|
||||
|
||||
public void Info(string source, string message) => Write(LogLevel.Information, source, message);
|
||||
|
||||
public void Warn(string source, string message, Exception? exception = null) => Write(LogLevel.Warning, source, message, exception);
|
||||
|
||||
public void Error(string source, string message, Exception? exception = null) => Write(LogLevel.Error, source, message, exception);
|
||||
|
||||
/// <summary>Writes one line. Never throws: a log that cannot be written must not stop Febe.</summary>
|
||||
public void Write(LogLevel level, string source, string message, Exception? exception = null)
|
||||
{
|
||||
if (level < LogLevel.Information)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var now = _clock.Now;
|
||||
var local = TimeZoneInfo.ConvertTime(now, _clock.LocalZone);
|
||||
var text = Scrub(message);
|
||||
if (exception is not null)
|
||||
{
|
||||
text += $" ({exception.GetType().Name}: {Scrub(FirstLine(exception.Message))})";
|
||||
}
|
||||
|
||||
var line = string.Create(CultureInfo.InvariantCulture, $"{local:yyyy-MM-dd HH:mm:ss.fff zzz} {Label(level)} [{source}] {text}");
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_console is not null && level >= ConsoleLevel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_console.WriteLine(line);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
WriteFileLocked(DateOnly.FromDateTime(local.DateTime), line);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The adapter for the browser layer (it logs only CDP command names, states and counts).</summary>
|
||||
public IBrowserLog ForBrowser() => new DelegateBrowserLog((level, message, exception) => Write(
|
||||
level switch
|
||||
{
|
||||
BrowserLogLevel.Error => LogLevel.Error,
|
||||
BrowserLogLevel.Warning => LogLevel.Warning,
|
||||
BrowserLogLevel.Information => LogLevel.Information,
|
||||
_ => LogLevel.Debug,
|
||||
},
|
||||
"browser",
|
||||
message,
|
||||
exception));
|
||||
|
||||
/// <summary>The adapter for ASP.NET Core (warnings and errors only; messages scrubbed like every other line).</summary>
|
||||
public ILoggerProvider ForAspNet() => new Provider(this);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_disposed = true;
|
||||
_file?.Dispose();
|
||||
_file = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Removes addresses (anything like <c>scheme://…</c>) and line breaks from a message.</summary>
|
||||
public static string Scrub(string? message)
|
||||
{
|
||||
if (string.IsNullOrEmpty(message))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var clean = Addresses().Replace(message, "<indirizzo>");
|
||||
return clean.Replace('\r', ' ').Replace('\n', ' ');
|
||||
}
|
||||
|
||||
/// <summary>Log files older than <paramref name="keepDays"/> days (today included) are removed; only <c>febe-*.log</c>.</summary>
|
||||
public static IReadOnlyList<string> ApplyRetention(string folder, DateOnly today, int keepDays)
|
||||
{
|
||||
var removed = new List<string>();
|
||||
if (!Directory.Exists(folder))
|
||||
{
|
||||
return removed;
|
||||
}
|
||||
|
||||
var oldestKept = today.AddDays(-(Math.Max(1, keepDays) - 1));
|
||||
foreach (var file in Directory.EnumerateFiles(folder, Prefix + "*" + Extension))
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(file);
|
||||
if (DateOnly.TryParseExact(name[Prefix.Length..], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) && day < oldestKept)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(file);
|
||||
removed.Add(file);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
public static string FileNameFor(DateOnly day) => Prefix + day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + Extension;
|
||||
|
||||
private void WriteFileLocked(DateOnly day, string line)
|
||||
{
|
||||
if (_folder is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_file is null || day != _day)
|
||||
{
|
||||
_file?.Dispose();
|
||||
_file = null;
|
||||
Directory.CreateDirectory(_folder);
|
||||
ApplyRetention(_folder, day, _keepDays);
|
||||
var path = Path.Combine(_folder, FileNameFor(day));
|
||||
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
|
||||
_written = stream.Length;
|
||||
_file = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true };
|
||||
_day = day;
|
||||
_capped = false;
|
||||
}
|
||||
|
||||
if (_capped)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_written + line.Length + 1 > _maxBytesPerDay)
|
||||
{
|
||||
_file.WriteLine("Registro di oggi troppo lungo: le righe successive vanno solo sulla console.");
|
||||
_capped = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_file.WriteLine(line);
|
||||
_written += Encoding.UTF8.GetByteCount(line) + 1;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// The disk is full or the folder went away: the console still has the line.
|
||||
_file?.Dispose();
|
||||
_file = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Label(LogLevel level) => level switch
|
||||
{
|
||||
LogLevel.Critical or LogLevel.Error => "ERRORE ",
|
||||
LogLevel.Warning => "AVVISO ",
|
||||
_ => "INFO ",
|
||||
};
|
||||
|
||||
private static string FirstLine(string text)
|
||||
{
|
||||
var line = text.Split('\n')[0].Trim();
|
||||
return line.Length > 300 ? line[..300] : line;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\b[a-zA-Z][a-zA-Z0-9+.-]*://\S+", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Addresses();
|
||||
|
||||
private sealed class Provider(ServerLog log) : ILoggerProvider
|
||||
{
|
||||
public ILogger CreateLogger(string categoryName) => new Logger(log, categoryName);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Logger(ServerLog log, string category) : ILogger
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state)
|
||||
where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(logLevel))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var source = category.StartsWith("Febe.", StringComparison.Ordinal) ? "web" : "aspnet";
|
||||
log.Write(logLevel, source, formatter(state, exception), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Web;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration of the real server (spec §11): environment variables of the container, plus a few command-line
|
||||
/// options for development (other folders, the local test site, a short first-session delay). The password comes only
|
||||
/// from the environment, never from the command line (which other users of the machine can read).
|
||||
/// </summary>
|
||||
internal sealed record ServerOptions
|
||||
{
|
||||
public const string DefaultZone = "Europe/Rome";
|
||||
|
||||
public const string DefaultLanguage = "it_IT.UTF-8";
|
||||
|
||||
public const int DefaultDebugPort = 9222;
|
||||
|
||||
public const string DefaultDisplay = ":99";
|
||||
|
||||
/// <summary>FEBE_PASSWORD: the interface password. Mandatory; never logged or shown.</summary>
|
||||
public string? Password { get; init; }
|
||||
|
||||
/// <summary>Where Kestrel listens: every address in Docker (the port is published), 127.0.0.1 with <c>--ascolta</c>.</summary>
|
||||
public IPAddress ListenAddress { get; init; } = IPAddress.Any;
|
||||
|
||||
/// <summary>FEBE_PORTA, 8480 by default.</summary>
|
||||
public int Port { get; init; } = FebeListen.DefaultPort;
|
||||
|
||||
/// <summary>TZ, Europe/Rome by default: the clock of the engine, file names, and the browser's time zone.</summary>
|
||||
public string ZoneId { get; init; } = DefaultZone;
|
||||
|
||||
public TimeZoneInfo Zone { get; init; } = FindZone(DefaultZone) ?? TimeZoneInfo.Utc;
|
||||
|
||||
/// <summary>LANG, it_IT.UTF-8 by default: the browser's language comes from it (spec §6.1).</summary>
|
||||
public string Language { get; init; } = DefaultLanguage;
|
||||
|
||||
/// <summary>Data folder: database, browser profile, thumbnails, backups, log (/dati).</summary>
|
||||
public string DataFolder { get; init; } = "/dati";
|
||||
|
||||
/// <summary>Library folder (/libreria).</summary>
|
||||
public string LibraryFolder { get; init; } = "/libreria";
|
||||
|
||||
/// <summary>Import sources, read-only (/importa).</summary>
|
||||
public string ImportFolder { get; init; } = "/importa";
|
||||
|
||||
/// <summary>FEBE_HOST: names the interface is reached with (comma separated). Empty: any name.</summary>
|
||||
public IReadOnlyList<string> Hosts { get; init; } = [];
|
||||
|
||||
/// <summary>FEBE_PROXY_FIDATO=1: behind an HTTPS reverse proxy, X-Forwarded-Host counts for the Origin check.</summary>
|
||||
public bool TrustForwardedHost { get; init; }
|
||||
|
||||
/// <summary>FEBE_SENZA_SANDBOX=1: Chromium with <c>--no-sandbox</c> (the compromise of S5, written in docs/docker.md).</summary>
|
||||
public bool NoSandbox { get; init; }
|
||||
|
||||
/// <summary>FEBE_CHROMIUM: Chromium executable (default: Debian's chromium from PATH).</summary>
|
||||
public string? ChromiumPath { get; init; }
|
||||
|
||||
/// <summary>FEBE_PORTA_DEBUG: the fixed DevTools port, on 127.0.0.1 only and never published (spec §6.1).</summary>
|
||||
public int DebugPort { get; init; } = DefaultDebugPort;
|
||||
|
||||
/// <summary>FEBE_DISPLAY: the Xvfb display (:99).</summary>
|
||||
public string Display { get; init; } = DefaultDisplay;
|
||||
|
||||
/// <summary>Size of the browser window, always the same (spec §6.1); Xvfb's screen has the same size.</summary>
|
||||
public int WindowWidth { get; init; } = 1280;
|
||||
|
||||
public int WindowHeight { get; init; } = 900;
|
||||
|
||||
/// <summary>Development: the local test site (tools/Febe.SitoDiProva) instead of Instagram.</summary>
|
||||
public Uri? TestSite { get; init; }
|
||||
|
||||
/// <summary>Development: the «CDN» of the test site (default: 127.0.0.2, site port + 1, as the tool starts it).</summary>
|
||||
public Uri? TestCdn { get; init; }
|
||||
|
||||
/// <summary>Development, test site only: opens the site once at start-up so its session cookie exists, as after a login.</summary>
|
||||
public bool TestSiteAutoLogin { get; init; }
|
||||
|
||||
/// <summary>Development: the first session comes after this delay instead of 2–10 minutes.</summary>
|
||||
public TimeSpan? FirstSessionDelay { get; init; }
|
||||
|
||||
/// <summary>FEBE_INTERFACCIA: serve the interface from this folder (development).</summary>
|
||||
public string? InterfaceFolder { get; init; }
|
||||
|
||||
/// <summary>Warnings found while reading the configuration (unknown time zone...), for the log.</summary>
|
||||
public IReadOnlyList<string> Warnings { get; init; } = [];
|
||||
|
||||
/// <summary>The site the browser works on: Instagram, or the local test site in development.</summary>
|
||||
public CollectionSite Site => TestSite is { } site
|
||||
? CollectionSite.TestSite(site.Authority, (TestCdn ?? DefaultCdn(site)).Authority)
|
||||
: CollectionSite.Instagram;
|
||||
|
||||
/// <summary>
|
||||
/// The page «Accedi a Instagram» opens (PROTOCOLLO.md): Instagram's real login page, or a page of the test site,
|
||||
/// whose first visit starts its session (it has no login form).
|
||||
/// </summary>
|
||||
public string LoginUrl => TestSite is { } site ? new Uri(site, "/benvenuto").AbsoluteUri : "https://www.instagram.com/accounts/login/";
|
||||
|
||||
/// <summary>The interface options of the Docker edition.</summary>
|
||||
public FebeWebOptions WebOptions() => new()
|
||||
{
|
||||
Edition = FebeEdition.Docker,
|
||||
Access = AccessMode.Password,
|
||||
Password = string.IsNullOrEmpty(Password) ? null : Password,
|
||||
AllowedHosts = AllowedHostList(),
|
||||
TrustForwardedHost = TrustForwardedHost,
|
||||
InterfaceFolder = InterfaceFolder,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// FEBE_HOST names with any port, plus the loopback names (the health check comes from inside the container).
|
||||
/// Empty when FEBE_HOST is not set: any name, as documented for Docker (password and Origin protect it).
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> AllowedHostList()
|
||||
{
|
||||
if (Hosts.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var list = new List<string>();
|
||||
foreach (var host in Hosts.Concat(["127.0.0.1", "localhost", "[::1]"]))
|
||||
{
|
||||
list.Add(host);
|
||||
list.Add(host + ":*");
|
||||
}
|
||||
|
||||
return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the configuration. <paramref name="environment"/> gives environment variables (tests pass their own).
|
||||
/// Returns false with an Italian <paramref name="problem"/> for a wrong command line.
|
||||
/// </summary>
|
||||
public static bool TryParse(string[] args, Func<string, string?> environment, out ServerOptions options, out string problem)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(args);
|
||||
ArgumentNullException.ThrowIfNull(environment);
|
||||
options = new ServerOptions();
|
||||
problem = string.Empty;
|
||||
var warnings = new List<string>();
|
||||
|
||||
string? Env(string name) => environment(name) is { Length: > 0 } value ? value.Trim() : null;
|
||||
bool Flag(string name) => Env(name) is { } value && value is "1" or "true" or "sì" or "si" or "yes";
|
||||
|
||||
var zoneId = Env("TZ") ?? DefaultZone;
|
||||
var zone = FindZone(zoneId);
|
||||
if (zone is null)
|
||||
{
|
||||
warnings.Add($"Fuso orario sconosciuto in TZ («{zoneId}»): uso {DefaultZone}.");
|
||||
zoneId = DefaultZone;
|
||||
zone = FindZone(DefaultZone) ?? TimeZoneInfo.Utc;
|
||||
}
|
||||
|
||||
var port = FebeListen.DefaultPort;
|
||||
if (Env("FEBE_PORTA") is { } portText && !TryPort(portText, out port))
|
||||
{
|
||||
problem = $"FEBE_PORTA non valida («{portText}»): un numero fra 1 e 65535.";
|
||||
return false;
|
||||
}
|
||||
|
||||
var debugPort = DefaultDebugPort;
|
||||
if (Env("FEBE_PORTA_DEBUG") is { } debugText && (!TryPort(debugText, out debugPort) || debugPort < 1024))
|
||||
{
|
||||
problem = $"FEBE_PORTA_DEBUG non valida («{debugText}»): un numero fra 1024 e 65535.";
|
||||
return false;
|
||||
}
|
||||
|
||||
options = options with
|
||||
{
|
||||
Password = environment("FEBE_PASSWORD") is { Length: > 0 } password ? password : null,
|
||||
Port = port,
|
||||
ZoneId = zoneId,
|
||||
Zone = zone,
|
||||
Language = Env("LANG") ?? DefaultLanguage,
|
||||
Hosts = SplitHosts(Env("FEBE_HOST")),
|
||||
TrustForwardedHost = Flag("FEBE_PROXY_FIDATO"),
|
||||
NoSandbox = Flag("FEBE_SENZA_SANDBOX"),
|
||||
ChromiumPath = Env("FEBE_CHROMIUM"),
|
||||
DebugPort = debugPort,
|
||||
Display = Env("FEBE_DISPLAY") ?? DefaultDisplay,
|
||||
InterfaceFolder = Env("FEBE_INTERFACCIA") is { } folder && Directory.Exists(folder) ? folder : null,
|
||||
};
|
||||
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
var arg = args[i];
|
||||
string? Next() => i + 1 < args.Length ? args[++i] : null;
|
||||
switch (arg.ToLowerInvariant())
|
||||
{
|
||||
case "--dati":
|
||||
options = options with { DataFolder = Next() ?? string.Empty };
|
||||
break;
|
||||
case "--libreria":
|
||||
options = options with { LibraryFolder = Next() ?? string.Empty };
|
||||
break;
|
||||
case "--importa":
|
||||
options = options with { ImportFolder = Next() ?? string.Empty };
|
||||
break;
|
||||
case "--porta":
|
||||
{
|
||||
var text = Next();
|
||||
if (!TryPort(text, out var value))
|
||||
{
|
||||
problem = $"Porta non valida («{text}»): un numero fra 1 e 65535.";
|
||||
return false;
|
||||
}
|
||||
|
||||
options = options with { Port = value };
|
||||
break;
|
||||
}
|
||||
|
||||
case "--ascolta":
|
||||
{
|
||||
var text = Next();
|
||||
if (!IPAddress.TryParse(text, out var address))
|
||||
{
|
||||
problem = $"Indirizzo non valido dopo --ascolta («{text}»), per esempio 127.0.0.1.";
|
||||
return false;
|
||||
}
|
||||
|
||||
options = options with { ListenAddress = address };
|
||||
break;
|
||||
}
|
||||
|
||||
case "--porta-debug":
|
||||
{
|
||||
var text = Next();
|
||||
if (!TryPort(text, out var value) || value < 1024)
|
||||
{
|
||||
problem = $"Porta di debug non valida («{text}»): un numero fra 1024 e 65535.";
|
||||
return false;
|
||||
}
|
||||
|
||||
options = options with { DebugPort = value };
|
||||
break;
|
||||
}
|
||||
|
||||
case "--display":
|
||||
options = options with { Display = Next() ?? string.Empty };
|
||||
break;
|
||||
case "--chromium":
|
||||
options = options with { ChromiumPath = Next() };
|
||||
break;
|
||||
case "--senza-sandbox":
|
||||
options = options with { NoSandbox = true };
|
||||
break;
|
||||
case "--sito-di-prova":
|
||||
case "--cdn-di-prova":
|
||||
{
|
||||
var text = Next();
|
||||
if (!TryLocalAddress(text, out var address))
|
||||
{
|
||||
problem = $"Indirizzo non valido dopo {arg} («{text}»): serve un indirizzo http di questo computer, per esempio http://127.0.0.1:8481.";
|
||||
return false;
|
||||
}
|
||||
|
||||
options = arg.Equals("--sito-di-prova", StringComparison.OrdinalIgnoreCase)
|
||||
? options with { TestSite = address }
|
||||
: options with { TestCdn = address };
|
||||
break;
|
||||
}
|
||||
|
||||
case "--accesso-di-prova":
|
||||
options = options with { TestSiteAutoLogin = true };
|
||||
break;
|
||||
case "--prima-sessione":
|
||||
{
|
||||
var text = Next();
|
||||
if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var seconds) || seconds is < 1 or > 3600)
|
||||
{
|
||||
problem = $"Valore non valido dopo --prima-sessione («{text}»): secondi fra 1 e 3600.";
|
||||
return false;
|
||||
}
|
||||
|
||||
options = options with { FirstSessionDelay = TimeSpan.FromSeconds(seconds) };
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
problem = $"Opzione sconosciuta: {arg}.";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(options.DataFolder) || string.IsNullOrWhiteSpace(options.LibraryFolder) || string.IsNullOrWhiteSpace(options.ImportFolder))
|
||||
{
|
||||
problem = "Dopo --dati, --libreria e --importa serve una cartella.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.TestSiteAutoLogin && options.TestSite is null)
|
||||
{
|
||||
problem = "--accesso-di-prova vale solo con --sito-di-prova: con Instagram l'accesso lo fa sempre Alberto, a mano.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.TestCdn is not null && options.TestSite is null)
|
||||
{
|
||||
problem = "--cdn-di-prova vale solo con --sito-di-prova.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.Display.Length < 2 || options.Display[0] != ':')
|
||||
{
|
||||
problem = $"Display non valido («{options.Display}»): si scrive come «:99».";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (options.DebugPort == options.Port)
|
||||
{
|
||||
problem = "La porta di debug del browser deve essere diversa da quella dell'interfaccia.";
|
||||
return false;
|
||||
}
|
||||
|
||||
options = options with { Warnings = warnings };
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The time zone named by TZ, or null when unknown.</summary>
|
||||
public static TimeZoneInfo? FindZone(string id) =>
|
||||
TimeZoneInfo.TryFindSystemTimeZoneById(id, out var zone) ? zone : null;
|
||||
|
||||
/// <summary>The environment of Chromium: LANG and TZ (defaults when unset), a home of its own, and no proxy (rule 2).</summary>
|
||||
public IReadOnlyDictionary<string, string?> BrowserEnvironment(string home) => new Dictionary<string, string?>
|
||||
{
|
||||
["LANG"] = Language,
|
||||
["TZ"] = ZoneId,
|
||||
["HOME"] = home,
|
||||
["LANGUAGE"] = null,
|
||||
["LC_ALL"] = null,
|
||||
["http_proxy"] = null,
|
||||
["https_proxy"] = null,
|
||||
["HTTP_PROXY"] = null,
|
||||
["HTTPS_PROXY"] = null,
|
||||
["ALL_PROXY"] = null,
|
||||
["all_proxy"] = null,
|
||||
["no_proxy"] = null,
|
||||
["NO_PROXY"] = null,
|
||||
};
|
||||
|
||||
/// <summary>How the browser is started (spec §6.1, §11).</summary>
|
||||
public ChromiumLaunchOptions LaunchOptions(string home) => new()
|
||||
{
|
||||
NoSandbox = NoSandbox,
|
||||
Environment = BrowserEnvironment(home),
|
||||
SessionCookie = Site.SessionCookie,
|
||||
SeedProfilePreferences = true,
|
||||
};
|
||||
|
||||
private static Uri DefaultCdn(Uri site) => new UriBuilder(site) { Host = "127.0.0.2", Port = site.Port + 1, Path = "/" }.Uri;
|
||||
|
||||
private static IReadOnlyList<string> SplitHosts(string? value) => value is null
|
||||
? []
|
||||
: [.. value.Split([',', ' ', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(h => h.ToLowerInvariant())];
|
||||
|
||||
private static bool TryPort(string? text, out int port) =>
|
||||
int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) && port is >= 1 and <= 65535;
|
||||
|
||||
/// <summary>The test site must be on this computer: the switch can never point the browser elsewhere.</summary>
|
||||
private static bool TryLocalAddress(string? text, out Uri address)
|
||||
{
|
||||
address = null!;
|
||||
if (!Uri.TryCreate(text, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttp)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var local = uri.IsLoopback || (IPAddress.TryParse(uri.Host, out var ip) && IPAddress.IsLoopback(ip));
|
||||
if (!local)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
address = new Uri(uri.GetLeftPart(UriPartial.Authority) + "/");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Febe.Core.Library;
|
||||
using Febe.Web.Connection;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
/// <summary>
|
||||
/// The checks made before anything starts (spec §8.2, §11): the interface password and the Data folder. With a problem
|
||||
/// the engine and the browser do not start, and the interface shows only the page that explains it.
|
||||
/// </summary>
|
||||
internal static class StartupChecks
|
||||
{
|
||||
public const string PasswordMissing = "password-mancante";
|
||||
|
||||
public const string DataNotWritable = "dati-non-scrivibili";
|
||||
|
||||
public const string DataOnNetwork = "dati-in-rete";
|
||||
|
||||
/// <summary>Every problem found, in the order the error page shows them.</summary>
|
||||
public static IReadOnlyList<ConfigurationProblem> Run(ServerOptions options, DataFolderCheck? check = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
var problems = new List<ConfigurationProblem>();
|
||||
if (string.IsNullOrEmpty(options.Password))
|
||||
{
|
||||
problems.Add(new ConfigurationProblem(
|
||||
PasswordMissing,
|
||||
"Manca la password dell'interfaccia",
|
||||
"Il contenitore è partito senza la variabile FEBE_PASSWORD. Senza password l'interfaccia, e con lei la vista "
|
||||
+ "remota del browser, sarebbe aperta a chiunque raggiunga il server: per questo Febe non ha avviato né il motore né il browser.",
|
||||
"Imposta FEBE_PASSWORD (nel modello di Unraid o in compose.yml) con una frase lunga che usi solo qui, poi riavvia il contenitore."));
|
||||
}
|
||||
|
||||
if ((check ?? new DataFolderCheck()).Check(options.DataFolder) is { } data)
|
||||
{
|
||||
problems.Add(new ConfigurationProblem(
|
||||
data.Kind == DataFolderProblemKind.NetworkPath ? DataOnNetwork : DataNotWritable,
|
||||
data.Title,
|
||||
data.Explanation,
|
||||
data.Remedy));
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The problems found at start-up; fixed for the life of the process (fixing one needs a restart).</summary>
|
||||
internal sealed class StartupProblems(IReadOnlyList<ConfigurationProblem> problems) : IConfigurationProblems
|
||||
{
|
||||
public IReadOnlyList<ConfigurationProblem> Current { get; } = problems;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The link to Instagram while a configuration problem keeps the browser from starting: always «browser non
|
||||
/// disponibile», and every command refused with the problem (the configuration gate refuses them earlier anyway).
|
||||
/// </summary>
|
||||
internal sealed class UnavailableConnectionService(IReadOnlyList<ConfigurationProblem> problems) : IConnectionService
|
||||
{
|
||||
public Task<ConnectionStatus> GetStatusAsync(CancellationToken ct) =>
|
||||
Task.FromResult(new ConnectionStatus(ConnectionState.BrowserUnavailable, null, null, false, null));
|
||||
|
||||
public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct) => throw Refused();
|
||||
|
||||
public Task<FinishResult> FinishAsync(CancellationToken ct) => throw Refused();
|
||||
|
||||
public Task CancelAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task DisconnectAsync(CancellationToken ct) => throw Refused();
|
||||
|
||||
private Febe.Web.Api.BadRequestException Refused() =>
|
||||
new($"{(problems.Count > 0 ? problems[0].Title : "Configurazione da sistemare")}: il browser di Febe non è partito.");
|
||||
}
|
||||
@@ -64,6 +64,7 @@ public static class SettingsApi
|
||||
}
|
||||
|
||||
d.Import.LibrarySettingsChanged();
|
||||
(d.Services.GetService(typeof(Febe.Core.Library.LibraryIngest)) as Febe.Core.Library.LibraryIngest)?.Apply(new LibraryNaming(general, highlight), body.SetFileTime);
|
||||
d.Changes.Publish(new LibraryChange(d.Clock.Now, null, "settings"));
|
||||
return ApiHttp.Json(await GeneralAsync(context, d, ct).ConfigureAwait(false), FebeJsonContext.Default.GeneralSettingsDto);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
using Febe.Web.Api;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
|
||||
namespace Febe.Web.Connection;
|
||||
|
||||
/// <summary>
|
||||
/// <c>GET /salute</c> (PROTOCOLLO.md, spec §11): <c>200 {"stato":"ok"}</c> or <c>503 {"stato":"problema"}</c> and
|
||||
/// nothing else, without authentication, for the Docker health check. It says no more than that on purpose.
|
||||
/// </summary>
|
||||
public static class HealthEndpoint
|
||||
{
|
||||
public const string Path = "/salute";
|
||||
|
||||
public const string Ok = """{"stato":"ok"}""";
|
||||
|
||||
public const string Problem = """{"stato":"problema"}""";
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(endpoints);
|
||||
endpoints.MapMethods(Path, [HttpMethods.Get, HttpMethods.Head], (HttpContext context, IConfigurationProblems problems) =>
|
||||
{
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
var healthy = problems.Current.Count == 0;
|
||||
return Results.Text(healthy ? Ok : Problem, "application/json; charset=utf-8", statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>True for the health check request, which needs neither a session nor an allowed Host.</summary>
|
||||
public static bool IsHealthRequest(HttpRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
return (HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method))
|
||||
&& string.Equals(request.Path.Value, Path, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// While a configuration problem keeps the engine from starting (spec §8.2, §11), the interface shows only the page
|
||||
/// that explains it: the API answers only what that page and the frame around it need, everything else (library,
|
||||
/// accounts, connection, remote view) gets 503 with the problem in Italian.
|
||||
/// </summary>
|
||||
public sealed class ConfigurationGateMiddleware(RequestDelegate next, IConfigurationProblems problems)
|
||||
{
|
||||
/// <summary>API addresses still answered while there is a problem.</summary>
|
||||
public static readonly IReadOnlyList<string> AllowedApi =
|
||||
["/api/capabilities", "/api/preferences", "/api/accesso", "/api/uscita", "/api/engine", "/api/eventi"];
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var current = problems.Current;
|
||||
var path = context.Request.Path;
|
||||
if (current.Count == 0
|
||||
|| !path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)
|
||||
|| AllowedApi.Any(a => string.Equals(path.Value, a, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
await next(context).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||
await context.Response.WriteAsJsonAsync(
|
||||
new ProblemDto($"{current[0].Title}. Il motore non è partito: {current[0].Remedy}"),
|
||||
FebeJsonContext.Default.ProblemDto).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
namespace Febe.Web.Connection;
|
||||
|
||||
/// <summary>
|
||||
/// The browser seen through the interface (Docker only, spec §4.1, §11, mockup 10). Implemented by the server
|
||||
/// composition over the real Chromium; the web layer only speaks the protocol of <c>PROTOCOLLO.md</c> over a WebSocket.
|
||||
/// </summary>
|
||||
public interface IRemoteViewHost
|
||||
{
|
||||
/// <summary>
|
||||
/// Opens a remote view: Alberto is now driving (the engine is still) and frames start. A view opened earlier
|
||||
/// (another tab) is closed with <see cref="RemoteViewEnd.Replaced"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="RemoteViewUnavailableException">The browser is not running: nothing to show.</exception>
|
||||
Task<IRemoteViewConnection> OpenAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>One open remote view. Disposing it stops the frames and ends «Alberto is driving».</summary>
|
||||
public interface IRemoteViewConnection : IAsyncDisposable
|
||||
{
|
||||
/// <summary>What goes to the page, in order: meta first, then frames (the oldest dropped when the page is slow).</summary>
|
||||
IAsyncEnumerable<RemoteViewOutput> ReadAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Why the view ended on the server side (null while it is open).</summary>
|
||||
RemoteViewEnd? Ended { get; }
|
||||
|
||||
Task MouseAsync(RemoteViewMouse input, CancellationToken ct);
|
||||
|
||||
Task KeyAsync(RemoteViewKey input, CancellationToken ct);
|
||||
|
||||
Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Why a remote view ended without Alberto closing it.</summary>
|
||||
public enum RemoteViewEnd
|
||||
{
|
||||
/// <summary>Opened again in another tab or window: the newest wins.</summary>
|
||||
Replaced,
|
||||
|
||||
/// <summary>The browser stopped or is restarting.</summary>
|
||||
BrowserStopped,
|
||||
|
||||
/// <summary>The server is shutting down.</summary>
|
||||
ShuttingDown,
|
||||
}
|
||||
|
||||
/// <summary>A message for the page: a JPEG frame, or a meta message (address and size).</summary>
|
||||
public abstract record RemoteViewOutput;
|
||||
|
||||
/// <summary>A frame of the screencast, sent as one binary WebSocket message.</summary>
|
||||
/// <param name="Jpeg">The JPEG bytes.</param>
|
||||
public sealed record RemoteViewFrame(ReadOnlyMemory<byte> Jpeg) : RemoteViewOutput;
|
||||
|
||||
/// <summary>Sent at the start and whenever the address or the size changes.</summary>
|
||||
/// <param name="Width">Page width in CSS pixels the frames represent.</param>
|
||||
/// <param name="Height">Page height in CSS pixels the frames represent.</param>
|
||||
/// <param name="Url">Address of the page without query string or fragment.</param>
|
||||
public sealed record RemoteViewMeta(int Width, int Height, string Url) : RemoteViewOutput;
|
||||
|
||||
public enum RemoteViewMouseAction
|
||||
{
|
||||
Move,
|
||||
Down,
|
||||
Up,
|
||||
Wheel,
|
||||
}
|
||||
|
||||
public enum RemoteViewButton
|
||||
{
|
||||
None,
|
||||
Left,
|
||||
Middle,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// <summary>A mouse event; <paramref name="X"/> and <paramref name="Y"/> are 0–1 of the frame.</summary>
|
||||
public sealed record RemoteViewMouse(
|
||||
RemoteViewMouseAction Action,
|
||||
double X,
|
||||
double Y,
|
||||
RemoteViewButton Button,
|
||||
int ClickCount,
|
||||
double DeltaX,
|
||||
double DeltaY);
|
||||
|
||||
public enum RemoteViewKeyAction
|
||||
{
|
||||
/// <summary>Key pressed; when it has <see cref="RemoteViewKey.Text"/> the text is inserted.</summary>
|
||||
Down,
|
||||
|
||||
Up,
|
||||
|
||||
/// <summary>Text only (composed characters): inserted without key codes.</summary>
|
||||
Char,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A key from the page. Contains what Alberto types, passwords included: never logged, never stored, never shown
|
||||
/// (spec §13.2). <see cref="ToString"/> hides everything on purpose.
|
||||
/// </summary>
|
||||
/// <param name="Action">Down, up or char.</param>
|
||||
/// <param name="Key">DOM <c>key</c>.</param>
|
||||
/// <param name="Code">DOM <c>code</c>.</param>
|
||||
/// <param name="Text">Text the key produces, if any.</param>
|
||||
/// <param name="Modifiers">Bit mask of <c>Input.dispatchKeyEvent</c>: Alt 1, Ctrl 2, Meta 4, Shift 8.</param>
|
||||
public sealed record RemoteViewKey(RemoteViewKeyAction Action, string Key, string Code, string? Text, int Modifiers)
|
||||
{
|
||||
public override string ToString() => "RemoteViewKey(…)";
|
||||
}
|
||||
|
||||
public enum RemoteViewNavigation
|
||||
{
|
||||
/// <summary>Back to the previous address of this view.</summary>
|
||||
Back,
|
||||
|
||||
/// <summary>Reload the current page.</summary>
|
||||
Reload,
|
||||
}
|
||||
|
||||
/// <summary>The browser is not available (starting, restarting, missing, or Febe stopped by a configuration problem).</summary>
|
||||
public sealed class RemoteViewUnavailableException : Exception
|
||||
{
|
||||
public RemoteViewUnavailableException()
|
||||
: base("Il browser di Febe non è disponibile in questo momento.")
|
||||
{
|
||||
}
|
||||
|
||||
public RemoteViewUnavailableException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public RemoteViewUnavailableException(string message, Exception? inner)
|
||||
: base(message, inner)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
using System.Buffers;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using Febe.Web.Api;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Web.Connection;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/vista</c>: the remote view over a WebSocket (PROTOCOLLO.md, spec §4.1, §11). The security middleware has
|
||||
/// already checked the session and the <c>Origin</c> (spec §13.1) before this runs. Frames go out as binary messages,
|
||||
/// meta as text; mouse, keys and back/reload come in as small JSON text messages and go to the browser. Nothing that
|
||||
/// comes in is ever logged: it contains what Alberto types.
|
||||
/// </summary>
|
||||
public static class RemoteViewSocket
|
||||
{
|
||||
public const string Path = "/api/vista";
|
||||
|
||||
/// <summary>Largest message accepted from the page; larger ones close the view.</summary>
|
||||
public const int MaxMessageBytes = 4096;
|
||||
|
||||
/// <summary>Close code when the view was opened again elsewhere (the newest wins).</summary>
|
||||
public const int CloseReplaced = 4001;
|
||||
|
||||
/// <summary>Close code when the browser stopped or is restarting.</summary>
|
||||
public const int CloseBrowserStopped = 4002;
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(endpoints);
|
||||
endpoints.Map(Path, HandleAsync);
|
||||
}
|
||||
|
||||
public static async Task HandleAsync(HttpContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var options = context.RequestServices.GetRequiredService<FebeWebOptions>();
|
||||
if (options.Edition == FebeEdition.Desktop && !options.Demo)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status404NotFound, "Sul desktop il browser di Febe ha la sua finestra: la vista remota c'è solo nel contenitore.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!context.WebSockets.IsWebSocketRequest)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status400BadRequest, "La vista remota si apre solo con una connessione WebSocket.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.RequestServices.GetService<IRemoteViewHost>() is not { } host)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, "La vista remota non è disponibile: il browser di Febe non è in funzione.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
IRemoteViewConnection connection;
|
||||
try
|
||||
{
|
||||
connection = await host.OpenAsync(context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
catch (RemoteViewUnavailableException ex)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, ex.Message).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await using (connection.ConfigureAwait(false))
|
||||
{
|
||||
using var socket = await context.WebSockets.AcceptWebSocketAsync(new WebSocketAcceptContext
|
||||
{
|
||||
KeepAliveInterval = TimeSpan.FromSeconds(20),
|
||||
DangerousEnableCompression = false,
|
||||
}).ConfigureAwait(false);
|
||||
await RunAsync(socket, connection, context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pumps one view until either side closes it.</summary>
|
||||
internal static async Task RunAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken aborted)
|
||||
{
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(aborted);
|
||||
var sender = Task.Run(() => SendLoopAsync(socket, connection, stop.Token), CancellationToken.None);
|
||||
var closeStatus = WebSocketCloseStatus.NormalClosure;
|
||||
var closeText = "Vista chiusa";
|
||||
try
|
||||
{
|
||||
if (!await ReceiveLoopAsync(socket, connection, stop.Token).ConfigureAwait(false))
|
||||
{
|
||||
closeStatus = WebSocketCloseStatus.MessageTooBig;
|
||||
closeText = "Messaggio troppo lungo";
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException)
|
||||
{
|
||||
// The page went away.
|
||||
}
|
||||
finally
|
||||
{
|
||||
await stop.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await sender.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
||||
try
|
||||
{
|
||||
await socket.CloseOutputAsync(closeStatus, closeText, timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task SendLoopAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken ct)
|
||||
{
|
||||
await foreach (var output in connection.ReadAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
switch (output)
|
||||
{
|
||||
case RemoteViewMeta meta:
|
||||
await socket.SendAsync(MetaJson(meta), WebSocketMessageType.Text, endOfMessage: true, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case RemoteViewFrame frame:
|
||||
await socket.SendAsync(frame.Jpeg, WebSocketMessageType.Binary, endOfMessage: true, ct).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// The server ended the view (another tab, browser stopped, shutdown): tell the page why.
|
||||
if (!ct.IsCancellationRequested && socket.State == WebSocketState.Open)
|
||||
{
|
||||
var (status, text) = connection.Ended switch
|
||||
{
|
||||
RemoteViewEnd.Replaced => ((WebSocketCloseStatus)CloseReplaced, "Vista aperta in un'altra finestra"),
|
||||
RemoteViewEnd.ShuttingDown => (WebSocketCloseStatus.EndpointUnavailable, "Febe si sta fermando"),
|
||||
_ => ((WebSocketCloseStatus)CloseBrowserStopped, "Il browser si è fermato"),
|
||||
};
|
||||
await socket.CloseOutputAsync(status, text, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the page's messages until it closes. Returns false when a message was too long: the caller closes the
|
||||
/// view (only one task may send at a time, and the frames are being sent by another).
|
||||
/// </summary>
|
||||
private static async Task<bool> ReceiveLoopAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken ct)
|
||||
{
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(MaxMessageBytes + 1);
|
||||
try
|
||||
{
|
||||
while (socket.State == WebSocketState.Open && !ct.IsCancellationRequested)
|
||||
{
|
||||
var length = 0;
|
||||
ValueWebSocketReceiveResult result;
|
||||
do
|
||||
{
|
||||
if (length >= MaxMessageBytes + 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
result = await socket.ReceiveAsync(buffer.AsMemory(length, MaxMessageBytes + 1 - length), ct).ConfigureAwait(false);
|
||||
if (result.MessageType == WebSocketMessageType.Close)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
length += result.Count;
|
||||
}
|
||||
while (!result.EndOfMessage);
|
||||
|
||||
if (length > MaxMessageBytes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (result.MessageType != WebSocketMessageType.Text)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await DispatchAsync(buffer.AsMemory(0, length), connection, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Parses one message of the page and forwards it. Unknown or malformed messages are dropped silently.</summary>
|
||||
internal static async Task DispatchAsync(ReadOnlyMemory<byte> message, IRemoteViewConnection connection, CancellationToken ct)
|
||||
{
|
||||
object? input;
|
||||
try
|
||||
{
|
||||
input = Parse(message);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
switch (input)
|
||||
{
|
||||
case RemoteViewMouse mouse:
|
||||
await connection.MouseAsync(mouse, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case RemoteViewKey key:
|
||||
await connection.KeyAsync(key, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case RemoteViewNavigation navigation:
|
||||
await connection.NavigateAsync(navigation, ct).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException && ex is not OutOfMemoryException)
|
||||
{
|
||||
// A lost gesture (no frame yet, browser restarting): the page simply tries again. Never logged: it may
|
||||
// be a key of a password.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The input messages of PROTOCOLLO.md: <c>mouse</c>, <c>key</c>, <c>navigate</c>. Returns null for anything else
|
||||
/// (unknown type or action, missing fields, values out of range).
|
||||
/// </summary>
|
||||
internal static object? Parse(ReadOnlyMemory<byte> message)
|
||||
{
|
||||
using var document = JsonDocument.Parse(message, new JsonDocumentOptions { MaxDepth = 3 });
|
||||
var root = document.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object || Text(root, "type", 16) is not { } type)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var action = Text(root, "action", 16);
|
||||
switch (type)
|
||||
{
|
||||
case "mouse":
|
||||
{
|
||||
RemoteViewMouseAction? kind = action switch
|
||||
{
|
||||
"move" => RemoteViewMouseAction.Move,
|
||||
"down" => RemoteViewMouseAction.Down,
|
||||
"up" => RemoteViewMouseAction.Up,
|
||||
"wheel" => RemoteViewMouseAction.Wheel,
|
||||
_ => null,
|
||||
};
|
||||
if (kind is null || Number(root, "x") is not { } x || Number(root, "y") is not { } y || x is < 0 or > 1 || y is < 0 or > 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var button = Text(root, "button", 16) switch
|
||||
{
|
||||
"left" => RemoteViewButton.Left,
|
||||
"middle" => RemoteViewButton.Middle,
|
||||
"right" => RemoteViewButton.Right,
|
||||
_ => kind is RemoteViewMouseAction.Down or RemoteViewMouseAction.Up ? RemoteViewButton.Left : RemoteViewButton.None,
|
||||
};
|
||||
var clicks = (int)Math.Clamp(Number(root, "clickCount") ?? 1, 1, 3);
|
||||
var dx = Math.Clamp(Number(root, "deltaX") ?? 0, -5000, 5000);
|
||||
var dy = Math.Clamp(Number(root, "deltaY") ?? 0, -5000, 5000);
|
||||
return new RemoteViewMouse(kind.Value, x, y, button, clicks, dx, dy);
|
||||
}
|
||||
|
||||
case "key":
|
||||
{
|
||||
RemoteViewKeyAction? kind = action switch
|
||||
{
|
||||
"down" => RemoteViewKeyAction.Down,
|
||||
"up" => RemoteViewKeyAction.Up,
|
||||
"char" => RemoteViewKeyAction.Char,
|
||||
_ => null,
|
||||
};
|
||||
var key = Text(root, "key", 64) ?? string.Empty;
|
||||
var code = Text(root, "code", 64) ?? string.Empty;
|
||||
var text = Text(root, "text", 32);
|
||||
var modifiers = (int)Math.Clamp(Number(root, "modifiers") ?? 0, 0, 15);
|
||||
if (kind is null || (kind == RemoteViewKeyAction.Char ? string.IsNullOrEmpty(text) : key.Length == 0))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new RemoteViewKey(kind.Value, key, code, string.IsNullOrEmpty(text) ? null : text, modifiers);
|
||||
}
|
||||
|
||||
case "navigate":
|
||||
return action switch
|
||||
{
|
||||
"back" => RemoteViewNavigation.Back,
|
||||
"reload" => RemoteViewNavigation.Reload,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The meta message as UTF-8 JSON.</summary>
|
||||
internal static ReadOnlyMemory<byte> MetaJson(RemoteViewMeta meta)
|
||||
{
|
||||
var buffer = new ArrayBufferWriter<byte>(256);
|
||||
using (var writer = new Utf8JsonWriter(buffer))
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
writer.WriteString("type", "meta");
|
||||
writer.WriteNumber("width", meta.Width);
|
||||
writer.WriteNumber("height", meta.Height);
|
||||
writer.WriteString("url", meta.Url);
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
return buffer.WrittenMemory;
|
||||
}
|
||||
|
||||
private static string? Text(JsonElement root, string name, int maxLength) =>
|
||||
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && value.GetString() is { } s && s.Length <= maxLength
|
||||
? s
|
||||
: null;
|
||||
|
||||
private static double? Number(JsonElement root, string name) =>
|
||||
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var d) && double.IsFinite(d)
|
||||
? d
|
||||
: null;
|
||||
|
||||
private static Task RefuseAsync(HttpContext context, int status, string message)
|
||||
{
|
||||
context.Response.StatusCode = status;
|
||||
return context.Response.WriteAsJsonAsync(new ProblemDto(message), FebeJsonContext.Default.ProblemDto);
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,10 @@ public static class FebeWeb
|
||||
}
|
||||
|
||||
app.UseMiddleware<ApiErrorMiddleware>();
|
||||
app.UseMiddleware<ConfigurationGateMiddleware>();
|
||||
|
||||
// The remote view (/api/vista). Origin and session are checked by the security middleware above.
|
||||
app.UseWebSockets();
|
||||
var types = new FileExtensionContentTypeProvider();
|
||||
types.Mappings[".json"] = "application/json; charset=utf-8";
|
||||
types.Mappings[".js"] = "text/javascript; charset=utf-8";
|
||||
@@ -133,6 +137,8 @@ public static class FebeWeb
|
||||
SettingsApi.Map(endpoints);
|
||||
ImportApi.Map(endpoints);
|
||||
DuplicatesApi.Map(endpoints);
|
||||
RemoteViewSocket.Map(endpoints);
|
||||
HealthEndpoint.Map(endpoints);
|
||||
|
||||
endpoints.Map("/api/{**rest}", static context =>
|
||||
{
|
||||
|
||||
+27
-1
@@ -74,7 +74,7 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri
|
||||
|
||||
| Veste | Opzioni | Effetto |
|
||||
|---|---|---|
|
||||
| Docker | `Edition = Docker`, `Access = Password`, `Password = FEBE_PASSWORD`, `AllowedHosts` = nomi con cui si raggiunge il server (anche `nome:*`), `FebeListen.Any(8480)` | Pagina `/accesso`, cookie `febe_sessione` HttpOnly SameSite=Strict, blocco dopo 5 errori per client e 20 in tutto in 15 minuti. Senza password risponde 503 e non si apre |
|
||||
| Docker | `Edition = Docker`, `Access = Password`, `Password = FEBE_PASSWORD`, `AllowedHosts` = nomi con cui si raggiunge il server (anche `nome:*`), `FebeListen.Any(8480)` | Pagina `/accesso`, cookie `febe_sessione` HttpOnly SameSite=Strict, blocco dopo 5 errori per client e 20 in tutto in 15 minuti. Senza password risponde solo alla pagina dell'errore (indirizzi delle pagine, file dell'interfaccia, `GET /api/capabilities` e `/api/preferences`, `/salute`); tutto il resto, vista remota compresa, 503 |
|
||||
| Windows | `Edition = Desktop`, `Access = Token`, `AccessToken = AccessToken.Create()`, `AllowedHosts = FebeWebOptions.LoopbackHosts(porta)`, `FebeListen.Loopback(0)` | La finestra apre `/?gettone=…` una volta: il gettone diventa un cookie HttpOnly Strict e sparisce dall'indirizzo. Anche l'intestazione `X-Febe-Gettone` vale |
|
||||
| Prove e dimostrazione | `Access = None` | Solo su 127.0.0.1 |
|
||||
|
||||
@@ -124,6 +124,32 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
|
||||
|
||||
Ogni altro indirizzo senza estensione risponde con `index.html`; `/api/…` sconosciuto risponde 404 in JSON.
|
||||
|
||||
## Collegamento, vista remota, salute (veste Docker)
|
||||
|
||||
Il contratto con l'interfaccia è `Connection/PROTOCOLLO.md`. Lato server:
|
||||
|
||||
- `IConnectionService` lo registra la composizione (`Febe.Server/ServerConnectionService`, sul Chromium vero; con un
|
||||
problema di configurazione `UnavailableConnectionService`). Gli endpoint `/api/connection/*` lo usano.
|
||||
- `IRemoteViewHost` (`Connection/RemoteView.cs`) apre una vista: `IRemoteViewConnection.ReadAsync` dà prima `meta` poi
|
||||
fotogrammi (i vecchi si scartano se la pagina è lenta), `MouseAsync`/`KeyAsync`/`NavigateAsync` portano i gesti al
|
||||
browser. Una vista alla volta: aprirne un'altra chiude la precedente. Senza `IRemoteViewHost` registrato,
|
||||
`/api/vista` risponde 503.
|
||||
- `/api/vista` (`Connection/RemoteViewSocket.cs`): WebSocket dietro il controllo di sessione e di `Origin` del
|
||||
`SecurityMiddleware`; 404 sulla veste desktop (fuori dalla dimostrazione), 400 se non è un WebSocket, 503 senza
|
||||
browser. Messaggi in arrivo solo testo, al massimo 4 KB (oltre: chiusura 1009); quelli sconosciuti, malformati o con
|
||||
valori fuori intervallo (x e y fuori da 0–1) si scartano in silenzio. Mai registrati.
|
||||
- `modifiers` dei tasti: la maschera di `Input.dispatchKeyEvent` (Alt 1, Ctrl 2, Meta 4, Shift 8).
|
||||
- `key` con `action: "down"` e `text` inserisce il testo; `action: "char"` (con il solo `text`) inserisce un carattere
|
||||
composto senza codici tasto. Per un tasto normale si manda `down` (con `text`) e poi `up`, non anche `char`.
|
||||
- `navigate`: `back` torna all'indirizzo precedente di questa vista (con `Page.navigate`: fra i comandi ammessi di
|
||||
§6.1 non c'è la cronologia del browser), `reload` ricarica l'indirizzo attuale.
|
||||
- Chiusure dal server: 4001 «Vista aperta in un'altra finestra», 4002 «Il browser si è fermato», 1001 «Febe si sta
|
||||
fermando», 1000 normale.
|
||||
- `GET /salute` (`Connection/ConfigurationGate.cs`): senza sessione e con qualunque Host, `200 {"stato":"ok"}` o
|
||||
`503 {"stato":"problema"}` quando `IConfigurationProblems.Current` non è vuoto.
|
||||
- `ConfigurationGateMiddleware`: con un problema di configurazione l'API risponde solo a `capabilities`, `preferences`,
|
||||
`accesso`, `uscita`, `engine` (GET, motore spento) ed `eventi`; il resto 503 con il problema in italiano.
|
||||
|
||||
## Interfaccia (`wwwroot/`)
|
||||
|
||||
Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da disco:
|
||||
|
||||
@@ -14,6 +14,13 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
|
||||
public static readonly IReadOnlyList<string> PublicPrefixes =
|
||||
["/accesso", "/api/accesso", "/css/", "/caratteri/", "/img/", "/testi/", "/js/", "/favicon.ico"];
|
||||
|
||||
/// <summary>
|
||||
/// Without a password (FEBE_PASSWORD missing) only these answer, so that the interface can show the page that
|
||||
/// explains the problem (spec §11): the application page, its files, the capabilities with the problems, the
|
||||
/// preferences (theme). Everything else, the remote view first, gets 503.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> WithoutPasswordApi = ["/api/capabilities", "/api/preferences"];
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
@@ -21,6 +28,13 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
|
||||
var response = context.Response;
|
||||
SetHeaders(response);
|
||||
|
||||
// The Docker health check: no session, any Host (it comes from inside the container), «ok» or «problema» only.
|
||||
if (Connection.HealthEndpoint.IsHealthRequest(request))
|
||||
{
|
||||
await next(context).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!HostOriginGuard.HostAllowed(request, options))
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status400BadRequest, "Indirizzo non ammesso: apri Febe dal suo indirizzo.").ConfigureAwait(false);
|
||||
@@ -99,13 +113,18 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
|
||||
|
||||
private async Task<bool> PasswordAsync(HttpContext context)
|
||||
{
|
||||
var path = context.Request.Path.Value ?? "/";
|
||||
if (passwords is null)
|
||||
{
|
||||
if (OpenWithoutPassword(context.Request, path))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, "Manca la password dell'interfaccia (FEBE_PASSWORD): Febe non si apre senza.").ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
var path = context.Request.Path.Value ?? "/";
|
||||
if (PublicPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return true;
|
||||
@@ -130,6 +149,25 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti
|
||||
|
||||
private static bool IsApi(HttpRequest request) => request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>What may be read without a password: the error page and what it needs, never a command.</summary>
|
||||
private static bool OpenWithoutPassword(HttpRequest request, string path)
|
||||
{
|
||||
if (!HttpMethods.IsGet(request.Method) && !HttpMethods.IsHead(request.Method))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (IsApi(request))
|
||||
{
|
||||
return WithoutPasswordApi.Any(a => string.Equals(path, a, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
// Interface files, and page addresses (no extension) that answer with the application page.
|
||||
return PublicPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase))
|
||||
|| path.StartsWith("/icone/", StringComparison.OrdinalIgnoreCase)
|
||||
|| !Path.HasExtension(path);
|
||||
}
|
||||
|
||||
private static async Task RefuseAsync(HttpContext context, int status, string message)
|
||||
{
|
||||
context.Response.StatusCode = status;
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using Febe.Server;
|
||||
using Febe.Tests.Server.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Febe.Web;
|
||||
using Febe.Web.Connection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Server;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/vista</c> (PROTOCOLLO.md, spec §13.1) without a browser: session and Origin checks, frames as binary
|
||||
/// messages, meta as text, input parsed and forwarded, limits, and the reasons a view ends.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class RemoteViewSocketTests
|
||||
{
|
||||
private const string Password = "la password della vista";
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheViewNeedsTheSessionAndTheOriginOfTheInterface()
|
||||
{
|
||||
var host = new FakeRemoteViewHost();
|
||||
await using var server = await StartAsync(host);
|
||||
var cookies = await LoginAsync(server);
|
||||
|
||||
// No session: refused before the WebSocket opens.
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, await RefusedAsync(server, null, server.Origin));
|
||||
|
||||
// Another page (another origin) cannot open it, even with the session cookie of Alberto's browser.
|
||||
Assert.AreEqual(HttpStatusCode.Forbidden, await RefusedAsync(server, cookies, "http://pagina-di-altri.example"));
|
||||
Assert.IsEmpty(host.Opened);
|
||||
|
||||
// The interface itself can.
|
||||
using var socket = await ConnectAsync(server, cookies);
|
||||
Assert.AreEqual(WebSocketState.Open, socket.State);
|
||||
Assert.HasCount(1, host.Opened);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task FramesAreBinaryMetaIsTextAndGesturesComeBack()
|
||||
{
|
||||
var host = new FakeRemoteViewHost();
|
||||
await using var server = await StartAsync(host);
|
||||
var cookies = await LoginAsync(server);
|
||||
using var socket = await ConnectAsync(server, cookies);
|
||||
var view = host.Opened.Single();
|
||||
|
||||
view.Write(new RemoteViewMeta(1279, 760, "http://127.0.0.1:8481/benvenuto"));
|
||||
view.Write(new RemoteViewFrame(new byte[] { 0xFF, 0xD8, 1, 2, 3, 0xFF, 0xD9 }));
|
||||
var (metaType, meta) = await ReceiveAsync(socket);
|
||||
Assert.AreEqual(WebSocketMessageType.Text, metaType);
|
||||
Assert.AreEqual("""{"type":"meta","width":1279,"height":760,"url":"http://127.0.0.1:8481/benvenuto"}""", Encoding.UTF8.GetString(meta));
|
||||
var (frameType, frame) = await ReceiveAsync(socket);
|
||||
Assert.AreEqual(WebSocketMessageType.Binary, frameType);
|
||||
CollectionAssert.AreEqual(new byte[] { 0xFF, 0xD8, 1, 2, 3, 0xFF, 0xD9 }, frame);
|
||||
|
||||
foreach (var message in new[]
|
||||
{
|
||||
"""{"type":"mouse","action":"down","x":0.25,"y":0.5,"button":"left","clickCount":1}""",
|
||||
"""{"type":"key","action":"down","key":"a","code":"KeyA","text":"a","modifiers":0}""",
|
||||
"""{"type":"key","action":"char","text":"è"}""",
|
||||
"""{"type":"navigate","action":"back"}""",
|
||||
"""{"type":"mouse","action":"move","x":1.5,"y":0.5}""",
|
||||
"""{"type":"navigate","action":"vai","url":"https://altrove.example/"}""",
|
||||
"""{"type":"script","code":"alert(1)"}""",
|
||||
"non è JSON",
|
||||
})
|
||||
{
|
||||
await socket.SendAsync(Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text, true, TestContext.CancellationToken);
|
||||
}
|
||||
|
||||
await ServerTestBed.WaitUntilAsync(() => Task.FromResult(view.Inputs.Count >= 4), TimeSpan.FromSeconds(10), "quattro gesti inoltrati");
|
||||
await Task.Delay(200);
|
||||
var inputs = view.Inputs.ToArray();
|
||||
Assert.HasCount(4, inputs, "out-of-range, unknown and malformed messages are dropped");
|
||||
var mouse = (RemoteViewMouse)inputs[0];
|
||||
Assert.AreEqual(RemoteViewMouseAction.Down, mouse.Action);
|
||||
Assert.AreEqual(0.25, mouse.X);
|
||||
Assert.AreEqual(RemoteViewButton.Left, mouse.Button);
|
||||
var key = (RemoteViewKey)inputs[1];
|
||||
Assert.AreEqual(RemoteViewKeyAction.Down, key.Action);
|
||||
Assert.AreEqual("a", key.Text);
|
||||
Assert.AreEqual("RemoteViewKey(…)", key.ToString(), "a key never shows in a log line");
|
||||
Assert.AreEqual(RemoteViewKeyAction.Char, ((RemoteViewKey)inputs[2]).Action);
|
||||
Assert.AreEqual(RemoteViewNavigation.Back, inputs[3]);
|
||||
|
||||
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "fine", TestContext.CancellationToken);
|
||||
await ServerTestBed.WaitUntilAsync(() => Task.FromResult(view.Disposed), TimeSpan.FromSeconds(10), "la vista chiusa dal server");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AViewOpenedElsewhereReplacesTheOldOneAndATooLongMessageClosesIt()
|
||||
{
|
||||
var host = new FakeRemoteViewHost();
|
||||
await using var server = await StartAsync(host);
|
||||
var cookies = await LoginAsync(server);
|
||||
using var first = await ConnectAsync(server, cookies);
|
||||
using var second = await ConnectAsync(server, cookies);
|
||||
await ExpectCloseAsync(first, (WebSocketCloseStatus)RemoteViewSocket.CloseReplaced);
|
||||
Assert.AreEqual(RemoteViewEnd.Replaced, host.Opened[0].Ended);
|
||||
|
||||
await second.SendAsync(new byte[RemoteViewSocket.MaxMessageBytes + 10], WebSocketMessageType.Text, true, TestContext.CancellationToken);
|
||||
await ExpectCloseAsync(second, WebSocketCloseStatus.MessageTooBig);
|
||||
await ServerTestBed.WaitUntilAsync(() => Task.FromResult(host.Opened[1].Disposed), TimeSpan.FromSeconds(10), "la vista chiusa");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutBrowserOrOnTheDesktopThereIsNoView()
|
||||
{
|
||||
var host = new FakeRemoteViewHost { Unavailable = true };
|
||||
await using var server = await StartAsync(host);
|
||||
var cookies = await LoginAsync(server);
|
||||
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, await RefusedAsync(server, cookies, server.Origin));
|
||||
|
||||
// A plain request is not a WebSocket.
|
||||
using var client = new HttpClient(new HttpClientHandler { CookieContainer = cookies }) { BaseAddress = server.Address };
|
||||
using (var plain = await client.GetAsync("/api/vista", TestContext.CancellationToken))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, plain.StatusCode);
|
||||
}
|
||||
|
||||
await using var desktop = await WebTestServer.StartAsync(new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None }, s => s.AddSingleton<IRemoteViewHost>(new FakeRemoteViewHost()));
|
||||
using var response = await desktop.Client.GetAsync("/api/vista", TestContext.CancellationToken);
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void KeysGetTheVirtualCodesChromiumNeeds()
|
||||
{
|
||||
Assert.AreEqual(65, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "a", "KeyA", "a", 0)).KeyCode);
|
||||
Assert.AreEqual(8, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "Backspace", "Backspace", null, 0)).KeyCode);
|
||||
var enter = RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "Enter", "Enter", null, 0));
|
||||
Assert.AreEqual(13, enter.KeyCode);
|
||||
Assert.AreEqual("\r", enter.Text, "Enter submits forms only with its text");
|
||||
Assert.AreEqual(50, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "\"", "Digit2", "\"", 8)).KeyCode, "Italian layout: Shift+2");
|
||||
Assert.AreEqual(219, RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "è", "BracketLeft", "è", 0)).KeyCode, "Italian layout: è");
|
||||
Assert.AreEqual("KeyStroke(…)", RemoteKeys.ToStroke(new RemoteViewKey(RemoteViewKeyAction.Down, "x", "KeyX", "x", 0)).ToString());
|
||||
Assert.AreEqual("http://127.0.0.1:8481/profilo/marta.prova/", BrowserRemoteViewConnection.WithoutQuery("http://127.0.0.1:8481/profilo/marta.prova/?gettone=segreto#x"));
|
||||
Assert.AreEqual("about:blank", BrowserRemoteViewConnection.WithoutQuery("about:blank"));
|
||||
}
|
||||
|
||||
private static Task<WebTestServer> StartAsync(FakeRemoteViewHost host) =>
|
||||
WebTestServer.StartAsync(
|
||||
new FebeWebOptions { Edition = FebeEdition.Docker, Access = AccessMode.Password, Password = Password },
|
||||
s => s.AddSingleton<IRemoteViewHost>(host));
|
||||
|
||||
private async Task<CookieContainer> LoginAsync(WebTestServer server)
|
||||
{
|
||||
var cookies = new CookieContainer();
|
||||
using var client = new HttpClient(new HttpClientHandler { CookieContainer = cookies, UseCookies = true }) { BaseAddress = server.Address };
|
||||
using var request = server.Request(HttpMethod.Post, "/api/accesso", $$"""{"password":"{{Password}}"}""");
|
||||
using var response = await client.SendAsync(request, TestContext.CancellationToken);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
return cookies;
|
||||
}
|
||||
|
||||
private async Task<ClientWebSocket> ConnectAsync(WebTestServer server, CookieContainer cookies)
|
||||
{
|
||||
var socket = new ClientWebSocket();
|
||||
socket.Options.Cookies = cookies;
|
||||
socket.Options.SetRequestHeader("Origin", server.Origin);
|
||||
await socket.ConnectAsync(new UriBuilder(server.Address) { Scheme = "ws", Path = RemoteViewSocket.Path }.Uri, TestContext.CancellationToken);
|
||||
return socket;
|
||||
}
|
||||
|
||||
private async Task<HttpStatusCode?> RefusedAsync(WebTestServer server, CookieContainer? cookies, string origin)
|
||||
{
|
||||
using var socket = new ClientWebSocket();
|
||||
socket.Options.CollectHttpResponseDetails = true;
|
||||
socket.Options.SetRequestHeader("Origin", origin);
|
||||
if (cookies is not null)
|
||||
{
|
||||
socket.Options.Cookies = cookies;
|
||||
}
|
||||
|
||||
await Assert.ThrowsAsync<WebSocketException>(() => socket.ConnectAsync(new UriBuilder(server.Address) { Scheme = "ws", Path = RemoteViewSocket.Path }.Uri, TestContext.CancellationToken));
|
||||
return socket.HttpStatusCode;
|
||||
}
|
||||
|
||||
private async Task<(WebSocketMessageType Type, byte[] Data)> ReceiveAsync(ClientWebSocket socket)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.CancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
var buffer = new byte[8192];
|
||||
using var data = new MemoryStream();
|
||||
WebSocketReceiveResult result;
|
||||
do
|
||||
{
|
||||
result = await socket.ReceiveAsync(buffer, timeout.Token);
|
||||
data.Write(buffer, 0, result.Count);
|
||||
}
|
||||
while (!result.EndOfMessage);
|
||||
return (result.MessageType, data.ToArray());
|
||||
}
|
||||
|
||||
private async Task ExpectCloseAsync(ClientWebSocket socket, WebSocketCloseStatus status)
|
||||
{
|
||||
var (type, _) = await ReceiveAsync(socket);
|
||||
Assert.AreEqual(WebSocketMessageType.Close, type);
|
||||
Assert.AreEqual(status, socket.CloseStatus);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Server.Support;
|
||||
using Febe.Web.Connection;
|
||||
|
||||
namespace Febe.Tests.Server;
|
||||
|
||||
/// <summary>
|
||||
/// The real composition of the server (milestone M5) against the local test site, with Xvfb and a real Chromium: the
|
||||
/// password, the connection through the login page, accounts added through the API, «Controlla ora», a real session of
|
||||
/// the engine with the Governor's permits, files and thumbnails in the library, the stop on the verification page and
|
||||
/// the remote view. Never Instagram: the browser only sees 127.0.0.1.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public sealed partial class ServerEndToEndTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireBrowser()
|
||||
{
|
||||
if (ServerTestBed.UnavailableReason() is { } reason)
|
||||
{
|
||||
Assert.Inconclusive(reason);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(360_000, CooperativeCancellation = true)]
|
||||
public async Task TheRealServerCollectsFromTheTestSiteStopsAtTheVerificationAndShowsTheBrowser()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ServerTestBed.StartAsync();
|
||||
var server = bed.Server;
|
||||
Assert.IsEmpty(server.Problems);
|
||||
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
var connection = server.Connection!;
|
||||
|
||||
// The health check answers without a session; everything else wants the password.
|
||||
using (var health = await bed.Client.GetAsync("/salute", ct))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, health.StatusCode);
|
||||
Assert.AreEqual("""{"stato":"ok"}""", await health.Content.ReadAsStringAsync(ct));
|
||||
}
|
||||
|
||||
using (var anonymous = await bed.Client.GetAsync("/api/accounts", ct))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Unauthorized, anonymous.StatusCode);
|
||||
}
|
||||
|
||||
await bed.LoginAsync();
|
||||
|
||||
// A fresh profile: not connected, the engine waits.
|
||||
Assert.AreEqual(ConnectionState.NotConnected, (await connection.GetStatusAsync(ct)).State);
|
||||
|
||||
// Accounts added through the API, as from the «Aggiungi account» dialog.
|
||||
var added = await bed.JsonAsync(HttpMethod.Post, "/api/accounts", """{"usernames":["marta.prova","luca.prova"],"start":"everything"}""");
|
||||
Assert.AreEqual(2, added.GetProperty("added").GetInt32());
|
||||
var marta = await server.Database.Accounts.FindByUsernameAsync("marta.prova", ct) ?? throw new AssertFailedException("marta.prova manca");
|
||||
|
||||
// «Accedi a Instagram» opens the login page (here: the test site, whose first visit starts its session);
|
||||
// meanwhile Alberto is driving and the engine is still.
|
||||
await connection.BeginUserDrivingAsync(openLogin: true, ct);
|
||||
var driving = await connection.GetStatusAsync(ct);
|
||||
Assert.IsTrue(driving.UserIsDriving);
|
||||
Assert.IsTrue(server.Browser!.UserIsDriving);
|
||||
StringAssert.StartsWith(driving.CurrentUrl, bed.Site.SiteUrl, "the login page of the configured site, never Instagram in tests");
|
||||
|
||||
var finish = await connection.FinishAsync(ct);
|
||||
Assert.IsTrue(finish.Connected, finish.Message);
|
||||
Assert.IsFalse(server.Browser.UserIsDriving, "«Ho finito» ends the driving");
|
||||
Assert.IsNotNull(await server.Database.Settings.GetInt64Async(Febe.Server.ServerConnectionService.FirstConnectionKey, ct), "first connection recorded");
|
||||
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State);
|
||||
|
||||
// «Controlla ora».
|
||||
var check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now");
|
||||
if (check.GetProperty("status").GetString() == "needsConfirmation")
|
||||
{
|
||||
check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}""");
|
||||
}
|
||||
|
||||
Assert.AreEqual("queued", check.GetProperty("status").GetString(), check.GetProperty("message").GetString());
|
||||
|
||||
// The engine runs a session: every action toward the site has its Governor's permit in action_log.
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
async () => (await server.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.Clock.Now.AddDays(1), ct)).Any(a => a.AccountId == marta.Id),
|
||||
TimeSpan.FromSeconds(90),
|
||||
"un'azione del motore su marta.prova nel registro delle azioni");
|
||||
var actions = await server.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.Clock.Now.AddDays(1), ct);
|
||||
Assert.IsTrue(actions.All(a => a.SessionId is not null), "every counted action belongs to a session");
|
||||
Assert.IsNotNull(await server.Database.Sessions.GetLastAsync(ct));
|
||||
|
||||
// Files arrive in the library with the names of the scheme, and their thumbnails.
|
||||
var library = bed.Library;
|
||||
var thumbnails = bed.Thumbnails;
|
||||
List<(Entry Entry, Media Media)> stored = [];
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
async () =>
|
||||
{
|
||||
stored = await StoredAsync(server, marta.Id, ct);
|
||||
return stored.Count >= 3;
|
||||
},
|
||||
TimeSpan.FromSeconds(90),
|
||||
"tre file di marta.prova scaricati");
|
||||
foreach (var (entry, media) in stored)
|
||||
{
|
||||
var path = library.FullPath(marta, media.RelativePath!);
|
||||
Assert.IsTrue(File.Exists(path), path);
|
||||
Assert.AreEqual(media.Bytes, new FileInfo(path).Length, path);
|
||||
Assert.MatchesRegex(NamePattern(), media.RelativePath!, "naming scheme {tipo}/{anno}/{data}_{ora}_{codice}_{n}");
|
||||
if (media.Kind == MediaKind.Photo)
|
||||
{
|
||||
Assert.IsTrue(thumbnails.Exists(media.Sha256!), $"thumbnail of {media.RelativePath}");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsTrue(File.Exists(Path.Combine(library.AccountFolder(marta), AccountJournal.FileName)), "_febe.jsonl");
|
||||
var recipes = (await server.Database.Events.ListAsync(new EventQuery(), ct)).Where(e => e.Code.StartsWith("ricetta.", StringComparison.Ordinal)).ToList();
|
||||
Assert.IsNotEmpty(recipes, "one event line per recipe run");
|
||||
TestContext.WriteLine($"Ricette: {string.Join(", ", recipes.Select(r => r.Code).Distinct())}; file di marta.prova: {stored.Count}.");
|
||||
|
||||
// The site asks for a verification: at its next action toward the site the engine stops and the banner appears
|
||||
// in /api/engine. Usually still in the first session (two accounts to read in full); if that session already
|
||||
// ended, in the next one, after the minimum pause (20 minutes at 10×: two real minutes).
|
||||
var servedBefore = bed.Site.Control.CdnFilesServed;
|
||||
bed.Site.Control.Set(StopMode.Challenge);
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
async () =>
|
||||
{
|
||||
var engine = await bed.JsonAsync(HttpMethod.Get, "/api/engine");
|
||||
var snapshot = engine.GetProperty("snapshot");
|
||||
return snapshot.GetProperty("mode").GetString() == "StoppedForVerification" && snapshot.GetProperty("banner").ValueKind == JsonValueKind.Object;
|
||||
},
|
||||
TimeSpan.FromSeconds(200),
|
||||
"la striscia di arresto per la verifica in /api/engine");
|
||||
Assert.AreEqual(ConnectionState.VerificationRequired, (await connection.GetStatusAsync(ct)).State);
|
||||
TestContext.WriteLine($"CDN: {servedBefore} file prima del fermo, {bed.Site.Control.CdnFilesServed} adesso.");
|
||||
|
||||
// The remote view: meta first, then JPEG frames; Alberto is driving while it is open.
|
||||
using (var socket = await bed.OpenRemoteViewAsync(ct))
|
||||
{
|
||||
var (metaType, meta) = await ReceiveAsync(socket, ct);
|
||||
Assert.AreEqual(WebSocketMessageType.Text, metaType);
|
||||
using var metaJson = JsonDocument.Parse(meta);
|
||||
Assert.AreEqual("meta", metaJson.RootElement.GetProperty("type").GetString());
|
||||
Assert.IsGreaterThan(0, metaJson.RootElement.GetProperty("width").GetInt32());
|
||||
Assert.IsTrue(server.Browser.UserIsDriving, "the engine is still while the view is open");
|
||||
|
||||
byte[]? jpeg = null;
|
||||
for (var i = 0; i < 20 && jpeg is null; i++)
|
||||
{
|
||||
// A gesture makes the page repaint, so a frame comes even on a still page.
|
||||
await SendAsync(socket, """{"type":"mouse","action":"move","x":0.5,"y":0.5}""", ct);
|
||||
var (type, data) = await ReceiveAsync(socket, ct);
|
||||
if (type == WebSocketMessageType.Binary)
|
||||
{
|
||||
jpeg = data;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsNotNull(jpeg, "a JPEG frame");
|
||||
Assert.AreEqual(0xFF, jpeg[0]);
|
||||
Assert.AreEqual(0xD8, jpeg[1]);
|
||||
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "fine", ct);
|
||||
}
|
||||
|
||||
await ServerTestBed.WaitUntilAsync(() => Task.FromResult(!server.Browser.UserIsDriving), TimeSpan.FromSeconds(10), "la vista chiusa libera il browser");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task FinishWithoutSessionSaysSoAndDisconnectDeletesTheProfile()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ServerTestBed.StartAsync(autoLogin: true);
|
||||
var server = bed.Server;
|
||||
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
var connection = server.Connection!;
|
||||
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State, "the test site's automatic login");
|
||||
|
||||
// «Scollega»: engine stopped, profile deleted, browser restarted empty.
|
||||
var marker = Path.Combine(server.Browser!.ProfileDirectory, "segno-della-prova");
|
||||
await File.WriteAllTextAsync(marker, "x", ct);
|
||||
await connection.DisconnectAsync(ct);
|
||||
Assert.IsFalse(File.Exists(marker), "the profile folder was deleted");
|
||||
Assert.IsTrue(server.Browser.IsAvailable, "the browser runs again, with an empty profile");
|
||||
Assert.AreEqual(ConnectionState.NotConnected, (await connection.GetStatusAsync(ct)).State);
|
||||
Assert.IsFalse(server.Browser.UserIsDriving);
|
||||
Assert.IsTrue(server.Engine!.Services.Runtime.IsRunning || await WaitRunningAsync(server), "the engine loop runs again (and waits for a connection)");
|
||||
|
||||
// «Ho finito» without having logged in: Febe says it does not find the session.
|
||||
await connection.BeginUserDrivingAsync(openLogin: false, ct);
|
||||
Assert.IsTrue(server.Browser.UserIsDriving);
|
||||
var finish = await connection.FinishAsync(ct);
|
||||
Assert.IsFalse(finish.Connected);
|
||||
StringAssert.Contains(finish.Message, "non trova la sessione");
|
||||
Assert.IsFalse(server.Browser.UserIsDriving);
|
||||
|
||||
// «Annulla» ends the driving and leaves the browser on the rest page.
|
||||
await connection.BeginUserDrivingAsync(openLogin: true, ct);
|
||||
await connection.CancelAsync(ct);
|
||||
Assert.IsFalse(server.Browser.UserIsDriving);
|
||||
Assert.AreEqual("about:blank", (await connection.GetStatusAsync(ct)).CurrentUrl);
|
||||
|
||||
// The debugging port listens on 127.0.0.1 only.
|
||||
Assert.IsTrue(Febe.Browser.Hosting.LoopbackPortCheck.IsLoopbackOnly(bed.Options.DebugPort, out _));
|
||||
}
|
||||
|
||||
private static async Task<bool> WaitRunningAsync(Febe.Server.FebeServer server)
|
||||
{
|
||||
for (var i = 0; i < 40 && !server.Engine!.Services.Runtime.IsRunning; i++)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
}
|
||||
|
||||
return server.Engine!.Services.Runtime.IsRunning;
|
||||
}
|
||||
|
||||
private static async Task<List<(Entry Entry, Media Media)>> StoredAsync(Febe.Server.FebeServer server, long accountId, CancellationToken ct)
|
||||
{
|
||||
var list = new List<(Entry, Media)>();
|
||||
foreach (var entry in await server.Database.Entries.ListByAccountAsync(accountId, null, ct))
|
||||
{
|
||||
foreach (var media in await server.Database.Media.ListByEntryAsync(entry.Id, ct))
|
||||
{
|
||||
if (media.State == MediaState.Downloaded && media.RelativePath is not null && media.Sha256 is not null && entry.Kind != EntryKind.ProfilePicture)
|
||||
{
|
||||
list.Add((entry, media));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static Task SendAsync(ClientWebSocket socket, string json, CancellationToken ct) =>
|
||||
socket.SendAsync(Encoding.UTF8.GetBytes(json), WebSocketMessageType.Text, endOfMessage: true, ct);
|
||||
|
||||
private static async Task<(WebSocketMessageType Type, byte[] Data)> ReceiveAsync(ClientWebSocket socket, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
using var buffer = new MemoryStream();
|
||||
var chunk = new byte[64 * 1024];
|
||||
WebSocketReceiveResult result;
|
||||
do
|
||||
{
|
||||
result = await socket.ReceiveAsync(chunk, timeout.Token);
|
||||
buffer.Write(chunk, 0, result.Count);
|
||||
}
|
||||
while (!result.EndOfMessage);
|
||||
return (result.MessageType, buffer.ToArray());
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^(post|storie|evidenza/[^/]+|taggati)/(\d{4}/)?\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_[^_/]+_\d+\.(jpg|mp4)$")]
|
||||
private static partial Regex NamePattern();
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
using System.Net;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Server;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Web;
|
||||
|
||||
namespace Febe.Tests.Server;
|
||||
|
||||
/// <summary>The configuration of the container (spec §11) and the log of the server (spec §8.2, §13.2).</summary>
|
||||
[TestClass]
|
||||
public sealed class ServerOptionsTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void TheContainerDefaultsAreThoseOfTheSpecification()
|
||||
{
|
||||
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", "segreta")), out var o, out var problem), problem);
|
||||
Assert.AreEqual("segreta", o.Password);
|
||||
Assert.AreEqual(8480, o.Port);
|
||||
Assert.AreEqual(IPAddress.Any, o.ListenAddress);
|
||||
Assert.AreEqual("Europe/Rome", o.ZoneId);
|
||||
Assert.AreEqual("it_IT.UTF-8", o.Language);
|
||||
Assert.AreEqual("/dati", o.DataFolder);
|
||||
Assert.AreEqual("/libreria", o.LibraryFolder);
|
||||
Assert.AreEqual("/importa", o.ImportFolder);
|
||||
Assert.AreEqual(9222, o.DebugPort);
|
||||
Assert.AreEqual(":99", o.Display);
|
||||
Assert.IsFalse(o.NoSandbox, "--no-sandbox only when asked (S5)");
|
||||
Assert.AreEqual("instagram", o.Site.Name);
|
||||
Assert.AreEqual("https://www.instagram.com/accounts/login/", o.LoginUrl);
|
||||
Assert.IsEmpty(o.AllowedHostList(), "any host name by default");
|
||||
|
||||
var web = o.WebOptions();
|
||||
Assert.AreEqual(FebeEdition.Docker, web.Edition);
|
||||
Assert.AreEqual(AccessMode.Password, web.Access);
|
||||
Assert.AreEqual("segreta", web.Password);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheEnvironmentAndTheDevelopmentOptionsAreRead()
|
||||
{
|
||||
var env = Env(
|
||||
("FEBE_PASSWORD", "x"),
|
||||
("FEBE_PORTA", "9000"),
|
||||
("TZ", "Europe/London"),
|
||||
("LANG", "it_IT.UTF-8"),
|
||||
("FEBE_HOST", "tower.local, 192.168.1.10"),
|
||||
("FEBE_PROXY_FIDATO", "1"),
|
||||
("FEBE_SENZA_SANDBOX", "1"),
|
||||
("FEBE_PORTA_DEBUG", "9333"));
|
||||
Assert.IsTrue(ServerOptions.TryParse(["--dati", "/tmp/d", "--sito-di-prova", "http://127.0.0.1:8481", "--accesso-di-prova", "--prima-sessione", "5"], env, out var o, out var problem), problem);
|
||||
Assert.AreEqual(9000, o.Port);
|
||||
Assert.AreEqual("Europe/London", o.ZoneId);
|
||||
Assert.IsTrue(o.TrustForwardedHost);
|
||||
Assert.IsTrue(o.NoSandbox);
|
||||
Assert.AreEqual(9333, o.DebugPort);
|
||||
Assert.AreEqual("/tmp/d", o.DataFolder);
|
||||
Assert.AreEqual(TimeSpan.FromSeconds(5), o.FirstSessionDelay);
|
||||
Assert.AreEqual("prova", o.Site.Name);
|
||||
Assert.AreEqual("http://127.0.0.1:8481", o.Site.BaseUrl);
|
||||
Assert.AreEqual("127.0.0.2:8482", o.Site.Hosts.CdnHosts.Single(), "the CDN of the test site tool by default");
|
||||
Assert.AreEqual("sessione_prova", o.Site.SessionCookie.CookieName);
|
||||
Assert.AreEqual("http://127.0.0.1:8481/benvenuto", o.LoginUrl);
|
||||
CollectionAssert.IsSubsetOf(new[] { "tower.local", "tower.local:*", "192.168.1.10:*", "127.0.0.1:*", "localhost:*" }, o.AllowedHostList().ToList());
|
||||
|
||||
var browser = o.BrowserEnvironment("/dati/home");
|
||||
Assert.AreEqual("Europe/London", browser["TZ"]);
|
||||
Assert.AreEqual("/dati/home", browser["HOME"]);
|
||||
Assert.IsNull(browser["HTTPS_PROXY"], "no proxy for the browser (rule 2)");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void WrongValuesAreRefusedInItalian()
|
||||
{
|
||||
var env = Env(("FEBE_PASSWORD", "x"));
|
||||
foreach (var (args, fragment) in new (string[], string)[]
|
||||
{
|
||||
(["--porta", "0"], "Porta non valida"),
|
||||
(["--sito-di-prova", "https://www.instagram.com"], "indirizzo http di questo computer"),
|
||||
(["--sito-di-prova", "http://192.168.1.5:8481"], "indirizzo http di questo computer"),
|
||||
(["--accesso-di-prova"], "solo con --sito-di-prova"),
|
||||
(["--password", "segreta"], "Opzione sconosciuta"),
|
||||
(["--display", "99"], "Display non valido"),
|
||||
(["--porta-debug", "8480"], "diversa"),
|
||||
})
|
||||
{
|
||||
Assert.IsFalse(ServerOptions.TryParse(args, env, out _, out var problem), string.Join(' ', args));
|
||||
StringAssert.Contains(problem, fragment, string.Join(' ', args));
|
||||
}
|
||||
|
||||
Assert.IsFalse(ServerOptions.TryParse([], Env(("FEBE_PORTA", "porta")), out _, out var portProblem));
|
||||
StringAssert.Contains(portProblem, "FEBE_PORTA");
|
||||
|
||||
// An unknown time zone is a warning, not a stop.
|
||||
Assert.IsTrue(ServerOptions.TryParse([], Env(("TZ", "Luna/Febe")), out var o, out _));
|
||||
Assert.AreEqual("Europe/Rome", o.ZoneId);
|
||||
StringAssert.Contains(o.Warnings.Single(), "Luna/Febe");
|
||||
Assert.IsNull(o.Password, "the password comes only from FEBE_PASSWORD");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheBackupComesOnceADayAfterMidnight()
|
||||
{
|
||||
var zone = TestZones.Rome;
|
||||
var now = new DateTimeOffset(2026, 10, 13, 21, 0, 0, TimeSpan.FromHours(2));
|
||||
var wait = FebeServer.UntilNextBackup(now, zone);
|
||||
Assert.AreEqual(new DateTimeOffset(2026, 10, 14, 3, 20, 0, TimeSpan.FromHours(2)), now + wait);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheLogHasNoAddressesRotatesByDayAndKeepsTwoWeeks()
|
||||
{
|
||||
using var temp = new TempFolder("registro");
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 10, 13, 10, 0, 0, TimeSpan.Zero), TestZones.Rome);
|
||||
var folder = temp.Combine("registro");
|
||||
Directory.CreateDirectory(folder);
|
||||
var old = Path.Combine(folder, ServerLog.FileNameFor(new DateOnly(2026, 9, 1)));
|
||||
File.WriteAllText(old, "vecchio");
|
||||
var unrelated = Path.Combine(folder, "appunti.txt");
|
||||
File.WriteAllText(unrelated, "di Alberto");
|
||||
using var console = new StringWriter();
|
||||
using (var log = new ServerLog(folder, console, clock))
|
||||
{
|
||||
log.Info("prova", "Scaricato https://cdn.example/m/abc.jpg?firma=SEGRETA da marta.prova");
|
||||
log.Warn("prova", "Errore", new InvalidOperationException("riga uno https://x.example/?t=1\nriga due"));
|
||||
clock.Now = clock.Now.AddDays(1);
|
||||
log.Info("prova", "Il giorno dopo");
|
||||
}
|
||||
|
||||
var first = File.ReadAllText(Path.Combine(folder, ServerLog.FileNameFor(new DateOnly(2026, 10, 13))));
|
||||
Assert.DoesNotContain("SEGRETA", first);
|
||||
Assert.DoesNotContain("cdn.example", first);
|
||||
StringAssert.Contains(first, "<indirizzo>");
|
||||
StringAssert.Contains(first, "marta.prova");
|
||||
StringAssert.Contains(first, "InvalidOperationException: riga uno <indirizzo>");
|
||||
Assert.DoesNotContain("riga due", first);
|
||||
StringAssert.Contains(File.ReadAllText(Path.Combine(folder, ServerLog.FileNameFor(new DateOnly(2026, 10, 14)))), "Il giorno dopo");
|
||||
Assert.IsFalse(File.Exists(old), "older than fourteen days");
|
||||
Assert.IsTrue(File.Exists(unrelated), "only febe-*.log files are removed");
|
||||
StringAssert.Contains(console.ToString(), "Il giorno dopo");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheLogStopsGrowingAtItsDailyLimit()
|
||||
{
|
||||
using var temp = new TempFolder("registro");
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 10, 13, 10, 0, 0, TimeSpan.Zero), TestZones.Rome);
|
||||
using (var log = new ServerLog(temp.Path, null, clock, maxBytesPerDay: 2000))
|
||||
{
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
log.Info("prova", "Una riga di registro qualunque, abbastanza lunga da riempire il limite.");
|
||||
}
|
||||
}
|
||||
|
||||
var file = Path.Combine(temp.Path, ServerLog.FileNameFor(new DateOnly(2026, 10, 13)));
|
||||
Assert.IsLessThan(2200L, new FileInfo(file).Length);
|
||||
StringAssert.Contains(File.ReadAllText(file), "troppo lungo");
|
||||
}
|
||||
|
||||
private static Func<string, string?> Env(params (string Name, string Value)[] values)
|
||||
{
|
||||
var map = values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal);
|
||||
return name => map.GetValueOrDefault(name);
|
||||
}
|
||||
|
||||
private sealed class ManualClock(DateTimeOffset start, TimeZoneInfo zone) : IClock
|
||||
{
|
||||
public DateTimeOffset Now { get; set; } = start;
|
||||
|
||||
public TimeZoneInfo LocalZone { get; } = zone;
|
||||
|
||||
public Task Delay(TimeSpan time, CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Server;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Spec §8.2, §11: with the password missing, or the Data folder not writable or on a network share, neither the
|
||||
/// engine nor the browser start; the interface shows only the page that explains it and <c>/salute</c> says «problema».
|
||||
/// The remote view is never reachable without a password. No browser needed.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class StartupProblemTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutPasswordOnlyTheErrorPageAnswersAndNothingStarts()
|
||||
{
|
||||
using var temp = new TempFolder("server-problemi");
|
||||
await using var server = await FebeServer.StartAsync(Options(temp) with { Password = null }, Hooks());
|
||||
var problem = server.Problems.Single();
|
||||
Assert.AreEqual(StartupChecks.PasswordMissing, problem.Code);
|
||||
StringAssert.Contains(problem.Remedy, "FEBE_PASSWORD");
|
||||
Assert.IsNull(server.Browser, "no browser");
|
||||
Assert.IsNull(server.Engine, "no engine");
|
||||
Assert.IsFalse(Directory.Exists(temp.Combine("dati", "registro")), "nothing written in the Data folder");
|
||||
Assert.IsFalse(File.Exists(temp.Combine("dati", "febe.sqlite")));
|
||||
|
||||
using var client = Client(server);
|
||||
await AssertHealthAsync(client, HttpStatusCode.ServiceUnavailable, """{"stato":"problema"}""");
|
||||
|
||||
// The error page and what it needs.
|
||||
foreach (var path in new[] { "/", "/libreria", "/impostazioni/collegamento", "/css/febe.css", "/js/app.js", "/testi/it.json", "/api/capabilities" })
|
||||
{
|
||||
using var response = await client.GetAsync(path, TestContext.CancellationToken);
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, path);
|
||||
}
|
||||
|
||||
// Nothing else: library, accounts, engine commands, login, the remote view.
|
||||
foreach (var path in new[] { "/api/accounts", "/api/library/days", "/api/engine", "/api/eventi" })
|
||||
{
|
||||
using var response = await client.GetAsync(path, TestContext.CancellationToken);
|
||||
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, response.StatusCode, path);
|
||||
}
|
||||
|
||||
using (var login = await PostAsync(client, server, "/api/accesso", """{"password":"qualunque"}"""))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, login.StatusCode);
|
||||
}
|
||||
|
||||
await AssertNoRemoteViewAsync(server);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ADataFolderThatIsAFileStopsTheEngineEvenWithThePassword()
|
||||
{
|
||||
using var temp = new TempFolder("server-problemi");
|
||||
var file = temp.Combine("dati-file");
|
||||
await File.WriteAllTextAsync(file, "non una cartella", TestContext.CancellationToken);
|
||||
await using var server = await FebeServer.StartAsync(Options(temp) with { DataFolder = file }, Hooks());
|
||||
var problem = server.Problems.Single();
|
||||
Assert.AreEqual(StartupChecks.DataNotWritable, problem.Code);
|
||||
Assert.IsNull(server.Engine);
|
||||
|
||||
var cookies = new CookieContainer();
|
||||
using var client = Client(server, cookies);
|
||||
await AssertHealthAsync(client, HttpStatusCode.ServiceUnavailable, """{"stato":"problema"}""");
|
||||
|
||||
// The password works, then only the problem page's API answers.
|
||||
using (var login = await PostAsync(client, server, "/api/accesso", """{"password":"una password"}"""))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, login.StatusCode, await login.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
using (var capabilities = await client.GetAsync("/api/capabilities", TestContext.CancellationToken))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, capabilities.StatusCode);
|
||||
}
|
||||
|
||||
using (var engine = await client.GetAsync("/api/engine", TestContext.CancellationToken))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, engine.StatusCode, "the frame of the page may ask for the (offline) engine");
|
||||
}
|
||||
|
||||
using (var accounts = await client.GetAsync("/api/accounts", TestContext.CancellationToken))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, accounts.StatusCode);
|
||||
using var json = System.Text.Json.JsonDocument.Parse(await accounts.Content.ReadAsStringAsync());
|
||||
StringAssert.Contains(json.RootElement.GetProperty("message").GetString(), "Il motore non è partito");
|
||||
}
|
||||
|
||||
await AssertNoRemoteViewAsync(server, cookies);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ADataFolderOnANetworkShareIsRefused()
|
||||
{
|
||||
using var temp = new TempFolder("server-problemi");
|
||||
var data = temp.Combine("dati");
|
||||
var mounts = $"/dev/sda1 / ext4 rw 0 0\n//nas/condivisa {temp.Path} cifs rw 0 0\n";
|
||||
await using var server = await FebeServer.StartAsync(Options(temp), Hooks() with { DataFolderCheck = new DataFolderCheck(() => mounts) });
|
||||
var problem = server.Problems.Single();
|
||||
Assert.AreEqual(StartupChecks.DataOnNetwork, problem.Code);
|
||||
StringAssert.Contains(problem.Message, "cifs");
|
||||
Assert.IsFalse(Directory.Exists(Path.Combine(data, "registro")));
|
||||
using var client = Client(server);
|
||||
await AssertHealthAsync(client, HttpStatusCode.ServiceUnavailable, """{"stato":"problema"}""");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheHealthCheckCommandReadsSalute()
|
||||
{
|
||||
using var temp = new TempFolder("server-problemi");
|
||||
await using var server = await FebeServer.StartAsync(Options(temp) with { Password = null }, Hooks());
|
||||
using var output = new StringWriter();
|
||||
Assert.AreEqual(1, await HealthCheckCommand.CheckAsync(new Uri(server.Address, "/salute"), output));
|
||||
StringAssert.Contains(output.ToString(), "problema");
|
||||
|
||||
// Nobody listening: not healthy.
|
||||
Assert.AreEqual(1, await HealthCheckCommand.CheckAsync(new Uri($"http://127.0.0.1:{Febe.Tests.Browser.TestSupport.LocalTestSite.FreePort()}/salute"), TextWriter.Null));
|
||||
}
|
||||
|
||||
internal static ServerOptions Options(TempFolder temp) => new()
|
||||
{
|
||||
Password = "una password",
|
||||
ListenAddress = IPAddress.Loopback,
|
||||
Port = 0,
|
||||
DataFolder = temp.Combine("dati"),
|
||||
LibraryFolder = temp.Combine("libreria"),
|
||||
ImportFolder = temp.Combine("importa"),
|
||||
};
|
||||
|
||||
internal static ServerHooks Hooks() => new() { Console = TextWriter.Null };
|
||||
|
||||
private static HttpClient Client(FebeServer server, CookieContainer? cookies = null) =>
|
||||
new(new HttpClientHandler { UseCookies = cookies is not null, CookieContainer = cookies ?? new CookieContainer(), AllowAutoRedirect = false }) { BaseAddress = server.Address };
|
||||
|
||||
private static async Task<HttpResponseMessage> PostAsync(HttpClient client, FebeServer server, string path, string json)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, path) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
request.Headers.TryAddWithoutValidation("Origin", $"http://{server.Address.Authority}");
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
private async Task AssertHealthAsync(HttpClient client, HttpStatusCode status, string body)
|
||||
{
|
||||
using var response = await client.GetAsync("/salute", TestContext.CancellationToken);
|
||||
Assert.AreEqual(status, response.StatusCode);
|
||||
Assert.AreEqual(body, await response.Content.ReadAsStringAsync(TestContext.CancellationToken));
|
||||
}
|
||||
|
||||
private async Task AssertNoRemoteViewAsync(FebeServer server, CookieContainer? session = null)
|
||||
{
|
||||
using var socket = new ClientWebSocket();
|
||||
socket.Options.SetRequestHeader("Origin", $"http://{server.Address.Authority}");
|
||||
if (session is not null)
|
||||
{
|
||||
socket.Options.Cookies = session;
|
||||
}
|
||||
|
||||
socket.Options.CollectHttpResponseDetails = true;
|
||||
var address = new UriBuilder(server.Address) { Scheme = "ws", Path = "/api/vista" }.Uri;
|
||||
await Assert.ThrowsAsync<WebSocketException>(() => socket.ConnectAsync(address, TestContext.CancellationToken));
|
||||
Assert.AreNotEqual(HttpStatusCode.SwitchingProtocols, socket.HttpStatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Channels;
|
||||
using Febe.Web.Connection;
|
||||
|
||||
namespace Febe.Tests.Server.Support;
|
||||
|
||||
/// <summary>A remote view without browser: the test writes what goes to the page and reads what comes back.</summary>
|
||||
internal sealed class FakeRemoteViewHost : IRemoteViewHost
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
public List<FakeRemoteViewConnection> Opened { get; } = [];
|
||||
|
||||
public bool Unavailable { get; set; }
|
||||
|
||||
public Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
|
||||
{
|
||||
if (Unavailable)
|
||||
{
|
||||
throw new RemoteViewUnavailableException("Il browser di prova non c'è.");
|
||||
}
|
||||
|
||||
var connection = new FakeRemoteViewConnection();
|
||||
lock (_gate)
|
||||
{
|
||||
if (Opened.LastOrDefault() is { Disposed: false } previous)
|
||||
{
|
||||
previous.End(RemoteViewEnd.Replaced);
|
||||
}
|
||||
|
||||
Opened.Add(connection);
|
||||
}
|
||||
|
||||
return Task.FromResult<IRemoteViewConnection>(connection);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class FakeRemoteViewConnection : IRemoteViewConnection
|
||||
{
|
||||
private readonly Channel<RemoteViewOutput> _output = Channel.CreateUnbounded<RemoteViewOutput>();
|
||||
|
||||
public ConcurrentQueue<object> Inputs { get; } = new();
|
||||
|
||||
public bool Disposed { get; private set; }
|
||||
|
||||
public RemoteViewEnd? Ended { get; private set; }
|
||||
|
||||
public void Write(RemoteViewOutput output) => _output.Writer.TryWrite(output);
|
||||
|
||||
public void End(RemoteViewEnd reason)
|
||||
{
|
||||
Ended = reason;
|
||||
_output.Writer.TryComplete();
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<RemoteViewOutput> ReadAsync([EnumeratorCancellation] CancellationToken ct)
|
||||
{
|
||||
await foreach (var output in _output.Reader.ReadAllAsync(ct))
|
||||
{
|
||||
yield return output;
|
||||
}
|
||||
}
|
||||
|
||||
public Task MouseAsync(RemoteViewMouse input, CancellationToken ct)
|
||||
{
|
||||
Inputs.Enqueue(input);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task KeyAsync(RemoteViewKey input, CancellationToken ct)
|
||||
{
|
||||
Inputs.Enqueue(input);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct)
|
||||
{
|
||||
Inputs.Enqueue(action);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
Disposed = true;
|
||||
_output.Writer.TryComplete();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Server;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Tests.Collection.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Server.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The real server composition (<see cref="FebeServer"/>) against the local test site, with Xvfb and a real Chromium,
|
||||
/// in a temporary Data/Library/Import folder, on free ports and a free display. Never Instagram: the browser only ever
|
||||
/// sees 127.0.0.1. Time runs on a compressed clock (10×) in a time zone where it is around noon now, so that the
|
||||
/// engine is inside its active window whatever the hour of the test.
|
||||
/// </summary>
|
||||
internal sealed class ServerTestBed : IAsyncDisposable
|
||||
{
|
||||
public const string Password = "una password di prova per il server";
|
||||
|
||||
private ServerTestBed(TempFolder temp, TestSite site, FebeServer server, CompressedClock clock, ServerOptions options)
|
||||
{
|
||||
Temp = temp;
|
||||
Site = site;
|
||||
Server = server;
|
||||
Clock = clock;
|
||||
Options = options;
|
||||
Client = new HttpClient(new HttpClientHandler { UseCookies = true, CookieContainer = Cookies, AllowAutoRedirect = false })
|
||||
{
|
||||
BaseAddress = server.Address,
|
||||
Timeout = TimeSpan.FromSeconds(30),
|
||||
};
|
||||
}
|
||||
|
||||
public TempFolder Temp { get; }
|
||||
|
||||
public TestSite Site { get; }
|
||||
|
||||
public FebeServer Server { get; }
|
||||
|
||||
public CompressedClock Clock { get; }
|
||||
|
||||
public ServerOptions Options { get; }
|
||||
|
||||
public CookieContainer Cookies { get; } = new();
|
||||
|
||||
public HttpClient Client { get; }
|
||||
|
||||
/// <summary>«http://127.0.0.1:port»: the Origin of requests coming from the interface.</summary>
|
||||
public string Origin => $"{Server.Address.Scheme}://{Server.Address.Authority}";
|
||||
|
||||
public static string? UnavailableReason() => RealBrowser.UnavailableReason();
|
||||
|
||||
public static async Task<ServerTestBed> StartAsync(bool autoLogin = false, double factor = 10)
|
||||
{
|
||||
var temp = new TempFolder("server");
|
||||
var site = await TestSite.StartAsync(new TestSiteOptions());
|
||||
var zone = NoonZone();
|
||||
var clock = new CompressedClock(factor, zone);
|
||||
var options = new ServerOptions
|
||||
{
|
||||
Password = Password,
|
||||
ListenAddress = IPAddress.Loopback,
|
||||
Port = 0,
|
||||
ZoneId = zone.Id,
|
||||
Zone = zone,
|
||||
Language = "it_IT.UTF-8",
|
||||
DataFolder = temp.Combine("dati"),
|
||||
LibraryFolder = temp.Combine("libreria"),
|
||||
ImportFolder = temp.Combine("importa"),
|
||||
NoSandbox = RealBrowser.IsRoot,
|
||||
ChromiumPath = RealBrowser.ChromiumPath(),
|
||||
DebugPort = LocalTestSite.FreePort(),
|
||||
Display = XvfbProcess.FindFreeDisplay(300, 399) ?? throw new InvalidOperationException("Nessun display libero."),
|
||||
TestSite = new Uri(site.SiteUrl + "/"),
|
||||
TestCdn = new Uri(site.CdnUrl + "/"),
|
||||
TestSiteAutoLogin = autoLogin,
|
||||
FirstSessionDelay = TimeSpan.FromSeconds(1),
|
||||
};
|
||||
Directory.CreateDirectory(options.ImportFolder);
|
||||
FebeServer server;
|
||||
try
|
||||
{
|
||||
server = await FebeServer.StartAsync(options, new ServerHooks { Clock = clock, Random = new SeededRandom(20261013), Console = TextWriter.Null });
|
||||
}
|
||||
catch
|
||||
{
|
||||
await site.DisposeAsync();
|
||||
temp.Dispose();
|
||||
throw;
|
||||
}
|
||||
|
||||
return new ServerTestBed(temp, site, server, clock, options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A fixed-offset zone where the local time is between 12:00 and 13:00 now: inside the active window of every
|
||||
/// caution profile, so the test does not depend on when it runs.
|
||||
/// </summary>
|
||||
public static TimeZoneInfo NoonZone()
|
||||
{
|
||||
var offset = 12 - DateTimeOffset.UtcNow.Hour;
|
||||
if (offset > 12)
|
||||
{
|
||||
offset -= 24;
|
||||
}
|
||||
else if (offset < -12)
|
||||
{
|
||||
offset += 24;
|
||||
}
|
||||
|
||||
// The sign of the Etc/GMT names is inverted: Etc/GMT-2 is two hours east of Greenwich.
|
||||
var id = offset == 0 ? "Etc/GMT" : offset > 0 ? $"Etc/GMT-{offset}" : $"Etc/GMT+{-offset}";
|
||||
return TimeZoneInfo.FindSystemTimeZoneById(id);
|
||||
}
|
||||
|
||||
/// <summary>Logs in with the interface password (cookie in <see cref="Cookies"/>).</summary>
|
||||
public async Task LoginAsync()
|
||||
{
|
||||
using var response = await SendAsync(HttpMethod.Post, "/api/accesso", $$"""{"password":"{{Password}}"}""");
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
/// <summary>A request as the interface sends it: Origin of the interface, JSON body.</summary>
|
||||
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string path, string? json = null)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
request.Headers.TryAddWithoutValidation("Origin", Origin);
|
||||
if (json is not null)
|
||||
{
|
||||
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
}
|
||||
|
||||
return await Client.SendAsync(request);
|
||||
}
|
||||
|
||||
public async Task<JsonElement> JsonAsync(HttpMethod method, string path, string? json = null)
|
||||
{
|
||||
using var response = await SendAsync(method, path, json);
|
||||
var text = await response.Content.ReadAsStringAsync();
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
|
||||
return JsonDocument.Parse(text).RootElement.Clone();
|
||||
}
|
||||
|
||||
/// <summary>The remote view, opened like the Browser page does: session cookie and Origin of the interface.</summary>
|
||||
public async Task<ClientWebSocket> OpenRemoteViewAsync(CancellationToken ct)
|
||||
{
|
||||
var socket = new ClientWebSocket();
|
||||
socket.Options.Cookies = Cookies;
|
||||
socket.Options.SetRequestHeader("Origin", Origin);
|
||||
var address = new UriBuilder(Server.Address) { Scheme = "ws", Path = "/api/vista" }.Uri;
|
||||
await socket.ConnectAsync(address, ct);
|
||||
return socket;
|
||||
}
|
||||
|
||||
public LibraryLayout Library => Server.Library ?? throw new InvalidOperationException("Nessuna libreria.");
|
||||
|
||||
public ThumbnailStore Thumbnails => new(Server.Data!.Thumbnails);
|
||||
|
||||
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> otherwise.</summary>
|
||||
public static async Task WaitUntilAsync(Func<Task<bool>> condition, TimeSpan timeout, string what)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (true)
|
||||
{
|
||||
if (await condition())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail($"Tempo scaduto: {what}.");
|
||||
}
|
||||
|
||||
await Task.Delay(250);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Client.Dispose();
|
||||
await Server.DisposeAsync();
|
||||
await Site.DisposeAsync();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user