From b443adfa8bdcc4c85c80761ed99d6d919fbc6689 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 13 Oct 2026 21:50:25 +0000 Subject: [PATCH] =?UTF-8?q?M6=20Windows:=20composizione=20condivisa=20Febe?= =?UTF-8?q?.App=20per=20Server=20e=20Desktop;=20Febe=20per=20Windows=20(WP?= =?UTF-8?q?F)=20con=20l'interfaccia=20in=20WebView2,=20area=20di=20notific?= =?UTF-8?q?a,=20istanza=20unica,=20=C2=ABBrowser=20di=20Febe=C2=BB=20su=20?= =?UTF-8?q?WebView2=20con=20CDP=20filtrato=20(WebView2CdpSession)=20e=20ri?= =?UTF-8?q?pieghi=20di=20S2=20(composizione,=20Edge),=20guscio=20nativo,?= =?UTF-8?q?=20avvisi,=20spostamento=20verificato=20della=20cartella=20dei?= =?UTF-8?q?=20dati,=20icona=20del=20marchio;=20un=20solo=20Febe.exe,=20ins?= =?UTF-8?q?tallatore=20NSIS=20e=20zip=20portabile;=20guida=20docs/windows.?= =?UTF-8?q?md=20e=20prove=20dal=20vivo=20S1=E2=80=93S3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA --- .gitattributes | 6 + Febe.slnx | 2 + docker/Dockerfile | 2 + docs/prove-dal-vivo.md | 86 +++ docs/sonda/esito.md | 6 +- docs/windows.md | 206 ++++++ installer/costruisci.sh | 98 +++ installer/febe.nsi | 205 ++++++ src/Febe.App/Alerts.cs | 203 ++++++ .../BrowserConnectionService.cs} | 102 ++- .../ChromiumBrowser.cs} | 132 +++- .../DeferredRecipeRunner.cs | 4 +- src/Febe.App/Febe.App.csproj | 15 + src/Febe.App/FebeApp.cs | 639 ++++++++++++++++++ .../ServerLog.cs => Febe.App/FebeLog.cs} | 14 +- src/Febe.App/IFebeBrowser.cs | 53 ++ src/Febe.App/IFebePlatform.cs | 118 ++++ .../LiveBrowserPreview.cs} | 30 +- src/Febe.App/StartupProblems.cs | 54 ++ .../WebView2/WebView2CdpSession.cs | 347 ++++++++++ src/Febe.Core/Library/LibraryIngest.cs | 17 +- src/Febe.Desktop.Core/Autostart.cs | 68 ++ src/Febe.Desktop.Core/BrandIcon.cs | 246 +++++++ src/Febe.Desktop.Core/BrowserArguments.cs | 85 +++ src/Febe.Desktop.Core/DataFolderMove.cs | 301 +++++++++ src/Febe.Desktop.Core/DesktopOptions.cs | 277 ++++++++ src/Febe.Desktop.Core/DesktopPlatform.cs | 334 +++++++++ src/Febe.Desktop.Core/DesktopStartupChecks.cs | 62 ++ .../Febe.Desktop.Core.csproj | 16 + src/Febe.Desktop.Core/SingleInstance.cs | 75 ++ src/Febe.Desktop/App.xaml | 4 - src/Febe.Desktop/App.xaml.cs | 6 - src/Febe.Desktop/Browser/BrowserWindow.cs | 171 +++++ src/Febe.Desktop/Browser/CompositionHost.cs | 169 +++++ .../Browser/CoreWebView2DevTools.cs | 71 ++ src/Febe.Desktop/Browser/WebView2Browser.cs | 163 +++++ src/Febe.Desktop/Browser/WebView2Host.cs | 372 ++++++++++ src/Febe.Desktop/DesktopApplication.cs | 376 +++++++++++ src/Febe.Desktop/DesktopShell.cs | 107 +++ src/Febe.Desktop/Febe.Desktop.csproj | 35 +- src/Febe.Desktop/Febe.ico | Bin 0 -> 112119 bytes src/Febe.Desktop/LEGGIMI.md | 33 + src/Febe.Desktop/MainWindow.cs | 144 ++++ src/Febe.Desktop/Native/Win32.cs | 136 ++++ src/Febe.Desktop/Program.cs | 37 + src/Febe.Desktop/SingleInstanceGuard.cs | 124 ++++ src/Febe.Desktop/TrayIcon.cs | 80 +++ src/Febe.Desktop/WindowsShell.cs | 158 +++++ src/Febe.Desktop/app.manifest | 26 + src/Febe.Server/BrowserRemoteView.cs | 18 +- src/Febe.Server/DockerPlatform.cs | 65 ++ src/Febe.Server/Febe.Server.csproj | 1 + src/Febe.Server/FebeServer.cs | 590 ++-------------- src/Febe.Server/ServerOptions.cs | 19 + src/Febe.Server/StartupChecks.cs | 40 +- src/Febe.Web/Api/SettingsApi.cs | 7 +- src/Febe.Web/Hosting/EmbeddedWwwroot.cs | 10 +- src/Febe.Web/LEGGIMI.md | 15 +- src/Febe.Web/wwwroot/js/pages/connection.js | 2 + .../Desktop/DesktopCompositionTests.cs | 299 ++++++++ tests/Febe.Tests/Desktop/DesktopLogicTests.cs | 302 +++++++++ tests/Febe.Tests/Desktop/IconTests.cs | 134 ++++ tests/Febe.Tests/Desktop/InstallerTests.cs | 146 ++++ .../Desktop/SharedCompositionTests.cs | 86 +++ .../Desktop/Support/DesktopTestBed.cs | 123 ++++ .../Desktop/Support/FakeDesktopShell.cs | 261 +++++++ .../Desktop/Support/FakeDevTools.cs | 89 +++ .../Desktop/Support/MemoryLocationStore.cs | 15 + .../Febe.Tests/Desktop/Support/Repository.cs | 31 + .../Desktop/WebView2CdpSessionTests.cs | 329 +++++++++ tests/Febe.Tests/Febe.Tests.csproj | 2 + .../Febe.Tests/Server/ServerEndToEndTests.cs | 2 +- tests/Febe.Tests/Server/ServerOptionsTests.cs | 12 +- 73 files changed, 7914 insertions(+), 699 deletions(-) create mode 100644 .gitattributes create mode 100644 docs/windows.md create mode 100755 installer/costruisci.sh create mode 100644 installer/febe.nsi create mode 100644 src/Febe.App/Alerts.cs rename src/{Febe.Server/ServerConnectionService.cs => Febe.App/BrowserConnectionService.cs} (76%) rename src/{Febe.Server/BrowserSupervisor.cs => Febe.App/ChromiumBrowser.cs} (56%) rename src/{Febe.Server => Febe.App}/DeferredRecipeRunner.cs (92%) create mode 100644 src/Febe.App/Febe.App.csproj create mode 100644 src/Febe.App/FebeApp.cs rename src/{Febe.Server/ServerLog.cs => Febe.App/FebeLog.cs} (94%) create mode 100644 src/Febe.App/IFebeBrowser.cs create mode 100644 src/Febe.App/IFebePlatform.cs rename src/{Febe.Server/ServerBrowserPreview.cs => Febe.App/LiveBrowserPreview.cs} (58%) create mode 100644 src/Febe.App/StartupProblems.cs create mode 100644 src/Febe.Browser/WebView2/WebView2CdpSession.cs create mode 100644 src/Febe.Desktop.Core/Autostart.cs create mode 100644 src/Febe.Desktop.Core/BrandIcon.cs create mode 100644 src/Febe.Desktop.Core/BrowserArguments.cs create mode 100644 src/Febe.Desktop.Core/DataFolderMove.cs create mode 100644 src/Febe.Desktop.Core/DesktopOptions.cs create mode 100644 src/Febe.Desktop.Core/DesktopPlatform.cs create mode 100644 src/Febe.Desktop.Core/DesktopStartupChecks.cs create mode 100644 src/Febe.Desktop.Core/Febe.Desktop.Core.csproj create mode 100644 src/Febe.Desktop.Core/SingleInstance.cs delete mode 100644 src/Febe.Desktop/App.xaml delete mode 100644 src/Febe.Desktop/App.xaml.cs create mode 100644 src/Febe.Desktop/Browser/BrowserWindow.cs create mode 100644 src/Febe.Desktop/Browser/CompositionHost.cs create mode 100644 src/Febe.Desktop/Browser/CoreWebView2DevTools.cs create mode 100644 src/Febe.Desktop/Browser/WebView2Browser.cs create mode 100644 src/Febe.Desktop/Browser/WebView2Host.cs create mode 100644 src/Febe.Desktop/DesktopApplication.cs create mode 100644 src/Febe.Desktop/DesktopShell.cs create mode 100644 src/Febe.Desktop/Febe.ico create mode 100644 src/Febe.Desktop/LEGGIMI.md create mode 100644 src/Febe.Desktop/MainWindow.cs create mode 100644 src/Febe.Desktop/Native/Win32.cs create mode 100644 src/Febe.Desktop/Program.cs create mode 100644 src/Febe.Desktop/SingleInstanceGuard.cs create mode 100644 src/Febe.Desktop/TrayIcon.cs create mode 100644 src/Febe.Desktop/WindowsShell.cs create mode 100644 src/Febe.Desktop/app.manifest create mode 100644 src/Febe.Server/DockerPlatform.cs create mode 100644 tests/Febe.Tests/Desktop/DesktopCompositionTests.cs create mode 100644 tests/Febe.Tests/Desktop/DesktopLogicTests.cs create mode 100644 tests/Febe.Tests/Desktop/IconTests.cs create mode 100644 tests/Febe.Tests/Desktop/InstallerTests.cs create mode 100644 tests/Febe.Tests/Desktop/SharedCompositionTests.cs create mode 100644 tests/Febe.Tests/Desktop/Support/DesktopTestBed.cs create mode 100644 tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs create mode 100644 tests/Febe.Tests/Desktop/Support/FakeDevTools.cs create mode 100644 tests/Febe.Tests/Desktop/Support/MemoryLocationStore.cs create mode 100644 tests/Febe.Tests/Desktop/Support/Repository.cs create mode 100644 tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..c760a48 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# Gli script di shell restano con le righe Unix anche su un Windows con core.autocrlf: bash non regge il CR. +*.sh text eol=lf +# Il programma di installazione si costruisce anche da Linux con makensis. +*.nsi text eol=lf +# Binari: mai conversioni. +*.ico binary diff --git a/Febe.slnx b/Febe.slnx index 61fa93d..62cccd4 100644 --- a/Febe.slnx +++ b/Febe.slnx @@ -4,7 +4,9 @@ + + diff --git a/docker/Dockerfile b/docker/Dockerfile index 146ddb6..503522d 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -29,7 +29,9 @@ 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.App/Febe.App.csproj src/Febe.App/ COPY src/Febe.Server/Febe.Server.csproj src/Febe.Server/ +COPY src/Febe.Desktop.Core/Febe.Desktop.Core.csproj src/Febe.Desktop.Core/ 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/ diff --git a/docs/prove-dal-vivo.md b/docs/prove-dal-vivo.md index ba1e7e4..c34866e 100644 --- a/docs/prove-dal-vivo.md +++ b/docs/prove-dal-vivo.md @@ -124,3 +124,89 @@ Scopo: vedere Febe fare una sessione vera, piccola, con il profilo **Prudente**, Febe si ferma da sola al primo segnale e non riparte senza «Riprendi». Non premere «Riprendi» prima di aver risolto a mano nel browser e di avermi riferito che cosa è successo. + +--- + +## C. Febe per Windows (M6): ipotesi S1, S2, S3 + +Scopo: provare su un Windows vero ciò che su Linux non si può eseguire (`docs/windows.md`). C1–C4 usano **solo il sito +di prova locale**: nessun contatto con Instagram. Solo C5 usa Instagram, con l'account di prova. Ogni passo dice che +cosa aspettarsi; riferisci per ogni voce «sì/no» e, dove chiesto, la schermata o la riga del registro +(`%LOCALAPPDATA%\Febe\registro\` o la cartella dei dati di prova, `registro\`). + +### C1. Preparazione + +- Un Windows 10 o 11 a 64 bit (va bene una macchina virtuale **pulita**: è anche la prova d'installazione di M6). +- `Febe-Setup-.exe` (da `installer/costruisci.sh` o dalla release). +- Il sito di prova come eseguibile, preparato da Linux nel repository: + `dotnet publish tools/Febe.SitoDiProva -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -o out/sito-di-prova` + e copiato sul Windows (`febe-sito-di-prova.exe`). In alternativa, con il .NET SDK 10 sul Windows: + `dotnet run --project tools/Febe.SitoDiProva`. +- Nessun altro Febe acceso sullo stesso account (nemmeno il contenitore). + +### C2. Installazione (M6, «installazione su un Windows pulito») + +1. Apri il programma di installazione. Atteso: nessuna richiesta di permessi di amministratore; testi in italiano; + pagina con la scelta «Collegamento sul desktop». Se manca WebView2: il messaggio con la pagina di Microsoft. +2. Fine dell'installazione con «Apri Febe adesso». Atteso: si apre la finestra di Febe (benvenuto) e l'icona nell'area + di notifica; in App installate c'è «Febe», versione giusta, editore Alberto Balbo, con l'icona del marchio. +3. Riapri Febe dal menu Start mentre è già aperto. Atteso: torna in primo piano la stessa finestra, nessun secondo Febe. +4. Chiudi la finestra con la X. Atteso: Febe resta nell'area di notifica (la prima volta una notifica lo dice); + clic sull'icona: la finestra torna. +5. Menu dell'icona ▸ Esci. Atteso: l'icona sparisce, nessun processo `Febe.exe` né `msedgewebview2.exe` di Febe resta + in Gestione attività dopo una decina di secondi. + +### C3. S1 — CDP in WebView2 sul sito di prova + +1. Avvia il sito di prova: `febe-sito-di-prova.exe --porta 8481` (lascia aperta la finestra del terminale). Il suo + «CDN» ascolta su `127.0.0.2:8482`; se Windows non lo accetta, `--indirizzo-cdn 127.0.0.1` e a Febe, al passo 2, + anche `--cdn-di-prova http://127.0.0.1:8482`. +2. Avvia Febe **con cartelle di prova** (i dati veri non si toccano): + `"%LOCALAPPDATA%\Programs\Febe\Febe.exe" --dati C:\FebeProva\dati --libreria C:\FebeProva\libreria --sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30` +3. In Account ▸ Aggiungi account ▸ «Per nome utente»: `marta.prova` e `luca.prova`, «Scarica tutto e tieni aggiornato». +4. Su `marta.prova`: «Controlla ora». +5. Atteso entro qualche minuto, in **Attività**: una sessione con righe «ricetta.…» senza errori; l'anteprima del + browser mostra le pagine del sito di prova (fotogrammi con `Page.captureScreenshot`); in **Libreria** le foto e i video + di Marta con le miniature (corpo delle risposte con `Network.getResponseBody`, scorrimento con + `Input.dispatchMouseEvent`, scaricamenti con `Network.loadNetworkResource` e `IO.read`). +6. Riferisci: numero di file arrivati; eventuali righe gialle o rosse di Attività; nel registro, le righe + `[browser]` con «WebView2» e qualunque «Comando CDP … è fallito». +7. Prima prova di S3 senza Instagram: Esci, riapri Febe con lo stesso comando **senza** `--accesso-di-prova`. Atteso: + Collegamento dice «Collegato» (il cookie del sito di prova è rimasto nel profilo `C:\FebeProva\dati\browser`). + +### C4. S2 — la pagina lavora fuori vista + +Stessa configurazione di C3 (altra cartella dati, per partire puliti: `C:\FebeProva2\…`). + +1. **Fuori vista**: durante la sessione la finestra «Browser di Febe» non si vede (è fuori dallo schermo). Atteso: + la sessione procede come in C3 (le stesse ricette, i file arrivano), l'anteprima di Attività cambia. +2. **Finestra di Febe ridotta a icona**: riduci a icona la finestra di Febe, aspetta 5 minuti, riaprila. Atteso: la + sessione è andata avanti (nuove righe in Attività, nuovi file). +3. **Schermo bloccato**: «Controlla ora» su `luca.prova` (40 post, storico su più pagine), poi blocca lo schermo + (Win+L) per 10 minuti. Atteso: al rientro, lo storico di Luca è avanzato di più pagine; nessuna riga + «bersaglio non trovato» o «pagina vuota» nell'intervallo. +4. «Apri il browser» (Attività) durante una sessione. Atteso: la finestra viene in primo piano con la pagina, la + sessione si chiude (il motore si ferma mentre la usi); chiudendo la finestra torna fuori vista e il motore riprende + alla sessione successiva. +5. **Se 1–3 non reggono**: rifai C4 con `--browser composizione` (resta scelto per gli avvii successivi), poi con + `--browser edge` (serve Edge installato). Riferisci quale dei tre regge. Con `composizione`, prova anche a scrivere + e cliccare nella finestra del browser (mouse e tastiera passano da Febe). + +### C5. S3 — l'accesso sopravvive al riavvio (Instagram, account di prova) + +1. Avvia Febe normalmente (cartelle predefinite, nessuna opzione). Impostazioni ▸ Collegamento: accedi a mano nella + finestra «Browser di Febe» con l'**account di prova**, poi «Ho finito». Atteso: «Collegato». +2. Menu dell'icona ▸ **Esci**; riapri Febe. Atteso: Collegamento dice «Collegato» senza un nuovo accesso. +3. Riavvia Windows (con Febe aperto, senza Esci). Atteso: dopo il riavvio, aprendo Febe, ancora «Collegato». +4. «Avvia Febe all'accensione del computer» acceso, riavvia Windows. Atteso: Febe parte da solo nell'area di notifica, + senza finestra; collegato. +5. «Scollega» ▸ «Scollega e cancella la sessione». Atteso: «Non collegato»; la cartella `%LOCALAPPDATA%\Febe\browser` + è stata ricreata vuota. +6. Riferisci per ogni passo «sì/no»; se un passo fallisce, l'ora e le righe `[collegamento]` e `[browser]` del registro. + +### C6. Disinstallazione + +1. Esci da Febe, poi App installate ▸ Febe ▸ Disinstalla. Atteso: nessuna domanda sui dati; alla fine il testo dice dove + sono la cartella dei dati e la libreria; `%LOCALAPPDATA%\Febe` e `Immagini\Febe` sono ancora lì; sparisce il valore + `Febe` in `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`. +2. Con Febe aperto la disinstallazione deve dire di chiuderlo e non togliere nulla. diff --git a/docs/sonda/esito.md b/docs/sonda/esito.md index e8ed94e..5daabb9 100644 --- a/docs/sonda/esito.md +++ b/docs/sonda/esito.md @@ -19,9 +19,9 @@ Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvf | H9 | Un contenuto di una raccolta ha lo stesso identificativo che aveva come storia | **Da provare dal vivo** | Passo A3.5: aprire una raccolta che contenga una storia ancora attiva (o pubblicata e poi messa in evidenza dall'account di prova). Confrontare gli identificativi nei ripuliti: la ripulitura dà a valori uguali lo stesso valore finto | Raccolta in evidenza (collegamento senza riscaricare); sul sito di prova funziona così per costruzione | | H10 | Identificativo e nome dell'account collegato si ricavano dai dati, senza leggere i cookie | **Da provare dal vivo** | Passo A3.1: nei ripuliti della home cercare un nodo che descriva l'account collegato | `viewer` di `lettori.instagram.json`; il profilo «Tu» | | H11 | I bersagli si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | **Da provare dal vivo**. Scheletro pronto: `bersagli.instagram.json` | Durante tutta la sonda: passare col puntatore e cliccare i comandi elencati al passo A3; la sonda registra ruolo, nome accessibile e forma del collegamento in `interazioni.jsonl`. Alberto manda le righe dei soli comandi dell'interfaccia (passo A6) | Tutte le ricette | -| S1 | In WebView2 funzionano corpo delle risposte, gesti e fotogrammi | **Da provare** (Windows, M6) | Prova usa e getta in WPF con WebView2 sulla pagina locale del sito di prova: `CallDevToolsProtocolMethodAsync` per `Network.getResponseBody`, `Input.dispatchMouseEvent`, `Page.startScreencast` | `WebView2Host` | -| S2 | Su Windows la pagina carica e scorre con la finestra fuori vista | **Da provare** (Windows, M6) | Nell'ordine di §6.6: finestra separata fuori vista con occlusione disattivata; poi composizione; poi Edge con `ChromiumProcessHost` | `WebView2Host` | -| S3 | L'accesso a mano sopravvive al riavvio | **Provato in locale per Docker/Chromium** (cookie scritto con arresto SIGINT, 3 esecuzioni su 3; vedi `esito-locale.md`); **da provare** su Windows e nel contenitore vero | Docker: accedere, riavviare il contenitore, controllare il collegamento. Windows: lo stesso con l'applicazione | Profilo del browser nella cartella dei dati | +| S1 | In WebView2 funzionano corpo delle risposte, gesti e fotogrammi | **Da provare** su Windows. Pronto: `WebView2Browser` (Febe.Desktop) con l'adattatore `WebView2CdpSession` (stesso elenco ammesso del client Chromium, provato su Linux con un finto WebView2) | `docs/prove-dal-vivo.md`, parte C3: Febe per Windows con `--sito-di-prova`, una sessione intera (`Network.getResponseBody`, `Input.dispatchMouseEvent`, `Network.loadNetworkResource`/`IO.read`) e l'anteprima di Attività (`Page.captureScreenshot`). `Page.startScreencast` su Windows non serve (la vista remota è solo di Docker) | `WebView2Browser`, `WebView2CdpSession` | +| S2 | Su Windows la pagina carica e scorre con la finestra fuori vista | **Da provare** su Windows. Pronti i tre modi di §6.6, scelti con `Febe.exe --browser finestra\|composizione\|edge` (predefinito `finestra`: fuori dallo schermo, `IsVisible` sempre vero, `--disable-features=CalculateNativeWinOcclusion --disable-backgrounding-occluded-windows`) | `docs/prove-dal-vivo.md`, parte C4: sessione sul sito di prova con il browser fuori vista, con la finestra di Febe ridotta a icona e con lo schermo bloccato; se non regge, `composizione` e poi `edge` | `WebView2Browser`, `CompositionHost`, `EdgeBrowser` | +| S3 | L'accesso a mano sopravvive al riavvio | **Provato in locale per Docker/Chromium** (cookie scritto con arresto SIGINT, 3 esecuzioni su 3; vedi `esito-locale.md`); **da provare** su Windows (all'arresto Febe chiude WebView2 e ne aspetta l'uscita prima di finire) e nel contenitore vero | Docker: accedere, riavviare il contenitore, controllare il collegamento. Windows: `docs/prove-dal-vivo.md`, parti C3.7 (sito di prova) e C5 (Instagram, account di prova: Esci e riapri, riavvio di Windows, avvio con il computer) | Profilo del browser nella cartella dei dati | | S4 | In Docker, con la vista remota, si scrive in un modulo e si naviga con un ritardo sopportabile | **Provato in locale senza contenitore** (clic e tasti dalla vista remota arrivano alla pagina; vedi `esito-locale.md`); **da provare** nel contenitore su Unraid (M5) | Dalla pagina Collegamento: scrivere in un campo del sito di prova, poi accedere al sito vero con l'account di prova | Vista remota | | S5 | Chromium in Docker parte con la sandbox | **Provato in locale** (`esito-locale.md`): come utente normale la sandbox è attiva; come root Chromium non parte senza `--no-sandbox`. **Da provare** nel contenitore con il profilo seccomp predefinito (M5) | `chrome://sandbox` letto in sola lettura, come in `esito-locale.md` | Compromesso eventuale di §11, da scrivere nella guida | | S6 | Che cosa vede la pagina: `navigator.webdriver`, visibilità, fuoco, lingua, fuso | **Provato in locale per Chromium su Xvfb** (`esito-locale.md`): `webdriver` falso con porta fissa, pagina visibile, `it-IT`, `Europe/Rome`, fuoco dopo il primo evento del puntatore. **Da provare** con il Chromium di Debian (M5) e in WebView2 (M6) | Prova `BrowserIntegrationTests.ThePageSeesAnOrdinaryVisibleBrowser` | — | diff --git a/docs/windows.md b/docs/windows.md new file mode 100644 index 0000000..8a40afb --- /dev/null +++ b/docs/windows.md @@ -0,0 +1,206 @@ +# Febe per Windows + +La veste Windows di Febe (specifica §12): lo stesso motore e la stessa interfaccia del contenitore Docker, in +un'applicazione per Windows 10 e 11. La finestra di Febe mostra l'interfaccia; il browser con cui Febe visita Instagram +è una **seconda finestra, «Browser di Febe»**, che resta aperta ma fuori vista quando non ti serve. + +> **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. Le storie che Febe apre +> risultano viste da te. + +> **Stato.** Questa versione è stata costruita e provata su Linux: tutto ciò che non dipende da Windows ha le sue prove +> automatiche, ma **nessuna parte che richiede Windows è ancora stata eseguita su un Windows vero** (finestre, WebView2, +> area di notifica, registro, programma di installazione). Le prove da fare sono in fondo a questa pagina e in +> `docs/prove-dal-vivo.md`, parte C. + +## Che cosa serve + +- Windows 10 o 11 a 64 bit. +- Il **runtime WebView2** di Microsoft: c'è già in Windows 11 e in quasi tutti i Windows 10. Se manca, sia il programma + di installazione sia Febe lo dicono e offrono la pagina ufficiale: + (installazione «Evergreen», senza permessi di amministratore). +- Nessun permesso di amministratore: Febe si installa solo per il tuo utente. + +## Installazione + +1. Scarica `Febe-Setup-.exe` dalla pagina delle release del repository e aprilo. +2. Windows può avvisare che il programma non è firmato (SmartScreen): «Ulteriori informazioni» ▸ «Esegui comunque». +3. Il programma di installazione mette `Febe.exe` in `%LOCALAPPDATA%\Programs\Febe`, crea il collegamento nel menu Start + e, se lo lasci scelto, uno sul desktop. Febe compare in Impostazioni di Windows ▸ App installate (editore Alberto Balbo). +4. Alla fine puoi aprire Febe subito. + +**Versione portabile.** `Febe--portabile.zip` contiene lo stesso `Febe.exe` (e un `LEGGIMI.txt`): si copia +dove si vuole e si apre, senza installazione. Anche la versione portabile tiene i dati in `%LOCALAPPDATA%\Febe` e la +libreria in `Immagini\Febe`, finché non scegli altre cartelle. + +`Febe.exe` è un file solo (circa 86 MB): contiene il runtime .NET, l'interfaccia e le librerie native (SQLite, SkiaSharp, +WebView2Loader). Al primo avvio Windows estrae le librerie native in `%TEMP%\.net\Febe`: è normale. + +## Il primo collegamento a Instagram + +1. Apri Febe: la finestra mostra l'interfaccia (la prima volta, la schermata di benvenuto). +2. Vai in **Impostazioni ▸ Collegamento** (o «Collegati a Instagram» dal benvenuto). Si apre in primo piano la finestra + **«Browser di Febe»** con la vera pagina di accesso di Instagram. +3. Scrivi tu nome utente, password e l'eventuale codice della verifica in due passaggi **in quella finestra**: vanno + direttamente alla pagina di Instagram. Febe non riceve e non salva la password; il salvataggio delle password e la + compilazione automatica del browser sono spenti. +4. Quando vedi la tua pagina iniziale di Instagram, torna alla finestra di Febe e premi **«Ho finito»**: Febe controlla + che la sessione ci sia (guarda solo se il cookie esiste, mai il suo valore) e rimette il browser fuori vista. +5. La prima sessione arriva qualche minuto dopo, con calma: nei primi giorni i tetti sono ridotti (avvio graduale). + +La sessione resta nel profilo del browser, in `%LOCALAPPDATA%\Febe\browser`, e sopravvive ai riavvii di Febe e di +Windows (ipotesi S3, da confermare: vedi sotto). + +### La finestra «Browser di Febe» + +- Ha una dimensione fissa, sempre la stessa (la pagina è di 1280 × 900 punti), e sotto la pagina una barra con + «Indietro», «Ricarica» e l'indirizzo (senza la parte dopo il `?`). +- Quando non ti serve **non è chiusa né ridotta a icona**: è aperta ma spostata fuori dallo schermo, perché il browser + deve continuare a caricare e scorrere anche quando non lo guardi (ipotesi S2). Non ha un pulsante nella barra delle + applicazioni. +- La porti in primo piano dalla finestra di Febe: «Apri il browser» (Attività, striscia rossa di un arresto) o + «Portalo in primo piano» (Collegamento). +- **Mentre la usi il motore resta fermo.** Quando hai finito, chiudila (la X o «Ho finito» nel Collegamento): torna + fuori vista e il motore può ripartire. Dopo una verifica, «Riprendi» si accende solo dopo che hai usato il browser. +- «Scollega» (Collegamento) chiede conferma, ferma il motore, chiude il browser e cancella `Dati\browser` con la sessione. + Per chiudere la sessione anche dal lato di Instagram, prima esci dal sito usando tu il browser. + +## Un account, un motore + +**Non usare insieme Febe per Windows e il contenitore Docker con lo stesso account Instagram.** Due Febe che raccolgono +con lo stesso account sommano le visite e raddoppiano il rischio. Lo dice anche la pagina Collegamento. Per un secondo +account serve un secondo Febe con cartelle tutte sue (`Febe.exe --dati D:\FebeSecondo --libreria D:\FotoSecondo`). +Febe impedisce due avvii sulla stessa cartella dei dati: un secondo avvio porta in primo piano quello già aperto. + +## Area di notifica + +L'icona di Febe (il marchio: un quadrato blu con un anello e una luna) sta nell'area di notifica, accanto all'orologio. +Un clic apre la finestra; il menu ha **Apri**, **Metti in pausa** (o **Riprendi**, quando Febe è in pausa o fermo per una +verifica) ed **Esci**. Il suggerimento dell'icona dice che cosa sta facendo Febe. + +**Chiudendo la finestra Febe resta attivo** nell'area di notifica e continua a lavorare (Impostazioni ▸ Generali ▸ +Avvio, «Chiudendo la finestra, Febe resta attivo nell'area di notifica», acceso di serie). Per fermarlo davvero: +menu dell'icona ▸ **Esci**. Esci ferma tutto in ordine (motore, scaricamenti, browser): il browser si chiude in modo +pulito e la sessione resta scritta nel profilo. + +### Notifiche di Windows + +Gli avvisi di §13.3 (verifica richiesta, disconnessione, fermo per rallentamento e ripresa, storico completato, formato +non riconosciuto) arrivano come notifiche di Windows, dall'icona di Febe. Si scelgono in Impostazioni ▸ Notifiche +(«Notifiche di Windows» e gli eventi). Un clic sulla notifica apre Febe. + +## Avvio con il computer + +Impostazioni ▸ Generali ▸ Avvio ▸ «Avvia Febe all'accensione del computer». Febe scrive il valore `Febe` in +`HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run` (solo per il tuo utente) e all'accensione parte con +`--nascosto`: solo l'icona nell'area di notifica, la finestra resta chiusa. Togliendo la spunta il valore sparisce; +lo toglie anche la disinstallazione. + +## Dove stanno le cose + +| Che cosa | Dove | Note | +|---|---|---| +| Programma | `%LOCALAPPDATA%\Programs\Febe\Febe.exe` | Dove l'hai copiato, per la versione portabile | +| **Dati di Febe** | `%LOCALAPPDATA%\Febe` | Database `febe.sqlite`, **profilo del browser con la sessione di Instagram** (`browser\`), dati della finestra dell'interfaccia (`interfaccia\`), miniature, copie del database (`copie\`, sette giorni), registro (`registro\`, quattordici giorni) | +| **Libreria** | `Immagini\Febe` | Foto e video, una cartella per account, con `_febe.jsonl` | + +- **Chi ha la cartella dei dati, o una sua copia, ha la sessione di Instagram.** Trattala come una password: niente + copie su chiavette, cartelle condivise o servizi di sincronizzazione (OneDrive, Dropbox…). `%LOCALAPPDATA%` non è + sincronizzato da OneDrive: lasciala lì. +- La cartella dei dati deve stare su un **disco locale**: su una cartella di rete Febe non parte e lo spiega. +- **Cambiare la libreria** (Impostazioni ▸ Generali ▸ Libreria ▸ «Cambia…»): vale subito per i nuovi file; gli account + che hanno già file restano nelle loro cartelle. Febe non sposta nessun file. +- **Cambiare la cartella dei dati** (Impostazioni ▸ Generali ▸ Dati di Febe ▸ «Cambia…»): la nuova cartella deve essere + vuota e su un disco locale. Lo spostamento avviene **al prossimo avvio**, prima che Febe apra qualunque cosa: copia + ogni file, lo rilegge e ne confronta lo SHA-256 con l'originale; solo se tutte le copie sono uguali usa la nuova + cartella e cancella la vecchia (che conteneva una copia della sessione). Se qualcosa va storto la vecchia cartella resta + quella in uso, intatta, e la copia parziale viene tolta. Per farlo subito: Esci e riapri Febe. La cartella scelta è + scritta in `HKEY_CURRENT_USER\Software\Febe` (`CartellaDati`); con `--dati` decide invece la riga di comando. + +## Riga di comando + +| Opzione | Che cosa fa | +|---|---| +| `--nascosto` | Parte con la sola icona nell'area di notifica (lo usa l'avvio con il computer) | +| `--dati ` | Cartella dei dati diversa (un secondo account, le prove); «Cambia…» allora non c'è | +| `--libreria ` | Libreria di partenza diversa (una cartella scelta poi nelle Impostazioni vince) | +| `--browser finestra\|composizione\|edge` | Come è ospitato il browser di Instagram (prove di S2, sotto); la scelta resta per gli avvii successivi | +| `--sviluppo` | Strumenti di sviluppo nella finestra dell'interfaccia (mai nel browser di Febe) | +| `--sito-di-prova http://127.0.0.1:8481` | Sviluppo e prove: il browser lavora sul sito di prova locale invece che su Instagram | +| `--accesso-di-prova` | Solo con `--sito-di-prova`: apre il sito una volta, come dopo un accesso | +| `--prima-sessione ` | La prima sessione dopo questi secondi invece che dopo 2–10 minuti | + +## Sicurezza dell'interfaccia + +L'interfaccia è servita da Febe stesso su `127.0.0.1`, su una porta scelta a ogni avvio, e risponde solo con il +**gettone di quell'avvio**, che conosce solo la finestra di Febe: la finestra apre `/?gettone=…` una volta, il gettone +diventa un cookie `HttpOnly`, `SameSite=Strict` e sparisce dall'indirizzo. Si controllano anche `Host` e `Origin`: +un'altra pagina aperta nel tuo browser non può comandare Febe. Gli indirizzi esterni (guida, repository, «Apri su +Instagram») si aprono nel tuo browser predefinito, mai nel browser di Febe. + +## Il browser di Febe e le ipotesi S1–S3 + +Su Windows il browser di Instagram è WebView2 (il motore di Edge), pilotato con il protocollo DevTools attraverso +`CallDevToolsProtocolMethodAsync` e `GetDevToolsProtocolEventReceiver` (non il pacchetto `DevToolsProtocolExtension`, +deprecato), con lo **stesso elenco di comandi ammessi** del Chromium di Docker e gli stessi rifiuti: nessun comando +fuori elenco arriva al browser, `Runtime.evaluate` solo in lettura, nel registro solo i nomi dei comandi. + +Per S2 (la pagina deve continuare a caricare e scorrere quando la finestra non è in vista) ci sono tre modi, nell'ordine +della specifica (§6.6); si sceglie con `--browser` e la scelta resta: + +1. **`finestra`** (predefinito): la finestra «Browser di Febe» aperta ma fuori dallo schermo; il controllo WebView2 + resta sempre «visibile» (`IsVisible` vero: se diventa falso WebView2 smette di disegnare) e il rilevamento + dell'occlusione è spento dagli argomenti del browser: `--disable-features=CalculateNativeWinOcclusion` e + `--disable-backgrounding-occluded-windows`. Non sono vietati dalla regola 2: cambiano come il browser organizza il + proprio lavoro, non ciò che dichiara (user agent, client hints, `navigator`, lingua, fuso e intestazioni restano + quelli di un Edge normale; nella pagina non entra nulla). +2. **`composizione`**: lo stesso, con WebView2 ospitato come visual di DirectComposition invece che come finestra figlia; + Febe passa al browser il mouse e il puntatore della zona della pagina. +3. **`edge`**: Microsoft Edge avviato come processo e pilotato come il Chromium di Docker (`ChromiumProcessHost`, porta + di debug fissa 9222 solo su 127.0.0.1), profilo in `Dati\browser\edge`; la sua finestra viene spostata fuori + dallo schermo. Se Edge non c'è, Febe usa la `finestra`. + +Le prove da fare su un Windows vero, con la procedura esatta, sono in `docs/prove-dal-vivo.md`, **parte C**. In breve: + +- **S1** — con il sito di prova: una sessione intera (gesti, corpo delle risposte, scaricamenti) e l'anteprima di Attività. +- **S2** — la stessa sessione con il browser fuori vista, con la finestra di Febe ridotta a icona e con lo schermo bloccato; + poi, se serve, `composizione` e `edge`. +- **S3** — accesso a mano, «Esci», riapertura, riavvio di Windows: il collegamento deve restare. + +## Disinstallare + +Impostazioni di Windows ▸ App ▸ App installate ▸ Febe ▸ Disinstalla (oppure «Disinstalla Febe.exe» nella cartella del +programma). Prima esci da Febe (menu dell'icona ▸ Esci). + +La disinstallazione toglie il programma, i collegamenti, la voce in App installate e l'avvio con il computer. **Non +cancella mai la cartella dei dati né la libreria** e non chiede nulla su di loro: alla fine dice dove sono. Se non ti +servono più, cancellale tu — la cartella dei dati contiene la sessione di Instagram. + +## Costruire il programma di installazione + +Da Linux (CI, rilascio) o da Windows con bash, con il .NET SDK 10 e NSIS 3 (`apt-get install nsis`): + +```sh +installer/costruisci.sh # versione di Directory.Build.props +installer/costruisci.sh 0.2.0 # oppure una versione esplicita +``` + +Il risultato è in `out/`: `Febe-Setup-.exe` e `Febe--portabile.zip`, ognuno sotto i 100 MB +(limite degli allegati di Gitea; con la versione 0.1.0: Febe.exe 86 MB, installazione 80 MB, zip 81 MB). Lo script +controlla che la pubblicazione abbia prodotto un solo file e che nulla superi il limite. Lo script NSIS è +`installer/febe.nsi` (Unicode, testi in italiano, versione passata con `/DVERSION=…`). + +L'icona `src/Febe.Desktop/Febe.ico` (16, 24, 32, 48, 64, 128 e 256 pixel) è disegnata dal marchio dell'appendice C con +SkiaSharp e scritta a mano: per rigenerarla dopo un cambio del marchio, +`FEBE_RIGENERA_ICONA=1 dotnet test tests/Febe.Tests --filter IconTests`. + +## Problemi comuni + +| Che cosa vedi | Che cosa fare | +|---|---| +| All'avvio: «Manca il runtime WebView2 di Microsoft» | Installa il runtime dalla pagina ufficiale (il messaggio offre di aprirla), poi riapri Febe | +| «La cartella dei dati è su un disco di rete» o «non può scrivere» | Riapri Febe con una cartella dei dati su un disco locale (`--dati`), oppure libera la cartella | +| Aprendo Febe si porta solo in primo piano la finestra già aperta | È voluto: un solo Febe per cartella dei dati. Per fermarlo: menu dell'icona ▸ Esci | +| Il collegamento risulta perso dopo un riavvio | È l'ipotesi S3: riferiscilo (parte C di `docs/prove-dal-vivo.md`) con l'ora e il registro di quel giorno | +| Il browser sembra fermo mentre è fuori vista | È l'ipotesi S2: prova `Febe.exe --browser composizione`, poi `--browser edge`, e riferisci | +| Il registro | `%LOCALAPPDATA%\Febe\registro\febe-AAAA-MM-GG.log`: azioni ed esiti, mai password, cookie, tasti o contenuti | diff --git a/installer/costruisci.sh b/installer/costruisci.sh new file mode 100755 index 0000000..314292c --- /dev/null +++ b/installer/costruisci.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# Febe per Windows: pubblica Febe.exe in un file solo e ne fa il programma di installazione e lo zip portabile. +# +# installer/costruisci.sh [versione] +# +# Gira su Linux (CI e rilascio) come su Windows con bash: servono il .NET SDK 10 e makensis (NSIS 3, «apt-get install +# nsis»). La versione, se non la si passa, è quella di Directory.Build.props (il tag deve coincidere). +# Risultato in out/: +# Febe-Setup-.exe installazione per l'utente, senza permessi di amministratore +# Febe--portabile.zip Febe.exe e LEGGIMI.txt, da copiare dove si vuole +# Ognuno deve restare sotto i 100 MB (limite degli allegati di Gitea). +set -euo pipefail + +radice="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$radice" + +versione="${1:-$(sed -n 's:.*\(.*\).*:\1:p' Directory.Build.props | head -n 1)}" +if [[ ! "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$ ]]; then + echo "Versione non valida: «$versione» (serve x.y.z)." >&2 + exit 2 +fi + +# La versione dei file di Windows vuole quattro numeri. +numeri="${versione%%[-+]*}" +versione_file="${numeri}.0" + +command -v dotnet >/dev/null || { echo "Manca il .NET SDK (dotnet)." >&2; exit 2; } +command -v makensis >/dev/null || { echo "Manca makensis: installa NSIS (apt-get install nsis)." >&2; exit 2; } + +uscita="$radice/out" +pubblicazione="$uscita/pubblicazione" +rm -rf "$pubblicazione" +mkdir -p "$pubblicazione" + +echo "== Pubblicazione di Febe.exe $versione (win-x64, un file solo)" +dotnet publish src/Febe.Desktop/Febe.Desktop.csproj -c Release -r win-x64 --self-contained true \ + -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true \ + -p:Version="$versione" -nologo -o "$pubblicazione" + +# Un file solo: niente accanto all'eseguibile. +altri="$(find "$pubblicazione" -mindepth 1 ! -name Febe.exe)" +if [[ -n "$altri" ]]; then + echo "La pubblicazione ha prodotto altri file oltre a Febe.exe:" >&2 + echo "$altri" >&2 + exit 1 +fi + +echo "== Programma di installazione" +setup="$uscita/Febe-Setup-$versione.exe" +rm -f "$setup" +(cd installer && makensis -V2 -INPUTCHARSET UTF8 \ + -DVERSION="$versione" -DVERSIONE_FILE="$versione_file" \ + -DSORGENTE="$pubblicazione" -DUSCITA="$setup" febe.nsi) + +echo "== Zip portabile" +zip_portabile="$uscita/Febe-$versione-portabile.zip" +rm -f "$zip_portabile" +leggimi="$pubblicazione/LEGGIMI.txt" +cat > "$leggimi" </dev/null; then + (cd "$pubblicazione" && zip -q -9 "$zip_portabile" Febe.exe LEGGIMI.txt) +else + python3 - "$zip_portabile" "$pubblicazione" <<'PY' +import os, sys, zipfile +target, folder = sys.argv[1], sys.argv[2] +with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as archive: + for name in ("Febe.exe", "LEGGIMI.txt"): + archive.write(os.path.join(folder, name), name) +PY +fi +rm -f "$leggimi" + +limite=$((100 * 1024 * 1024)) +echo "== Risultato" +for file in "$pubblicazione/Febe.exe" "$setup" "$zip_portabile"; do + dimensione=$(stat -c %s "$file") + printf '%-48s %6.1f MB\n' "$(basename "$file")" "$(echo "$dimensione / 1048576" | bc -l)" + if (( dimensione >= limite )); then + echo "$(basename "$file") supera i 100 MB: Gitea non lo accetta come allegato." >&2 + exit 1 + fi +done diff --git a/installer/febe.nsi b/installer/febe.nsi new file mode 100644 index 0000000..4bb99f2 --- /dev/null +++ b/installer/febe.nsi @@ -0,0 +1,205 @@ +; Febe — programma di installazione per Windows (specifica §12, domanda 6 di §16). +; +; makensis -INPUTCHARSET UTF8 -DVERSION=0.1.0 -DVERSIONE_FILE=0.1.0.0 \ +; -DSORGENTE=out/pubblicazione -DUSCITA=out/Febe-Setup-0.1.0.exe installer/febe.nsi +; +; Di solito lo lancia installer/costruisci.sh, che prima pubblica Febe.exe in un file solo. +; +; - Installazione per l'utente, senza permessi di amministratore, in %LOCALAPPDATA%\Programs\Febe. +; - Collegamento nel menu Start; collegamento sul desktop facoltativo. +; - Disinstallazione registrata in HKCU (Programmi e funzionalità / App installate). +; - La disinstallazione non tocca MAI la cartella dei dati né la libreria e non chiede nulla su di loro: dice dove sono. +; - Controllo del runtime WebView2 di Microsoft, con il collegamento alla pagina ufficiale se manca. + +Unicode true +ManifestDPIAware true +RequestExecutionLevel user +SetCompressor /SOLID lzma + +!ifndef VERSION + !error "Manca la versione: passala con /DVERSION=x.y.z (installer/costruisci.sh la legge da Directory.Build.props)." +!endif +!ifndef SORGENTE + !define SORGENTE "../out/pubblicazione" +!endif +!ifndef USCITA + !define USCITA "../out/Febe-Setup-${VERSION}.exe" +!endif + +!define NOME "Febe" +!define EDITORE "Alberto Balbo" +!define ESEGUIBILE "Febe.exe" +!define DISINSTALLA "Disinstalla Febe.exe" +!define CHIAVE_DISINSTALLA "Software\Microsoft\Windows\CurrentVersion\Uninstall\Febe" +!define CHIAVE_FEBE "Software\Febe" +!define CHIAVE_AVVIO "Software\Microsoft\Windows\CurrentVersion\Run" +!define WEBVIEW2_GUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" +!define WEBVIEW2_PAGINA "https://developer.microsoft.com/microsoft-edge/webview2/" +!define SITO "https://gitea.encke-hake.ts.net/Alby96/Febe" + +Name "${NOME}" +OutFile "${USCITA}" +InstallDir "$LOCALAPPDATA\Programs\Febe" +BrandingText "${NOME} ${VERSION}" +ShowInstDetails show +ShowUninstDetails show + +!ifdef VERSIONE_FILE + VIProductVersion "${VERSIONE_FILE}" + VIAddVersionKey /LANG=1040 "ProductName" "${NOME}" + VIAddVersionKey /LANG=1040 "ProductVersion" "${VERSION}" + VIAddVersionKey /LANG=1040 "CompanyName" "${EDITORE}" + VIAddVersionKey /LANG=1040 "LegalCopyright" "${EDITORE}" + VIAddVersionKey /LANG=1040 "FileDescription" "Installazione di ${NOME}" + VIAddVersionKey /LANG=1040 "FileVersion" "${VERSION}" +!endif + +!include "MUI2.nsh" +!include "LogicLib.nsh" +!include "FileFunc.nsh" + +!define MUI_ICON "../src/Febe.Desktop/Febe.ico" +!define MUI_UNICON "../src/Febe.Desktop/Febe.ico" +!define MUI_ABORTWARNING + +; ------------------------------------------------------------------------------------------------ pagine +!define MUI_WELCOMEPAGE_TITLE "Installazione di Febe ${VERSION}" +!define MUI_WELCOMEPAGE_TEXT "Febe è l'archivio personale di foto, video e storie da Instagram.$\r$\n$\r$\nVerrà installato solo per te, in $LOCALAPPDATA\Programs\Febe: non servono permessi di amministratore.$\r$\n$\r$\nI dati di Febe (database e sessione del browser) andranno in $LOCALAPPDATA\Febe, le foto e i video nella cartella Immagini\Febe; le cartelle si possono cambiare dalle Impostazioni." +!insertmacro MUI_PAGE_WELCOME +!insertmacro MUI_PAGE_COMPONENTS +!insertmacro MUI_PAGE_INSTFILES +!define MUI_FINISHPAGE_TITLE "Febe è installato" +!define MUI_FINISHPAGE_TEXT "Febe si apre in una sua finestra e resta attivo nell'area di notifica, accanto all'orologio.$\r$\n$\r$\nPer collegarlo a Instagram: Impostazioni ▸ Collegamento. Non usare insieme Febe per Windows e il contenitore Docker con lo stesso account." +!define MUI_FINISHPAGE_RUN "$INSTDIR\${ESEGUIBILE}" +!define MUI_FINISHPAGE_RUN_TEXT "Apri Febe adesso" +!insertmacro MUI_PAGE_FINISH + +!define MUI_UNCONFIRMPAGE_TEXT_TOP "Il programma Febe verrà tolto da questo computer. I tuoi dati restano dove sono: la disinstallazione non cancella né la cartella dei dati né la libreria con le foto e i video." +!insertmacro MUI_UNPAGE_CONFIRM +!insertmacro MUI_UNPAGE_INSTFILES +!define MUI_FINISHPAGE_TITLE "Febe è stato disinstallato" +!define MUI_FINISHPAGE_TEXT "I dati di Febe non sono stati toccati:$\r$\n$\r$\n- cartella dei dati: $R8$\r$\n- libreria: $R9, o la cartella scelta nelle Impostazioni.$\r$\n$\r$\nLa cartella dei dati contiene la sessione di Instagram: se non ti serve più, cancellala tu." +!insertmacro MUI_UNPAGE_FINISH + +!insertmacro MUI_LANGUAGE "Italian" + +LangString DESC_Programma ${LANG_ITALIAN} "Febe.exe, il menu Start e la voce in App installate." +LangString DESC_Desktop ${LANG_ITALIAN} "Un collegamento a Febe sul desktop." + +; ------------------------------------------------------------------------------------------------ funzioni +; Febe in esecuzione tiene aperto Febe.exe: non si può sovrascrivere né cancellare. +!macro FebeChiuso UN +Function ${UN}FebeChiuso + IfFileExists "$INSTDIR\${ESEGUIBILE}" 0 fatto + riprova: + ClearErrors + FileOpen $0 "$INSTDIR\${ESEGUIBILE}" a + ${If} ${Errors} + MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "Febe è aperto. Chiudilo dall'area di notifica (clic destro sull'icona ▸ Esci), poi premi Riprova." /SD IDCANCEL IDRETRY riprova + Abort + ${EndIf} + FileClose $0 + fatto: +FunctionEnd +!macroend +!insertmacro FebeChiuso "" +!insertmacro FebeChiuso "un." + +; Il runtime WebView2 (Evergreen) è installato per tutto il computer o solo per l'utente: «pv» è la sua versione. +Function WebView2Presente + StrCpy $1 "" + ReadRegStr $1 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2_GUID}" "pv" + ${If} $1 == "" + ${OrIf} $1 == "0.0.0.0" + ReadRegStr $1 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2_GUID}" "pv" + ${EndIf} + ${If} $1 == "" + ${OrIf} $1 == "0.0.0.0" + ReadRegStr $1 HKCU "Software\Microsoft\EdgeUpdate\Clients\${WEBVIEW2_GUID}" "pv" + ${EndIf} + ${If} $1 == "0.0.0.0" + StrCpy $1 "" + ${EndIf} + Push $1 +FunctionEnd + +; ------------------------------------------------------------------------------------------------ installazione +Section "Febe" SEC_PROGRAMMA + SectionIn RO + Call FebeChiuso + SetOutPath "$INSTDIR" + File "${SORGENTE}/${ESEGUIBILE}" + WriteUninstaller "$INSTDIR\${DISINSTALLA}" + + ; Menu Start (dell'utente). + SetShellVarContext current + CreateShortCut "$SMPROGRAMS\Febe.lnk" "$INSTDIR\${ESEGUIBILE}" "" "$INSTDIR\${ESEGUIBILE}" 0 SW_SHOWNORMAL "" "Archivio personale di foto, video e storie da Instagram" + + ; App installate (Programmi e funzionalità), per l'utente. + WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "DisplayName" "${NOME}" + WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "DisplayVersion" "${VERSION}" + WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "Publisher" "${EDITORE}" + WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "DisplayIcon" "$INSTDIR\${ESEGUIBILE},0" + WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "InstallLocation" "$INSTDIR" + WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "UninstallString" '"$INSTDIR\${DISINSTALLA}"' + WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "QuietUninstallString" '"$INSTDIR\${DISINSTALLA}" /S' + WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "URLInfoAbout" "${SITO}" + WriteRegDWORD HKCU "${CHIAVE_DISINSTALLA}" "NoModify" 1 + WriteRegDWORD HKCU "${CHIAVE_DISINSTALLA}" "NoRepair" 1 + ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2 + WriteRegDWORD HKCU "${CHIAVE_DISINSTALLA}" "EstimatedSize" "$0" + + ; WebView2: senza, Febe non può mostrare nulla. Lo dice anche Febe al primo avvio. + Call WebView2Presente + Pop $1 + ${If} $1 == "" + DetailPrint "Runtime WebView2 di Microsoft: non trovato." + MessageBox MB_YESNO|MB_ICONINFORMATION "Febe ha bisogno del runtime WebView2 di Microsoft, che su questo computer non c'è (Windows 11 e quasi tutti i Windows 10 lo hanno già).$\r$\n$\r$\nSi installa gratis dalla pagina ufficiale di Microsoft, senza permessi di amministratore. Vuoi aprirla adesso?" /SD IDNO IDNO fine_webview2 + ExecShell "open" "${WEBVIEW2_PAGINA}" + fine_webview2: + ${Else} + DetailPrint "Runtime WebView2 di Microsoft: $1." + ${EndIf} +SectionEnd + +Section "Collegamento sul desktop" SEC_DESKTOP + SetShellVarContext current + CreateShortCut "$DESKTOP\Febe.lnk" "$INSTDIR\${ESEGUIBILE}" "" "$INSTDIR\${ESEGUIBILE}" 0 SW_SHOWNORMAL "" "Archivio personale di foto, video e storie da Instagram" +SectionEnd + +!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN + !insertmacro MUI_DESCRIPTION_TEXT ${SEC_PROGRAMMA} $(DESC_Programma) + !insertmacro MUI_DESCRIPTION_TEXT ${SEC_DESKTOP} $(DESC_Desktop) +!insertmacro MUI_FUNCTION_DESCRIPTION_END + +; ------------------------------------------------------------------------------------------------ disinstallazione +Function un.onInit + ; Dove sono i dati, per dirlo alla fine: la cartella scelta nelle Impostazioni o quella predefinita. + ReadRegStr $R8 HKCU "${CHIAVE_FEBE}" "CartellaDati" + ${If} $R8 == "" + StrCpy $R8 "$LOCALAPPDATA\Febe" + ${EndIf} + StrCpy $R9 "$PICTURES\Febe" +FunctionEnd + +Section "Uninstall" + Call un.FebeChiuso + SetShellVarContext current + + ; Solo i file del programma. MAI la cartella dei dati, MAI la libreria: non si chiede nulla su di loro. + Delete "$INSTDIR\${ESEGUIBILE}" + Delete "$INSTDIR\${DISINSTALLA}" + RMDir "$INSTDIR" + Delete "$SMPROGRAMS\Febe.lnk" + Delete "$DESKTOP\Febe.lnk" + + ; «Avvia Febe all'accensione del computer» punterebbe a un programma che non c'è più. + DeleteRegValue HKCU "${CHIAVE_AVVIO}" "Febe" + DeleteRegKey HKCU "${CHIAVE_DISINSTALLA}" + + ; Le librerie native che Febe.exe estrae da sé al primo avvio (non sono dati). + RMDir /r "$TEMP\.net\Febe" + + DetailPrint "I dati restano: cartella dei dati $R8; libreria $R9 (o quella scelta nelle Impostazioni)." + DetailPrint "La cartella dei dati contiene la sessione di Instagram: se non ti serve più, cancellala tu." +SectionEnd diff --git a/src/Febe.App/Alerts.cs b/src/Febe.App/Alerts.cs new file mode 100644 index 0000000..d4c1340 --- /dev/null +++ b/src/Febe.App/Alerts.cs @@ -0,0 +1,203 @@ +using System.Threading.Channels; +using Febe.Core.Alerts; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Storage; + +namespace Febe.App; + +/// The events of spec §13.3 that deserve an alert besides the red strip of the interface. +public enum AlertKind +{ + /// «Verifica richiesta». + Verification, + + /// «Disconnessione». + Disconnection, + + /// «Fermo per rallentamento e ripresa». + Throttle, + + /// «Storico di un account completato». + BackfillDone, + + /// «Disco quasi pieno». + DiskLow, + + /// «Formato non riconosciuto». + UnknownFormat, +} + +/// One alert: Italian title and text, no captions, bodies, cookies or addresses (spec §13.2). +public sealed record FebeAlert(AlertKind Kind, string Title, string Message, DateTimeOffset At, long? AccountId); + +/// +/// A channel alerts go to besides the red strip (spec §13.3): Windows notifications on the desktop; Telegram (M8) +/// registers its own. Registered by the shells in DI as IAlertChannel; calls them. +/// +public interface IAlertChannel +{ + /// Whether this channel is on with the settings of Impostazioni, Notifiche. + bool IsEnabled(AlertSettings settings); + + /// Sends one alert. Never logs the message or any address of the channel. + Task SendAsync(FebeAlert alert, AlertSettings settings, CancellationToken ct); +} + +/// Which engine events become alerts (spec §13.3), and whether Alberto wants them. +public static class AlertRules +{ + /// Code of the «disco quasi pieno» event, for whoever measures the free space (M8). + public const string DiskLowCode = "disco-quasi-pieno"; + + private const int MaxMessage = 240; + + /// The alert for a timeline event, or null when the event is not one of §13.3. + public static FebeAlert? FromEvent(EventRecord record) + { + ArgumentNullException.ThrowIfNull(record); + (AlertKind Kind, string Title)? match = record.Code switch + { + EngineEventCodes.ChallengeStop => (AlertKind.Verification, "Instagram chiede una verifica"), + EngineEventCodes.DisconnectStop => (AlertKind.Disconnection, "Febe è stato scollegato da Instagram"), + EngineEventCodes.ThrottleStop => (AlertKind.Throttle, "Febe si è fermato per un rallentamento"), + EngineEventCodes.ThrottleEnd => (AlertKind.Throttle, "Il fermo per rallentamento è finito"), + EngineEventCodes.Resumed => (AlertKind.Throttle, "Febe ha ripreso"), + EngineEventCodes.BackfillCompleted => (AlertKind.BackfillDone, "Storico completato"), + EngineEventCodes.FormatUnrecognized => (AlertKind.UnknownFormat, "Formato non riconosciuto"), + DiskLowCode => (AlertKind.DiskLow, "Disco quasi pieno"), + _ => null, + }; + if (match is not { } m) + { + return null; + } + + var text = record.Message.Length > MaxMessage ? record.Message[..(MaxMessage - 1)] + "…" : record.Message; + return new FebeAlert(m.Kind, m.Title, text, record.At, record.AccountId); + } + + /// True when Alberto wants alerts of this kind (Impostazioni, Notifiche). + public static bool Wanted(AlertKind kind, AlertEvents events) + { + ArgumentNullException.ThrowIfNull(events); + return kind switch + { + AlertKind.Verification => events.Verification, + AlertKind.Disconnection => events.Disconnection, + AlertKind.Throttle => events.Throttle, + AlertKind.BackfillDone => events.BackfillDone, + AlertKind.DiskLow => events.DiskLow, + AlertKind.UnknownFormat => events.UnknownFormat, + _ => false, + }; + } +} + +/// +/// The alerts hook of the shared composition (spec §13.3): listens to the engine's timeline, turns the events of §13.3 +/// into s and hands them, in order and off the engine's thread, to every enabled +/// . A channel that fails is logged by type only and never stops the others. +/// +public sealed class AlertDispatcher : IAsyncDisposable +{ + private readonly EngineEvents _events; + private readonly ISettingsStore _settings; + private readonly IReadOnlyList _channels; + private readonly FebeLog _log; + private readonly Channel _queue = Channel.CreateBounded(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true }); + private readonly CancellationTokenSource _stop = new(); + private readonly Task _loop; + + public AlertDispatcher(EngineEvents events, ISettingsStore settings, IEnumerable channels, FebeLog log) + { + _events = events ?? throw new ArgumentNullException(nameof(events)); + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _channels = [.. channels ?? throw new ArgumentNullException(nameof(channels))]; + _log = log ?? throw new ArgumentNullException(nameof(log)); + _events.Notified += OnNotified; + _loop = Task.Run(() => RunAsync(_stop.Token)); + } + + /// The channels alerts go to. + public IReadOnlyList Channels => _channels; + + /// Alerts sent since the start (tests). + public int Sent => Volatile.Read(ref _sent); + + private int _sent; + + public async ValueTask DisposeAsync() + { + _events.Notified -= OnNotified; + _queue.Writer.TryComplete(); + await _stop.CancelAsync().ConfigureAwait(false); + try + { + await _loop.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + + _stop.Dispose(); + } + + private void OnNotified(object? sender, EngineNotification notification) + { + if (_channels.Count == 0 || notification.Kind != EngineNotificationKind.Event || notification.Event is not { } record) + { + return; + } + + if (AlertRules.FromEvent(record) is { } alert) + { + _queue.Writer.TryWrite(alert); + } + } + + private async Task RunAsync(CancellationToken ct) + { + await foreach (var alert in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false)) + { + AlertSettings settings; + try + { + settings = await AlertSettingsStore.LoadAsync(_settings, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException) + { + _log.Warn("avvisi", "Impostazioni degli avvisi non leggibili: avviso non inviato.", ex); + continue; + } + + if (!AlertRules.Wanted(alert.Kind, settings.Events)) + { + continue; + } + + foreach (var channel in _channels) + { + if (!channel.IsEnabled(settings)) + { + continue; + } + + try + { + await channel.SendAsync(alert, settings, ct).ConfigureAwait(false); + Interlocked.Increment(ref _sent); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // Type only: the message of a channel's exception could contain its address (Telegram's has the token). + _log.Warn("avvisi", $"Un avviso non è partito ({channel.GetType().Name}: {ex.GetType().Name})."); + } + } + } + } +} diff --git a/src/Febe.Server/ServerConnectionService.cs b/src/Febe.App/BrowserConnectionService.cs similarity index 76% rename from src/Febe.Server/ServerConnectionService.cs rename to src/Febe.App/BrowserConnectionService.cs index b031f6e..80cf36a 100644 --- a/src/Febe.Server/ServerConnectionService.cs +++ b/src/Febe.App/BrowserConnectionService.cs @@ -9,15 +9,18 @@ using Febe.Web.Api; using Febe.Web.Connection; using Febe.Web.Engine; -namespace Febe.Server; +namespace Febe.App; /// -/// 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 (Network.getCookies, -/// 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. +/// The link to Instagram over the real browser, the same in both shells (spec §4.1, §10.3, PROTOCOLLO.md). «Collegato» +/// means that the session cookie exists in the browser profile: only its existence is checked +/// (Network.getCookies, 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. +/// On Windows the browser is the window «Browser di Febe»: «Accedi» and «Portalo in primo piano» bring it to the front, +/// «Ho finito» and «Annulla» put it back out of view, «Scollega» closes it before deleting the profile. In Docker +/// showing and hiding do nothing (the remote view shows the browser). /// -internal sealed class ServerConnectionService : IConnectionService, IAsyncDisposable +public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposable { /// Setting written at the first connection ever (Unix ms): the gradual start begins only once. public const string FirstConnectionKey = "collegamento.primo"; @@ -28,11 +31,11 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos /// How often the cookie is looked at in the background (outside sessions it is the only way to notice). public static readonly TimeSpan BackgroundCheck = TimeSpan.FromSeconds(30); - private readonly BrowserSupervisor _browser; + private readonly IFebeBrowser _browser; private readonly IFebeStorage _storage; private readonly BrowserUseTracker _tracker; private readonly IClock _clock; - private readonly ServerLog _log; + private readonly FebeLog _log; private readonly string _loginUrl; private readonly SessionCookieOptions _cookie; private readonly SemaphoreSlim _commands = new(1, 1); @@ -42,7 +45,7 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos private bool? _connected; private DateTimeOffset _checkedAt = DateTimeOffset.MinValue; - public ServerConnectionService(BrowserSupervisor browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, ServerLog log, string loginUrl, SessionCookieOptions cookie) + public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, SessionCookieOptions cookie) { _browser = browser ?? throw new ArgumentNullException(nameof(browser)); _storage = storage ?? throw new ArgumentNullException(nameof(storage)); @@ -108,7 +111,7 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos { lock (_gate) { - _lease ??= _browser.Host.UserDriving.Begin(); + _lease ??= _browser.UserDriving.Begin(); } _tracker.MarkUsed(_clock.Now); @@ -116,7 +119,7 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos { // 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); + var result = await _browser.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)."); @@ -125,6 +128,9 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos { _log.Info("collegamento", "Alberto usa il browser."); } + + // Windows: the window «Browser di Febe» comes to the front (Docker: nothing, the remote view shows it). + await ShowQuietlyAsync(ct).ConfigureAwait(false); } finally { @@ -147,6 +153,7 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos _tracker.MarkUsed(_clock.Now); var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false); await RestQuietlyAsync().ConfigureAwait(false); + await HideQuietlyAsync().ConfigureAwait(false); ReleaseLease(); var stopped = _engine?.Services.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected; @@ -185,6 +192,7 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos if (_browser.IsAvailable) { await RestQuietlyAsync().ConfigureAwait(false); + await HideQuietlyAsync().ConfigureAwait(false); } ReleaseLease(); @@ -199,7 +207,7 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos public async Task DisconnectAsync(CancellationToken ct) { await _commands.WaitAsync(ct).ConfigureAwait(false); - var hold = _browser.Host.UserDriving.Begin(); + var hold = _browser.UserDriving.Begin(); try { var engine = _engine; @@ -208,18 +216,42 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos await engine.StopAsync().ConfigureAwait(false); } - await _browser.RestartWithEmptyProfileAsync(ct).ConfigureAwait(false); - SetConnected(false); + // Windows: the browser window goes out of view and WebView2 closes before its folder is deleted. + await HideQuietlyAsync().ConfigureAwait(false); + Exception? failure = null; + try + { + await _browser.RestartWithEmptyProfileAsync(ct).ConfigureAwait(false); + SetConnected(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A file of the profile stayed (Windows: a process of the browser held it). The engine starts again + // anyway; whether the session is still there is checked again, never assumed. + failure = ex; + await RefreshAsync(CancellationToken.None).ConfigureAwait(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); + if (failure is 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); } + if (failure is not null) + { + _log.Warn("collegamento", "«Scollega»: il profilo del browser non si è potuto cancellare del tutto.", failure); + throw new BadRequestException("«Scollega» non è riuscito del tutto: " + failure.Message); + } + _log.Info("collegamento", "«Scollega»: motore fermo, profilo del browser cancellato, browser ripartito vuoto."); } finally @@ -294,7 +326,7 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos bool has; try { - has = await SessionCookieProbe.HasSessionCookieAsync(_browser.Host.Cdp, _cookie, ct).ConfigureAwait(false); + has = await SessionCookieProbe.HasSessionCookieAsync(_browser.Cdp, _cookie, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException) { @@ -367,8 +399,8 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos { try { - var url = await _browser.Host.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false); - return BrowserRemoteViewConnection.WithoutQuery(url); + var url = await _browser.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false); + return Addresses.WithoutQuery(url); } catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or KeyNotFoundException or InvalidOperationException) { @@ -380,7 +412,7 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos { try { - await _browser.Host.RestAsync().ConfigureAwait(false); + await _browser.RestAsync(CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException) { @@ -388,6 +420,30 @@ internal sealed class ServerConnectionService : IConnectionService, IAsyncDispos } } + private async Task ShowQuietlyAsync(CancellationToken ct) + { + try + { + await _browser.ShowToUserAsync(ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or IOException) + { + _log.Warn("collegamento", "La finestra del browser non è venuta in primo piano.", ex); + } + } + + private async Task HideQuietlyAsync() + { + try + { + await _browser.HideFromUserAsync(CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or IOException) + { + _log.Warn("collegamento", "La finestra del browser non si è nascosta.", ex); + } + } + private void ReleaseLease() { IDisposable? lease; diff --git a/src/Febe.Server/BrowserSupervisor.cs b/src/Febe.App/ChromiumBrowser.cs similarity index 56% rename from src/Febe.Server/BrowserSupervisor.cs rename to src/Febe.App/ChromiumBrowser.cs index 9d1af8a..893b5a2 100644 --- a/src/Febe.Server/BrowserSupervisor.cs +++ b/src/Febe.App/ChromiumBrowser.cs @@ -1,59 +1,107 @@ using System.Globalization; +using Febe.Browser.Cdp; using Febe.Browser.Hosting; using Febe.Core.Abstractions; -namespace Febe.Server; +namespace Febe.App; + +/// How a Chromium-family browser is started and looked after (spec §6.1, §11; S2 fallback on Windows). +public sealed record ChromiumBrowserSettings +{ + /// The profile folder given to the browser (--user-data-dir): it holds the Instagram session. + public required string ProfileDirectory { get; init; } + + /// + /// The folder «Scollega» deletes while the browser is stopped. Null: . On Windows the + /// Edge profile is a subfolder of Dati\browser, and «Scollega» deletes the whole Dati\browser. + /// + public string? ProfileFolderToDelete { get; init; } + + /// Folder created before the start (Docker: the HOME of the browser process). Null: none. + public string? HomeDirectory { get; init; } + + /// Size of the browser window, always the same (spec §6.1). + public int WindowWidth { get; init; } = 1280; + + public int WindowHeight { get; init; } = 900; + + /// The fixed DevTools port, on 127.0.0.1 only (spec §6.1). + public int DebugPort { get; init; } = 9222; + + /// The executable; null: . + public string? ExecutablePath { get; init; } + + /// The Xvfb display (Docker, «:99»). Null: no virtual display, the browser opens a normal window. + public string? Display { get; init; } + + /// Arguments, environment, cookie of the session, restart policy. + public ChromiumLaunchOptions Launch { get; init; } = new(); + + /// Added to the «browser ready» log line (Docker: «, senza sandbox (FEBE_SENZA_SANDBOX)»). + public string? ReadyRemark { get; init; } + + /// Added to a start error that mentions the sandbox (Docker: where the seccomp profile is explained). + public string? SandboxAdvice { get; init; } +} /// -/// 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 and restart what crashes. +/// A Chromium-family browser started and supervised by Febe itself, never by a shell script (spec §5, §6.1, §11): the +/// distribution's Chromium on Xvfb in Docker, or Edge on Windows as the last fallback of S2. A start that fails +/// (browser missing, sandbox refused, port taken) is retried with a growing wait; once running, the supervisors of +/// and restart what crashes. /// -internal sealed class BrowserSupervisor : IAsyncDisposable +public sealed class ChromiumBrowser : IFebeBrowser { 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 ChromiumBrowserSettings _settings; private readonly IClock _clock; - private readonly ServerLog _log; + private readonly FebeLog _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) + public ChromiumBrowser(ChromiumBrowserSettings settings, IClock clock, FebeLog log) { - _options = options ?? throw new ArgumentNullException(nameof(options)); + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); 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()); + ProfileDirectory = Path.GetFullPath(settings.ProfileDirectory); + HomeDirectory = settings.HomeDirectory is { } home ? Path.GetFullPath(home) : null; + Host = new ChromiumProcessHost(settings.Launch, _clock, log.ForBrowser()); BrowserOptions = new BrowserOptions( ProfileDirectory, - options.WindowWidth, - options.WindowHeight, - options.DebugPort, - options.ChromiumPath, - UsesXvfb ? options.Display : null); + settings.WindowWidth, + settings.WindowHeight, + settings.DebugPort, + settings.ExecutablePath, + settings.Display); } - /// The browser: stable for the whole life of the server (a «Scollega» restarts it in place). + /// The browser: stable for the whole life of the composition (a «Scollega» restarts it in place). public ChromiumProcessHost Host { get; } public BrowserOptions BrowserOptions { get; } - /// Dati/browser: holds the Instagram session. + public ICdpSession Cdp => Host.Cdp; + + public UserDrivingGate UserDriving => Host.UserDriving; + public string ProfileDirectory { get; } - /// HOME of the browser process (certificate database, font cache). - public string HomeDirectory { get; } + /// HOME of the browser process (certificate database, font cache); null when not set. + public string? HomeDirectory { get; } - /// Linux needs the virtual display; elsewhere (development on Windows) the browser opens a normal window. - public static bool UsesXvfb => OperatingSystem.IsLinux(); + public int WindowWidth => BrowserOptions.WindowWidth; + + public int WindowHeight => BrowserOptions.WindowHeight; + + /// True when the browser runs on a virtual display (Docker). + public bool UsesXvfb => _settings.Display is not null; /// True when the browser runs and a page connection is attached. public bool IsAvailable => _started && Host.IsAttached; @@ -61,12 +109,10 @@ internal sealed class BrowserSupervisor : IAsyncDisposable /// Completes when the browser started the first time. public Task Ready => _ready.Task; - /// Why the last start failed, in Italian (for the log and the connection status); null when running. public string? LastError => _lastError; public bool UserIsDriving => Host.UserIsDriving; - /// Starts Xvfb and Chromium, retrying until it works or is cancelled. public async Task RunAsync(CancellationToken ct) { for (var attempt = 0; !ct.IsCancellationRequested; attempt++) @@ -77,7 +123,7 @@ internal sealed class BrowserSupervisor : IAsyncDisposable _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)}."); + _log.Info("browser", $"Browser pronto: finestra {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, porta di debug {_settings.DebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1{_settings.ReadyRemark}."); return; } catch (OperationCanceledException) when (ct.IsCancellationRequested) @@ -103,9 +149,17 @@ internal sealed class BrowserSupervisor : IAsyncDisposable } } + public Task RestAsync(CancellationToken ct) => Host.RestAsync(ct); + + /// Nothing: in Docker the remote view shows the browser (on Windows, EdgeBrowser moves the window). + public Task ShowToUserAsync(CancellationToken ct) => Task.CompletedTask; + + /// Nothing: on Xvfb the window is never in anyone's view. + public Task HideFromUserAsync(CancellationToken ct) => Task.CompletedTask; + /// - /// «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. + /// «Scollega» (spec §4.1): stops the browser (SIGINT on Linux, so it closes cleanly), deletes the profile folder with + /// the Instagram session, and starts the browser again with an empty profile. /// public async Task RestartWithEmptyProfileAsync(CancellationToken ct) { @@ -126,11 +180,15 @@ internal sealed class BrowserSupervisor : IAsyncDisposable private async Task StartOnceAsync(CancellationToken ct) { - Directory.CreateDirectory(HomeDirectory); - if (UsesXvfb && _xvfb is null) + if (HomeDirectory is { } home) { - RemoveStaleDisplayLock(_options.Display); - var xvfb = new XvfbProcess(_options.Display, _options.WindowWidth, _options.WindowHeight, clock: _clock, log: _log.ForBrowser()); + Directory.CreateDirectory(home); + } + + if (_settings.Display is { } display && _xvfb is null) + { + RemoveStaleDisplayLock(display); + var xvfb = new XvfbProcess(display, WindowWidth, WindowHeight, clock: _clock, log: _log.ForBrowser()); await xvfb.StartAsync(ct).ConfigureAwait(false); _xvfb = xvfb; } @@ -158,9 +216,10 @@ internal sealed class BrowserSupervisor : IAsyncDisposable private void DeleteProfile() { - if (Directory.Exists(ProfileDirectory)) + var folder = _settings.ProfileFolderToDelete is { } root ? Path.GetFullPath(root) : ProfileDirectory; + if (Directory.Exists(folder)) { - Directory.Delete(ProfileDirectory, recursive: true); + Directory.Delete(folder, recursive: true); } } @@ -228,13 +287,12 @@ internal sealed class BrowserSupervisor : IAsyncDisposable } } - private static string Explain(Exception ex) => ex switch + private 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.", + InvalidOperationException when ex.Message.Contains("sandbox", StringComparison.OrdinalIgnoreCase) => ex.Message + _settings.SandboxAdvice, _ => $"{ex.GetType().Name}: {ex.Message}", }; } diff --git a/src/Febe.Server/DeferredRecipeRunner.cs b/src/Febe.App/DeferredRecipeRunner.cs similarity index 92% rename from src/Febe.Server/DeferredRecipeRunner.cs rename to src/Febe.App/DeferredRecipeRunner.cs index bfbb669..b64837a 100644 --- a/src/Febe.Server/DeferredRecipeRunner.cs +++ b/src/Febe.App/DeferredRecipeRunner.cs @@ -1,13 +1,13 @@ using Febe.Core.Engine; -namespace Febe.Server; +namespace Febe.App; /// /// 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 /// is set, so a recipe never runs without it. /// -internal sealed class DeferredRecipeRunner : IRecipeRunner +public sealed class DeferredRecipeRunner : IRecipeRunner { private volatile IRecipeRunner? _target; diff --git a/src/Febe.App/Febe.App.csproj b/src/Febe.App/Febe.App.csproj new file mode 100644 index 0000000..e537fea --- /dev/null +++ b/src/Febe.App/Febe.App.csproj @@ -0,0 +1,15 @@ + + + + + + + + + + + + + diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs new file mode 100644 index 0000000..73c9e1e --- /dev/null +++ b/src/Febe.App/FebeApp.cs @@ -0,0 +1,639 @@ +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; +using Microsoft.Extensions.Logging; + +namespace Febe.App; + +/// +/// The engine of Febe composed once for both shells (spec §5 «I due involucri»): Febe.Server (Docker) and Febe.Desktop +/// (Windows) differ only in their . Start-up checks first: with a problem (password missing +/// in Docker, Data folder not writable or on a network share, WebView2 missing on Windows) 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, the browser of the platform, the collection pipeline, the download queue, +/// the engine, the connection, the alerts hook and the interface. Disposing stops everything in order. +/// +public sealed class FebeApp : IAsyncDisposable +{ + private readonly FebeAppOptions _options; + private readonly IFebePlatform _platform; + private readonly CancellationTokenSource _lifetime = new(); + private readonly List _background = []; + private readonly List _disposables = []; + private readonly List _unsubscribe = []; + private readonly TaskCompletionSource _running = new(TaskCreationOptions.RunContinuationsAsynchronously); + private string? _temporaryFolder; + private int _disposed; + + private FebeApp(FebeAppOptions options, IFebePlatform platform, FebeLog log, IClock clock, IReadOnlyList problems) + { + _options = options; + _platform = platform; + Log = log; + Clock = clock; + Problems = problems; + } + + public IClock Clock { get; } + + public FebeLog Log { get; } + + public FebeAppOptions Options => _options; + + public IFebePlatform Platform => _platform; + + public IReadOnlyList Problems { get; } + + public WebApplication Web { get; private set; } = null!; + + /// Where the interface answers (with 127.0.0.1 in place of «any address»). + public Uri Address { get; private set; } = null!; + + public FebeDatabase Database { get; private set; } = null!; + + public DataFolderLayout? Data { get; private set; } + + /// The library layout at start-up (the desktop may change the folder later: ). + public LibraryLayout? Library { get; private set; } + + public IFebeBrowser? Browser { get; private set; } + + public BrowserConnectionService? Connection { 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; } + + /// When Alberto last used the browser («Riprendi» after a verification). + public BrowserUseTracker Tracker { get; } = new(); + + /// The alerts hook (null with a configuration problem). + public AlertDispatcher? Alerts { get; private set; } + + /// Completes when browser, pipeline and engine are running (never, with a configuration problem). + public Task Running => _running.Task; + + public static async Task StartAsync(FebeAppOptions options, IFebePlatform platform, FebeAppHooks? hooks = null, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(platform); + hooks ??= new FebeAppHooks(); + var clock = hooks.Clock ?? new SystemClock(options.Zone); + var problems = platform.CheckConfiguration(options, hooks.DataFolderCheck ?? new DataFolderCheck()); + var logFolder = problems.Count == 0 ? new DataFolderLayout(options.DataFolder).Logs : null; + var log = new FebeLog(logFolder, hooks.Console, clock); + var app = new FebeApp(options, platform, log, clock, problems); + try + { + foreach (var warning in options.Warnings) + { + log.Warn("avvio", warning); + } + + if (problems.Count > 0) + { + await app.StartWithProblemsAsync(hooks, ct).ConfigureAwait(false); + } + else + { + await app.StartNormallyAsync(hooks, ct).ConfigureAwait(false); + } + + return app; + } + catch + { + await app.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + /// + /// 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. + /// + private async Task StartWithProblemsAsync(FebeAppHooks 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(Database); + services.AddSingleton(library); + services.AddSingleton(Clock); + services.AddSingleton(Tracker); + services.AddSingleton(Import); + services.AddSingleton(new DailyBackup(Database, Clock, data.Backups)); + services.AddSingleton(new StartupProblems(Problems)); + services.AddSingleton(new ProblemConnectionService(Problems)); + _platform.RegisterProblemServices(services, this); + }).ConfigureAwait(false); + } + + private async Task StartNormallyAsync(FebeAppHooks hooks, CancellationToken ct) + { + var o = _options; + var random = hooks.Random ?? new SystemRandom(); + var data = new DataFolderLayout(o.DataFolder); + Data = data; + + // Database first: on Windows the library folder is a setting stored in it. + Database = await FebeDatabase.OpenAsync(data.Root, ct).ConfigureAwait(false); + var settings = await LibrarySettings.LoadAsync(Database.Settings, o.LibraryFolder, ct).ConfigureAwait(false); + var libraryRoot = o.LibraryFolderFromSettings ? settings.LibraryRoot : o.LibraryFolder; + var importRoot = o.ImportFolder is { } import ? Path.GetFullPath(import) : null; + Log.Info("avvio", $"Febe {typeof(FebeApp).Assembly.GetName().Version?.ToString(3)}: dati in {data.Root}, libreria in {Path.GetFullPath(libraryRoot)}{(importRoot is null ? string.Empty : ", importazioni da " + importRoot)}, 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."); + } + + // Library. + var layout = new LibraryLayout(libraryRoot); + 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). Docker: sources under /importa, read-only, over the fixed library; what was running when + // Febe stopped becomes «interrotto». Windows: the web layer's ImportHub builds the service over the library + // and builds it again when the library folder changes in Impostazioni (any source folder, native picker). + if (!o.LibraryFolderFromSettings) + { + 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 = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot), + DataFolder = data.Root, + }); + LogRecovered(await Import.RecoverAsync(ct).ConfigureAwait(false)); + } + + // Browser, connection, engine. The engine loop starts only once the browser is up. + var browser = await _platform.CreateBrowserAsync(new FebePlatformContext(o, data, Database, Clock, Log, Tracker), ct).ConfigureAwait(false); + Browser = browser; + var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, o.Site.SessionCookie); + Connection = connection; + 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); + EventHandler drivingChanged = (_, _) => engine.NotifyUserDrivingChanged(); + browser.UserDriving.Changed += drivingChanged; + _unsubscribe.Add(() => browser.UserDriving.Changed -= drivingChanged); + + await StartWebAsync(hooks, s => + { + s.AddSingleton(Database); + s.AddSingleton(library); + s.AddSingleton(Clock); + s.AddSingleton(Tracker); + s.AddSingleton(engine.Monitor); + s.AddSingleton(new EngineHostControl(engine)); + s.AddSingleton(connection); + s.AddSingleton(new EngineHostSettingsControl(engine)); + s.AddSingleton(ingest); + s.AddSingleton(new LiveBrowserPreview(browser, Clock)); + s.AddSingleton(new StartupProblems([])); + if (Import is not null) + { + s.AddSingleton(Import); + } + + s.AddSingleton(new DailyBackup(Database, Clock, data.Backups)); + _platform.RegisterServices(s, this); + }).ConfigureAwait(false); + + if (Import is null) + { + // The hub's own service: built now, so that an import interrupted by the last stop is marked at once. + await Web.Services.GetRequiredService().GetAsync(ct).ConfigureAwait(false); + } + + // The alerts hook: the channels the shell registered (Windows notifications; Telegram with M8). + Alerts = new AlertDispatcher(services.Events, Database.Settings, Web.Services.GetServices(), Log); + + // 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(FebeAppHooks hooks, Action register) + { + var web = FebeWebHost.Build( + _platform.WebOptions, + _platform.Listen, + services => + { + register(services); + services.Configure(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)}."); + } + + /// The browser, then the pipeline, the downloads, the connection check and the engine. + 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.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(); + _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(EngineEventCodes.RecipePrefix, 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); + } + } + + /// + /// Development with the test site only (--accesso-di-prova): what Alberto does by hand on Instagram — open + /// the site once, so that its session cookie exists — then back to the rest page. + /// + private async Task TestSiteLoginAsync(CancellationToken ct) + { + var browser = Browser!; + await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, _options.LoginUrl, ct).ConfigureAwait(false); + await Febe.Browser.Cdp.CdpPageExtensions.WaitForLoadAsync(browser.Cdp, Clock, TimeSpan.FromSeconds(15), ct).ConfigureAwait(false); + await browser.RestAsync(ct).ConfigureAwait(false); + await Connection!.RefreshAsync(ct).ConfigureAwait(false); + Log.Info("collegamento", "Sito di prova: accesso automatico fatto."); + } + + /// + /// 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. + /// + 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; + } + } + } + } + + /// The daily copy of the database (spec §8.5): at start-up if today's is missing, then once a day. + 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 ({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; + } + } + } + + /// The next copy: a few minutes after local midnight (03:20, outside the active window of every profile). + public 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; + } + + /// Temporary files left by an interrupted run (only .febe-*.part: never a library file, rule 12). + 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 LogRecovered(int recovered) + { + if (recovered > 0) + { + Log.Info("importazione", $"{recovered.ToString(CultureInfo.InvariantCulture)} importazioni interrotte dall'arresto precedente: si riprendono dalla pagina Importa."); + } + } + + 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); + } + } + + /// + /// Stops everything in order: the shell's own first (remote view), interface, engine, downloads, alerts, import, + /// pipeline, browser, database. + /// + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) == 1) + { + return; + } + + Log.Info("arresto", "Arresto in corso."); + await Quietly(_platform.StoppingAsync).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 (Alerts is { } alerts) + { + await Quietly(() => alerts.DisposeAsync().AsTask()).ConfigureAwait(false); + } + + 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, WebView2 closed and waited for, so that the session is written to the profile (S3). + 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 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); + } + } + } +} diff --git a/src/Febe.Server/ServerLog.cs b/src/Febe.App/FebeLog.cs similarity index 94% rename from src/Febe.Server/ServerLog.cs rename to src/Febe.App/FebeLog.cs index c77c5f4..90dbac2 100644 --- a/src/Febe.Server/ServerLog.cs +++ b/src/Febe.App/FebeLog.cs @@ -5,16 +5,16 @@ using Febe.Browser.Diagnostics; using Febe.Core.Abstractions; using Microsoft.Extensions.Logging; -namespace Febe.Server; +namespace Febe.App; /// -/// The log of the server (spec §8.2, §13.2): one file per local day in Dati/registro -/// (febe-AAAA-MM-GG.log), kept fourteen days, at most 20 MB a day, and the same lines on the console +/// The log of Febe, the same in both shells (spec §8.2, §13.2): one file per local day in Dati/registro +/// (febe-AAAA-MM-GG.log), kept fourteen days, at most 20 MB a day, and the same lines on the console, if any /// (docker logs). Only actions and outcomes: every message passes through , 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. /// -internal sealed partial class ServerLog : IDisposable +public sealed partial class FebeLog : IDisposable { public const int DefaultKeepDays = 14; @@ -40,7 +40,7 @@ internal sealed partial class ServerLog : IDisposable /// Time of the lines and of the daily file. /// Days of files kept. /// Above this the day's file stops growing (the console still gets the lines). - public ServerLog(string? folder, TextWriter? console, IClock clock, int keepDays = DefaultKeepDays, long maxBytesPerDay = DefaultMaxBytesPerDay) + public FebeLog(string? folder, TextWriter? console, IClock clock, int keepDays = DefaultKeepDays, long maxBytesPerDay = DefaultMaxBytesPerDay) { _folder = folder is null ? null : Path.GetFullPath(folder); _console = console; @@ -231,7 +231,7 @@ internal sealed partial class ServerLog : IDisposable [GeneratedRegex(@"\b[a-zA-Z][a-zA-Z0-9+.-]*://\S+", RegexOptions.CultureInvariant)] private static partial Regex Addresses(); - private sealed class Provider(ServerLog log) : ILoggerProvider + private sealed class Provider(FebeLog log) : ILoggerProvider { public ILogger CreateLogger(string categoryName) => new Logger(log, categoryName); @@ -240,7 +240,7 @@ internal sealed partial class ServerLog : IDisposable } } - private sealed class Logger(ServerLog log, string category) : ILogger + private sealed class Logger(FebeLog log, string category) : ILogger { public IDisposable? BeginScope(TState state) where TState : notnull => null; diff --git a/src/Febe.App/IFebeBrowser.cs b/src/Febe.App/IFebeBrowser.cs new file mode 100644 index 0000000..ab3ef18 --- /dev/null +++ b/src/Febe.App/IFebeBrowser.cs @@ -0,0 +1,53 @@ +using Febe.Browser.Cdp; +using Febe.Browser.Hosting; +using Febe.Core.Abstractions; + +namespace Febe.App; + +/// +/// The browser of Febe as the shared composition sees it (spec §5, §6.1): Chromium on Xvfb in Docker, WebView2 in the +/// window «Browser di Febe» on Windows, or Edge started as a process (the last fallback of S2). It owns the +/// , starts it with retries, and does the few things the composition needs around it: rest +/// page, «Alberto is driving», showing and hiding the window, «Scollega». +/// +public interface IFebeBrowser : IAsyncDisposable +{ + /// The page session: stable for the whole life of the composition (a restart keeps the same object). + ICdpSession Cdp { get; } + + /// Leases taken while Alberto uses the browser (connection page, remote view, the window in front). + UserDrivingGate UserDriving { get; } + + /// True while at least one lease is open: the engine does not act. + bool UserIsDriving { get; } + + /// True when the browser runs and commands can be sent. + bool IsAvailable { get; } + + /// Why the last start failed, in Italian; null when running. + string? LastError { get; } + + /// Dati/browser: holds the Instagram session. + string ProfileDirectory { get; } + + /// Width of the page, always the same (spec §6.1). + int WindowWidth { get; } + + /// Height of the page, always the same (spec §6.1). + int WindowHeight { get; } + + /// Starts the browser, retrying with a growing wait until it works or is cancelled. + Task RunAsync(CancellationToken ct); + + /// Puts the browser at rest on the blank page (spec §6.1). + Task RestAsync(CancellationToken ct); + + /// Windows: brings the browser window to the front. Docker: nothing (the remote view shows it). + Task ShowToUserAsync(CancellationToken ct); + + /// Windows: puts the window out of view, still open and painting (S2). Docker: nothing. + Task HideFromUserAsync(CancellationToken ct); + + /// «Scollega» (spec §4.1): closes the browser, deletes the profile folder and starts it again empty. + Task RestartWithEmptyProfileAsync(CancellationToken ct); +} diff --git a/src/Febe.App/IFebePlatform.cs b/src/Febe.App/IFebePlatform.cs new file mode 100644 index 0000000..607c0b0 --- /dev/null +++ b/src/Febe.App/IFebePlatform.cs @@ -0,0 +1,118 @@ +using Febe.Browser.Recipes; +using Febe.Core.Abstractions; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Web; +using Febe.Web.Connection; +using Febe.Web.Engine; +using Microsoft.Extensions.DependencyInjection; + +namespace Febe.App; + +/// +/// The parts of a shell that differ between Docker and Windows (spec §5 «I due involucri»): how the interface is +/// protected and where it listens, which checks stop the engine at start-up, which browser visits the site and how it +/// is supervised, and the native services (folder picker, notifications, remote view…). Everything else — database, +/// library, import, backups, collection pipeline, downloads, engine, connection, alerts, web host — is +/// , the same for both. +/// +public interface IFebePlatform +{ + /// Interface options: edition, access (password in Docker, per-start token on Windows), allowed hosts. + FebeWebOptions WebOptions { get; } + + /// Where Kestrel listens (Docker: every address on 8480; Windows: 127.0.0.1 on a port chosen at start-up). + FebeListen Listen { get; } + + /// + /// Problems that keep the engine and the browser from starting (spec §8.2, §11, §12). With any, only the interface + /// starts, on a temporary database, and shows the page that explains them. + /// + IReadOnlyList CheckConfiguration(FebeAppOptions options, DataFolderCheck dataFolderCheck); + + /// The browser of this shell. Called once, after the database is open and before the engine exists. + Task CreateBrowserAsync(FebePlatformContext context, CancellationToken ct); + + /// + /// Services of this shell for a normal start, registered before the web layer (whose fallbacks use TryAdd): + /// native shell, browser window, remote view, change of the Data folder, alert channels. + /// + void RegisterServices(IServiceCollection services, FebeApp app); + + /// Services of this shell while a configuration problem keeps everything else still. + void RegisterProblemServices(IServiceCollection services, FebeApp app); + + /// Called first when the composition stops (Docker: the open remote view is closed with its reason). + Task StoppingAsync(); +} + +/// What a platform gets to build its browser. +/// The options of the composition. +/// The Data folder (profile in ). +/// The database (settings of the shell, e.g. the S2 hosting mode on Windows). +/// The clock of the engine. +/// The log. +/// When Alberto last used the browser: the desktop window marks it when he uses and closes it. +public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker); + +/// Options of the shared composition, filled by each shell from its own configuration. +public sealed record FebeAppOptions +{ + /// Data folder: database, browser profile, thumbnails, backups, log (Docker /dati; Windows %LOCALAPPDATA%\Febe). + public required string DataFolder { get; init; } + + /// Library folder (Docker /libreria, fixed; Windows Immagini\Febe, the default of the setting). + public required string LibraryFolder { get; init; } + + /// + /// Windows: the library folder chosen in Impostazioni (stored in the database) wins over , + /// which is only its default. Docker: false, the volume decides. + /// + public bool LibraryFolderFromSettings { get; init; } + + /// Docker: the read-only root of the import sources (/importa). Null: any folder, chosen with the picker. + public string? ImportFolder { get; init; } + + /// Time zone of the engine, of file names and (Docker) of the browser. + public string ZoneId { get; init; } = "Europe/Rome"; + + public TimeZoneInfo Zone { get; init; } = TimeZoneInfo.Local; + + /// Language of the browser, for the log (Docker: LANG; Windows: the language of the system). + public string Language { get; init; } = "it_IT.UTF-8"; + + /// The site the browser works on: Instagram, or the local test site in development. + public CollectionSite Site { get; init; } = CollectionSite.Instagram; + + /// The page «Accedi a Instagram» opens. + public string LoginUrl { get; init; } = "https://www.instagram.com/accounts/login/"; + + /// Development: the local test site (only for the warning in the log). + public Uri? TestSite { get; init; } + + /// Development, test site only: opens the site once at start-up so its session cookie exists. + public bool TestSiteAutoLogin { get; init; } + + /// Development: the first session comes after this delay instead of 2–10 minutes. + public TimeSpan? FirstSessionDelay { get; init; } + + /// Warnings found while reading the configuration, for the log. + public IReadOnlyList Warnings { get; init; } = []; +} + +/// Things tests (and only tests) replace in the composition. +public sealed record FebeAppHooks +{ + public IClock? Clock { get; init; } + + public IRandomSource? Random { get; init; } + + /// The Data folder check (tests inject a mount table with a network share). + public DataFolderCheck? DataFolderCheck { get; init; } + + /// Console writer for the log; null: none (the desktop has no console). + public TextWriter? Console { get; init; } + + /// How long the web host waits for open requests (events, remote view) when stopping. + public TimeSpan ShutdownTimeout { get; init; } = TimeSpan.FromSeconds(3); +} diff --git a/src/Febe.Server/ServerBrowserPreview.cs b/src/Febe.App/LiveBrowserPreview.cs similarity index 58% rename from src/Febe.Server/ServerBrowserPreview.cs rename to src/Febe.App/LiveBrowserPreview.cs index 9fdd59c..862f57f 100644 --- a/src/Febe.Server/ServerBrowserPreview.cs +++ b/src/Febe.App/LiveBrowserPreview.cs @@ -1,17 +1,16 @@ using Febe.Browser.Cdp; -using Febe.Browser.Hosting; using Febe.Browser.RemoteView; using Febe.Core.Abstractions; using Febe.Web.Engine; -namespace Febe.Server; +namespace Febe.App; /// /// 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. +/// rest page there is nothing to show. The same in both shells. /// -internal sealed class ServerBrowserPreview(BrowserSupervisor browser, IClock clock) : IBrowserPreview +public sealed class LiveBrowserPreview(IFebeBrowser browser, IClock clock) : IBrowserPreview { private static readonly TimeSpan MinimumAge = TimeSpan.FromSeconds(4); private readonly SemaphoreSlim _gate = new(1, 1); @@ -33,15 +32,15 @@ internal sealed class ServerBrowserPreview(BrowserSupervisor browser, IClock clo return cached; } - var url = await browser.Host.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false); + var url = await browser.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); + var jpeg = await PagePreview.CaptureAsync(browser.Cdp, ct: ct).ConfigureAwait(false); + _last = new BrowserFrame(jpeg, Addresses.WithoutQuery(url), now); return _last; } catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or KeyNotFoundException or InvalidOperationException) @@ -54,3 +53,20 @@ internal sealed class ServerBrowserPreview(BrowserSupervisor browser, IClock clo } } } + +/// Addresses as Febe may show them. +public static class Addresses +{ + /// The address without query string or fragment (they may carry tokens). + public static string WithoutQuery(string url) + { + ArgumentNullException.ThrowIfNull(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; + } +} diff --git a/src/Febe.App/StartupProblems.cs b/src/Febe.App/StartupProblems.cs new file mode 100644 index 0000000..77338b6 --- /dev/null +++ b/src/Febe.App/StartupProblems.cs @@ -0,0 +1,54 @@ +using Febe.Core.Library; +using Febe.Web.Connection; + +namespace Febe.App; + +/// The problems found at start-up; fixed for the life of the process (fixing one needs a restart). +public sealed class StartupProblems(IReadOnlyList problems) : IConfigurationProblems +{ + public IReadOnlyList Current { get; } = problems; +} + +/// Checks shared by both shells (spec §8.2): the Data folder is local and writable. +public static class DataFolderProblems +{ + public const string DataNotWritable = "dati-non-scrivibili"; + + public const string DataOnNetwork = "dati-in-rete"; + + /// The problem with the Data folder, or null when it is fine. + public static ConfigurationProblem? Check(string dataFolder, DataFolderCheck? check = null) + { + if ((check ?? new DataFolderCheck()).Check(dataFolder) is not { } data) + { + return null; + } + + return new ConfigurationProblem( + data.Kind == DataFolderProblemKind.NetworkPath ? DataOnNetwork : DataNotWritable, + data.Title, + data.Explanation, + data.Remedy); + } +} + +/// +/// 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). +/// +public sealed class ProblemConnectionService(IReadOnlyList problems) : IConnectionService +{ + public Task GetStatusAsync(CancellationToken ct) => + Task.FromResult(new ConnectionStatus(ConnectionState.BrowserUnavailable, null, null, false, null)); + + public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct) => throw Refused(); + + public Task 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."); +} diff --git a/src/Febe.Browser/WebView2/WebView2CdpSession.cs b/src/Febe.Browser/WebView2/WebView2CdpSession.cs new file mode 100644 index 0000000..5f641ed --- /dev/null +++ b/src/Febe.Browser/WebView2/WebView2CdpSession.cs @@ -0,0 +1,347 @@ +using System.Text; +using System.Text.Json; +using System.Threading.Channels; +using Febe.Browser.Cdp; +using Febe.Browser.Diagnostics; +using Febe.Core.Abstractions; + +namespace Febe.Browser.WebView2; + +/// +/// The two WebView2 calls Febe needs for the DevTools protocol (spec §6.1, Windows): CallDevToolsProtocolMethodAsync +/// and GetDevToolsProtocolEventReceiver, never the deprecated DevToolsProtocolExtension package. The desktop +/// implements it on CoreWebView2, on the UI thread; tests use a fake. Everything else — the allowlist, the +/// read-only guard, JSON, event dispatch, logging — is , testable without Windows. +/// +public interface IWebView2DevTools +{ + /// + /// CoreWebView2.CallDevToolsProtocolMethodAsync(methodName, parametersAsJson): the result object as JSON. A + /// protocol error faults the task; its message may carry the error object ({"code":…,"message":…}). When the + /// WebView is gone the task faults with . + /// + Task CallMethodAsync(string methodName, string parametersAsJson); + + /// + /// GetDevToolsProtocolEventReceiver(eventName).DevToolsProtocolEventReceived: gets + /// ParameterObjectAsJson. Disposing removes the handler. + /// + IDisposable Subscribe(string eventName, Action onEvent); +} + +/// Options of . +/// How long to wait for the answer to a command before giving up (60 s by default). +public sealed record WebView2CdpOptions(TimeSpan? CommandTimeout = null) +{ + internal TimeSpan EffectiveTimeout => CommandTimeout ?? TimeSpan.FromSeconds(60); +} + +/// +/// The of WebView2 (spec §5, §6.1): the same rules as over the two +/// WebView2 calls of . +/// +/// +/// +/// Only commands of are sent; Runtime.evaluate also passes +/// . A refused command never reaches WebView2. +/// The log receives command and event names only: never parameters, results, event payloads or the text of +/// WebView2's exceptions (a protocol error keeps only its code and message, like ). +/// Events arrive on WebView2's UI thread; they are queued and handed to the handlers in order on one background +/// loop, so a slow handler never blocks the window and a handler may send commands without deadlocking it. +/// Like : subscriptions survive a new WebView ( after the +/// browser process restarted), and commands fail fast with while detached. +/// +/// +public sealed class WebView2CdpSession : ICdpSession, ICdpConnectionEvents, IAsyncDisposable +{ + private static readonly JsonSerializerOptions ParameterOptions = new(JsonSerializerDefaults.Web) + { + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, + }; + + private readonly IBrowserLog _log; + private readonly WebView2CdpOptions _options; + private readonly Lock _gate = new(); + private readonly Dictionary>> _handlers = new(StringComparer.Ordinal); + private readonly Dictionary _native = new(StringComparer.Ordinal); + private readonly Channel _events = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true }); + private readonly Task _dispatch; + private IWebView2DevTools? _devTools; + private bool _everAttached; + private int _disposed; + + public WebView2CdpSession(IBrowserLog? log = null, WebView2CdpOptions? options = null) + { + _log = log ?? NullBrowserLog.Instance; + _options = options ?? new WebView2CdpOptions(); + _dispatch = Task.Run(DispatchLoopAsync); + } + + /// Raised after replaced an earlier WebView (not for the first one). + public event EventHandler? Reconnected; + + /// True while a WebView is attached. + public bool IsAttached + { + get + { + lock (_gate) + { + return _devTools is not null; + } + } + } + + /// Uses from now on and subscribes it to every event that has handlers. + public void Attach(IWebView2DevTools devTools) + { + ArgumentNullException.ThrowIfNull(devTools); + bool reconnect; + lock (_gate) + { + DetachLocked(); + _devTools = devTools; + foreach (var name in _handlers.Keys) + { + _native[name] = SubscribeNative(devTools, name); + } + + reconnect = _everAttached; + _everAttached = true; + } + + _log.Write(BrowserLogLevel.Debug, "CDP: WebView2 collegato."); + if (reconnect) + { + Reconnected?.Invoke(this, EventArgs.Empty); + } + } + + /// Stops using the current WebView (it is closing or gone); commands fail until the next . + public void Detach() + { + lock (_gate) + { + DetachLocked(); + } + } + + public async Task SendAsync(string method, object? parameters = null, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrEmpty(method); + CdpCommandPolicy.EnsureAllowed(method); + var node = CdpParameters.ToNode(parameters, ParameterOptions); + if (method == "Runtime.evaluate") + { + ReadOnlyScriptGuard.EnsureReadOnly(CdpParameters.GetString(node, "expression")); + } + + IWebView2DevTools devTools; + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed == 1, this); + devTools = _devTools ?? throw new BrowserUnavailableException(); + } + + var json = node?.ToJsonString() ?? "{}"; + _log.Write(BrowserLogLevel.Debug, $"CDP → {method}"); + string result; + try + { + result = await devTools.CallMethodAsync(method, json).WaitAsync(_options.EffectiveTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + throw new TimeoutException($"Il browser non ha risposto al comando «{method}» entro {_options.EffectiveTimeout.TotalSeconds:0} s."); + } + catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or OperationCanceledException) + { + throw; + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + var error = ProtocolError(method, ex); + _log.Write(BrowserLogLevel.Debug, $"CDP ✗ {method} (codice {error.Code})"); + throw error; + } + + return Parse(result); + } + + public IDisposable On(string eventName, Action handler) + { + ArgumentException.ThrowIfNullOrEmpty(eventName); + ArgumentNullException.ThrowIfNull(handler); + lock (_gate) + { + if (!_handlers.TryGetValue(eventName, out var list)) + { + list = []; + _handlers[eventName] = list; + if (_devTools is { } devTools) + { + _native[eventName] = SubscribeNative(devTools, eventName); + } + } + + list.Add(handler); + } + + return new Subscription(() => + { + lock (_gate) + { + if (_handlers.TryGetValue(eventName, out var list) && list.Remove(handler) && list.Count == 0) + { + _handlers.Remove(eventName); + if (_native.Remove(eventName, out var native)) + { + native.Dispose(); + } + } + } + }); + } + + /// Waits until every event received so far was handed to its handlers (tests). + public Task DrainAsync() + { + var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + if (!_events.Writer.TryWrite(new QueuedEvent(string.Empty, string.Empty, done))) + { + done.TrySetResult(); + } + + return done.Task; + } + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) == 1) + { + return; + } + + lock (_gate) + { + DetachLocked(); + } + + _events.Writer.TryComplete(); + await _dispatch.ConfigureAwait(false); + } + + /// + /// The protocol error of a failed WebView2 call. WebView2 puts the error object in the exception's message; only its + /// code and message are kept (never the text around it nor its data, which can echo parameters). + /// + internal static CdpCommandException ProtocolError(string method, Exception ex) + { + var bytes = Encoding.UTF8.GetBytes(ex.Message ?? string.Empty); + CdpCommandException? found = null; + + // The last object with a numeric code and a string message: text and other JSON around it are ignored. + for (var i = Array.IndexOf(bytes, (byte)'{'); i >= 0; i = Array.IndexOf(bytes, (byte)'{', i + 1)) + { + try + { + var reader = new Utf8JsonReader(bytes.AsSpan(i)); + using var document = JsonDocument.ParseValue(ref reader); + var root = document.RootElement; + if (root.ValueKind == JsonValueKind.Object + && root.TryGetProperty("message", out var m) && m.ValueKind == JsonValueKind.String + && root.TryGetProperty("code", out var c) && c.TryGetInt32(out var code)) + { + found = new CdpCommandException(method, code, m.GetString() ?? string.Empty); + } + } + catch (JsonException) + { + } + } + + return found ?? new CdpCommandException(method, ex.HResult, "errore di WebView2"); + } + + private static JsonElement Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + return default; + } + + // ParseValue yields a self-contained element and needs no serializer (trimmed and single-file builds). + var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json)); + return JsonElement.ParseValue(ref reader); + } + + private IDisposable SubscribeNative(IWebView2DevTools devTools, string eventName) => + devTools.Subscribe(eventName, json => _events.Writer.TryWrite(new QueuedEvent(eventName, json ?? string.Empty, null))); + + private void DetachLocked() + { + foreach (var native in _native.Values) + { + try + { + native.Dispose(); + } + catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException or CdpDisconnectedException) + { + // The WebView is already gone: its handlers went with it. + } + } + + _native.Clear(); + _devTools = null; + } + + private async Task DispatchLoopAsync() + { + await foreach (var (name, json, drained) in _events.Reader.ReadAllAsync().ConfigureAwait(false)) + { + if (drained is not null) + { + drained.TrySetResult(); + continue; + } + + Action[] handlers; + lock (_gate) + { + if (!_handlers.TryGetValue(name, out var list) || list.Count == 0) + { + continue; + } + + handlers = [.. list]; + } + + JsonElement parameters; + try + { + parameters = Parse(json); + } + catch (JsonException ex) + { + _log.Write(BrowserLogLevel.Warning, $"CDP: evento {name} non leggibile.", ex); + continue; + } + + foreach (var handler in handlers) + { + try + { + handler(parameters); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + _log.Write(BrowserLogLevel.Warning, $"CDP: errore nel gestore dell'evento {name}.", ex); + } + } + } + } + + /// An event waiting for its handlers, or (with ) the mark of . + private readonly record struct QueuedEvent(string Name, string Json, TaskCompletionSource? Drained); +} diff --git a/src/Febe.Core/Library/LibraryIngest.cs b/src/Febe.Core/Library/LibraryIngest.cs index 8d47112..d35a0b0 100644 --- a/src/Febe.Core/Library/LibraryIngest.cs +++ b/src/Febe.Core/Library/LibraryIngest.cs @@ -90,6 +90,20 @@ public sealed class LibraryIngest( private readonly SafeFileWriter _writer = writer ?? new SafeFileWriter(layout.MaxPathLength); private volatile LibraryNaming _naming = naming; private volatile bool _setFileTimeToPublication = setFileTimeToPublication; + private volatile LibraryLayout _layout = layout; + + /// The library the next files go to. + public LibraryLayout Layout => _layout; + + /// + /// The library folder changed (desktop, Impostazioni ▸ Generali): the next files go to the new folder. Accounts whose + /// folder already exists were fixed to it before the change, so nothing moves (spec §4.7, rule 12). + /// + public void UseLayout(LibraryLayout newLayout) + { + ArgumentNullException.ThrowIfNull(newLayout); + _layout = newLayout; + } /// /// Applies new naming schemes and the file-time choice from the settings page. They hold for the next files only: @@ -133,6 +147,7 @@ public sealed class LibraryIngest( throw new ArgumentException("Il file deve appartenere all'elemento e l'elemento all'account, già registrati nel database.", nameof(media)); } + var layout = _layout; var folder = layout.AccountFolder(account); var scheme = _naming.For(entry.Kind); var zone = clock.LocalZone; @@ -238,7 +253,7 @@ public sealed class LibraryIngest( ?? throw new KeyNotFoundException($"Account {stored.Entry.AccountId} non trovato."); var highlights = await storage.Highlights.ListForEntryAsync(entryId, ct).ConfigureAwait(false); await journal.AppendSavedAsync( - layout.AccountFolder(account), + _layout.AccountFolder(account), account, stored.Entry, stored.Media, diff --git a/src/Febe.Desktop.Core/Autostart.cs b/src/Febe.Desktop.Core/Autostart.cs new file mode 100644 index 0000000..bd331c1 --- /dev/null +++ b/src/Febe.Desktop.Core/Autostart.cs @@ -0,0 +1,68 @@ +namespace Febe.Desktop.Core; + +/// +/// «Avvia Febe all'accensione del computer» (spec §12): the value Febe under +/// HKCU\Software\Microsoft\Windows\CurrentVersion\Run, per user, no administrator rights. Febe then starts with +/// --nascosto: only the icon in the notification area, the window stays closed. +/// +public static class Autostart +{ + /// The registry key, under HKEY_CURRENT_USER. + public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; + + /// The name of the value. + public const string ValueName = "Febe"; + + /// The command written in the value: the quoted executable and --nascosto. + public static string Command(string executable) + { + ArgumentException.ThrowIfNullOrWhiteSpace(executable); + if (executable.Contains('"', StringComparison.Ordinal)) + { + throw new ArgumentException("Percorso dell'eseguibile non valido.", nameof(executable)); + } + + return $"\"{executable}\" --nascosto"; + } + + /// True when starts this executable (a value left by another copy of Febe is not ours). + public static bool PointsTo(string? value, string executable) + { + if (string.IsNullOrWhiteSpace(value) || string.IsNullOrWhiteSpace(executable)) + { + return false; + } + + var text = value.Trim(); + string target; + if (text.StartsWith('"')) + { + var end = text.IndexOf('"', 1); + if (end < 0) + { + return false; + } + + target = text[1..end]; + } + else + { + var space = text.IndexOf(' ', StringComparison.Ordinal); + target = space < 0 ? text : text[..space]; + } + + return string.Equals(Normalize(target), Normalize(executable), StringComparison.OrdinalIgnoreCase); + } + + private static string Normalize(string path) + { + try + { + return Path.GetFullPath(path); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return path; + } + } +} diff --git a/src/Febe.Desktop.Core/BrandIcon.cs b/src/Febe.Desktop.Core/BrandIcon.cs new file mode 100644 index 0000000..88c3e38 --- /dev/null +++ b/src/Febe.Desktop.Core/BrandIcon.cs @@ -0,0 +1,246 @@ +using System.Buffers.Binary; +using SkiaSharp; + +namespace Febe.Desktop.Core; + +/// +/// The brand mark of appendix C — a rounded square in the accent colour with a ring and a dot, a body and its moon — +/// drawn with SkiaSharp at any size, the same way the SVG describes it: +/// +/// <rect width="32" height="32" rx="8" fill="#0F5C8C"/> +/// <circle cx="14.5" cy="17.5" r="7.4" fill="none" stroke="#FFFFFF" stroke-width="2.6"/> +/// <circle cx="23.2" cy="8.8" r="3.1" fill="#FFFFFF"/> +/// +/// +public static class BrandMark +{ + /// The sizes of the Windows icon: window, notification area, taskbar, Explorer, installer. + public static IReadOnlyList IconSizes { get; } = [16, 24, 32, 48, 64, 128, 256]; + + private static readonly SKColor Accent = new(0x0F, 0x5C, 0x8C); + + /// The mark as a square bitmap of pixels, premultiplied BGRA, transparent corners. + public static SKBitmap Render(int size) + { + ArgumentOutOfRangeException.ThrowIfLessThan(size, 1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(size, 1024); + var bitmap = new SKBitmap(new SKImageInfo(size, size, SKColorType.Bgra8888, SKAlphaType.Premul)); + using var canvas = new SKCanvas(bitmap); + canvas.Clear(SKColors.Transparent); + var scale = size / 32f; + canvas.Scale(scale); + using (var square = new SKPaint { Color = Accent, IsAntialias = true, Style = SKPaintStyle.Fill }) + { + canvas.DrawRoundRect(new SKRect(0, 0, 32, 32), 8, 8, square); + } + + using (var ring = new SKPaint { Color = SKColors.White, IsAntialias = true, Style = SKPaintStyle.Stroke, StrokeWidth = 2.6f }) + { + canvas.DrawCircle(14.5f, 17.5f, 7.4f, ring); + } + + using (var moon = new SKPaint { Color = SKColors.White, IsAntialias = true, Style = SKPaintStyle.Fill }) + { + canvas.DrawCircle(23.2f, 8.8f, 3.1f, moon); + } + + canvas.Flush(); + return bitmap; + } + + /// The multi-size Windows icon () of the mark, as the bytes of an .ico file. + public static byte[] RenderIcon() + { + var images = new List(); + try + { + foreach (var size in IconSizes) + { + images.Add(Render(size)); + } + + return IcoWriter.Write(images); + } + finally + { + foreach (var image in images) + { + image.Dispose(); + } + } + } +} + +/// +/// Writes Windows .ico files by hand (no package for it, spec §3): the 256-pixel image as PNG, the smaller ones as +/// 32-bit DIBs (BGRA with alpha, bottom-up, plus the 1-bit AND mask), which every part of Windows reads — window icons, +/// the notification area, Explorer, NSIS. +/// +public static class IcoWriter +{ + /// Images at or above this size are stored as PNG (the Vista format); smaller ones as DIB. + public const int PngFrom = 256; + + private const int DirectoryHeader = 6; + private const int DirectoryEntry = 16; + private const int BitmapInfoHeader = 40; + + /// The .ico bytes of square (1 to 256 pixels), in the order given. + public static byte[] Write(IReadOnlyList images) + { + ArgumentNullException.ThrowIfNull(images); + if (images.Count is 0 or > ushort.MaxValue) + { + throw new ArgumentException("Un'icona contiene da 1 a 65535 immagini.", nameof(images)); + } + + var payloads = new List(images.Count); + foreach (var image in images) + { + if (image.Width != image.Height || image.Width is < 1 or > 256) + { + throw new ArgumentException("Le immagini di un'icona sono quadrate, da 1 a 256 pixel.", nameof(images)); + } + + payloads.Add(image.Width >= PngFrom ? Png(image) : Dib(image)); + } + + using var output = new MemoryStream(); + Span header = stackalloc byte[DirectoryHeader]; + BinaryPrimitives.WriteUInt16LittleEndian(header, 0); // reserved + BinaryPrimitives.WriteUInt16LittleEndian(header[2..], 1); // 1 = icon + BinaryPrimitives.WriteUInt16LittleEndian(header[4..], (ushort)images.Count); + output.Write(header); + + var offset = DirectoryHeader + (DirectoryEntry * images.Count); + Span entry = stackalloc byte[DirectoryEntry]; + for (var i = 0; i < images.Count; i++) + { + var size = images[i].Width; + entry.Clear(); + entry[0] = (byte)(size >= 256 ? 0 : size); // 0 means 256 + entry[1] = (byte)(size >= 256 ? 0 : size); + entry[2] = 0; // no palette + entry[3] = 0; // reserved + BinaryPrimitives.WriteUInt16LittleEndian(entry[4..], 1); // colour planes + BinaryPrimitives.WriteUInt16LittleEndian(entry[6..], 32); // bits per pixel + BinaryPrimitives.WriteUInt32LittleEndian(entry[8..], (uint)payloads[i].Length); + BinaryPrimitives.WriteUInt32LittleEndian(entry[12..], (uint)offset); + output.Write(entry); + offset += payloads[i].Length; + } + + foreach (var payload in payloads) + { + output.Write(payload); + } + + return output.ToArray(); + } + + /// Reads the directory of an .ico file: size, bytes, whether the image is PNG (tests, checks). + public static IReadOnlyList ReadDirectory(ReadOnlySpan ico) + { + if (ico.Length < DirectoryHeader || BinaryPrimitives.ReadUInt16LittleEndian(ico) != 0 || BinaryPrimitives.ReadUInt16LittleEndian(ico[2..]) != 1) + { + throw new InvalidDataException("Non è un file .ico."); + } + + var count = BinaryPrimitives.ReadUInt16LittleEndian(ico[4..]); + var entries = new List(count); + for (var i = 0; i < count; i++) + { + var e = ico.Slice(DirectoryHeader + (i * DirectoryEntry), DirectoryEntry); + var size = e[0] == 0 ? 256 : e[0]; + var length = (int)BinaryPrimitives.ReadUInt32LittleEndian(e[8..]); + var offset = (int)BinaryPrimitives.ReadUInt32LittleEndian(e[12..]); + if (offset < 0 || length < 0 || offset + length > ico.Length) + { + throw new InvalidDataException("Immagine fuori dal file .ico."); + } + + var data = ico.Slice(offset, length); + var png = data.Length >= 8 && data[..8].SequenceEqual(PngSignature); + entries.Add(new IcoEntry(size, BinaryPrimitives.ReadUInt16LittleEndian(e[6..]), offset, length, png)); + } + + return entries; + } + + /// The image of an entry as a bitmap (DIB or PNG), for comparisons. + public static SKBitmap Decode(ReadOnlySpan ico, IcoEntry entry) + { + ArgumentNullException.ThrowIfNull(entry); + var data = ico.Slice(entry.Offset, entry.Length); + if (entry.IsPng) + { + return SKBitmap.Decode(data.ToArray()) ?? throw new InvalidDataException("PNG dell'icona non leggibile."); + } + + var size = entry.Size; + var bitmap = new SKBitmap(new SKImageInfo(size, size, SKColorType.Bgra8888, SKAlphaType.Unpremul)); + var pixels = data[BitmapInfoHeader..]; + for (var y = 0; y < size; y++) + { + var row = pixels.Slice((size - 1 - y) * size * 4, size * 4); + for (var x = 0; x < size; x++) + { + bitmap.SetPixel(x, y, new SKColor(row[(x * 4) + 2], row[(x * 4) + 1], row[x * 4], row[(x * 4) + 3])); + } + } + + return bitmap; + } + + private static ReadOnlySpan PngSignature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + private static byte[] Png(SKBitmap image) + { + using var data = image.Encode(SKEncodedImageFormat.Png, 100) ?? throw new InvalidOperationException("Codifica PNG non riuscita."); + return data.ToArray(); + } + + /// A 32-bit DIB: BITMAPINFOHEADER with twice the height (image + mask), BGRA rows bottom-up, AND mask. + private static byte[] Dib(SKBitmap image) + { + var size = image.Width; + var maskStride = ((size + 31) / 32) * 4; + var pixelBytes = size * size * 4; + var result = new byte[BitmapInfoHeader + pixelBytes + (maskStride * size)]; + var span = result.AsSpan(); + BinaryPrimitives.WriteUInt32LittleEndian(span, BitmapInfoHeader); + BinaryPrimitives.WriteInt32LittleEndian(span[4..], size); + BinaryPrimitives.WriteInt32LittleEndian(span[8..], size * 2); + BinaryPrimitives.WriteUInt16LittleEndian(span[12..], 1); // planes + BinaryPrimitives.WriteUInt16LittleEndian(span[14..], 32); // bits per pixel + BinaryPrimitives.WriteUInt32LittleEndian(span[16..], 0); // BI_RGB + BinaryPrimitives.WriteUInt32LittleEndian(span[20..], (uint)(pixelBytes + (maskStride * size))); + + var pixels = span[BitmapInfoHeader..]; + var mask = span[(BitmapInfoHeader + pixelBytes)..]; + for (var y = 0; y < size; y++) + { + var row = pixels.Slice((size - 1 - y) * size * 4, size * 4); + for (var x = 0; x < size; x++) + { + // GetPixel gives straight (not premultiplied) alpha, as icons want it. + var c = image.GetPixel(x, y); + row[x * 4] = c.Blue; + row[(x * 4) + 1] = c.Green; + row[(x * 4) + 2] = c.Red; + row[(x * 4) + 3] = c.Alpha; + if (c.Alpha == 0) + { + // Transparent pixels are also set in the AND mask, for the readers that ignore the alpha channel. + var maskRow = mask.Slice((size - 1 - y) * maskStride, maskStride); + maskRow[x / 8] |= (byte)(0x80 >> (x % 8)); + } + } + } + + return result; + } +} + +/// One image of an .ico file. +public sealed record IcoEntry(int Size, int BitsPerPixel, int Offset, int Length, bool IsPng); diff --git a/src/Febe.Desktop.Core/BrowserArguments.cs b/src/Febe.Desktop.Core/BrowserArguments.cs new file mode 100644 index 0000000..8b3744f --- /dev/null +++ b/src/Febe.Desktop.Core/BrowserArguments.cs @@ -0,0 +1,85 @@ +using Febe.Browser.Hosting; + +namespace Febe.Desktop.Core; + +/// +/// The arguments of the browser of Febe on Windows for S2 (spec §6.6): the page must keep loading and scrolling while +/// the window «Browser di Febe» is open but out of view. +/// +/// +/// +/// --disable-features=CalculateNativeWinOcclusion stops Chromium from computing whether its window is covered or +/// off-screen; --disable-backgrounding-occluded-windows stops it from treating such a window as hidden (lower +/// priority, no painting, throttled timers). They are not forbidden by rule 2 of spec §2: they change how the browser +/// schedules its own work, not what it declares. User agent, client hints, navigator properties (including +/// webdriver), language, time zone and headers stay exactly those of a normal Edge/WebView2; nothing is +/// injected into the page. The page sees a visible window, as it does with Chromium on Xvfb in Docker and with any +/// browser window left open behind others where Windows does not report occlusion. Spec §6.6 itself prescribes this +/// first attempt of S2. +/// +/// +/// WebView2 also stops painting when its controller's IsVisible is false: the desktop never sets it to false and +/// moves the window off-screen instead of hiding or minimising it. +/// +/// +public static class BrowserArguments +{ + /// The switches of S2, the same for WebView2 and for Edge. + public static IReadOnlyList KeepPaintingOutOfView { get; } = + [ + "--disable-features=CalculateNativeWinOcclusion", + "--disable-backgrounding-occluded-windows", + ]; + + /// + /// CoreWebView2EnvironmentOptions.AdditionalBrowserArguments of the browser of Febe. Each switch passes the + /// same check as Chromium's extra arguments (). + /// + public static string ForWebView2() + { + foreach (var argument in KeepPaintingOutOfView) + { + ChromiumCommandLine.EnsureAllowed(argument); + } + + return string.Join(' ', KeepPaintingOutOfView); + } + + /// Extra arguments of Edge started as a process (fallback «edge»), checked the same way. + public static IReadOnlyList ForEdge() => KeepPaintingOutOfView; +} + +/// Finds Microsoft Edge for the last fallback of S2 (spec §6.6): App Paths first, then the usual folders. +public static class EdgeLocator +{ + /// + /// The places Edge is looked for, in order: the App Paths\msedge.exe value of the registry (passed by the + /// desktop), Program Files (x86), Program Files, and a per-user installation in %LOCALAPPDATA%. + /// + public static IReadOnlyList Candidates(string? appPathsValue, string? programFilesX86, string? programFiles, string? localAppData) + { + var list = new List(); + if (!string.IsNullOrWhiteSpace(appPathsValue)) + { + list.Add(appPathsValue.Trim().Trim('"')); + } + + foreach (var root in new[] { programFilesX86, programFiles, localAppData }) + { + if (!string.IsNullOrWhiteSpace(root)) + { + list.Add(Path.Combine(root, "Microsoft", "Edge", "Application", "msedge.exe")); + } + } + + return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + } + + /// The first candidate that exists, or null. + public static string? Find(IEnumerable candidates, Func? exists = null) + { + ArgumentNullException.ThrowIfNull(candidates); + exists ??= File.Exists; + return candidates.FirstOrDefault(c => c.EndsWith("msedge.exe", StringComparison.OrdinalIgnoreCase) && exists(c)); + } +} diff --git a/src/Febe.Desktop.Core/DataFolderMove.cs b/src/Febe.Desktop.Core/DataFolderMove.cs new file mode 100644 index 0000000..b88abbb --- /dev/null +++ b/src/Febe.Desktop.Core/DataFolderMove.cs @@ -0,0 +1,301 @@ +using System.Security.Cryptography; +using Febe.Core.Library; +using Febe.Web.Api; +using Febe.Web.Library; + +namespace Febe.Desktop.Core; + +/// +/// Where the Data folder of the Windows application is recorded, outside the folder itself (the desktop keeps it in +/// HKCU\Software\Febe): the folder in use after a move, and a move asked from Impostazioni for the next start. +/// +public interface IDataFolderLocationStore +{ + /// The Data folder in use after a move; null: the default (%LOCALAPPDATA%\Febe). + string? Current { get; } + + /// The folder chosen in Impostazioni, used from the next start; null: none. + string? Pending { get; } + + void SetCurrent(string? folder); + + void SetPending(string? folder); +} + +/// What happened to a move of the Data folder at start-up. +public enum DataFolderMoveOutcome +{ + /// No move was asked. + NotRequested, + + /// Every file was copied and verified; the new folder is in use and the old one was deleted. + Moved, + + /// Moved, but the old folder could not be deleted entirely (it still holds a copy of the session). + MovedOldFolderLeft, + + /// The move did not happen: Febe goes on with the old folder, untouched. + Failed, +} + +/// Outcome of , with an Italian message for the log and a notification. +public sealed record DataFolderMoveResult(DataFolderMoveOutcome Outcome, string DataFolder, string? Message); + +/// Progress of the copy: files and bytes. +public sealed record DataFolderMoveProgress(int FilesDone, int FilesTotal, long BytesDone, long BytesTotal); + +/// +/// «Cambia…» of the Data folder on Windows (spec §8.2). The Data folder holds the database and the browser profile with +/// the Instagram session, so it never moves while Febe runs: the choice is recorded and applied at the next start, +/// before anything opens the folder. Every file is copied and read back (SHA-256); only when every copy matches is the +/// new folder used and the old one deleted — it holds a copy of the session, which must not stay behind (spec §13.2). +/// Any error leaves the old folder in use and untouched, and removes the partial copy. +/// +public static class DataFolderMove +{ + /// Why cannot become the Data folder, in Italian; null when it can. + public static string? Validate(string current, string requested, DataFolderCheck? check = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(current); + if (string.IsNullOrWhiteSpace(requested) || !Path.IsPathFullyQualified(requested)) + { + return "Serve il percorso completo di una cartella."; + } + + var from = Normalize(current); + var to = Normalize(requested); + if (Same(from, to)) + { + return "È già la cartella dei dati."; + } + + if (Inside(to, from) || Inside(from, to)) + { + return "La nuova cartella dei dati non può stare dentro quella attuale, né contenerla."; + } + + if (Directory.Exists(to) && Directory.EnumerateFileSystemEntries(to).Any()) + { + return "Scegli una cartella vuota (o una nuova): Febe non mescola i suoi dati con altri file."; + } + + if (File.Exists(to)) + { + return "Il percorso indica un file, non una cartella."; + } + + var existed = Directory.Exists(to); + try + { + if ((check ?? new DataFolderCheck()).Check(to) is { } problem) + { + return $"{problem.Title}. {problem.Remedy}"; + } + } + finally + { + // The check may have created the folder to try writing in it: a choice that is not applied leaves nothing. + if (!existed) + { + TryDeleteEmpty(to); + } + } + + return null; + } + + /// + /// Applies the move asked from Impostazioni, if any. Call it before anything opens . + /// + public static DataFolderMoveResult ApplyPending(IDataFolderLocationStore store, string current, IProgress? progress = null, DataFolderCheck? check = null) + { + ArgumentNullException.ThrowIfNull(store); + ArgumentException.ThrowIfNullOrWhiteSpace(current); + if (store.Pending is not { } pending) + { + return new DataFolderMoveResult(DataFolderMoveOutcome.NotRequested, current, null); + } + + var from = Normalize(current); + var to = Normalize(pending); + if (Validate(from, to, check) is { } reason) + { + store.SetPending(null); + return new DataFolderMoveResult(DataFolderMoveOutcome.Failed, from, $"La cartella dei dati non è stata spostata in {to}: {reason} Febe usa ancora {from}."); + } + + if (!Directory.Exists(from)) + { + // Nothing to copy (Febe never ran here): the new folder is simply used from now on. + Directory.CreateDirectory(to); + store.SetCurrent(to); + store.SetPending(null); + return new DataFolderMoveResult(DataFolderMoveOutcome.Moved, to, $"Cartella dei dati: {to}."); + } + + var createdTarget = !Directory.Exists(to); + try + { + CopyVerified(from, to, progress); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) + { + RemovePartialCopy(to, createdTarget); + store.SetPending(null); + return new DataFolderMoveResult( + DataFolderMoveOutcome.Failed, + from, + $"La cartella dei dati non è stata spostata in {to}: {ex.Message} Febe usa ancora {from}, che non è stata toccata; la copia parziale è stata tolta."); + } + + store.SetCurrent(to); + store.SetPending(null); + try + { + Directory.Delete(from, recursive: true); + return new DataFolderMoveResult(DataFolderMoveOutcome.Moved, to, $"Cartella dei dati spostata in {to}: ogni file è stato copiato e controllato, la vecchia cartella è stata cancellata."); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return new DataFolderMoveResult( + DataFolderMoveOutcome.MovedOldFolderLeft, + to, + $"Cartella dei dati spostata in {to}, ma la vecchia ({from}) non si è potuta cancellare del tutto ({ex.Message}). Cancellala tu: contiene ancora una copia della sessione di Instagram."); + } + } + + /// Copies every file of into and reads each copy back. + internal static void CopyVerified(string from, string to, IProgress? progress) + { + var files = new DirectoryInfo(from) + .EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = FileAttributes.ReparsePoint, IgnoreInaccessible = false }) + .ToList(); + var total = files.Sum(f => f.Length); + long bytes = 0; + var done = 0; + Directory.CreateDirectory(to); + foreach (var directory in Directory.EnumerateDirectories(from, "*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = FileAttributes.ReparsePoint })) + { + Directory.CreateDirectory(Path.Combine(to, Path.GetRelativePath(from, directory))); + } + + foreach (var file in files) + { + var relative = Path.GetRelativePath(from, file.FullName); + var target = Path.Combine(to, relative); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + byte[] sourceHash; + using (var source = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (var destination = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) + { + var buffer = new byte[1024 * 1024]; + int read; + while ((read = source.Read(buffer, 0, buffer.Length)) > 0) + { + sha.AppendData(buffer, 0, read); + destination.Write(buffer, 0, read); + } + + destination.Flush(flushToDisk: true); + sourceHash = sha.GetHashAndReset(); + } + + byte[] copyHash; + using (var copy = new FileStream(target, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + copyHash = SHA256.HashData(copy); + } + + if (!CryptographicOperations.FixedTimeEquals(sourceHash, copyHash)) + { + throw new InvalidDataException($"la copia di {relative} non corrisponde all'originale."); + } + + File.SetLastWriteTimeUtc(target, file.LastWriteTimeUtc); + bytes += file.Length; + done++; + progress?.Report(new DataFolderMoveProgress(done, files.Count, bytes, total)); + } + } + + private static void RemovePartialCopy(string to, bool createdTarget) + { + try + { + if (createdTarget) + { + Directory.Delete(to, recursive: true); + } + else + { + // The folder existed and was empty (Validate): empty it again. + foreach (var entry in new DirectoryInfo(to).EnumerateFileSystemInfos()) + { + if (entry is DirectoryInfo directory) + { + directory.Delete(recursive: true); + } + else + { + entry.Delete(); + } + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } + + private static void TryDeleteEmpty(string folder) + { + try + { + if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any()) + { + Directory.Delete(folder); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } + + private static string Normalize(string path) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); + + private static StringComparison Comparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + private static bool Same(string a, string b) => string.Equals(a, b, Comparison); + + private static bool Inside(string path, string folder) => path.StartsWith(folder + Path.DirectorySeparatorChar, Comparison); +} + +/// +/// of the Windows application: «Cambia…» records the new folder, which +/// moves to at the next start. Not available when the Data folder was given +/// on the command line (--dati): then it is the command line that decides. +/// +public sealed class DesktopDataFolderChange(IDataFolderLocationStore store, string currentDataFolder, bool fixedByCommandLine, DataFolderCheck? check = null) : IDataFolderChange +{ + public bool CanChange => !fixedByCommandLine; + + public Task RequestChangeAsync(string newFolder, CancellationToken ct) + { + if (fixedByCommandLine) + { + throw new BadRequestException("Febe è stato avviato con --dati: la cartella dei dati la decide la riga di comando."); + } + + if (DataFolderMove.Validate(currentDataFolder, newFolder, check) is { } reason) + { + throw new BadRequestException(reason); + } + + var target = Path.TrimEndingDirectorySeparator(Path.GetFullPath(newFolder)); + store.SetPending(target); + return Task.FromResult( + $"Al prossimo avvio Febe sposterà i suoi dati in {target}: copia ogni file, lo controlla e solo dopo cancella la " + + "vecchia cartella. Per farlo subito, esci da Febe dall'area di notifica e riaprilo."); + } +} diff --git a/src/Febe.Desktop.Core/DesktopOptions.cs b/src/Febe.Desktop.Core/DesktopOptions.cs new file mode 100644 index 0000000..7d0c1cd --- /dev/null +++ b/src/Febe.Desktop.Core/DesktopOptions.cs @@ -0,0 +1,277 @@ +using System.Globalization; +using System.Net; +using Febe.App; +using Febe.Browser.Recipes; + +namespace Febe.Desktop.Core; + +/// +/// How the browser of Instagram is hosted on Windows: the three attempts of S2, in the order of spec §6.6. The first is +/// the default; the others are fallbacks Alberto chooses with --browser while testing S2 (docs/windows.md). +/// +public enum BrowserHosting +{ + /// «finestra»: WebView2 in its own window «Browser di Febe», kept open but out of view, occlusion off. + Window, + + /// «composizione»: the same window, with WebView2 hosted as a DirectComposition visual. + Composition, + + /// «edge»: Microsoft Edge started as a process and driven like Chromium in Docker (ChromiumProcessHost). + Edge, +} + +/// Italian names of , for the command line, the setting and the log. +public static class BrowserHostingNames +{ + /// Setting key (table setting) of the hosting chosen with --browser; it stays for the next starts. + public const string SettingKey = "desktop.browser"; + + public static string Name(BrowserHosting hosting) => hosting switch + { + BrowserHosting.Composition => "composizione", + BrowserHosting.Edge => "edge", + _ => "finestra", + }; + + public static bool TryParse(string? text, out BrowserHosting hosting) + { + switch (text?.Trim().ToLowerInvariant()) + { + case "finestra": + hosting = BrowserHosting.Window; + return true; + case "composizione": + hosting = BrowserHosting.Composition; + return true; + case "edge": + hosting = BrowserHosting.Edge; + return true; + default: + hosting = BrowserHosting.Window; + return false; + } + } +} + +/// The folders Windows gives Febe by default (spec §12): tests pass their own. +/// %LOCALAPPDATA%. +/// The user's Pictures folder («Immagini»). +public sealed record DesktopFolders(string LocalAppData, string Pictures) +{ + /// The folders of the current user. + public static DesktopFolders Current() => new( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify), + Environment.GetFolderPath(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify)); + + /// Default Data folder: %LOCALAPPDATA%\Febe. + public string DefaultDataFolder => Path.Combine(LocalAppData, "Febe"); + + /// Default library: Immagini\Febe. + public string DefaultLibraryFolder => Path.Combine(Pictures, "Febe"); +} + +/// Configuration of the Windows application, from its command line (spec §12). +public sealed record DesktopOptions +{ + /// Data folder chosen with --dati (development, a second account); null: the recorded or default one. + public string? DataFolder { get; init; } + + /// + /// Library chosen with --libreria (tests on Windows, a second account): the default of the setting instead of + /// Immagini\Febe. A folder chosen later in Impostazioni still wins. + /// + public string? LibraryFolder { get; init; } + + /// --nascosto: start with the icon in the notification area only (start with the computer). + public bool StartHidden { get; init; } + + /// --browser finestra|composizione|edge: the hosting of S2, stored for the next starts. + public BrowserHosting? Hosting { get; init; } + + /// --sviluppo: the developer tools of the interface window (never of the browser of Febe). + public bool DeveloperTools { get; init; } + + /// Development: the local test site (tools/Febe.SitoDiProva) instead of Instagram, for S1 and S2. + public Uri? TestSite { get; init; } + + /// Development: the «CDN» of the test site (default: 127.0.0.2, site port + 1). + public Uri? TestCdn { get; init; } + + /// Development, test site only: opens the site once at start-up so its session cookie exists. + public bool TestSiteAutoLogin { get; init; } + + /// Development: the first session after this delay instead of 2–10 minutes. + public TimeSpan? FirstSessionDelay { get; init; } + + /// The fixed DevTools port of Edge (fallback «edge» only), on 127.0.0.1. + public int EdgeDebugPort { get; init; } = 9222; + + /// Size of the page of the browser of Febe, always the same (spec §6.1). + public int BrowserWidth { get; init; } = 1280; + + public int BrowserHeight { get; init; } = 900; + + /// The site the browser works on: Instagram, or the local test site in development. + public CollectionSite Site => TestSite is { } site + ? CollectionSite.TestSite(site.Authority, (TestCdn ?? DefaultCdn(site)).Authority) + : CollectionSite.Instagram; + + /// The page «Accedi a Instagram» opens: the real login page, or a page of the test site. + public string LoginUrl => TestSite is { } site ? new Uri(site, "/benvenuto").AbsoluteUri : "https://www.instagram.com/accounts/login/"; + + /// The options of the shared composition. + public FebeAppOptions AppOptions(string dataFolder, DesktopFolders folders) => new() + { + DataFolder = dataFolder, + LibraryFolder = LibraryFolder ?? folders.DefaultLibraryFolder, + LibraryFolderFromSettings = true, + ImportFolder = null, + ZoneId = TimeZoneInfo.Local.Id, + Zone = TimeZoneInfo.Local, + Language = CultureInfo.CurrentUICulture.Name, + Site = Site, + LoginUrl = LoginUrl, + TestSite = TestSite, + TestSiteAutoLogin = TestSiteAutoLogin, + FirstSessionDelay = FirstSessionDelay, + }; + + private static Uri DefaultCdn(Uri site) => new UriBuilder(site) { Host = "127.0.0.2", Port = site.Port + 1, Path = "/" }.Uri; +} + +/// Reads the command line of Febe.exe. Nothing secret ever passes on it. +public static class DesktopCommandLine +{ + public const string Usage = + "Uso: Febe.exe [--nascosto] [--dati cartella] [--libreria cartella] [--browser finestra|composizione|edge] [--sviluppo]\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]"; + + public static bool TryParse(string[] args, out DesktopOptions options, out string problem) + { + ArgumentNullException.ThrowIfNull(args); + options = new DesktopOptions(); + problem = string.Empty; + 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 "--nascosto": + options = options with { StartHidden = true }; + break; + case "--sviluppo": + options = options with { DeveloperTools = true }; + break; + case "--dati": + { + var text = Next(); + if (string.IsNullOrWhiteSpace(text) || !Path.IsPathFullyQualified(text)) + { + problem = "Dopo --dati serve il percorso completo di una cartella."; + return false; + } + + options = options with { DataFolder = Path.GetFullPath(text) }; + break; + } + + case "--libreria": + { + var text = Next(); + if (string.IsNullOrWhiteSpace(text) || !Path.IsPathFullyQualified(text)) + { + problem = "Dopo --libreria serve il percorso completo di una cartella."; + return false; + } + + options = options with { LibraryFolder = Path.GetFullPath(text) }; + break; + } + + case "--browser": + { + var text = Next(); + if (!BrowserHostingNames.TryParse(text, out var hosting)) + { + problem = $"Valore non valido dopo --browser («{text}»): finestra, composizione oppure edge."; + return false; + } + + options = options with { Hosting = hosting }; + 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 (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; + } + + return true; + } + + /// The test site must be on this computer: the switch can never point the browser elsewhere. + 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; + } +} diff --git a/src/Febe.Desktop.Core/DesktopPlatform.cs b/src/Febe.Desktop.Core/DesktopPlatform.cs new file mode 100644 index 0000000..24ed7ad --- /dev/null +++ b/src/Febe.Desktop.Core/DesktopPlatform.cs @@ -0,0 +1,334 @@ +using System.Globalization; +using Febe.App; +using Febe.Browser.Cdp; +using Febe.Browser.Hosting; +using Febe.Core.Abstractions; +using Febe.Core.Library; +using Febe.Web; +using Febe.Web.Api; +using Febe.Web.Connection; +using Febe.Web.Library; +using Febe.Web.Native; +using Microsoft.Extensions.DependencyInjection; + +namespace Febe.Desktop.Core; + +/// How the window «Browser di Febe» hosts WebView2 (spec §6.1, §12, S2). +/// The WebView2 user data folder: Dati\browser, with the Instagram session. +/// Width of the page in CSS pixels, always the same. +/// Height of the page in CSS pixels, always the same. +/// or . +/// The switches of S2 (). +public sealed record WebView2BrowserSettings(string ProfileDirectory, int Width, int Height, BrowserHosting Hosting, string AdditionalBrowserArguments); + +/// +/// What the Windows-only part of the desktop (Febe.Desktop, WPF) gives the platform: the native shell, the WebView2 +/// browser, Edge's window, the notifications, the WebView2 runtime probe. Tests on Linux pass fakes. +/// +public interface IDesktopShell +{ + /// Folder picker, «Mostra nella cartella», default browser, notifications, start with the computer. + INativeShell Native { get; } + + /// Windows notifications (balloon tips of the notification-area icon); null when there is no icon. + IAlertChannel? Notifications { get; } + + /// The installed WebView2 runtime; null when missing. + string? WebView2Version(); + + /// The window «Browser di Febe» on WebView2. + IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context); + + /// Microsoft Edge (fallback «edge» of S2); null when it is not installed. + string? FindEdge(); + + /// Brings the main window of a process (Edge) to the front, on screen. + Task ShowProcessWindowAsync(int processId, CancellationToken ct); + + /// Moves the main window of a process (Edge) out of view, still open: never minimised (S2). + Task HideProcessWindowAsync(int processId, CancellationToken ct); +} + +/// +/// The Windows edition's parts of the composition (spec §12, §13.1): the interface on 127.0.0.1 with a port chosen at +/// start-up and a token of this start, the Data folder and the WebView2 runtime checked at start-up, the browser of +/// Instagram in its own window (or, for S2, as a composition visual or as Edge), and the native functions. +/// +public sealed class DesktopPlatform : IFebePlatform +{ + private readonly DesktopOptions _options; + private readonly IDesktopShell _shell; + private readonly IDataFolderLocationStore _locations; + private readonly bool _dataFolderFixed; + + /// The command line. + /// The Windows-only part. + /// Where a move of the Data folder is recorded. + /// True when the Data folder came from --dati: «Cambia…» is not offered. + public DesktopPlatform(DesktopOptions options, IDesktopShell shell, IDataFolderLocationStore locations, bool dataFolderFixed) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + _shell = shell ?? throw new ArgumentNullException(nameof(shell)); + _locations = locations ?? throw new ArgumentNullException(nameof(locations)); + _dataFolderFixed = dataFolderFixed; + WebOptions = new FebeWebOptions + { + Edition = FebeEdition.Desktop, + Access = AccessMode.Token, + AccessToken = AccessToken, + AllowedHosts = FebeWebOptions.LoopbackHosts(0), + }; + } + + /// The token of this start: the interface window opens /?gettone=… once. Never logged. + public string AccessToken { get; } = Febe.Web.Security.AccessToken.Create(); + + public FebeWebOptions WebOptions { get; } + + /// 127.0.0.1 only, on a port chosen at start-up. + public FebeListen Listen => FebeListen.Loopback(0); + + /// The hosting actually used (after a missing Edge fell back to the window). + public BrowserHosting? Hosting { get; private set; } + + /// The address the interface window opens once: the token becomes a cookie and leaves the address. + public Uri FirstAddress(Uri address) + { + ArgumentNullException.ThrowIfNull(address); + return new Uri(address, "/?" + Febe.Web.Security.AccessToken.QueryName + "=" + Uri.EscapeDataString(AccessToken)); + } + + public IReadOnlyList CheckConfiguration(FebeAppOptions options, DataFolderCheck dataFolderCheck) + { + ArgumentNullException.ThrowIfNull(options); + return DesktopStartupChecks.Run(options.DataFolder, _shell.WebView2Version, dataFolderCheck); + } + + public async Task CreateBrowserAsync(FebePlatformContext context, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(context); + var settings = context.Storage.Settings; + BrowserHosting hosting; + if (_options.Hosting is { } chosen) + { + hosting = chosen; + await settings.SetAsync(BrowserHostingNames.SettingKey, BrowserHostingNames.Name(chosen), ct).ConfigureAwait(false); + } + else + { + BrowserHostingNames.TryParse(await settings.GetAsync(BrowserHostingNames.SettingKey, ct).ConfigureAwait(false), out hosting); + } + + var profile = context.Data.BrowserProfile; + if (hosting == BrowserHosting.Edge) + { + if (_shell.FindEdge() is { } edge) + { + Hosting = hosting; + context.Log.Info("browser", $"Browser di Febe: Microsoft Edge avviato come processo (ripiego di S2), porta di debug {_options.EdgeDebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1."); + return new EdgeBrowser(CreateEdge(context, edge), _shell, context); + } + + context.Log.Warn("browser", "Microsoft Edge non si trova su questo computer: il browser di Febe usa la sua finestra WebView2."); + hosting = BrowserHosting.Window; + } + + Hosting = hosting; + context.Log.Info("browser", $"Browser di Febe: WebView2 nella sua finestra ({BrowserHostingNames.Name(hosting)}), fuori vista quando non serve."); + return _shell.CreateWebView2Browser( + new WebView2BrowserSettings(profile, _options.BrowserWidth, _options.BrowserHeight, hosting, BrowserArguments.ForWebView2()), + context); + } + + public void RegisterServices(IServiceCollection services, FebeApp app) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(app); + services.AddSingleton(_shell.Native); + services.AddSingleton(new DesktopBrowserWindow(() => app.Browser)); + services.AddSingleton(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed)); + if (_shell.Notifications is { } notifications) + { + services.AddSingleton(notifications); + } + } + + public void RegisterProblemServices(IServiceCollection services, FebeApp app) + { + ArgumentNullException.ThrowIfNull(services); + services.AddSingleton(_shell.Native); + } + + public Task StoppingAsync() => Task.CompletedTask; + + /// + /// Edge for the last fallback of S2: the same as Docker, with its fixed DevTools + /// port on 127.0.0.1, a profile of its own inside Dati\browser (so «Scollega» deletes both), preferences + /// with password saving and autofill off, and the switches of S2. + /// + private ChromiumBrowser CreateEdge(FebePlatformContext context, string executable) => new( + new ChromiumBrowserSettings + { + ProfileDirectory = Path.Combine(context.Data.BrowserProfile, "edge"), + ProfileFolderToDelete = context.Data.BrowserProfile, + WindowWidth = _options.BrowserWidth, + WindowHeight = _options.BrowserHeight, + DebugPort = _options.EdgeDebugPort, + ExecutablePath = executable, + Display = null, + Launch = new ChromiumLaunchOptions + { + ExtraArguments = BrowserArguments.ForEdge(), + SessionCookie = _options.Site.SessionCookie, + SeedProfilePreferences = true, + }, + }, + context.Clock, + context.Log); +} + +/// +/// «Apri il browser» on Windows (spec §10.3): brings the window «Browser di Febe» to the front. While it is in front +/// Alberto is driving and the engine is still; closing the window ends it. +/// +public sealed class DesktopBrowserWindow(Func browser) : IBrowserWindow +{ + public bool IsSeparateWindow => true; + + public async Task ShowAsync(CancellationToken ct) + { + if (browser() is not { } current) + { + throw new BadRequestException("Il browser di Febe non è in funzione in questo momento."); + } + + if (!current.IsAvailable) + { + throw new BadRequestException(current.LastError is { } error + ? "Il browser di Febe non è in funzione: " + error + : "Il browser di Febe si sta avviando: riprova fra qualche secondo."); + } + + await current.ShowToUserAsync(ct).ConfigureAwait(false); + } +} + +/// +/// Edge started as a process (the last fallback of S2): a whose window is moved out of +/// view after every start and brought to the front when Alberto uses it. While it is in front Alberto is driving. +/// +public sealed class EdgeBrowser : IFebeBrowser +{ + private readonly ChromiumBrowser _inner; + private readonly IDesktopShell _shell; + private readonly FebePlatformContext _context; + private readonly Lock _gate = new(); + private IDisposable? _lease; + + public EdgeBrowser(ChromiumBrowser inner, IDesktopShell shell, FebePlatformContext context) + { + _inner = inner ?? throw new ArgumentNullException(nameof(inner)); + _shell = shell ?? throw new ArgumentNullException(nameof(shell)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + _inner.Host.Connection.Reconnected += OnRestarted; + } + + public ChromiumBrowser Inner => _inner; + + public ICdpSession Cdp => _inner.Cdp; + + public UserDrivingGate UserDriving => _inner.UserDriving; + + public bool UserIsDriving => _inner.UserIsDriving; + + public bool IsAvailable => _inner.IsAvailable; + + public string? LastError => _inner.LastError; + + public string ProfileDirectory => _inner.ProfileDirectory; + + public int WindowWidth => _inner.WindowWidth; + + public int WindowHeight => _inner.WindowHeight; + + public async Task RunAsync(CancellationToken ct) + { + await _inner.RunAsync(ct).ConfigureAwait(false); + if (_inner.IsAvailable) + { + await MoveOutOfViewAsync(ct).ConfigureAwait(false); + } + } + + public Task RestAsync(CancellationToken ct) => _inner.RestAsync(ct); + + public async Task ShowToUserAsync(CancellationToken ct) + { + lock (_gate) + { + _lease ??= _inner.UserDriving.Begin(); + } + + _context.Tracker.MarkUsed(_context.Clock.Now); + if (_inner.Host.ProcessId is { } pid) + { + await _shell.ShowProcessWindowAsync(pid, ct).ConfigureAwait(false); + } + } + + public async Task HideFromUserAsync(CancellationToken ct) + { + ReleaseLease(); + await MoveOutOfViewAsync(ct).ConfigureAwait(false); + } + + public Task RestartWithEmptyProfileAsync(CancellationToken ct) => _inner.RestartWithEmptyProfileAsync(ct); + + public async ValueTask DisposeAsync() + { + _inner.Host.Connection.Reconnected -= OnRestarted; + ReleaseLease(); + await _inner.DisposeAsync().ConfigureAwait(false); + } + + private async Task MoveOutOfViewAsync(CancellationToken ct) + { + if (_inner.Host.ProcessId is { } pid) + { + await _shell.HideProcessWindowAsync(pid, ct).ConfigureAwait(false); + } + } + + /// Edge restarted (it crashed, or Alberto closed its window): a new window opens on screen, it goes out of view. + private void OnRestarted(object? sender, EventArgs e) + { + ReleaseLease(); + _ = Task.Run(async () => + { + try + { + await MoveOutOfViewAsync(CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (ex is InvalidOperationException or IOException) + { + _context.Log.Warn("browser", "La finestra di Edge non è andata fuori vista.", ex); + } + }); + } + + private void ReleaseLease() + { + IDisposable? lease; + lock (_gate) + { + lease = _lease; + _lease = null; + } + + if (lease is not null) + { + lease.Dispose(); + _context.Tracker.MarkUsed(_context.Clock.Now); + } + } +} diff --git a/src/Febe.Desktop.Core/DesktopStartupChecks.cs b/src/Febe.Desktop.Core/DesktopStartupChecks.cs new file mode 100644 index 0000000..e9c809d --- /dev/null +++ b/src/Febe.Desktop.Core/DesktopStartupChecks.cs @@ -0,0 +1,62 @@ +using Febe.App; +using Febe.Core.Library; +using Febe.Web.Connection; + +namespace Febe.Desktop.Core; + +/// +/// The checks made before anything starts on Windows (spec §8.2, §12): the Data folder is on a local disk and writable, +/// and the WebView2 runtime is installed (it is in Windows 11 and in almost every Windows 10). With a problem the engine +/// and the browser do not start. +/// +public static class DesktopStartupChecks +{ + public const string WebView2Missing = "webview2-assente"; + + /// The official page of the WebView2 runtime (Microsoft), with the Evergreen installer. + public const string WebView2DownloadPage = "https://developer.microsoft.com/microsoft-edge/webview2/"; + + /// + /// Every problem found, in the order the error page shows them. + /// + /// The Data folder. + /// + /// The installed WebView2 runtime (CoreWebView2Environment.GetAvailableBrowserVersionString), null when missing. + /// + /// The Data folder check (tests inject a mount table). + public static IReadOnlyList Run(string dataFolder, Func webView2Version, DataFolderCheck? check = null) + { + ArgumentNullException.ThrowIfNull(webView2Version); + var problems = new List(); + if (DataFolderProblems.Check(dataFolder, check) is { } data) + { + problems.Add(data); + } + + string? version; + try + { + version = webView2Version(); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + version = null; + } + + if (string.IsNullOrWhiteSpace(version)) + { + problems.Add(WebView2Problem()); + } + + return problems; + } + + /// «Manca il runtime WebView2», with the link to the official page. + public static ConfigurationProblem WebView2Problem() => new( + WebView2Missing, + "Manca il runtime WebView2 di Microsoft", + "Febe mostra la sua interfaccia e apre Instagram con WebView2, il componente di Microsoft Edge che Windows 11 e " + + "quasi tutti i Windows 10 hanno già. Su questo computer non c'è, quindi Febe non ha avviato né il motore né il browser.", + $"Installa il runtime WebView2 «Evergreen» dalla pagina ufficiale di Microsoft ({WebView2DownloadPage}), poi riavvia Febe. " + + "Non servono permessi di amministratore e non cambia nulla nel tuo Edge."); +} diff --git a/src/Febe.Desktop.Core/Febe.Desktop.Core.csproj b/src/Febe.Desktop.Core/Febe.Desktop.Core.csproj new file mode 100644 index 0000000..c551457 --- /dev/null +++ b/src/Febe.Desktop.Core/Febe.Desktop.Core.csproj @@ -0,0 +1,16 @@ + + + + + + + + + + + + + diff --git a/src/Febe.Desktop.Core/SingleInstance.cs b/src/Febe.Desktop.Core/SingleInstance.cs new file mode 100644 index 0000000..bb61e20 --- /dev/null +++ b/src/Febe.Desktop.Core/SingleInstance.cs @@ -0,0 +1,75 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Febe.Desktop.Core; + +/// +/// One Febe at a time for a Data folder (spec §12, rule 4): the names of the mutex and of the pipe through which a +/// second launch asks the first one to show its window. Derived from the Data folder, so that a second account with +/// folders of its own (spec §3) is a second instance; the same folder is the same instance whatever the case of its +/// letters. +/// +public static class InstanceIdentity +{ + /// A short stable name for a Data folder: «Febe-» and 16 hexadecimal digits of SHA-256 of its full path. + public static string For(string dataFolder) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder); + var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(dataFolder)).ToUpperInvariant(); + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(full)); + return "Febe-" + Convert.ToHexString(hash, 0, 8).ToLowerInvariant(); + } + + /// The named mutex, in the session namespace (one per logged-in user). + public static string MutexName(string dataFolder) => @"Local\" + For(dataFolder); + + /// The named pipe of the first instance (current user only). + public static string PipeName(string dataFolder) => For(dataFolder); +} + +/// What a second launch asks the running Febe. +public enum InstanceRequest +{ + /// Show the window (a normal launch: Start menu, desktop shortcut). + Show, + + /// Nothing visible (a start with the computer while Febe already runs). + StayHidden, +} + +/// +/// The one-line messages between two launches of Febe, over a pipe that only the current user can open. A message +/// carries no path and no secret; anything else than the two known lines is ignored. +/// +public static class InstanceMessages +{ + private const string Prefix = "FEBE1 "; + + /// The longest message read (anything longer is not one of ours). + public const int MaxLength = 64; + + /// The message a second launch with these options sends. + public static string For(DesktopOptions options) + { + ArgumentNullException.ThrowIfNull(options); + return Format(options.StartHidden ? InstanceRequest.StayHidden : InstanceRequest.Show); + } + + public static string Format(InstanceRequest request) => Prefix + (request == InstanceRequest.StayHidden ? "nascosto" : "mostra"); + + /// The request in a message; null for anything that is not one of ours. + public static InstanceRequest? Parse(string? message) + { + if (message is null || message.Length > MaxLength) + { + return null; + } + + return message.Trim() switch + { + "FEBE1 mostra" => InstanceRequest.Show, + "FEBE1 nascosto" => InstanceRequest.StayHidden, + _ => null, + }; + } +} diff --git a/src/Febe.Desktop/App.xaml b/src/Febe.Desktop/App.xaml deleted file mode 100644 index 528bac6..0000000 --- a/src/Febe.Desktop/App.xaml +++ /dev/null @@ -1,4 +0,0 @@ - - diff --git a/src/Febe.Desktop/App.xaml.cs b/src/Febe.Desktop/App.xaml.cs deleted file mode 100644 index 5560664..0000000 --- a/src/Febe.Desktop/App.xaml.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Febe.Desktop; - -/// Windows shell. Filled in by milestone M6. -public partial class App : System.Windows.Application -{ -} diff --git a/src/Febe.Desktop/Browser/BrowserWindow.cs b/src/Febe.Desktop/Browser/BrowserWindow.cs new file mode 100644 index 0000000..d5017b8 --- /dev/null +++ b/src/Febe.Desktop/Browser/BrowserWindow.cs @@ -0,0 +1,171 @@ +using System.ComponentModel; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Interop; +using System.Windows.Media; + +namespace Febe.Desktop.Browser; + +/// +/// The window «Browser di Febe» (spec §4.1, §12): the page of Instagram at a fixed size, always the same, and below it a +/// thin bar with «Indietro», «Ricarica» and the address without its query string. WebView2 draws into the upper area +/// (as a child window, or as a DirectComposition visual for S2). When Alberto does not use it the window stays open +/// but out of view, never hidden nor minimised: WebView2 would stop painting (S2). Closing it only puts it out of view. +/// +internal sealed class BrowserWindow : Window +{ + /// Height of the bar under the page, in device-independent pixels. + public const double BarHeight = 40; + + private readonly TextBlock _address; + private bool _allowClose; + + public BrowserWindow(int pageWidth, int pageHeight, ImageSource? icon) + { + PageWidth = pageWidth; + PageHeight = pageHeight; + Title = "Browser di Febe"; + Icon = icon; + ResizeMode = ResizeMode.CanMinimize; + SizeToContent = SizeToContent.WidthAndHeight; + WindowStartupLocation = WindowStartupLocation.Manual; + ShowActivated = false; + + // No taskbar button: out of view the window must not be reachable by accident (a click on a button that shows + // nothing). It comes to the front from the interface: «Apri il browser», «Portalo in primo piano», the login. + ShowInTaskbar = false; + Background = new SolidColorBrush(Color.FromRgb(0xF4, 0xF5, 0xF7)); + + var back = BarButton("Indietro", "Torna alla pagina precedente"); + back.Click += (_, _) => BackRequested?.Invoke(this, EventArgs.Empty); + var reload = BarButton("Ricarica", "Ricarica la pagina"); + reload.Click += (_, _) => ReloadRequested?.Invoke(this, EventArgs.Empty); + _address = new TextBlock + { + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(12, 0, 12, 0), + TextTrimming = TextTrimming.CharacterEllipsis, + Foreground = new SolidColorBrush(Color.FromRgb(0x2A, 0x2F, 0x36)), + FontFamily = new FontFamily("Segoe UI"), + FontSize = 13, + }; + var hint = new TextBlock + { + Text = "Chiudi questa finestra quando hai finito: Febe la tiene aperta fuori vista.", + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(0, 0, 12, 0), + Foreground = new SolidColorBrush(Color.FromRgb(0x5B, 0x63, 0x6E)), + FontFamily = new FontFamily("Segoe UI"), + FontSize = 12, + }; + + var bar = new DockPanel { Height = BarHeight, LastChildFill = true, Background = new SolidColorBrush(Color.FromRgb(0xFF, 0xFF, 0xFF)) }; + DockPanel.SetDock(back, Dock.Left); + DockPanel.SetDock(reload, Dock.Left); + DockPanel.SetDock(hint, Dock.Right); + bar.Children.Add(back); + bar.Children.Add(reload); + bar.Children.Add(hint); + bar.Children.Add(_address); + + // The page area: WebView2 covers it (its bounds are computed from PageWidth/PageHeight and the DPI). + var page = new Border { Width = pageWidth, Height = pageHeight, Background = Brushes.White }; + var layout = new DockPanel { LastChildFill = true }; + DockPanel.SetDock(bar, Dock.Bottom); + layout.Children.Add(bar); + layout.Children.Add(page); + Content = layout; + } + + /// Width of the page in device-independent pixels (CSS pixels of the page at zoom 100%). + public int PageWidth { get; } + + public int PageHeight { get; } + + /// Raised by «Indietro». + public event EventHandler? BackRequested; + + /// Raised by «Ricarica». + public event EventHandler? ReloadRequested; + + /// Raised when Alberto closes or minimises the window: the owner puts it out of view. + public event EventHandler? DoneRequested; + + /// The window handle (created on first use). + public IntPtr Handle => new WindowInteropHelper(this).EnsureHandle(); + + /// The scale of the monitor the window is on (1 at 96 DPI). + public double Scale => VisualTreeHelper.GetDpi(this).DpiScaleX; + + /// Where WebView2 draws, in physical pixels of the client area. + public System.Drawing.Rectangle PageBounds => new(0, 0, (int)Math.Round(PageWidth * Scale), (int)Math.Round(PageHeight * Scale)); + + /// True while the window is on a screen, false while it is parked out of view. + public bool IsOnScreen => + Left < SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth + && Left + ActualWidth > SystemParameters.VirtualScreenLeft; + + /// Shows the address of the page, without query string or fragment (they may carry tokens). + public void ShowAddress(string? address) => _address.Text = address ?? string.Empty; + + /// Centres the window on the work area of the primary screen. + public void MoveOnScreen() + { + var area = SystemParameters.WorkArea; + var width = ActualWidth > 0 ? ActualWidth : PageWidth; + var height = ActualHeight > 0 ? ActualHeight : PageHeight + BarHeight; + Left = area.Left + Math.Max(0, (area.Width - width) / 2); + Top = area.Top + Math.Max(0, (area.Height - height) / 2); + } + + /// + /// Parks the window just right of every screen: open, «visible» for Windows and for WebView2, out of Alberto's view + /// (S2). Never Hide() and never minimised. + /// + public void MoveOffScreen() + { + Left = SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth + 64; + Top = SystemParameters.VirtualScreenTop; + } + + /// Lets the window really close (Febe is stopping). + public void CloseForGood() + { + _allowClose = true; + Close(); + } + + protected override void OnClosing(CancelEventArgs e) + { + if (!_allowClose) + { + // The browser stays open: closing the window means «ho finito», it goes out of view. + e.Cancel = true; + DoneRequested?.Invoke(this, EventArgs.Empty); + } + + base.OnClosing(e); + } + + protected override void OnStateChanged(EventArgs e) + { + if (WindowState == WindowState.Minimized) + { + // A minimised window stops painting (S2): back to normal, out of view. + WindowState = WindowState.Normal; + DoneRequested?.Invoke(this, EventArgs.Empty); + } + + base.OnStateChanged(e); + } + + private static Button BarButton(string text, string tip) => new() + { + Content = text, + ToolTip = tip, + Margin = new Thickness(8, 6, 0, 6), + Padding = new Thickness(12, 0, 12, 0), + FontFamily = new FontFamily("Segoe UI"), + FontSize = 13, + }; +} diff --git a/src/Febe.Desktop/Browser/CompositionHost.cs b/src/Febe.Desktop/Browser/CompositionHost.cs new file mode 100644 index 0000000..3d450ec --- /dev/null +++ b/src/Febe.Desktop/Browser/CompositionHost.cs @@ -0,0 +1,169 @@ +using System.Runtime.InteropServices; +using System.Windows.Interop; +using Febe.Desktop.Native; +using Microsoft.Web.WebView2.Core; + +namespace Febe.Desktop.Browser; + +/// +/// The second attempt of S2 (spec §6.6, «composizione»): WebView2 hosted as a DirectComposition visual of the window +/// «Browser di Febe» instead of a child window. The window owns the visual tree (a topmost target with one visual, +/// the WebView at its origin over the page area); WebView2 gets no window of its own to be occluded or hidden, but +/// then the host forwards the mouse (SendMouseInput) and the cursor. The keyboard reaches the page through the +/// focus WebView2 keeps (MoveFocus). The bar of the window stays below the page and keeps its own input. +/// +/// To be tested on Windows (docs/windows.md, S2): it cannot run here. +internal sealed class CompositionHost : IDisposable +{ + private readonly IntPtr _window; + private readonly Func _page; + private readonly IDCompositionDevice _device; + private readonly IDCompositionTarget _target; + private readonly IDCompositionVisual _visual; + private HwndSource? _source; + private CoreWebView2CompositionController? _controller; + private bool _tracking; + private bool _captured; + + public CompositionHost(IntPtr window, Func pageBounds) + { + _window = window; + _page = pageBounds ?? throw new ArgumentNullException(nameof(pageBounds)); + var iid = typeof(IDCompositionDevice).GUID; + Marshal.ThrowExceptionForHR(Win32.DCompositionCreateDevice2(IntPtr.Zero, ref iid, out var device)); + _device = (IDCompositionDevice)device; + _target = _device.CreateTargetForHwnd(window, topmost: true); + _visual = _device.CreateVisual(); + _target.SetRoot(_visual); + _device.Commit(); + } + + /// Gives the visual to WebView2 and starts forwarding the mouse of the page area. + public void Attach(CoreWebView2CompositionController controller) + { + _controller = controller ?? throw new ArgumentNullException(nameof(controller)); + controller.RootVisualTarget = _visual; + _device.Commit(); + _source = HwndSource.FromHwnd(_window); + _source?.AddHook(Hook); + } + + public void Dispose() + { + _source?.RemoveHook(Hook); + _source = null; + if (_controller is { } controller) + { + try + { + controller.RootVisualTarget = null; + } + catch (Exception ex) when (ex is InvalidOperationException or COMException) + { + // The WebView is already closed. + } + } + + _controller = null; + Marshal.ReleaseComObject(_visual); + Marshal.ReleaseComObject(_target); + Marshal.ReleaseComObject(_device); + } + + private IntPtr Hook(IntPtr window, int message, IntPtr wParam, IntPtr lParam, ref bool handled) + { + if (_controller is not { } controller) + { + return IntPtr.Zero; + } + + if (message == Win32.WmSetCursor) + { + if (Win32.LowWord(lParam) == Win32.HtClient && CursorInPage(window, out _)) + { + Win32.SetCursor(controller.Cursor); + handled = true; + return new IntPtr(1); + } + + return IntPtr.Zero; + } + + var isMouse = message is >= Win32.WmMouseFirst and <= Win32.WmMouseHWheel || message == Win32.WmMouseLeave; + if (!isMouse) + { + return IntPtr.Zero; + } + + var point = new Win32.Point { X = Win32.LowWord(lParam), Y = Win32.HighWord(lParam) }; + if (message is Win32.WmMouseWheel or Win32.WmMouseHWheel) + { + // Wheel messages carry screen coordinates. + Win32.ScreenToClient(window, ref point); + } + + var page = _page(); + var inside = point.X >= page.Left && point.X < page.Right && point.Y >= page.Top && point.Y < page.Bottom; + if (message != Win32.WmMouseLeave && !inside && !_captured) + { + return IntPtr.Zero; + } + + var kind = (CoreWebView2MouseEventKind)message; + var keys = message == Win32.WmMouseLeave ? CoreWebView2MouseEventVirtualKeys.None : (CoreWebView2MouseEventVirtualKeys)(Win32.LowWord(wParam) & 0xFFFF); + uint data = message switch + { + Win32.WmMouseWheel or Win32.WmMouseHWheel => unchecked((uint)Win32.HighWord(wParam)), + 0x020B or 0x020C or 0x020D => unchecked((uint)Win32.HighWord(wParam)), // X buttons: which one + _ => 0, + }; + + switch (message) + { + case 0x0201 or 0x0204 or 0x0207 or 0x020B: + Win32.SetCapture(window); + _captured = true; + break; + case 0x0202 or 0x0205 or 0x0208 or 0x020C: + Win32.ReleaseCapture(); + _captured = false; + break; + case Win32.WmMouseLeave: + _tracking = false; + break; + } + + if (message == Win32.WmMouseFirst && !_tracking) + { + var track = new Win32.TrackMouseEventInfo + { + Size = (uint)Marshal.SizeOf(), + Flags = Win32.TmeLeave, + Window = window, + }; + _tracking = Win32.TrackMouseEvent(ref track); + } + + controller.SendMouseInput(kind, keys, data, new System.Drawing.Point(point.X - page.Left, point.Y - page.Top)); + handled = true; + return IntPtr.Zero; + } + + private bool CursorInPage(IntPtr window, out Win32.Point point) + { + point = default; + if (!GetCursorPos(out var screen)) + { + return false; + } + + point = screen; + Win32.ScreenToClient(window, ref point); + var page = _page(); + return point.X >= page.Left && point.X < page.Right && point.Y >= page.Top && point.Y < page.Bottom; + } + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetCursorPos(out Win32.Point point); +} diff --git a/src/Febe.Desktop/Browser/CoreWebView2DevTools.cs b/src/Febe.Desktop/Browser/CoreWebView2DevTools.cs new file mode 100644 index 0000000..7c6901d --- /dev/null +++ b/src/Febe.Desktop/Browser/CoreWebView2DevTools.cs @@ -0,0 +1,71 @@ +using System.Windows.Threading; +using Febe.Browser.Cdp; +using Febe.Browser.WebView2; +using Microsoft.Web.WebView2.Core; + +namespace Febe.Desktop.Browser; + +/// +/// The two WebView2 calls of on a (spec §6.1, Windows): +/// CallDevToolsProtocolMethodAsync and GetDevToolsProtocolEventReceiver. WebView2 objects live on the UI +/// thread: every call is queued on its dispatcher (in order), never waited for synchronously, so no thread of the +/// engine can block the window. Allowlist, guard, JSON and logging are in . +/// +internal sealed class CoreWebView2DevTools(Dispatcher ui, CoreWebView2 core) : IWebView2DevTools +{ + private volatile bool _closed; + + /// The WebView is closing: calls fail with from now on. + public void Close() => _closed = true; + + public Task CallMethodAsync(string methodName, string parametersAsJson) + { + if (_closed) + { + return Task.FromException(new CdpDisconnectedException("Il browser di Febe si sta chiudendo.")); + } + + return ui.InvokeAsync(() => + { + if (_closed) + { + throw new CdpDisconnectedException("Il browser di Febe si sta chiudendo."); + } + + return core.CallDevToolsProtocolMethodAsync(methodName, parametersAsJson); + }).Task.Unwrap(); + } + + public IDisposable Subscribe(string eventName, Action onEvent) + { + CoreWebView2DevToolsProtocolEventReceiver? receiver = null; + void Handler(object? sender, CoreWebView2DevToolsProtocolEventReceivedEventArgs e) => onEvent(e.ParameterObjectAsJson); + + // Queued, not waited for: the session may call this while holding its lock. + ui.InvokeAsync(() => + { + if (_closed) + { + return; + } + + receiver = core.GetDevToolsProtocolEventReceiver(eventName); + receiver.DevToolsProtocolEventReceived += Handler; + }); + + return new Removal(() => ui.InvokeAsync(() => + { + if (receiver is not null && !_closed) + { + receiver.DevToolsProtocolEventReceived -= Handler; + } + })); + } + + private sealed class Removal(Action remove) : IDisposable + { + private Action? _remove = remove; + + public void Dispose() => Interlocked.Exchange(ref _remove, null)?.Invoke(); + } +} diff --git a/src/Febe.Desktop/Browser/WebView2Browser.cs b/src/Febe.Desktop/Browser/WebView2Browser.cs new file mode 100644 index 0000000..f717b11 --- /dev/null +++ b/src/Febe.Desktop/Browser/WebView2Browser.cs @@ -0,0 +1,163 @@ +using System.Globalization; +using System.Windows.Media; +using System.Windows.Threading; +using Febe.App; +using Febe.Browser.Cdp; +using Febe.Browser.Hosting; +using Febe.Core.Abstractions; +using Febe.Desktop.Core; + +namespace Febe.Desktop.Browser; + +/// +/// The browser of Instagram on Windows as the shared composition sees it (): a +/// started with retries like starts Chromium, started again +/// when its browser process goes away, and emptied by «Scollega» (spec §4.1) once WebView2 has closed. +/// +internal sealed class WebView2Browser : IFebeBrowser +{ + private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)]; + + private readonly WebView2BrowserSettings _settings; + private readonly FebePlatformContext _context; + private readonly IClock _wallClock; + private readonly BrowserOptions _options; + private volatile bool _started; + private volatile string? _lastError; + + public WebView2Browser(Dispatcher ui, WebView2BrowserSettings settings, FebePlatformContext context, ImageSource? icon) + { + ArgumentNullException.ThrowIfNull(ui); + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _context = context ?? throw new ArgumentNullException(nameof(context)); + + // Starts and retries in wall-clock time, whatever clock the engine runs on. + _wallClock = new SystemClock(context.Clock.LocalZone); + ProfileDirectory = Path.GetFullPath(settings.ProfileDirectory); + _options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height); + Host = new WebView2Host( + ui, + new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now)), + context.Log); + Host.BrowserProcessFailed += (_, _) => _ = RecoverAsync(); + } + + /// The host: window «Browser di Febe», WebView2, CDP. + public WebView2Host Host { get; } + + public ICdpSession Cdp => Host.Cdp; + + public UserDrivingGate UserDriving => Host.UserDriving; + + public bool UserIsDriving => Host.UserIsDriving; + + public bool IsAvailable => _started && Host.IsAttached; + + public string? LastError => _lastError; + + public string ProfileDirectory { get; } + + public int WindowWidth => _settings.Width; + + public int WindowHeight => _settings.Height; + + public async Task RunAsync(CancellationToken ct) + { + for (var attempt = 0; !ct.IsCancellationRequested; attempt++) + { + try + { + await Host.StartAsync(_options, ct).ConfigureAwait(false); + _started = true; + _lastError = null; + _context.Log.Info("browser", $"Browser di Febe pronto: WebView2 {Host.Version}, pagina {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, {BrowserHostingNames.Name(_settings.Hosting)}, fuori vista."); + return; + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + _lastError = $"WebView2 non parte ({ex.GetType().Name}: {FirstLine(ex.Message)})."; + var wait = Retry[Math.Min(attempt, Retry.Length - 1)]; + _context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s."); + await Host.ResetAsync().ConfigureAwait(false); + try + { + await _wallClock.Delay(wait, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return; + } + } + } + } + + public Task RestAsync(CancellationToken ct) => Host.Cdp.RestAsync(ct); + + public Task ShowToUserAsync(CancellationToken ct) => Host.ShowToUserAsync(); + + public Task HideFromUserAsync(CancellationToken ct) => Host.HideFromUserAsync(); + + /// «Scollega»: WebView2 closes and its process exits, Dati\browser is deleted, the browser starts empty. + public async Task RestartWithEmptyProfileAsync(CancellationToken ct) + { + try + { + await Host.RestartAsync(DeleteProfileAsync, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", ex); + } + + _context.Log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto."); + } + + public ValueTask DisposeAsync() => Host.DisposeAsync(); + + /// The browser process of WebView2 went away by itself: it starts again with the same profile. + private async Task RecoverAsync() + { + try + { + await Host.RestartAsync(null, CancellationToken.None).ConfigureAwait(false); + _context.Log.Info("browser", "Browser di Febe ripartito dopo l'arresto del suo processo."); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + _started = false; + _lastError = $"WebView2 non riparte ({ex.GetType().Name})."; + _context.Log.Error("browser", _lastError); + } + } + + /// Deletes the profile; a process of WebView2 may still hold a file for a moment. + private async Task DeleteProfileAsync() + { + for (var attempt = 0; ; attempt++) + { + try + { + if (Directory.Exists(ProfileDirectory)) + { + Directory.Delete(ProfileDirectory, recursive: true); + } + + return; + } + catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && attempt < 10) + { + await Task.Delay(500).ConfigureAwait(true); + } + } + } + + private static string FirstLine(string text) + { + var line = text.Split('\n')[0].Trim(); + return line.Length > 200 ? line[..200] : line; + } +} diff --git a/src/Febe.Desktop/Browser/WebView2Host.cs b/src/Febe.Desktop/Browser/WebView2Host.cs new file mode 100644 index 0000000..22d4b95 --- /dev/null +++ b/src/Febe.Desktop/Browser/WebView2Host.cs @@ -0,0 +1,372 @@ +using System.Runtime.InteropServices; +using System.Windows.Media; +using System.Windows.Threading; +using Febe.App; +using Febe.Browser.Cdp; +using Febe.Browser.Diagnostics; +using Febe.Browser.Hosting; +using Febe.Browser.WebView2; +using Febe.Core.Abstractions; +using Febe.Desktop.Core; +using Microsoft.Web.WebView2.Core; + +namespace Febe.Desktop.Browser; + +/// Windows-only settings of , on top of . +/// or (S2). +/// The switches of S2 (). +/// The icon of the window. +/// Called when Alberto uses the browser and when he is done with it («Riprendi»). +internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed); + +/// +/// The browser host of the Windows edition (spec §5, §6.1, §12): WebView2 in the window «Browser di Febe», with its own +/// user data folder (, Dati\browser), driven through +/// — the same allowlist and refusals as the Chromium client — over +/// CallDevToolsProtocolMethodAsync and GetDevToolsProtocolEventReceiver. No port, no process of ours. +/// +/// +/// +/// Password saving and general autofill off; no developer tools, no zoom: the page has a fixed size. +/// S2: the window is open but parked out of view when Alberto does not use it; the controller stays visible; the +/// switches of turn off occlusion detection. Never hidden, never minimised. +/// Alberto is driving (the engine is still) from «Apri il browser», «Portalo in primo piano» or the login — the +/// window comes on screen — and whenever he clicks into it while it is on screen, until he closes it or presses +/// «Ho finito»; using and closing it marks the browser as used for «Riprendi». +/// Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3); +/// («Scollega») does the same before deleting the profile. +/// Every WebView2 call runs on the UI thread through its dispatcher. +/// +/// +internal sealed class WebView2Host : IBrowserHost +{ + private static readonly TimeSpan ExitWait = TimeSpan.FromSeconds(15); + + private readonly Dispatcher _ui; + private readonly WebView2HostOptions _settings; + private readonly FebeLog _log; + private readonly WebView2CdpSession _session; + private BrowserOptions? _options; + private BrowserWindow? _window; + private CoreWebView2Environment? _environment; + private CoreWebView2Controller? _controller; + private CompositionHost? _composition; + private CoreWebView2DevTools? _devTools; + private TaskCompletionSource? _exited; + private IDisposable? _lease; + private bool _closing; + private bool _restarting; + + public WebView2Host(Dispatcher ui, WebView2HostOptions settings, FebeLog log) + { + _ui = ui ?? throw new ArgumentNullException(nameof(ui)); + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _log = log ?? throw new ArgumentNullException(nameof(log)); + _session = new WebView2CdpSession(log.ForBrowser()); + } + + /// The page session: stable for the whole life of the host (a restart attaches a new WebView to it). + public ICdpSession Cdp => _session; + + /// Raised when a new WebView replaced the previous one (subscriptions survive; domains are enabled again). + public ICdpConnectionEvents Connection => _session; + + /// Leases taken while Alberto uses the browser. + public UserDrivingGate UserDriving { get; } = new(); + + public bool UserIsDriving => UserDriving.IsDriving; + + /// True while a WebView is attached (commands can be sent). + public bool IsAttached => _session.IsAttached; + + /// The version of the WebView2 runtime in use (for the log). + public string? Version => _environment?.BrowserVersionString; + + /// Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts). + public event EventHandler? BrowserProcessFailed; + + /// Creates the window (once), the environment and the controller, and attaches the CDP session. + public Task StartAsync(BrowserOptions options, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(options); + _options = options; + return OnUiAsync(StartCoreAsync); + } + + public Task ShowToUserAsync() => OnUiAsync(() => + { + if (_window is not { } window) + { + return Task.CompletedTask; + } + + window.MoveOnScreen(); + window.Activate(); + window.Topmost = true; + window.Topmost = false; + _controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic); + TakeLease(); + return Task.CompletedTask; + }); + + public Task HideFromUserAsync() => OnUiAsync(() => + { + _window?.MoveOffScreen(); + ReleaseLease(); + return Task.CompletedTask; + }); + + /// + /// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs + /// — «Scollega» deletes the profile there — and starts it again. + /// stays the same object. The browser starts again even when fails; its error is + /// thrown afterwards. + /// + public Task RestartAsync(Func? whileStopped, CancellationToken ct) => OnUiAsync(async () => + { + _restarting = true; + try + { + await CloseWebViewAsync().ConfigureAwait(true); + Exception? failure = null; + try + { + if (whileStopped is not null) + { + await whileStopped().ConfigureAwait(true); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + failure = ex; + } + + await StartCoreAsync().ConfigureAwait(true); + if (failure is not null) + { + throw failure; + } + } + finally + { + _restarting = false; + } + }); + + /// Closes what a failed start left, so that the next start begins clean. + public Task ResetAsync() => OnUiAsync(CloseWebViewAsync); + + public async ValueTask DisposeAsync() + { + try + { + await OnUiAsync(async () => + { + _closing = true; + ReleaseLease(); + await CloseWebViewAsync().ConfigureAwait(true); + _window?.CloseForGood(); + _window = null; + }).ConfigureAwait(false); + } + catch (Exception ex) when (ex is InvalidOperationException or TaskCanceledException) + { + // The dispatcher already stopped: Windows closes what is left. + } + + await _session.DisposeAsync().ConfigureAwait(false); + } + + private async Task StartCoreAsync() + { + var options = _options ?? throw new InvalidOperationException("Opzioni del browser mancanti."); + if (_window is null) + { + var window = new BrowserWindow(options.WindowWidth, options.WindowHeight, _settings.Icon); + window.MoveOffScreen(); + window.Show(); + window.Activated += OnActivated; + window.DoneRequested += (_, _) => Done(); + window.BackRequested += (_, _) => UserNavigation(core => core.GoBack(), core => core.CanGoBack); + window.ReloadRequested += (_, _) => UserNavigation(core => core.Reload(), _ => true); + window.DpiChanged += (_, _) => UpdateBounds(); + _window = window; + } + + var profile = Path.GetFullPath(options.ProfileDirectory); + Directory.CreateDirectory(profile); + var environmentOptions = new CoreWebView2EnvironmentOptions { AdditionalBrowserArguments = _settings.AdditionalBrowserArguments }; + _environment = await CoreWebView2Environment.CreateAsync(null, profile, environmentOptions).ConfigureAwait(true); + _exited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _environment.BrowserProcessExited += OnBrowserProcessExited; + + var hwnd = _window.Handle; + if (_settings.Hosting == BrowserHosting.Composition) + { + var composition = await _environment.CreateCoreWebView2CompositionControllerAsync(hwnd).ConfigureAwait(true); + _composition = new CompositionHost(hwnd, () => _window?.PageBounds ?? default); + _composition.Attach(composition); + _controller = composition; + } + else + { + _controller = await _environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true); + } + + var controller = _controller; + controller.BoundsMode = CoreWebView2BoundsMode.UseRawPixels; + controller.Bounds = _window.PageBounds; + + // WebView2 stops painting when IsVisible is false (S2): it stays true for the whole life of the browser. + controller.IsVisible = true; + + var core = controller.CoreWebView2; + var s = core.Settings; + s.IsPasswordAutosaveEnabled = false; + s.IsGeneralAutofillEnabled = false; + s.AreDevToolsEnabled = false; + s.IsZoomControlEnabled = false; + s.IsPinchZoomEnabled = false; + s.IsSwipeNavigationEnabled = false; + core.NewWindowRequested += OnNewWindowRequested; + core.DownloadStarting += (_, e) => e.Cancel = true; + core.PermissionRequested += (_, e) => e.State = CoreWebView2PermissionState.Deny; + core.SourceChanged += (_, _) => _window?.ShowAddress(Addresses.WithoutQuery(core.Source)); + core.ProcessFailed += OnProcessFailed; + core.Navigate(CdpPageExtensions.RestUrl); + + _devTools = new CoreWebView2DevTools(_ui, core); + _session.Attach(_devTools); + await _session.SendAsync("Page.enable", null, CancellationToken.None).ConfigureAwait(true); + } + + /// Closes the controller and waits for the browser process to exit (the profile is written). UI thread. + private async Task CloseWebViewAsync() + { + _session.Detach(); + _devTools?.Close(); + _devTools = null; + var exited = _exited; + if (_controller is { } controller) + { + _controller = null; + try + { + _composition?.Dispose(); + controller.Close(); + } + catch (Exception ex) when (ex is COMException or InvalidOperationException) + { + // The browser process is already gone (it crashed): nothing left to close. + } + + _composition = null; + if (exited is not null) + { + await Task.WhenAny(exited.Task, Task.Delay(ExitWait)).ConfigureAwait(true); + } + } + + if (_environment is { } environment) + { + environment.BrowserProcessExited -= OnBrowserProcessExited; + _environment = null; + } + } + + private void OnBrowserProcessExited(object? sender, CoreWebView2BrowserProcessExitedEventArgs e) => _exited?.TrySetResult(); + + private void OnProcessFailed(object? sender, CoreWebView2ProcessFailedEventArgs e) + { + _log.Warn("browser", $"WebView2: processo terminato ({e.ProcessFailedKind})."); + if (_closing || _restarting) + { + return; + } + + if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited) + { + // The whole browser is gone: the owner starts it again (same profile), as the supervisor does with Chromium. + _session.Detach(); + BrowserProcessFailed?.Invoke(this, EventArgs.Empty); + } + else if (e.ProcessFailedKind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive) + { + // The page crashed: back to the rest page (spec §6.1); a running recipe ends on its own errors. + (sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl); + } + } + + private void OnNewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e) + { + // Pages that open a new window stay in this one: the session stays in the profile of Febe. + e.Handled = true; + if (sender is CoreWebView2 core && Uri.TryCreate(e.Uri, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https") + { + core.Navigate(uri.AbsoluteUri); + } + } + + /// + /// Alberto clicked into the window while it is on screen: he is driving. An activation while it is parked out of view + /// is not his (Windows activates the next window when another one closes) and changes nothing. + /// + private void OnActivated(object? sender, EventArgs e) + { + if (_window is not { } window || _closing || !window.IsOnScreen) + { + return; + } + + TakeLease(); + } + + /// Alberto closed or minimised the window: done, out of view. + private void Done() + { + _window?.MoveOffScreen(); + ReleaseLease(); + } + + private void UserNavigation(Action action, Func allowed) + { + // «Indietro» and «Ricarica» of the bar are Alberto's own navigation (rule 7): never an engine action. + if (_controller?.CoreWebView2 is { } core && allowed(core)) + { + TakeLease(); + action(core); + } + } + + private void UpdateBounds() + { + if (_controller is { } controller && _window is { } window) + { + controller.Bounds = window.PageBounds; + } + } + + private void TakeLease() + { + if (_lease is null) + { + _lease = UserDriving.Begin(); + _log.Info("browser", "Alberto usa il browser di Febe: il motore resta fermo."); + } + + _settings.MarkUsed(); + } + + private void ReleaseLease() + { + if (_lease is { } lease) + { + _lease = null; + _settings.MarkUsed(); + lease.Dispose(); + _log.Info("browser", "Browser di Febe fuori vista."); + } + } + + private Task OnUiAsync(Func action) => _ui.CheckAccess() ? action() : _ui.InvokeAsync(action).Task.Unwrap(); +} diff --git a/src/Febe.Desktop/DesktopApplication.cs b/src/Febe.Desktop/DesktopApplication.cs new file mode 100644 index 0000000..3fe73ab --- /dev/null +++ b/src/Febe.Desktop/DesktopApplication.cs @@ -0,0 +1,376 @@ +using System.Diagnostics; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Threading; +using Febe.App; +using Febe.Core.Abstractions; +using Febe.Core.Storage; +using Febe.Desktop.Core; +using Febe.Web.Library; + +namespace Febe.Desktop; + +/// +/// Febe for Windows (spec §5, §12): the shared composition with the , +/// the main window on the interface, the icon in the notification area, the window «Browser di Febe». Closing the main +/// window keeps Febe working in the notification area (setting «Chiudendo la finestra, Febe resta attivo…», on by +/// default); «Esci» stops everything in order, the browser of Instagram last but one, so its session is on disk. +/// +internal sealed class DesktopApplication : Application +{ + private const string TrayNoticeKey = "desktop.avviso-area-di-notifica"; + + private readonly DesktopOptions _options; + private readonly DesktopFolders _folders; + private readonly IDataFolderLocationStore _locations; + private readonly bool _dataFolderFixed; + private readonly SingleInstanceGuard _instance; + private readonly CancellationTokenSource _lifetime = new(); + private string _dataFolder; + private ImageSource? _iconImage; + private TrayIcon? _tray; + private DesktopPlatform? _platform; + private FebeApp? _app; + private MainWindow? _main; + private Task? _opening; + private bool _exiting; + + public DesktopApplication(DesktopOptions options, DesktopFolders folders, IDataFolderLocationStore locations, string dataFolder, bool dataFolderFixed, SingleInstanceGuard instance) + { + _options = options; + _folders = folders; + _locations = locations; + _dataFolder = dataFolder; + _dataFolderFixed = dataFolderFixed; + _instance = instance; + ShutdownMode = ShutdownMode.OnExplicitShutdown; + DispatcherUnhandledException += OnDispatcherUnhandledException; + TaskScheduler.UnobservedTaskException += (_, e) => e.SetObserved(); + SessionEnding += OnSessionEnding; + } + + protected override async void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + try + { + await StartAsync().ConfigureAwait(true); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + _app?.Log.Error("avvio", "Febe non è partito.", ex); + MessageBox.Show( + $"Febe non è riuscito a partire: {ex.Message}\n\nControlla il registro nella cartella dei dati ({Path.Combine(_dataFolder, "registro")}) e riprova.", + "Febe", + MessageBoxButton.OK, + MessageBoxImage.Error); + await ExitAsync().ConfigureAwait(true); + } + } + + private async Task StartAsync() + { + var icon = LoadIcon(); + _iconImage = LoadIconImage(); + _tray = new TrayIcon(icon, NeedsResume); + _tray.OpenRequested += (_, _) => ShowMain(); + _tray.PauseToggleRequested += (_, resume) => _ = TogglePauseAsync(resume); + _tray.ExitRequested += (_, _) => _ = ExitAsync(); + + // A move of the Data folder asked in Impostazioni happens now, before anything opens the folder. + DataFolderMoveResult? moved = null; + if (!_dataFolderFixed && _locations.Pending is not null) + { + moved = await MoveDataFolderAsync().ConfigureAwait(true); + _dataFolder = moved.DataFolder; + if (moved.Message is { } message) + { + _tray.Notify("Cartella dei dati", message, moved.Outcome != DataFolderMoveOutcome.Moved); + } + } + + var native = new WindowsShell(Dispatcher, () => _main, () => _tray); + var shell = new DesktopShell(Dispatcher, _iconImage, native, new WindowsNotificationChannel(Dispatcher, () => _tray)); + _platform = new DesktopPlatform(_options, shell, _locations, _dataFolderFixed); + _app = await FebeApp.StartAsync(_options.AppOptions(_dataFolder, _folders), _platform, new FebeAppHooks(), _lifetime.Token).ConfigureAwait(true); + if (moved?.Message is { } outcome) + { + if (moved.Outcome == DataFolderMoveOutcome.Moved) + { + _app.Log.Info("dati", outcome); + } + else + { + _app.Log.Warn("dati", outcome); + } + } + + if (_app.Problems.FirstOrDefault(p => p.Code == DesktopStartupChecks.WebView2Missing) is { } missing) + { + // Without WebView2 not even the error page can be shown: a dialog of Windows says it. + var answer = MessageBox.Show( + $"{missing.Title}.\n\n{missing.Message}\n\n{missing.Remedy}\n\nVuoi aprire adesso la pagina di Microsoft?", + "Febe", + MessageBoxButton.YesNo, + MessageBoxImage.Warning); + if (answer == MessageBoxResult.Yes) + { + await native.OpenUrlAsync(new Uri(DesktopStartupChecks.WebView2DownloadPage), CancellationToken.None).ConfigureAwait(true); + } + + await ExitAsync().ConfigureAwait(true); + return; + } + + _instance.Listen(request => Dispatcher.InvokeAsync(() => + { + if (request == InstanceRequest.Show) + { + ShowMain(); + } + })); + _ = Task.Run(() => FollowEngineAsync(_lifetime.Token)); + + if (!_options.StartHidden || _app.Problems.Count > 0) + { + ShowMain(); + } + } + + /// Opens (the first time) and shows the main window. + private void ShowMain() + { + if (_exiting || _app is null || _platform is null) + { + return; + } + + if (_main is null) + { + // The window keeps its own WebView2 data in Dati\interfaccia; with a problem of the Data folder (on a network + // share, not writable) it cannot go there, and the page that explains the problem must still show. + var interfaceData = _app.Problems.Count == 0 + ? Path.Combine(_dataFolder, "interfaccia") + : Path.Combine(Path.GetTempPath(), "Febe-interfaccia"); + _main = new MainWindow(_iconImage, interfaceData, _app.Address, _options.DeveloperTools, uri => OpenOutside(uri)); + _main.CloseRequested += (_, _) => _ = MainClosedAsync(); + } + + _main.Present(); + _opening ??= OpenInterfaceAsync(_main, _platform.FirstAddress(_app.Address)); + } + + private async Task OpenInterfaceAsync(MainWindow window, Uri first) + { + try + { + await window.OpenAsync(first).ConfigureAwait(true); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + _app?.Log.Error("finestra", "L'interfaccia non si è aperta nella finestra.", ex); + _opening = null; + } + } + + private Task OpenOutside(Uri uri) => + _app?.Web.Services.GetService(typeof(Febe.Web.Native.INativeShell)) is Febe.Web.Native.INativeShell shell + ? shell.OpenUrlAsync(uri, CancellationToken.None) + : Task.FromResult(false); + + /// The X of the main window: into the notification area (default), or exit. + private async Task MainClosedAsync() + { + if (_app is null || _main is null) + { + return; + } + + var keep = _app.Problems.Count == 0 + && await _app.Database.Settings.GetBoolAsync(DesktopSettingKeys.KeepInTray, true, CancellationToken.None).ConfigureAwait(true); + if (!keep) + { + await ExitAsync().ConfigureAwait(true); + return; + } + + _main.Hide(); + if (!await _app.Database.Settings.GetBoolAsync(TrayNoticeKey, false, CancellationToken.None).ConfigureAwait(true)) + { + await _app.Database.Settings.SetBoolAsync(TrayNoticeKey, true, CancellationToken.None).ConfigureAwait(true); + _tray?.Notify("Febe continua a lavorare", "Febe resta attivo qui, nell'area di notifica. Per fermarlo: clic destro sull'icona ▸ Esci."); + } + } + + /// «Riprendi» needs Alberto: after a pause, a verification or a disconnection. + private bool NeedsResume() + { + if (_app?.Engine is not { } engine) + { + return false; + } + + return engine.Services.Runtime.IsPaused + || engine.Services.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected; + } + + private async Task TogglePauseAsync(bool resume) + { + if (_app?.Engine is not { } engine || _tray is null) + { + return; + } + + try + { + if (!resume) + { + await engine.PauseAsync(CancellationToken.None).ConfigureAwait(true); + _tray.Notify("Febe è in pausa", "Non apre nulla finché non premi «Riprendi»."); + return; + } + + var breaker = engine.Services.Breaker.State; + if (breaker.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected + && !(_app.Tracker.LastUsedAt is { } used && used >= (breaker.LastSignal?.At ?? DateTimeOffset.MinValue))) + { + // The same rule as the interface (mockup 11): first the browser, then «Riprendi». + _tray.Notify("Prima il browser", "Instagram ha chiesto una verifica: completala nel browser di Febe (pagina Collegamento), poi premi «Riprendi».", warning: true); + ShowMain(); + return; + } + + var result = await engine.ResumeAsync(CancellationToken.None).ConfigureAwait(true); + _tray.Notify(result.Resumed ? "Febe riprende" : "Febe non riprende", result.Message, !result.Resumed); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + _app.Log.Warn("area-di-notifica", "Comando del menu non riuscito.", ex); + } + } + + /// The tooltip of the icon follows the engine (the line of the sidebar). + private async Task FollowEngineAsync(CancellationToken ct) + { + if (_app?.Engine is not { } engine) + { + return; + } + + try + { + await foreach (var _ in engine.Monitor.SubscribeAsync(ct).ConfigureAwait(false)) + { + var snapshot = await engine.Monitor.GetSnapshotAsync(ct).ConfigureAwait(false); + await Dispatcher.InvokeAsync(() => _tray?.SetStatus(snapshot.SidebarLine)); + } + } + catch (OperationCanceledException) + { + } + catch (Exception ex) when (ex is InvalidOperationException or TaskCanceledException) + { + } + } + + private async Task MoveDataFolderAsync() + { + var text = new TextBlock { Text = "Febe sposta la cartella dei dati: copia ogni file e lo controlla.", Margin = new Thickness(0, 0, 0, 12), TextWrapping = TextWrapping.Wrap }; + var bar = new ProgressBar { Height = 16, Minimum = 0, Maximum = 1 }; + var window = new Window + { + Title = "Febe", + Icon = _iconImage, + Width = 460, + SizeToContent = SizeToContent.Height, + ResizeMode = ResizeMode.NoResize, + WindowStartupLocation = WindowStartupLocation.CenterScreen, + Content = new StackPanel { Margin = new Thickness(20), Children = { text, bar } }, + }; + window.Show(); + try + { + var progress = new Progress(p => + { + bar.Maximum = Math.Max(1, p.FilesTotal); + bar.Value = p.FilesDone; + }); + var current = _dataFolder; + return await Task.Run(() => DataFolderMove.ApplyPending(_locations, current, progress)).ConfigureAwait(true); + } + finally + { + window.Close(); + } + } + + /// «Esci»: everything stops in order (engine, downloads, browser, database), then the process ends. + private async Task ExitAsync() + { + if (_exiting) + { + return; + } + + _exiting = true; + _main?.Hide(); + await StopAsync().ConfigureAwait(true); + Shutdown(); + } + + private async Task StopAsync() + { + await _lifetime.CancelAsync().ConfigureAwait(true); + if (_app is { } app) + { + _app = null; + await app.DisposeAsync().ConfigureAwait(true); + } + + _main?.CloseForGood(); + _main = null; + _tray?.Dispose(); + _tray = null; + } + + /// Windows is shutting down or Alberto logs off: stop in order while the messages still flow (S3). + private void OnSessionEnding(object sender, SessionEndingCancelEventArgs e) + { + if (_exiting) + { + return; + } + + _exiting = true; + var stop = StopAsync(); + var frame = new DispatcherFrame(); + _ = stop.ContinueWith(_ => frame.Continue = false, TaskScheduler.Default); + var timer = new DispatcherTimer(TimeSpan.FromSeconds(20), DispatcherPriority.Send, (_, _) => frame.Continue = false, Dispatcher); + timer.Start(); + Dispatcher.PushFrame(frame); + timer.Stop(); + } + + private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) + { + // Logged by type and first line only (no addresses, see FebeLog); Febe keeps running. + _app?.Log.Error("finestra", "Errore imprevisto nell'interfaccia di Windows.", e.Exception); + e.Handled = true; + } + + private static System.Drawing.Icon LoadIcon() + { + using var stream = typeof(DesktopApplication).Assembly.GetManifestResourceStream("Febe.ico") + ?? throw new InvalidOperationException("Febe.ico non è incorporata."); + return new System.Drawing.Icon(stream, System.Windows.Forms.SystemInformation.SmallIconSize); + } + + /// The icon for WPF windows: the frame of the .ico, whose decoder lets WPF pick the small and large sizes. + private static ImageSource? LoadIconImage() + { + using var stream = typeof(DesktopApplication).Assembly.GetManifestResourceStream("Febe.ico"); + return stream is null ? null : BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); + } +} diff --git a/src/Febe.Desktop/DesktopShell.cs b/src/Febe.Desktop/DesktopShell.cs new file mode 100644 index 0000000..6d4376c --- /dev/null +++ b/src/Febe.Desktop/DesktopShell.cs @@ -0,0 +1,107 @@ +using System.Diagnostics; +using System.Windows; +using System.Windows.Media; +using System.Windows.Threading; +using Febe.App; +using Febe.Desktop.Browser; +using Febe.Desktop.Core; +using Febe.Desktop.Native; +using Febe.Web.Native; +using Microsoft.Web.WebView2.Core; +using Microsoft.Win32; + +namespace Febe.Desktop; + +/// The Windows-only part the desktop platform needs (WebView2, Edge's window, native shell, notifications). +internal sealed class DesktopShell(Dispatcher ui, ImageSource? icon, INativeShell native, IAlertChannel notifications) : IDesktopShell +{ + public INativeShell Native { get; } = native; + + public IAlertChannel? Notifications { get; } = notifications; + + public string? WebView2Version() + { + try + { + return CoreWebView2Environment.GetAvailableBrowserVersionString(); + } + catch (WebView2RuntimeNotFoundException) + { + return null; + } + } + + public IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context) => + new WebView2Browser(ui, settings, context, icon); + + public string? FindEdge() + { + string? appPath = null; + foreach (var hive in new[] { Registry.CurrentUser, Registry.LocalMachine }) + { + using var key = hive.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\App Paths\msedge.exe", writable: false); + if (key?.GetValue(null) is string value && !string.IsNullOrWhiteSpace(value)) + { + appPath = value; + break; + } + } + + return EdgeLocator.Find(EdgeLocator.Candidates( + appPath, + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData))); + } + + public Task ShowProcessWindowAsync(int processId, CancellationToken ct) => ui.InvokeAsync(() => + { + if (MainWindowOf(processId) is not { } window) + { + return; + } + + if (Win32.IsIconic(window)) + { + Win32.ShowWindow(window, Win32.SwRestore); + } + + var area = SystemParameters.WorkArea; + var dpi = Win32.SystemScale; + Win32.SetWindowPos(window, IntPtr.Zero, (int)(area.Left * dpi) + 40, (int)(area.Top * dpi) + 40, 0, 0, Win32.SwpNoSize | Win32.SwpNoZOrder); + Win32.SetForegroundWindow(window); + }).Task; + + public Task HideProcessWindowAsync(int processId, CancellationToken ct) => ui.InvokeAsync(() => + { + if (MainWindowOf(processId) is not { } window) + { + return; + } + + // Out of view, never minimised (S2): just right of every screen. + var dpi = Win32.SystemScale; + var x = (int)((SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth) * dpi) + 64; + var y = (int)(SystemParameters.VirtualScreenTop * dpi); + if (Win32.IsIconic(window)) + { + Win32.ShowWindow(window, Win32.SwShowNoActivate); + } + + Win32.SetWindowPos(window, IntPtr.Zero, x, y, 0, 0, Win32.SwpNoSize | Win32.SwpNoZOrder | Win32.SwpNoActivate); + }).Task; + + private static IntPtr? MainWindowOf(int processId) + { + try + { + using var process = Process.GetProcessById(processId); + process.Refresh(); + return process.MainWindowHandle == IntPtr.Zero ? null : process.MainWindowHandle; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + { + return null; + } + } +} diff --git a/src/Febe.Desktop/Febe.Desktop.csproj b/src/Febe.Desktop/Febe.Desktop.csproj index 646ada6..d66b943 100644 --- a/src/Febe.Desktop/Febe.Desktop.csproj +++ b/src/Febe.Desktop/Febe.Desktop.csproj @@ -1,6 +1,9 @@ + Si compila anche da Linux grazie a EnableWindowsTargeting (CI e rilascio), ma gira solo su Windows. + Pubblicazione in un solo Febe.exe (specifica §12): il comando completo è in installer/costruisci.sh. + Le librerie native (e_sqlite3, libSkiaSharp, WebView2Loader e quelle di WPF) stanno dentro l'eseguibile e si + estraggono da sole al primo avvio; i file di configurazione e i simboli non escono accanto all'eseguibile. --> WinExe net10.0-windows @@ -9,12 +12,42 @@ true Febe Febe.Desktop + Febe.ico + app.manifest + Febe.Desktop.Program + false + + embedded + false + + $(NoWarn);WFO0003 + + + + + + + + + + + + + + + + + + diff --git a/src/Febe.Desktop/Febe.ico b/src/Febe.Desktop/Febe.ico new file mode 100644 index 0000000000000000000000000000000000000000..9665cdbdf4e593dd186ee44e6c9c828badf882ba GIT binary patch literal 112119 zcmeGl2Rzl^_e-I&DvGAGheT3JQle5xB@NF^Lz5^J*&233A(W<3Mv{_@gi2OMC?hI6 zWY71%=kFpQh~$Md=2 z7?y+HO_}oJ*%O7^$A)170{=bFz%Vu*3|qPK$Mb9n40|kzVJ0U3JrAS9a?T)x2mpW8 zOblbRr^9BWXM_s9`SBiIu$3sC_P`d$y3rcP_R>a?y#oF4UHmE_EW`m^Hj1p9y9nP2 zJ`@+n7TfLkD6Tb*y^=J(qXsYjeawA)^|vqh=EgdFQEnnWz(KKH8pz{19hr^deZ_x_ z55hlnJ%abO-GPtwv%)vjR^p?)&DzC5ns!c72tMxf^>YS$MN67*sG4g z*H?e*kTzm`Kii%7nu;R)t<&N^aX9Se#wR^@#~0=#{Cr0Y-`@3wr!l^*wS^$R;@l)W z@T52|8J`q(9pBVYgU?QU(j^}E6N?D)i@awA^FIlgCjZ208y6Oo2j7z{zh}*OB17)x$<=2D`Fmw+fF4QxqD#K89MW}xOlPapy zIs+R8HYFPz`vX*ud?Dv^SI>kvC@$b2Ps3&x>ueiEwuY{7Q2ZUoUVR=nd?GO&R98Kr zIBwVVC_xuce*6J{&+5^x>TE(i+bQk$%+?a>xU4q;_|zA7@XtL?;9YeDe%05G@&tUr zu@$w)8>p93qwfAJd!#olO%3>nI|f~+(E;vD`*`r*3O^E1wzf3m)1$rdj~sX7pWoEQ z=ch&fObXhA_Gs($ozh5rUP>4NNBP$*yvHfg-*7x~RL3{ge`S|{m`yM+(dj(Hv_mG7wR%BF%Hz}0KjkJ zyN<5!!aWFKA6``HGAt2CQm7jtPS`EIF5^I(0N`(r>oP16fAoDzLY%C)hn>c8P~*ba zeJ>+~y<@z()38L`aJ{Cz0N>nHPl$K_{FV;my?uO{5T@kQJG`y(=nlh?;wIihTMf`u zUyb)ZEBjmAC~s4O?m*da*A@QlI}uN3*Y`0#gf!aPS_y4$T+l^4$mZ*ZH$UE^wmQno z6rU1#3;(_RGogCB-!c>@^dCrGOMB16vO-McnY-4n_yKnh+7=g0 zK75StIXu+ekUyw%f1v~6wpL_S`{f;3ebke0fE(H{7#H*ePy2D%q5wC5jlwVQ-+4{4Fo;Vq91 zL2(i~j7P(=0coHyMk1t1qyf>S-&bi9(?Pnf1?gKUu+2dCjl}nTc13+@J4LqX1esIG zUl^A|+uK<`iIRN$r*ED1gNb;c%`VK2C-l3B^)_5#PT}jvIK0of-`iVa+zzju^plBk zV62_+)QL37_U}=jF#gF^yqyZ?uXTNAyzQb5gZ>AxT_+~mP+LK058nh`AY2>ks)(Nm zSHgH0^_7YA_v8w5EkuBHerqTH%Nz82i2ZH|4}H0wqziFx8?7Srl>i^iVK^O`(q-9Kh2J0~-;?|UPl)n|Ik)zB)X}@{#v{i^)PKlK;AJ(6Xb8Hphsb)u_=6lLHP58w zzrLmd59PbF_|BU1@Wi?h<|}(z{voXxzwn7@#|SaB9;d4-aWV+5kWY8iQnzhv~)VBx2rwP=Ln9XiNxW!`>c$LcX2%VGP7{ z$*(X*M)`JzF*EwnZ2V2owRXnel^Dhzfnh^T&@=)3$myZ=GclbAlqRGN^ArN;r;2_* z=PA${H#K0Rz_P+tk~N2LP&!xlaQt&n+ecB4b2c1){;>Cz+R^n z)$I5=c*g@%DXSl;)}R0Qf@9YJIrM~nSbKlz zV@?=v{OsJ4+`#-7%=v(A6SeDxUC~9L9mk&6Rk-%P!#Eh$p{RkHibBFzuDkO$F&fxBvu^>N0p=!vHqvk% z-NU%?b7t%>@!^3MbJ`uHN&23+zE30o_}QJg3#f}o0p!`;`A|~&I=d&Gw?4&^v z-^uYhsE@-}mgExA5U#)*@^G|#CfXDd6K&6Sl$!Lw&J=7tegaw}x~ws!*YW_ivZO$2 z_el-iq+xU4JtsxkEn5##d>!4x93?4$zIHZu(-9u>_pbx(NzvjHLtJ`={~o87|B?>a z?vm5eo#((ys=wfcw!Axdx{3qqr=$S3dtJq$ndJH--&CvM5M5$ z)KOSkya#^4`W7jW+V@kFhSwPxQZ$77@H?k^m42X)Xah=`IM`eNW&_yCSQcm}+AQ-f7+pw(gF8i zn+$u0puK=_V0Q}kt3Wr{%eDt#p9c?Q>?z8KeL&dz1M?WPq?;5MjQL1y=G&vI zt9LLb@$iB&VLiINuuwmMT{LOBw7v&Be4^cTdo*(kI@BjO^jL&@ofXKL)&iFmtnh5j_`34=ayTGTzlehRR+hj99;Z5ItH0_!D^rnt^rz zTLqR?=(+h%(9yj#*_x~s*d>2Z|KmSe2f%d?*MDm{o%EY&jThE>Noj|BJTj9YtY7!% zvH-Lxuo(ia_0dTRw%b<~Gz*DnCgPVa-L&^)c4>TEB?hxUwA2MGP* ze$XfGEB-^@`=UI{7$OgPYfnjE<)=I8K%OE07jYO{cWmvtlV*R4gZhe%u&<+c{Wkr- zz64t;*pnW9`y|1?5!_SkpQ)GX0W^kO*IT*|c9f5u_Tyo_0Op)K0$5W58x^oSpoQ%v zH97`)M|A;B_p@EtGl8&P0=}`R1z7ib6<~{pbx~^a(cQ3wym!-1__s9CIxy_p1AkaO z1=zn2K81cugVyDMkoTUi)4;lLe){ig;63F-UP?G&&AIpZ(DS@Q9R~KvlmM&^g0Hfo zoWx)JId&Eo?3uy#zxR0X|2mr5G+><<>?}G0uuXwApL^!(+NB@t0X)s63HAjI$VX{M z0CqI(?#HEdd7uIx=zM4Ebje}Y@t5{ZZa3fU@fqw~QzCA5!~%j3QEF^r+Dn6$?}&aI z$O&#j``-N>DEDJWP7~MyG1QF$L*X#Ns z6zdeN@=K1Vqq-jaNs@={?lZX^FOd;o=h9uAw1@}xPwfHNIMD(>DUSAh6F}PC^@T`^ zySw+K{$hxHXhQwltA}RNJpbUsqP@C+5}%sg&0kmX$nE=q2Vfi2RlM$gC*R)!=~3cC zy1VIh77u)TwI`46?pf(9E#f!m2a`ineNB)3qY&{^bM2_?_rzaJSLuU2a(nP6>HzXR z13(w})9ES?J^fDVD~-qt*mKuYywt`g_18qCgI49H39sEB#;OqpiLE7VKN1b-pOYclGd0^6V3y zyLCoE7c%R}4?|z??gP!_HCC^KDp25Dmqcx4&r&sn^H_7*Q z68Qk<1oUQGLk%woXA=+!Bf0kG{8wk^Cs9K?t-`|I-i`qFL%SVcNU<)!*&Q&4(h+=0 z4W}3vt@76u9yq_Hy}l`F9>8x2^wry&yM=d9XAsZ-AdN?QUs05e=8|~`IKa0o`0oU~ zvHsS0IA6tvM*ge2%5Qt$VOa`+%c(*xw63xCh^7u-4OAy5N_d8UX)To#7j3 z-(U|pH9-B@N&SrJRP&?GL)z4@=4$s@LF9-f3cd zGC)iIK%OD*0La%aC$fp}^*xldq`ybFkk4&W`*#8l{=k`LJ<3BT^?H|h+ws+HvJxAL z>VcRpjAj`*&1l?GJ{kEfW75Nmu?|_NI?9^N58s1ts6)-wdeUFe@oMtp8P1{s=+J-2kI#eu zd&&Wm9|(T(JL1RlPkH41cxEEXjVMQ=T#0ff${qYfm_QsPxu1R_hW!~aBA-!wNRPLp zdiMnKJ8&6|&mW@aWK@q;{^@e|r_%=>051?<0)Oy^^@J^seFyLi#5WMZS_xw&oJ$1f zXZ_Xt?y2afbz_Y1AMc!zzYbYDd2D!p*9ACl9_={}`O{_UZ%iN6nf0iCcnm!5PkI18 z7Z6=X2>qsR==k3#t6t9&jy)T-8T;GwchOh60d+jI=SVLLdp*B{de#110{C#kvFd^> z`bzGQj+Fwl04ndfgL3cP_Mc+@!g}8>X8yj=0m4|hKlq0mtP_5%6VRLms*5{4Z?h-* zfyS3~s6T3e+WLX#`}beb6_5>%%?M=G6IqkTg|P?BwNhLk{VV+LulYoC3AE}P5@e6& zAO~gNPuhA4bq>|liL}rGRPOH#%6?$UorOj1 z5tQhFtpeM6)Sqk}l;0ngUk}R}$j}PMzJ?N+6T^T#0ct<~`L&t9M)#3jn3V$C45ECy zx}v$oKX%5>U&HermRnl$0c6^h+~GU;4yAS4gZTPK8v?TJOb5W9KI-$m8y!w~CXf6-5ZU?d^ZwJsg!Gz{% z^|L}$sEc)VL#MBo$EzD1i)YB8+49+*_RCRE%X#WgI}B12*+L1HGkaCPM?)S zG$#z_Bn`CrKJX9v@RAC_uTEWcImI%jG+^ELGJ@aFhZj}a^=;N?^67*6lOX#6vc?N? zhclF#(K#G_1>g(vRe((oeNpt^z6G-F(CY8!BZ8lt@H?j{_LbHfx&ieJobLv-{7vPb zAp8E>_d{(voHN(iIZVAF>&|e3FCsY4?yu1SB>Voj)(drgM`!VLCZE3g*8AtT^-Y@r zvPW$|zw(LUsx5&3hWx_zcK{lx^GVk?GNq<&0@?Q`J0DMr_4tOms{StepY(x$PoS9^ zp7*D){YmzrH+1mrod@!h+5PkeXa?H*lUxTHEeTJZXewP8Bf{CGaHbyk&U_Pe0sr># zWx_qYt1Qk%=TFqrG|jljmj-p98*>&gw(BW?FXj(#AK^nij#G7p;C0=_gfqK8#s?vP z&K;lAN-2HMJx&bj02MmmgU(8CYi*^Jy}yNPM12J~JHk$dqsM%QGXUXC-}cUA`z_%P zUO-+3a(|#N+YLBFqY<5Z(j91PYsJGk#JzD|4*2_r^NJyj?f~>(;p~XM$L3>RtKs)ikdfOl4C8XV*wkqtF{vV^6TDkN^c<|{?>6te~9f5O_ z`or1qa7Oa?^3O!FD7w~FmHzc>$kgZ!oa;pm!1?RIcWTn;&9FdAd*@bmmZ#_kXZj8O zy~&%daKo8baK1S;;O~Izcf5mh?Wh6BGo1C+6@UKr?+GE!)UXX77j&`T@(j)?qz3-= zxj{JNrlq-&VwS-i?VmpHuCww8{rWE--cX#MmgXirocG-s&cFE^HSIp=3Fu3I=ZDL& z`R$&W-jP!L%l!a2`;k(BwV?hkdm?>cPfjVo*|5ZT|I!uCd8HJZ8|w*YqYf1Qz?t1Z zGo=81;DM4iTG0t>AQz?ZIH_ZW;zn=0jH#wA2_7Kj5?rC~`9UpAK zCM8XgYhu$0dEm*%Gqc%GDfeov9E$3M9;;PXnU zPG-LHqlhQ4pNdkP{WaXDvCIZ;=1{7$1uA3iSk~{2S=uGG6&o#*@^6U;pQ)zo00uX)ith8Tr2rcBF_W zFn>1Cb-ny+7Dah|^T=Vq=ao`fMcy-_h$rA*gHoLRH5}|kq6EN?NPo=(t?2?^8I%Go z_HfafeoFCCGyfBKS?!;ZzxP>LO2v=Ab$Z~=|K2r~qBx)b(*8i$r$s5iTp^|9t-pnf z@jFjxHu13UvA@yZTl9dPB-rp%0l*rrto>wrBPbom&VZYEol^-qW27f)&K!2VmrKaA8JST>@{L``r{Q4fQVVb%5BQSki#iq3fH8Y_&Km;XmXJqE`SCA?10Si>`hz0s z3+xwxedV^wqiN1#zzKe&!FOAC0Q|rHOKZG6(OuXJ*AoCg?tzz7@%CzCd#ndAp9i)% zfU_syb8ho*w7?mKVBZkqd-j)K=ymM@x#ztnGAEAUu z1K4i^K04qB_pm3SH_m?`^;-meMyk&vMS1}C(*NptwBXyhJARgb5&R!`XhU=R&u{Af zEW6Mib*IlrBpvobI&04RiSKVM^X=se{47&yFGl3opS;3cAj}67^YYAHizej2oY%i< zD*(QpVZNuo!}szpzsyHKAFs8giDqQO{J}uBi6@qc?p$H5s3 zgYidYNiMCE!N2e{{+R|bt$*bTx({OmO8qL(ocZk_1Y0j?>&eR{`1$V*fIUS}7XB5P zx0g>iN99eRJKvVU53<#(KR8Uq8nE)8(I32jCv;0iy3)62|ep#dq-05an%#=5d9(5 z&KK>Cd2VvP4#a2JF9JU1z`p8R;fIb`*yVeuzhVBy*JeA_dr)9bx3}TSp&4E3;Xsrh zt!V~-qfkG9-B_^m0YVuDAKl=06@G9ZA(7X6) zQ_uES8li92n*jT#doS-u_Bi&u-oyWQ%bv(LYR)*IR#)y@ZS6hzBiUOkvb`eaWANHN zeZ7wCQfXm7LarO2SG_3{ki9jI&A&I(_*Za)Utd}R*t+)iSpgt>YaFZ7zapdF%qOe~ zQR?rO5M421YPKL*%RcCWN)p&w)0<+ zPhaE{>~;!s5;~P{XCJ{HwJ+#|G^`Za)}7ytv7&aMv9Hqn7t#US5Lhp6sIBZw)W3Wy z%#O#yTtZ)+dkZpm-iI+@2yAd{PyPkD^mQI#zbmW{enS4OVI7YgU~VTd)D`b#xv|g6 z{7)VrnS<;B&>Voq&-bWa7`&%F51@bOqRB^C%K=;eKW^WNWd1|?7-l8U%#G@Rwn4em zUhe&pr%2ZJiX+Am zo%FjEj(rUpC$Yxq`FdaaBcsoV5>D0)&qp&8b*f696mj`uVVCVp9^Do)SW5YX= zXLsLQE3nF<_N01H5BjGbpt-y6R*Ecg-IXsT@qV-i>~9Bkpr7dgj_ozA>ie$r0PKba z+k^fif2i+Gg&`D)WlHEyteXw^m{qYl~w$gzAI{n13A9 zhwkYE@D6y0+Sr4@)1J!ZPs9hhfqolBHV5>(jr8{^%2Pb5C-Tv+?w{8U-~r+V@C0}R zJR9aTS^5+1Q};Db+t92n%lAP4>(4w(F!)h_GHh+o5ZSs&;98lH*#nY=w9Z!gH7$=e(9_K3W_ z`t8|-lpxgJ{X!6GV1FS9wU@sTz=QmslEybi4KN8pLIX~MkkDR}AVAR({2u{&IKO$* zTGkQcN1&Ii((5F*qBa=a(qY43Hc3(2b04}4)sc|iHVlE`us!E6YzihVxoVrfYk9Vw z;Wqg!rpnx>a+g?~Ev}4QHhuadY%4wenYlM+drIDx-cm3B{)EzWD<9v?pdnL3N_;~~ zy^rr4!+B?fhhFjU`71q#&p&eU?Z%lpIpVW7Y;ZI9=4MdX*cLVG_2;GR&L3w5yH-zR zob=G%aLLCwnFqX8S8M{V6Ad8Ct4x#D@Ayyf;n+lN+8joCG7 zf9Nn*CB~>#2`86Dq)bY!Fi>e_p(mPTP_~4a=q0a@rm!4SnRd^&vLIm5+pbE^LE#Qsp<_mQJH2h zoXmvRNmqHh$w{>YW4CXwdu)^Be)0Xap)ovasuvF4lU%p=SS6oU-K70FjSR_B6Iz3~ z8}`z93YM5hvgEwB3HWxfP~x1Qh(F!LiqDDekG7R79{nQDFy(+LZ>sip!I-Lr+*#gk zY`otK43=gXH2SV#_ODFd8Wd<6&S{c#A%)RIjZyuaoG6!sWWhwH$SR38SLwL41gSLo z&FVGH0W9xW7#DAjUp{Qh5GIwc`}EV73N=1aSn4T<%?wqUmOA4(L*A|!r!9^XhgA)k zsC6vi9@oy$ihQ4|%$FytWYRlaoSG&waiP0l-C~(^-p|G&YZvctaWpG>p?TSG_l=!& z!^R0td!aGgncZLVPRw*kg9ZhCG4?sa&2K3O`yx_H+LUdKpT?SwO5Q0A0s z)-eWrS{i8o@c9ew<}-q0=j!rF)R<+`twod45 ziY67Re0@4WeA>Yr6DN9y%e&cxKZL2Xm|MP_HQhwZZbswL*l9bR@~? za0?yF^S$;m>u%)lymVDXUBIX*eCpDuHwxHcX`c6jPTAq_wkb<|j$QirWcJrcJIh2B zhk17oGfdG)ZD!s0*8dD$vUc=zi;p%#)^5;0P?4Xx;QEzm?tBbW79BVxv#;(b(`uom z`J*J>#6$|^Ej<2OMWpJXU%>S1fznN>jDdRNCbd}1Ha8VMoB51W`g)e3?H3%~It5jK zoR#rz7Pr$f79+QwwDGXc-uj4Jn%U4Lu3$A?9$%`q_DmDyu<0v@dGV*uN_A}%j_^4> zN2R=E)UvEAFCyH1zSVO`7{+p22fx%bJ5=%J;ECD3+rRkRI=j!VdY8uXw%%Zv#mMVg zT7FzbIJd=L`P9wJ} zx!$@geMhN!Us&j^g?@e?XF%b|f5!#ba=Fb-4Op-9&bYHRR`-rF=c(zRPYN8bSt=@V zPRqt4u=QNIp5v(_QVX6eOBCl|Ss^Pr9dSxW@iU{IVq~y!*tVR~xhsYU7~D&Vls)%Y z;7r#2)RtA2e)B4<9}A{%uzvJu6iXUDeA^wH`V((ADl4VGj}sf>pkLf9@o=ieY>9mR zdmsI-)-rr3@_Np_)6C)iFkUNF)!~nm<>D0mckH8c5V^+3H&5c+?l+=WD)iYSR%k1% zP4IUU#Ak@1Y@K#B7xH=(=QfimyNbm`XgZLvLVz*m`59@wmaGTYhfP{KgVE+rvhQ}Wt$TF~O&)BSF-Kw#=h48ab3dMWr8VK^izA-u?5mD?aO_&j<{E!&%Dh<9 z`yVBOQnty=(XTkfD(RP7e$_KvJbCu5RT7C;SOsryVE(ALV^K+#`Mef)`g;@R=}wBW z|6s2g?XEss*MReN8jqq_x+XtnGXhI?%J5Xs{}#51``sM|3G=t|O*!MY3r#K_dvQ^zyj-ajXZ^A`V5J%1iz> zpI7kYtowJrB}%?AtIasQ9GCv2&B9!?dcm$2{xv7Bj=~OKad=joH>-_*D&J7!@gEsD znjV{H&b}+Q*Ke_Hz}*w-d^x(@6$`Q~YEr%|PEDT9xGyM8`-BeWHQKj^k;hYatHtGe z`+d%2v?T0YE|$ly#)KEPpys_cK8x{k8?m*1 z|L&H18ypI>yxpw$L<-#v_0)a#h-qj_GKp8M^FJ=n=_#yzqna-QIWd1VvJMr zL6MZr3&)Geq;5LnfU}i8Y|h1~w?)+UT8-v=PC1^6Te{;P3Zl=`hwN|LvU~W`xx6z+ zq{P-@`cp4iCnE#doE-x{e6+h|r%)4cnQQ%+IV)b-_y z3}dEiatwD(nSoVJkegg#p5-w{_KWDt%$kD61=dH zX;K-hD~qz{r)|2me%T^x$y|L_l~phTs)%Y*8w+s~UO zVCR|`^{lp|=i&*uLuay%7l_7SfMc zoIK0J?2=tV8uff4Ck36Xdx2RmPENPsq#QDb`DE&UQMpvy6pQ5@H`rWO7qM%r_Lp2A9u-~Af+XiS ztt$<(>@6Y7=3ok~#+&IXS6@)$)p$RhK442w65m3W_-Rq2CXKT@^=a|0{OfVY@?Jfi zI593^)tc>WY}cRLD8&Y9t?*lSr9uAK_ucOK>Q-7SWUq;`ZlT-k{E|Csv9CG5;FhBC zay&{3k{)UgHhZY2GY5MpKVhwZbWlH~P*(YEYqYk@|f1Hxt+y(c1S_%Z$4IKGfrVM&Kf@tiYjf>tMc>dwCC%l~H1aYxl^ zkCdJMf|HmR-(en?B3B}{$zwyHeX{TCyF%F33%>J9)b}K&bGwYheR*&{b>wbA4;4eX z8f#4}FZJg9vk%S+7-SnA7C*Hq{n*3m5yDE?@;l0kb7yZCwLR!TKV@gDi?Be6`(p0o zTVq_-Xy|>qBbH%y?0JEpuio;7548mhTIt^I3RbzIq+7q&eeH)eC-%ISV=dm#?~yvM zK|y-tT+B>z?U{lgH8BBHS83?GG*1$?XNgt0cq%VQExRiFtGPb@Y`lnzqg=VZPu=9$ zSMCq?#&3}h|0d?EJ0fij!^(Zh7e49F_hLG8JU!Rcc;0!z>Dk$%?T=eW)#KRIN^Z^< zIsUlBp!h+S&P3nQ?0hqiv@PS$JhrWz(_7}6_%U(LvAd&lCqH9SAN`@EEh60UCHI*V z)=^PP>Q(VB&l^h3SYOS*-@>-6G5YA?#8(pbPZ%YtIeGnFSxy@FJ%?k<==h;EqtqiR zn)D*R70c#VDVyq5=C0e#QqcS;%J+b*szk1?eABM`S-0X-id5>|HzPeoO0+8W>xGP( zgq<5thO)m{w2Vv9LhITXRQ{vx>c!ktuYM!kyfO4xf5YH#1q5^acaD z)J+nH4xVNFR4|J%uT}8$=Ga7o3?Hve8UmALZPs22(LF4t%_!yj@ZJ=zr|VUPCnVq6 z8?{iSK+`DOfIelc<`z-b>q+BQj$tiHnkag2g{fM$#_Bt7R9TSVgmpKarf;2FbfY=* z-6R+1t+bwz!E|Dq=olGw7JW4>F22*J^__+A zVTwT$Ca}A2Umol&a(WJrU!sx^s_|~nZ#I3IZtGv{7MmP!QY=U=+1A3T30O5f$K#ss zy;SP}WBjOl{9k=8;-svyXK+`2+8w{C_4$}FCfXZ|QrN7OC!f*6Ib?YiZ7NSv-k-O-?+@Q;ciOoyZPV(-HJmqCG;KG&ER_~plUt7pu|c=2EB_Mj?iXJ!8C zbDE<)cJj|!@KybDjZ}tliP>)Txwa!B()OpuDf5_KVLj;Ow%+ogHuJHDvb__R>J8t| zFS@ztc+{ukQCk$vLT}Dv)+&qKo?*7pe^)&EJLi31^~UE4=WM;b&VLIkzPCUv@0yP0 zweg1+uG7E2cHVUMa#ZC+2g$_E*Z!1pN3=59O3B65U2zPZ3dT2ch>_6=k!6ja)WdA< zPec_7+cUfUYR$aMrBQR#SLujsKxyPwCMSM4VVtMJQOS_^?DN{BV6!>i>*r{n z^w;>n%a?g)}I|EsDys6FhflGjr{W!^48J!<2TI zrr6$}$Yi&-aCfG!dc%QOHO05=_s!eZ(BZJV_N8ZspVqu?ag$Tli>rF^T~v3)zY5K} z9+)%!{qX1wt1DtEzs*-$L}W#{;+f1+ zHqV8R-5C_=G_w5{Z^xgwJh!!Q@#N*U`&Xz~T{2ph_H6)4&^x?urM{*BL%N$~Jyzitej+H$gPe2ZT7Dyi5pd-dzL>l^G@kjf^n zYx^>wY~pczb?|K6=ER&c3S675P1|bATCI3meCpj+7G4c|7az%vRWG^g5f`VTb~;O1 zD)z|OQFe(&OExD9*7B>S(=X5Tdw#RDal`uO`sz8$LL1`!^bD^&I1zo6{p-Fviz&A*R%J87 zGIa8np9)>Z@yu@ToQ28`nYXj#CO%I-O{YJbcY8qE>3Q`NVU51&}d3E)~~PEn4PjqsuJ70a6<>qA0w{P=cA&zansXYf|x zne2tCySC-bK5K$Gs<}eKhBwrCD(jVr&I)EX`e^k!Fnt)$+IdEe^M|Y&%MtQ;q^L^7 zKH+Jv4!i?+$SfQ zo)T$T8O)FuKkB(feRcD(X0?qiryP?6AMrJQNZUF6$tAm07c0|WNqVRkIrB5GyjnE- zW6Jt6+wipJO{y)kHdxqsFv%L$38haODXQiv`(dU=?zX3!R-L*TNAIxwkxx=X>_Z)a zgE6}=pE@CK`C|VaWxESPV?TYiT<%d2y6Dlhq=r*>p3#rYeZt=qd}uCTn9ob|*t-jE zHWta}XQkUqD!M=xZN1G znfs1dso1K({ZUY1XA5eCG-N{9!;}MeXc(09y5Vk|-1Ef0;nZy(`pRwix){_U z-q2p8f*sz@aq6Y8gP8C8IKdOi`!WkIUX#Ivj&Y3>zZ0@Q?o8^u8>3OEWm0R0A6WPF z6n?mCh@@DdWZbJaky(%A9>xlfV=dw=H=YpIG$EeLy1+;H;?=^7!J0ORp7o4*)m=+3@j&^+fs zlDrveKi^Ca-msBVW2>gLbAuRUuN7=s0!Ysj<~*^tVC zlFIOOc^La~!b*dt#%s@=zvIi)Z+c>v*9J1&*refKHo<6_>rq8r&baZHwkhi#x-`y^&kJ5m<>#uE z2xM3(DbH0Ex7Is`_r|afMUz)Ldtx6~zFffLM)m82>PnZ8DNhE!B0!#hZXkNk#fa_r8wu z=BS#S)M5vTopTD7ja!rUo^NYgeV*ab3uS^pcwR%JVy61m=GnE;sh7gzI39fGLtKow zW44>~*_Y=mo|DE~j9+wQo3QYaRS(4(-yRd$vT_Ms-0e)XGyZJi8tX8@f$zE><$CDv&FA_r@PD z>XBCO+{g%uwreBf$27jJbx&dgtM}M@&2r(#3^whFo1CKIkn~JO9fD+k@EvEv*l0XS zs>QD8{9WdVoVV4pXJ5gyRrnvBzt>*+P5ruHkxcckB32i4n{Jk&(vrepqN5sU()#&Z zMaIPK&Pyio?qv>e(!wjn@3nt+zV76Ghr7%ec6hn|`Z}jo`#8Rp&c-j8{xmSsZMW*e zH^#Yp3nEh<#->7XWThX06)jx3C2FW^+v+49rsv6qbPeS@$GRRpS$}DWiNOb9sashd z4`XL6IkeMo)`kv$~;od6hdi4HB1I4;0r*2!*=gq0z{W@Wq#BTBA;7Q}(2QZ(X z^a@?n5Boiq*lisCWh5GH@&?qd;bOq(WgGcsPFrDgGu$D=wCvKXiZS1d*y$GxuU&^K z+4!)HpT{n@thD%7<4;VVE_( zz;0S9ou}1tc??s1b2DC|Akis_Ct%C>CBCW8#%>W7JaRun$Wt%;!}LXAlZ$<^vK8*O z!p%aK(ZMdZPNK(VXR~{nO$i)TJ(JB+DsM#Gm}m9{dCnVN!O-jth5EuQFRzy>Bce)|icF9&Y!Mv@U^P4W1enaJEd2Qwbi6(}R(uvz`{lEI%N}g&mlUZu* z8TD+OI_C%ZIetm!@3mD~PgO5gTFGg0iL1J*rf|cU2@4(@&A;FHL1Xz$&kwfZAmY+o zBgI#bbM`t{7AJ~aE!cc`xtP$-f(n@}qQhsPan!gIWswq(uZM6Ttw%*OY5Bs5s6%)* z*2j-=%&L9U!VJHz*k~v~H8ufy_KW}N-m(Ywb?(#w5at$*a3f>dm(C>jgSzj5jwYRsa}1oN!*kG|cI zfu==Fxx#l@aufzVRoh#zOxLg}6_eN9%s*TAR`d1n$k*15Xc)PlPG`85%q9>!F>>H)#loULv#PM+R6HhJ3OlGci&N9K%+mgPD3?s>8Lx{`4YEcr>}>et zW6}dn=3!5=mP8y}eDjcXla>7uhv|6Tgj5iB3!V#}u1vNt zNDez-anSnuUH&XHzwH%U_8xxD{A7d4gwt&`Q&@I9jbtj^@p#EKG_10IJjpD|>)XpK zNmGO-uRj-kD;xLeTLz=*+y(lsfk(yNTeY8tNEhu~$%S-vNfj?kS<=SxMZUPuR)MdY z>!Ms*ooA2r|B~r86lYVE79zMNCxy{`jLR#zaT|0eM;DE=MuYzM^kEpP#aq6YXdOSS zEL*UsfqBi=B^B0>aD`YKtC7T zA!T8yTJ?GQ%e4B6sW+ZTXEKHf%L?gCtC7ez*-$>c<$T~v^V}X%1nF|XG6cDZLg?Ny}e4_m`Arb z<}j`GjT~=Wp`*HaztO$xxTl38o0Q(Hz5ZCH<(r^$`WQ54@wPCoviP0b!F!|qxwWM8 z^V*iOr^&um*2B*GB}%T@ZinV*VmySdIy5x#so_E{z4?^4X}AqP-CS)n8&P9ejzhEm zJIl8%()@Jy`1G(9%x4pow~LN>;V{n>CZslh{;pboWHhVqS%&_K;{X({`ZX`)=&yGy4@T7I3X;NXTkCvFrp+An^Wb?DSnS!H_MDu)Gv z$7NUuvdD{a&0jBiVw8$sjlCVSSyv`uF(M_VWE zD)M9xSs1g#$IUuDdWo;~0{5p2^4^aw6F*6pXcScv`dO<1|{bQ|Gyd-*M1S2~l^si}$r`*w)(iWMh6*~Pc7zc^DPcg~I_ z)_V15f%~`(*>7j^&8f`~-!eJ+IfgO1f-S(cl&Z-52O{e^ZZA47XfzVDdGc`f6vr)e zBl9)3v$;1Kj#GAawDM3=P}Pv&JN5Xmr-FHW$=q7)`?BJeQaETYu z*xqFVsuRS5uF@U0&5~xYa(O%jEkDq+&v8SWnhdE$c!9?9X zu2Gufc4fF98!N@{5_E6L#E;I#uScJ`llaURUmRfX?lM9kgr#x_>mkdV@=;kDnK#C| zq_VC){@ev|VeRdWmY)>uhO7XvNMIr%@dS3r|()|aQm)eIAiF6 zeO6bi{N!I-jl4N5L7*bWUh`Q|u)WI_I!1gZpZ&DbwD9OW?C2Ry5vE#=nUZTonDh*6f|c@fw_~nCm+Xh^ys>ki#mE_aS_#c5M{vs7 z$4-tfa9Y2g&Z1~YVV?Wex;D2k-B@~uCHvoP!sc1*Uo&hAh7ZulvDW+e)%z_&iE>OX zhYJUvo@1;Sa_> z$4e_mFZ~+l&dDn&l28?&)_iiWx4*QK^qdWhBJ(+CNy_QdEqM~xTFQ={u~N><44;~t zrHe7G7SGh4W-%;!=}fM-E{bZ`!q*3R#p{UP)v;T&Ya!u-_+=ishGTn`aZgvIG0S~a z%^4v(YZz}y^}^-0mpL`j`%g0>gnggSvv>JW=NHRe`dLobVx*c#<(A0%pN+TI)yiji z-OStgNyk;)AP8YR7abskf26)uKJ3mxT-xos`X47sW7Jd8JAf9Zq**QJenba^*hxu#?x}MbdcvJ+G2;uC~ajW-V&mSq_ zJx#dc;>jsjR#bQ&#d7O>l$%1Cj~?bONI+%%3eC?2=)1|yUB=4_FY1dYH0}aBhi^7IM(H!Ej2f9| zDHH4c=c;~9QE)gfJ}OdAYr!GCpksb~pL1DjOcTw^Js37bB;o2ZEQZcb z2w0RmU(C#s!}^QOybt3dPKdXvY;pe}=wP1c^U`NH?--mDPXRYyeIz^Ye(e3ReLTWP z7BU%J3Mi2gnL6F!nB7*!wlz6r(iPaob=Qnc8S+Macy*wD-RSFy5mTk?rOqj9Rr2{= zWz~D@{Akl>kr$|kXJO+sN^Q~Qw@f>4jxHE=bFZuV0k8KWVOrmqGjGOjy^U<1E{^3s z=p>Z8NA=P;IW0wrMH1)b+HiA>rlfNV23^||F$;UPp*Uc8l}gJJ%{lJ#oUVoLdcEa~ z@rcc)W=~&VtG>xBs$*9edBLxy!J=V|ogrJO1D8_9u3~eZgRXQRXHP${{&pl^yedmn z+FSFHca*XX>#uDMu6KN4xnQrC<5?9&YbNo!RZO=`!{fObz1*02Zyu}MJK4Ub@ZsXJ zZ5LHIO%6${J)JZr&)7p^Wz9MB1w*d3DdZ@hUSI7)uO(CDyraUK+nlj)&mT(Lbeqpe3G>~sUho57Bs=#M z+pn&s78_>T-Oxv;jljSm8Art<^{K4D&ZtU4FrIR~j<8;$qS> z3k;-*B@1I|D2HW&;;#qQFFdY%{1A#z@eCKp&Keq-fq6GZ9K8^ VG8snsOkmuGNlR^#^p#LG`yc;oo@W36 literal 0 HcmV?d00001 diff --git a/src/Febe.Desktop/LEGGIMI.md b/src/Febe.Desktop/LEGGIMI.md new file mode 100644 index 0000000..ba11416 --- /dev/null +++ b/src/Febe.Desktop/LEGGIMI.md @@ -0,0 +1,33 @@ +# Febe.Desktop + +L'eseguibile per Windows (WPF, `net10.0-windows`; specifica §5, §12). Si compila anche da Linux +(`EnableWindowsTargeting`), ma gira solo su Windows: tutto ciò che si può provare altrove sta in +`src/Febe.Desktop.Core` (`net10.0`, prove in `tests/Febe.Tests/Desktop`). Guida per l'uso: `docs/windows.md`. + +## Come è fatto + +| File | Che cosa fa | +|---|---| +| `Program.cs` | Riga di comando (`DesktopCommandLine`), cartella dei dati, istanza unica: un secondo avvio chiede al primo di mostrarsi ed esce | +| `DesktopApplication.cs` | Avvio: area di notifica, spostamento della cartella dei dati se chiesto, `FebeApp` con `DesktopPlatform`, finestra principale; «Esci», fine sessione di Windows | +| `MainWindow.cs` | La finestra con l'interfaccia (WebView2 di WPF, cartella `Dati\interfaccia`): apre `/?gettone=…` una volta, ogni altro indirizzo va al browser predefinito | +| `Browser/WebView2Host.cs` | `IBrowserHost` di Windows: finestra «Browser di Febe», ambiente e controllo WebView2 in `Dati\browser`, CDP con `WebView2CdpSession`, fuori vista e in primo piano (S2), chi guida | +| `Browser/WebView2Browser.cs` | `IFebeBrowser` per la composizione: avvio con nuovi tentativi, ripartenza dopo un arresto del processo, «Scollega» | +| `Browser/BrowserWindow.cs` | La finestra «Browser di Febe»: pagina a misura fissa, barra con Indietro, Ricarica e indirizzo; chiudere = fuori vista | +| `Browser/CoreWebView2DevTools.cs` | Le due chiamate di WebView2 per il CDP, sul thread dell'interfaccia (`IWebView2DevTools`) | +| `Browser/CompositionHost.cs` | Secondo tentativo di S2 (`--browser composizione`): visual di DirectComposition, mouse e puntatore inoltrati | +| `DesktopShell.cs` | `IDesktopShell`: sonda del runtime WebView2, Edge e la sua finestra (terzo tentativo di S2), notifiche | +| `WindowsShell.cs` | `INativeShell` (cartelle, Esplora risorse, browser predefinito, notifiche, avvio con il computer), canale degli avvisi, posizione della cartella dei dati nel registro | +| `TrayIcon.cs` | Icona nell'area di notifica (Windows Forms `NotifyIcon`): Apri, Metti in pausa/Riprendi, Esci, notifiche | +| `SingleInstanceGuard.cs` | Mutex con nome e pipe (solo l'utente corrente) per l'istanza unica | +| `Native/Win32.cs` | Le poche chiamate Win32 e le interfacce di DirectComposition | +| `Febe.ico` | Il marchio (appendice C) a 16–256 pixel, generato da `BrandMark`/`IcoWriter` (`FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests`) | + +Regole che valgono anche qui: le chiamate a WebView2 solo sul thread dell'interfaccia; il browser di Febe non si nasconde +e non si riduce mai a icona (S2); nel registro mai indirizzi con il gettone, cookie o tasti; nessun pacchetto oltre a +`Microsoft.Web.WebView2` (WPF e Windows Forms vengono con il .NET per Windows). + +## Pubblicazione + +`installer/costruisci.sh` pubblica un solo `Febe.exe` (autosufficiente, compresso, librerie native incluse) e ne fa +`out/Febe-Setup-.exe` (NSIS, `installer/febe.nsi`) e `out/Febe--portabile.zip`. diff --git a/src/Febe.Desktop/MainWindow.cs b/src/Febe.Desktop/MainWindow.cs new file mode 100644 index 0000000..cf395fd --- /dev/null +++ b/src/Febe.Desktop/MainWindow.cs @@ -0,0 +1,144 @@ +using System.ComponentModel; +using System.Windows; +using System.Windows.Media; +using Microsoft.Web.WebView2.Core; +using Microsoft.Web.WebView2.Wpf; + +namespace Febe.Desktop; + +/// +/// The main window (spec §12): a WebView2 showing the interface served in this process on 127.0.0.1. It opens +/// /?gettone=… once — the token of this start becomes an HttpOnly cookie and leaves the address — and never +/// leaves the interface: any other address opens in Alberto's default browser. Its WebView2 has a user data folder of +/// its own (Dati\interfaccia), separate from the browser of Instagram. +/// +internal sealed class MainWindow : Window +{ + private readonly WebView2 _view; + private readonly Uri _origin; + private readonly Func _openOutside; + private bool _allowClose; + + public MainWindow(ImageSource? icon, string userDataFolder, Uri origin, bool developerTools, Func openOutside) + { + _origin = origin ?? throw new ArgumentNullException(nameof(origin)); + _openOutside = openOutside ?? throw new ArgumentNullException(nameof(openOutside)); + Title = "Febe"; + Icon = icon; + var area = SystemParameters.WorkArea; + Width = Math.Min(1440, area.Width * 0.92); + Height = Math.Min(900, area.Height * 0.92); + MinWidth = 380; + MinHeight = 480; + WindowStartupLocation = WindowStartupLocation.CenterScreen; + Background = new SolidColorBrush(Color.FromRgb(0xF4, 0xF5, 0xF7)); + _view = new WebView2 + { + CreationProperties = new CoreWebView2CreationProperties { UserDataFolder = userDataFolder }, + }; + Content = _view; + DeveloperTools = developerTools; + } + + /// The developer tools of the interface (only with --sviluppo). + public bool DeveloperTools { get; } + + /// Raised when Alberto closes the window; the application decides (notification area or exit). + public event EventHandler? CloseRequested; + + /// Creates the WebView and opens the interface at (the address with the token). + public async Task OpenAsync(Uri first) + { + await _view.EnsureCoreWebView2Async().ConfigureAwait(true); + var core = _view.CoreWebView2; + var s = core.Settings; + s.AreDevToolsEnabled = DeveloperTools; + s.IsPasswordAutosaveEnabled = false; + s.IsGeneralAutofillEnabled = false; + s.IsStatusBarEnabled = false; + core.NavigationStarting += OnNavigationStarting; + core.NewWindowRequested += OnNewWindowRequested; + core.ProcessFailed += (_, e) => + { + if (e.ProcessFailedKind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive) + { + core.Reload(); + } + }; + core.Navigate(first.AbsoluteUri); + } + + /// Shows the window in front, restoring it if minimised. + public void Present() + { + if (!IsVisible) + { + Show(); + } + + if (WindowState == WindowState.Minimized) + { + WindowState = WindowState.Normal; + } + + Activate(); + Topmost = true; + Topmost = false; + _view.Focus(); + } + + /// Closes the window for good (Febe is stopping). + public void CloseForGood() + { + _allowClose = true; + Close(); + _view.Dispose(); + } + + protected override void OnClosing(CancelEventArgs e) + { + if (!_allowClose) + { + e.Cancel = true; + CloseRequested?.Invoke(this, EventArgs.Empty); + } + + base.OnClosing(e); + } + + private bool IsInterface(Uri uri) => + uri.Scheme == _origin.Scheme && string.Equals(uri.Authority, _origin.Authority, StringComparison.OrdinalIgnoreCase); + + private void OnNavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs e) + { + if (!Uri.TryCreate(e.Uri, UriKind.Absolute, out var uri) || IsInterface(uri) || uri.Scheme is "about" or "data") + { + return; + } + + // The window shows only Febe: the guide, the repository, Instagram links open in Alberto's own browser. + e.Cancel = true; + if (uri.Scheme is "http" or "https") + { + _ = _openOutside(uri); + } + } + + private void OnNewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e) + { + e.Handled = true; + if (!Uri.TryCreate(e.Uri, UriKind.Absolute, out var uri)) + { + return; + } + + if (IsInterface(uri)) + { + _view.CoreWebView2.Navigate(uri.AbsoluteUri); + } + else if (uri.Scheme is "http" or "https") + { + _ = _openOutside(uri); + } + } +} diff --git a/src/Febe.Desktop/Native/Win32.cs b/src/Febe.Desktop/Native/Win32.cs new file mode 100644 index 0000000..528208d --- /dev/null +++ b/src/Febe.Desktop/Native/Win32.cs @@ -0,0 +1,136 @@ +using System.Runtime.InteropServices; + +namespace Febe.Desktop.Native; + +/// The few Win32 calls the desktop needs (windows of other processes, mouse capture, DirectComposition). +internal static class Win32 +{ + public const int SwRestore = 9; + public const int SwShowNoActivate = 4; + + public const uint SwpNoSize = 0x0001; + public const uint SwpNoZOrder = 0x0004; + public const uint SwpNoActivate = 0x0010; + + public const int WmSetCursor = 0x0020; + public const int WmMouseFirst = 0x0200; + public const int WmMouseWheel = 0x020A; + public const int WmMouseHWheel = 0x020E; + public const int WmMouseLeave = 0x02A3; + public const int HtClient = 1; + + public const uint TmeLeave = 0x00000002; + + [StructLayout(LayoutKind.Sequential)] + public struct Rect + { + public int Left; + public int Top; + public int Right; + public int Bottom; + } + + [StructLayout(LayoutKind.Sequential)] + public struct Point + { + public int X; + public int Y; + } + + [StructLayout(LayoutKind.Sequential)] + public struct TrackMouseEventInfo + { + public uint Size; + public uint Flags; + public IntPtr Window; + public uint HoverTime; + } + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool SetForegroundWindow(IntPtr window); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool ShowWindow(IntPtr window, int command); + + [DllImport("user32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool SetWindowPos(IntPtr window, IntPtr insertAfter, int x, int y, int width, int height, uint flags); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool GetWindowRect(IntPtr window, out Rect rect); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool IsIconic(IntPtr window); + + [DllImport("user32.dll")] + public static extern IntPtr SetCursor(IntPtr cursor); + + [DllImport("user32.dll")] + public static extern IntPtr SetCapture(IntPtr window); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool ReleaseCapture(); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool ScreenToClient(IntPtr window, ref Point point); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool TrackMouseEvent(ref TrackMouseEventInfo info); + + /// The DirectComposition device of the S2 fallback «composizione» (null rendering device: WebView2 draws). + [DllImport("dcomp.dll")] + public static extern int DCompositionCreateDevice2(IntPtr renderingDevice, ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object device); + + /// The scale of the system DPI (SystemParameters are in device-independent pixels at this scale). + public static double SystemScale => GetDpiForSystem() / 96.0; + + [DllImport("user32.dll")] + public static extern uint GetDpiForSystem(); + + public static int LowWord(IntPtr value) => unchecked((short)(long)value); + + public static int HighWord(IntPtr value) => unchecked((short)((long)value >> 16)); +} + +/// IDCompositionDevice (dcomp.h): only the first methods, in their order in the table; the rest is never called. +[ComImport] +[Guid("C37EA93A-E7AA-450D-B16F-9746CB0407F3")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IDCompositionDevice +{ + void Commit(); + + void WaitForCommitCompletion(); + + void GetFrameStatistics(IntPtr statistics); + + [return: MarshalAs(UnmanagedType.Interface)] + IDCompositionTarget CreateTargetForHwnd(IntPtr window, [MarshalAs(UnmanagedType.Bool)] bool topmost); + + [return: MarshalAs(UnmanagedType.Interface)] + IDCompositionVisual CreateVisual(); +} + +/// IDCompositionTarget (dcomp.h). +[ComImport] +[Guid("EACDD04C-117E-4E17-88F4-D1B12B0E3D89")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IDCompositionTarget +{ + void SetRoot([MarshalAs(UnmanagedType.Interface)] IDCompositionVisual visual); +} + +/// IDCompositionVisual (dcomp.h): handed to WebView2 as its root visual target, no method called here. +[ComImport] +[Guid("4D93059D-097B-4651-9A60-F0F25116E2F3")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IDCompositionVisual +{ +} diff --git a/src/Febe.Desktop/Program.cs b/src/Febe.Desktop/Program.cs new file mode 100644 index 0000000..8c0b831 --- /dev/null +++ b/src/Febe.Desktop/Program.cs @@ -0,0 +1,37 @@ +using System.Windows; +using Febe.Desktop.Core; + +namespace Febe.Desktop; + +/// +/// Entry point of Febe.exe (spec §12). Reads the command line, finds the Data folder (--dati, the folder recorded +/// after a move, or %LOCALAPPDATA%\Febe), makes sure only one Febe runs on it — a second launch asks the first to +/// show its window and exits — and starts the application. +/// +internal static class Program +{ + [STAThread] + public static int Main(string[] args) + { + // The menu of the notification-area icon is Windows Forms: with the visual styles of Windows. + System.Windows.Forms.Application.EnableVisualStyles(); + if (!DesktopCommandLine.TryParse(args, out var options, out var problem)) + { + MessageBox.Show($"{problem}\n\n{DesktopCommandLine.Usage}", "Febe", MessageBoxButton.OK, MessageBoxImage.Warning); + return 2; + } + + var folders = DesktopFolders.Current(); + var locations = new RegistryLocationStore(); + var dataFolder = options.DataFolder ?? locations.Current ?? folders.DefaultDataFolder; + using var instance = SingleInstanceGuard.TryAcquire(dataFolder); + if (instance is null) + { + SingleInstanceGuard.SignalFirst(dataFolder, InstanceMessages.For(options)); + return 0; + } + + var application = new DesktopApplication(options, folders, locations, dataFolder, options.DataFolder is not null, instance); + return application.Run(); + } +} diff --git a/src/Febe.Desktop/SingleInstanceGuard.cs b/src/Febe.Desktop/SingleInstanceGuard.cs new file mode 100644 index 0000000..220a52b --- /dev/null +++ b/src/Febe.Desktop/SingleInstanceGuard.cs @@ -0,0 +1,124 @@ +using System.IO.Pipes; +using System.Text; +using Febe.Desktop.Core; + +namespace Febe.Desktop; + +/// +/// One Febe at a time for a Data folder (spec §12): a named mutex in the session namespace, and a named pipe (current +/// user only) through which a second launch asks the first to show its window, then exits. +/// +internal sealed class SingleInstanceGuard : IDisposable +{ + private readonly Mutex _mutex; + private readonly string _pipeName; + private readonly CancellationTokenSource _stop = new(); + private Task? _listener; + + private SingleInstanceGuard(Mutex mutex, string pipeName) + { + _mutex = mutex; + _pipeName = pipeName; + } + + /// The guard of the first instance, or null when another Febe already runs on this Data folder. + public static SingleInstanceGuard? TryAcquire(string dataFolder) + { + var mutex = new Mutex(initiallyOwned: true, InstanceIdentity.MutexName(dataFolder), out var created); + if (!created) + { + mutex.Dispose(); + return null; + } + + return new SingleInstanceGuard(mutex, InstanceIdentity.PipeName(dataFolder)); + } + + /// A second launch: hands its request to the first instance (best effort, a few seconds at most). + public static void SignalFirst(string dataFolder, string message) + { + try + { + using var pipe = new NamedPipeClientStream(".", InstanceIdentity.PipeName(dataFolder), PipeDirection.Out, PipeOptions.CurrentUserOnly); + pipe.Connect(3000); + var bytes = Encoding.UTF8.GetBytes(message + "\n"); + pipe.Write(bytes, 0, bytes.Length); + pipe.Flush(); + } + catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException) + { + // The first instance is starting or stopping: nothing more to do. + } + } + + /// Starts listening for second launches; runs on a background thread. + public void Listen(Action onRequest) + { + ArgumentNullException.ThrowIfNull(onRequest); + _listener = Task.Run(() => ListenAsync(onRequest, _stop.Token)); + } + + public void Dispose() + { + _stop.Cancel(); + try + { + _listener?.Wait(TimeSpan.FromSeconds(2)); + } + catch (AggregateException) + { + } + + try + { + _mutex.ReleaseMutex(); + } + catch (ApplicationException) + { + // Released on another thread already: Windows releases it when the process ends. + } + + _mutex.Dispose(); + _stop.Dispose(); + } + + private async Task ListenAsync(Action onRequest, CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try + { + await using var pipe = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + await pipe.WaitForConnectionAsync(ct).ConfigureAwait(false); + var buffer = new byte[InstanceMessages.MaxLength + 2]; + var read = 0; + using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct)) + { + timeout.CancelAfter(TimeSpan.FromSeconds(3)); + int n; + while (read < buffer.Length && (n = await pipe.ReadAsync(buffer.AsMemory(read), timeout.Token).ConfigureAwait(false)) > 0) + { + read += n; + if (Array.IndexOf(buffer, (byte)'\n', 0, read) >= 0) + { + break; + } + } + } + + if (InstanceMessages.Parse(Encoding.UTF8.GetString(buffer, 0, read)) is { } request) + { + onRequest(request); + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or UnauthorizedAccessException) + { + // A broken or slow client: wait for the next one. + } + } + } +} diff --git a/src/Febe.Desktop/TrayIcon.cs b/src/Febe.Desktop/TrayIcon.cs new file mode 100644 index 0000000..2b83403 --- /dev/null +++ b/src/Febe.Desktop/TrayIcon.cs @@ -0,0 +1,80 @@ +using Forms = System.Windows.Forms; + +namespace Febe.Desktop; + +/// +/// The icon in the notification area (spec §12): a click opens the window; the menu has «Apri», «Metti in pausa» or +/// «Riprendi», «Esci». Its balloon tips are the Windows notifications of Febe (spec §13.3): Windows 10 and 11 show them +/// as notifications, without any extra package. +/// +internal sealed class TrayIcon : IDisposable +{ + private readonly Forms.NotifyIcon _icon; + private readonly Forms.ToolStripMenuItem _pause; + private readonly Func _isPaused; + + /// The icon of the mark. + /// Whether the engine is paused or stopped (the menu then says «Riprendi»). + public TrayIcon(System.Drawing.Icon icon, Func isPaused) + { + _isPaused = isPaused ?? throw new ArgumentNullException(nameof(isPaused)); + var menu = new Forms.ContextMenuStrip(); + var open = new Forms.ToolStripMenuItem("Apri") { Font = new System.Drawing.Font(menu.Font, System.Drawing.FontStyle.Bold) }; + open.Click += (_, _) => OpenRequested?.Invoke(this, EventArgs.Empty); + _pause = new Forms.ToolStripMenuItem("Metti in pausa"); + _pause.Click += (_, _) => PauseToggleRequested?.Invoke(this, _isPaused()); + var exit = new Forms.ToolStripMenuItem("Esci"); + exit.Click += (_, _) => ExitRequested?.Invoke(this, EventArgs.Empty); + menu.Items.Add(open); + menu.Items.Add(_pause); + menu.Items.Add(new Forms.ToolStripSeparator()); + menu.Items.Add(exit); + menu.Opening += (_, _) => _pause.Text = _isPaused() ? "Riprendi" : "Metti in pausa"; + + _icon = new Forms.NotifyIcon + { + Icon = icon, + Text = "Febe", + ContextMenuStrip = menu, + Visible = true, + }; + _icon.MouseClick += (_, e) => + { + if (e.Button == Forms.MouseButtons.Left) + { + OpenRequested?.Invoke(this, EventArgs.Empty); + } + }; + _icon.BalloonTipClicked += (_, _) => OpenRequested?.Invoke(this, EventArgs.Empty); + } + + /// «Apri», a click on the icon or on a notification. + public event EventHandler? OpenRequested; + + /// «Metti in pausa» (false) or «Riprendi» (true: the engine was paused or stopped). + public event EventHandler? PauseToggleRequested; + + /// «Esci». + public event EventHandler? ExitRequested; + + /// A Windows notification. Title and text in Italian; never secrets, captions or addresses. + public void Notify(string title, string text, bool warning = false) + { + _icon.BalloonTipTitle = Trim(title, 63); + _icon.BalloonTipText = Trim(text, 255); + _icon.BalloonTipIcon = warning ? Forms.ToolTipIcon.Warning : Forms.ToolTipIcon.Info; + _icon.ShowBalloonTip(10_000); + } + + /// The tooltip of the icon: what Febe is doing (at most 127 characters for Windows). + public void SetStatus(string status) => _icon.Text = Trim("Febe: " + status, 127); + + public void Dispose() + { + _icon.Visible = false; + _icon.ContextMenuStrip?.Dispose(); + _icon.Dispose(); + } + + private static string Trim(string text, int max) => text.Length <= max ? text : text[..(max - 1)] + "…"; +} diff --git a/src/Febe.Desktop/WindowsShell.cs b/src/Febe.Desktop/WindowsShell.cs new file mode 100644 index 0000000..0f024f6 --- /dev/null +++ b/src/Febe.Desktop/WindowsShell.cs @@ -0,0 +1,158 @@ +using System.Diagnostics; +using System.Windows; +using System.Windows.Threading; +using Febe.App; +using Febe.Core.Alerts; +using Febe.Desktop.Core; +using Febe.Web.Native; +using Microsoft.Win32; + +namespace Febe.Desktop; + +/// +/// The native functions of Windows offered to the interface (spec §12): folder picker (), +/// «Mostra nella cartella» (explorer.exe /select,"…"), addresses in the default browser (shell execute), Windows +/// notifications (balloon tips of the notification-area icon) and start with the computer +/// (HKCU\…\Run, value Febe). Paths and addresses never come from the page: the web layer resolves them. +/// +internal sealed class WindowsShell(Dispatcher ui, Func owner, Func tray) : INativeShell +{ + public bool CanPickFolder => true; + + public bool CanShowInFolder => true; + + public bool CanOpenUrl => true; + + public bool CanNotify => true; + + public bool SupportsAutostart => true; + + public Task PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => + ui.InvokeAsync(() => + { + var dialog = new OpenFolderDialog { Title = title, Multiselect = false }; + if (!string.IsNullOrWhiteSpace(initialFolder) && Directory.Exists(initialFolder)) + { + dialog.InitialDirectory = initialFolder; + } + + var window = owner(); + var chosen = window is { IsVisible: true } ? dialog.ShowDialog(window) : dialog.ShowDialog(); + return chosen == true ? dialog.FolderName : null; + }).Task; + + public Task ShowInFolderAsync(string fullPath, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(fullPath) || !Path.IsPathFullyQualified(fullPath) || fullPath.Contains('"', StringComparison.Ordinal) || !File.Exists(fullPath)) + { + return Task.FromResult(false); + } + + var explorer = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe"); + try + { + using var process = Process.Start(new ProcessStartInfo(explorer, $"/select,\"{fullPath}\"") { UseShellExecute = false }); + return Task.FromResult(process is not null); + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) + { + return Task.FromResult(false); + } + } + + public Task OpenUrlAsync(Uri address, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(address); + if (!address.IsAbsoluteUri || address.Scheme is not ("http" or "https")) + { + return Task.FromResult(false); + } + + try + { + // The default browser of Alberto (never the browser of Febe), through the shell. + using var process = Process.Start(new ProcessStartInfo(address.AbsoluteUri) { UseShellExecute = true }); + return Task.FromResult(true); + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) + { + return Task.FromResult(false); + } + } + + public Task NotifyAsync(string title, string message, CancellationToken ct) => + ui.InvokeAsync(() => tray()?.Notify(title, message)).Task; + + public Task GetAutostartAsync(CancellationToken ct) + { + using var key = Registry.CurrentUser.OpenSubKey(Autostart.RunKey, writable: false); + var value = key?.GetValue(Autostart.ValueName) as string; + return Task.FromResult(Environment.ProcessPath is { } exe && Autostart.PointsTo(value, exe)); + } + + public Task SetAutostartAsync(bool enabled, CancellationToken ct) + { + using var key = Registry.CurrentUser.CreateSubKey(Autostart.RunKey, writable: true); + if (enabled) + { + var exe = Environment.ProcessPath ?? throw new InvalidOperationException("Percorso di Febe.exe sconosciuto."); + key.SetValue(Autostart.ValueName, Autostart.Command(exe), RegistryValueKind.String); + } + else + { + key.DeleteValue(Autostart.ValueName, throwOnMissingValue: false); + } + + return Task.CompletedTask; + } +} + +/// Windows notifications for the alerts of spec §13.3 (Impostazioni ▸ Notifiche ▸ «Notifiche di Windows»). +internal sealed class WindowsNotificationChannel(Dispatcher ui, Func tray) : IAlertChannel +{ + public bool IsEnabled(AlertSettings settings) => settings?.WindowsNotifications == true; + + public Task SendAsync(FebeAlert alert, AlertSettings settings, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(alert); + var warning = alert.Kind is AlertKind.Verification or AlertKind.Disconnection or AlertKind.Throttle or AlertKind.DiskLow; + return ui.InvokeAsync(() => tray()?.Notify(alert.Title, alert.Message, warning)).Task; + } +} + +/// +/// The Data folder in use after a move, and a move asked for the next start (), under +/// HKCU\Software\Febe: values «CartellaDati» and «NuovaCartellaDati». The uninstaller reads the first to say +/// where the data are. +/// +internal sealed class RegistryLocationStore : IDataFolderLocationStore +{ + public const string Key = @"Software\Febe"; + + public string? Current => Read("CartellaDati"); + + public string? Pending => Read("NuovaCartellaDati"); + + public void SetCurrent(string? folder) => Write("CartellaDati", folder); + + public void SetPending(string? folder) => Write("NuovaCartellaDati", folder); + + private static string? Read(string name) + { + using var key = Registry.CurrentUser.OpenSubKey(Key, writable: false); + return key?.GetValue(name) is string value && !string.IsNullOrWhiteSpace(value) ? value : null; + } + + private static void Write(string name, string? value) + { + using var key = Registry.CurrentUser.CreateSubKey(Key, writable: true); + if (value is null) + { + key.DeleteValue(name, throwOnMissingValue: false); + } + else + { + key.SetValue(name, value, RegistryValueKind.String); + } + } +} diff --git a/src/Febe.Desktop/app.manifest b/src/Febe.Desktop/app.manifest new file mode 100644 index 0000000..6f44287 --- /dev/null +++ b/src/Febe.Desktop/app.manifest @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2 + true + + + diff --git a/src/Febe.Server/BrowserRemoteView.cs b/src/Febe.Server/BrowserRemoteView.cs index 2810fd4..ac3ffbf 100644 --- a/src/Febe.Server/BrowserRemoteView.cs +++ b/src/Febe.Server/BrowserRemoteView.cs @@ -1,5 +1,6 @@ using System.Runtime.CompilerServices; using System.Text.Json; +using Febe.App; using Febe.Browser.Cdp; using Febe.Browser.Gestures; using Febe.Browser.RemoteView; @@ -14,7 +15,7 @@ namespace Febe.Server; /// 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. /// -internal sealed class BrowserRemoteViewHost(BrowserSupervisor browser, BrowserUseTracker tracker, IClock clock, ServerLog log) : IRemoteViewHost +internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log) : IRemoteViewHost { private readonly Lock _gate = new(); private BrowserRemoteViewConnection? _current; @@ -101,7 +102,7 @@ internal sealed class BrowserRemoteViewHost(BrowserSupervisor browser, BrowserUs internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection { private readonly BrowserRemoteViewHost _owner; - private readonly BrowserSupervisor _browser; + private readonly ChromiumBrowser _browser; private readonly BrowserUseTracker _tracker; private readonly IClock _clock; private readonly RemoteViewSession _session; @@ -122,7 +123,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection private int _disposed; private bool _used; - public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, BrowserSupervisor browser, BrowserUseTracker tracker, IClock clock) + public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock) { _owner = owner; _browser = browser; @@ -389,16 +390,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection } /// The address without query string or fragment (they may carry tokens). - 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; - } + internal static string WithoutQuery(string url) => Addresses.WithoutQuery(url); } /// Turns the DOM key of the page into what Input.dispatchKeyEvent needs (virtual key codes). diff --git a/src/Febe.Server/DockerPlatform.cs b/src/Febe.Server/DockerPlatform.cs new file mode 100644 index 0000000..e37aca2 --- /dev/null +++ b/src/Febe.Server/DockerPlatform.cs @@ -0,0 +1,65 @@ +using Febe.App; +using Febe.Core.Library; +using Febe.Web; +using Febe.Web.Connection; +using Microsoft.Extensions.DependencyInjection; + +namespace Febe.Server; + +/// +/// The Docker edition's parts of the composition (spec §11): password-protected interface on every address, the +/// password and the Data folder checked at start-up, Chromium on Xvfb supervised by Febe itself, the remote view of the +/// browser in the Collegamento and Browser pages. No native shell: folders are read-only in the interface. +/// +internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform +{ + public ServerOptions Options { get; } = options ?? throw new ArgumentNullException(nameof(options)); + + public FebeWebOptions WebOptions => Options.WebOptions(); + + public FebeListen Listen => new(Options.ListenAddress, Options.Port); + + /// The remote view of the browser, once the composition registered it. + public BrowserRemoteViewHost? RemoteView { get; private set; } + + public IReadOnlyList CheckConfiguration(FebeAppOptions appOptions, DataFolderCheck dataFolderCheck) => + StartupChecks.Run(Options, dataFolderCheck); + + public Task CreateBrowserAsync(FebePlatformContext context, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(context); + var home = Path.Combine(context.Data.Root, "home"); + return Task.FromResult(new ChromiumBrowser( + new ChromiumBrowserSettings + { + ProfileDirectory = context.Data.BrowserProfile, + HomeDirectory = home, + WindowWidth = Options.WindowWidth, + WindowHeight = Options.WindowHeight, + DebugPort = Options.DebugPort, + ExecutablePath = Options.ChromiumPath, + + // Linux needs the virtual display; elsewhere (development on Windows) the browser opens a normal window. + Display = OperatingSystem.IsLinux() ? Options.Display : null, + Launch = Options.LaunchOptions(Path.GetFullPath(home)), + ReadyRemark = Options.NoSandbox ? ", senza sandbox (FEBE_SENZA_SANDBOX)" : null, + SandboxAdvice = " Se il registro parla della sandbox, vedi docs/docker.md: profilo seccomp oppure FEBE_SENZA_SANDBOX=1.", + }, + context.Clock, + context.Log)); + } + + public void RegisterServices(IServiceCollection services, FebeApp app) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(app); + RemoteView = new BrowserRemoteViewHost((ChromiumBrowser)app.Browser!, app.Tracker, app.Clock, app.Log); + services.AddSingleton(RemoteView); + } + + public void RegisterProblemServices(IServiceCollection services, FebeApp app) + { + } + + public Task StoppingAsync() => RemoteView?.ShutdownAsync() ?? Task.CompletedTask; +} diff --git a/src/Febe.Server/Febe.Server.csproj b/src/Febe.Server/Febe.Server.csproj index 92c5f34..ce6b18b 100644 --- a/src/Febe.Server/Febe.Server.csproj +++ b/src/Febe.Server/Febe.Server.csproj @@ -11,6 +11,7 @@ + diff --git a/src/Febe.Server/FebeServer.cs b/src/Febe.Server/FebeServer.cs index ebd7589..834e6f8 100644 --- a/src/Febe.Server/FebeServer.cs +++ b/src/Febe.Server/FebeServer.cs @@ -1,20 +1,12 @@ -using System.Globalization; +using Febe.App; 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; @@ -32,577 +24,81 @@ internal sealed record ServerHooks /// How long the web host waits for open requests (events, remote view) when stopping. public TimeSpan ShutdownTimeout { get; init; } = TimeSpan.FromSeconds(3); + + public FebeAppHooks ForApp() => new() + { + Clock = Clock, + Random = Random, + DataFolderCheck = DataFolderCheck, + Console = Console ?? System.Console.Out, + ShutdownTimeout = ShutdownTimeout, + }; } /// -/// 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). +/// The real composition of the Docker edition (spec §5, §11, milestone M5): the shared with the +/// — password-protected interface, Xvfb and Chromium supervised by Febe, the remote view. +/// 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. Disposing stops +/// everything in order (remote view, engine, downloads, browser with SIGINT, Xvfb). /// internal sealed class FebeServer : IAsyncDisposable { - private readonly ServerOptions _options; - private readonly ServerLog _log; - private readonly CancellationTokenSource _lifetime = new(); - private readonly List _background = []; - private readonly List _disposables = []; - private readonly List _unsubscribe = []; - private string? _temporaryFolder; - private int _disposed; + private readonly FebeApp _app; + private readonly DockerPlatform _platform; - private FebeServer(ServerOptions options, ServerLog log, IClock clock, IReadOnlyList problems) + private FebeServer(FebeApp app, DockerPlatform platform) { - _options = options; - _log = log; - Clock = clock; - Problems = problems; + _app = app; + _platform = platform; } - public IClock Clock { get; } + public FebeApp App => _app; - public IReadOnlyList Problems { get; } + public IClock Clock => _app.Clock; - public WebApplication Web { get; private set; } = null!; + public IReadOnlyList Problems => _app.Problems; + + public WebApplication Web => _app.Web; /// Where the interface answers (with 127.0.0.1 in place of «any address»). - public Uri Address { get; private set; } = null!; + public Uri Address => _app.Address; - public FebeDatabase Database { get; private set; } = null!; + public FebeDatabase Database => _app.Database; - public DataFolderLayout? Data { get; private set; } + public DataFolderLayout? Data => _app.Data; - public LibraryLayout? Library { get; private set; } + public LibraryLayout? Library => _app.Library; - public BrowserSupervisor? Browser { get; private set; } + /// Xvfb and Chromium (null with a configuration problem). + public ChromiumBrowser? Browser => _app.Browser as ChromiumBrowser; - public ServerConnectionService? Connection { get; private set; } + public BrowserConnectionService? Connection => _app.Connection; - public BrowserRemoteViewHost? RemoteView { get; private set; } + public BrowserRemoteViewHost? RemoteView => _platform.RemoteView; - public EngineHost? Engine { get; private set; } + public EngineHost? Engine => _app.Engine; - public CollectionPipeline? Pipeline { get; private set; } + public CollectionPipeline? Pipeline => _app.Pipeline; - public ImportService? Import { get; private set; } + public ImportService? Import => _app.Import; - public PerceptualHashIndex? HashIndex { get; private set; } + public PerceptualHashIndex? HashIndex => _app.HashIndex; /// Completes when browser, pipeline and engine are running (never, with a configuration problem). - public Task Running => _running.Task; - - private readonly TaskCompletionSource _running = new(TaskCreationOptions.RunContinuationsAsynchronously); + public Task Running => _app.Running; public static async Task 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; - } - } - - /// - /// 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. - /// - 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(Database); - services.AddSingleton(library); - services.AddSingleton(Clock); - services.AddSingleton(Import); - services.AddSingleton(new DailyBackup(Database, Clock, data.Backups)); - services.AddSingleton(new StartupProblems(Problems)); - services.AddSingleton(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(Database); - s.AddSingleton(library); - s.AddSingleton(Clock); - s.AddSingleton(tracker); - s.AddSingleton(engine.Monitor); - s.AddSingleton(new EngineHostControl(engine)); - s.AddSingleton(connection); - s.AddSingleton(RemoteView); - s.AddSingleton(new EngineHostSettingsControl(engine)); - s.AddSingleton(ingest); - s.AddSingleton(new ServerBrowserPreview(browser, Clock)); - s.AddSingleton(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 register) - { - var web = FebeWebHost.Build( - _options.WebOptions(), - new FebeListen(_options.ListenAddress, _options.Port), - services => - { - register(services); - services.Configure(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)}."); - } - - /// Xvfb and Chromium, then the pipeline, the downloads, the connection check and the engine. - 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(); - _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); - } - } - - /// - /// Development with the test site only (--accesso-di-prova): what Alberto does by hand on Instagram — open - /// the site once, so that its session cookie exists — then back to the rest page. - /// - 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."); - } - - /// - /// 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. - /// - 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; - } - } - } - } - - /// The daily copy of the database (spec §8.5): at start-up if today's is missing, then once a day. - 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; - } - } + var platform = new DockerPlatform(options); + var app = await FebeApp.StartAsync(options.AppOptions(), platform, hooks.ForApp(), ct).ConfigureAwait(false); + return new FebeServer(app, platform); } /// The next copy: a few minutes after local midnight (03:20, outside the active window of every profile). - 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; - } + internal static TimeSpan UntilNextBackup(DateTimeOffset now, TimeZoneInfo zone) => FebeApp.UntilNextBackup(now, zone); - /// Temporary files left by an interrupted run (only .febe-*.part: never a library file, rule 12). - 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); - } - } - - /// Stops everything in order: remote view, interface, engine, downloads, import, pipeline, browser, database. - 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 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); - } - } - } + public ValueTask DisposeAsync() => _app.DisposeAsync(); } diff --git a/src/Febe.Server/ServerOptions.cs b/src/Febe.Server/ServerOptions.cs index 17086aa..6e40921 100644 --- a/src/Febe.Server/ServerOptions.cs +++ b/src/Febe.Server/ServerOptions.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Net; +using Febe.App; using Febe.Browser.Hosting; using Febe.Browser.Recipes; using Febe.Web; @@ -99,6 +100,24 @@ internal sealed record ServerOptions /// public string LoginUrl => TestSite is { } site ? new Uri(site, "/benvenuto").AbsoluteUri : "https://www.instagram.com/accounts/login/"; + /// The options of the shared composition for the Docker edition. + public FebeAppOptions AppOptions() => new() + { + DataFolder = DataFolder, + LibraryFolder = LibraryFolder, + LibraryFolderFromSettings = false, + ImportFolder = ImportFolder, + ZoneId = ZoneId, + Zone = Zone, + Language = Language, + Site = Site, + LoginUrl = LoginUrl, + TestSite = TestSite, + TestSiteAutoLogin = TestSiteAutoLogin, + FirstSessionDelay = FirstSessionDelay, + Warnings = Warnings, + }; + /// The interface options of the Docker edition. public FebeWebOptions WebOptions() => new() { diff --git a/src/Febe.Server/StartupChecks.cs b/src/Febe.Server/StartupChecks.cs index a36596b..8c3f183 100644 --- a/src/Febe.Server/StartupChecks.cs +++ b/src/Febe.Server/StartupChecks.cs @@ -1,3 +1,4 @@ +using Febe.App; using Febe.Core.Library; using Febe.Web.Connection; @@ -11,9 +12,9 @@ internal static class StartupChecks { public const string PasswordMissing = "password-mancante"; - public const string DataNotWritable = "dati-non-scrivibili"; + public const string DataNotWritable = DataFolderProblems.DataNotWritable; - public const string DataOnNetwork = "dati-in-rete"; + public const string DataOnNetwork = DataFolderProblems.DataOnNetwork; /// Every problem found, in the order the error page shows them. public static IReadOnlyList Run(ServerOptions options, DataFolderCheck? check = null) @@ -30,42 +31,11 @@ internal static class StartupChecks "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) + if (DataFolderProblems.Check(options.DataFolder, check) is { } data) { - problems.Add(new ConfigurationProblem( - data.Kind == DataFolderProblemKind.NetworkPath ? DataOnNetwork : DataNotWritable, - data.Title, - data.Explanation, - data.Remedy)); + problems.Add(data); } return problems; } } - -/// The problems found at start-up; fixed for the life of the process (fixing one needs a restart). -internal sealed class StartupProblems(IReadOnlyList problems) : IConfigurationProblems -{ - public IReadOnlyList Current { get; } = problems; -} - -/// -/// 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). -/// -internal sealed class UnavailableConnectionService(IReadOnlyList problems) : IConnectionService -{ - public Task GetStatusAsync(CancellationToken ct) => - Task.FromResult(new ConnectionStatus(ConnectionState.BrowserUnavailable, null, null, false, null)); - - public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct) => throw Refused(); - - public Task 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."); -} diff --git a/src/Febe.Web/Api/SettingsApi.cs b/src/Febe.Web/Api/SettingsApi.cs index 6f8d403..b9ee234 100644 --- a/src/Febe.Web/Api/SettingsApi.cs +++ b/src/Febe.Web/Api/SettingsApi.cs @@ -64,7 +64,12 @@ 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); + if (d.Services.GetService(typeof(Febe.Core.Library.LibraryIngest)) is Febe.Core.Library.LibraryIngest ingest) + { + // The scheme and a new library folder (desktop) hold for the next downloads, without a restart. + ingest.Apply(new LibraryNaming(general, highlight), body.SetFileTime); + ingest.UseLayout(d.Library.Layout); + } d.Changes.Publish(new LibraryChange(d.Clock.Now, null, "settings")); return ApiHttp.Json(await GeneralAsync(context, d, ct).ConfigureAwait(false), FebeJsonContext.Default.GeneralSettingsDto); }); diff --git a/src/Febe.Web/Hosting/EmbeddedWwwroot.cs b/src/Febe.Web/Hosting/EmbeddedWwwroot.cs index 64e249e..36415aa 100644 --- a/src/Febe.Web/Hosting/EmbeddedWwwroot.cs +++ b/src/Febe.Web/Hosting/EmbeddedWwwroot.cs @@ -1,4 +1,5 @@ using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Primitives; @@ -27,6 +28,7 @@ public sealed class EmbeddedWwwroot : IFileProvider { } + [UnconditionalSuppressMessage("SingleFile", "IL3000:Avoid accessing Assembly file path when publishing as a single file", Justification = "In a single file the location is empty and the executable's own time is used instead.")] public EmbeddedWwwroot(Assembly assembly) { _assembly = assembly ?? throw new ArgumentNullException(nameof(assembly)); @@ -48,8 +50,14 @@ public sealed class EmbeddedWwwroot : IFileProvider } } - // Embedded files change only with the assembly: its time is a good Last-Modified (and ETag) for all of them. + // Embedded files change only with the assembly: its time is a good Last-Modified (and ETag) for all of them. In a + // single-file executable (Windows) the assembly has no file of its own: the executable's time stands for it. var location = assembly.Location; + if (string.IsNullOrEmpty(location)) + { + location = Environment.ProcessPath ?? string.Empty; + } + _lastModified = !string.IsNullOrEmpty(location) && File.Exists(location) ? new DateTimeOffset(File.GetLastWriteTimeUtc(location), TimeSpan.Zero) : DateTimeOffset.UtcNow; diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index e9bec26..fa1ca61 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -23,6 +23,13 @@ Qui sotto le convenzioni per chi continua il lavoro (composizione di Server e De ## Ospitare l'interfaccia (Server e Desktop) +Le due vesti non compongono più l'interfaccia a mano: lo fa **`Febe.App`** (`FebeApp.StartAsync(opzioni, piattaforma)`), +la composizione condivisa di database, libreria, importazione, copie, browser, raccolta, scaricamenti, motore, +collegamento (`BrowserConnectionService`), avvisi (`AlertDispatcher`, canali `IAlertChannel`) e interfaccia. Ciò che +cambia sta in `IFebePlatform`: `Febe.Server/DockerPlatform` (password, Chromium su Xvfb, vista remota) e +`Febe.Desktop.Core/DesktopPlatform` (gettone, 127.0.0.1 su porta scelta all'avvio, WebView2, guscio di Windows). Il +modello qui sotto resta valido per chi ospita l'interfaccia da sé (prove, dimostrazione). + ```csharp var app = FebeWebHost.Build(options, FebeListen.Any(8480) /* Docker */ or FebeListen.Loopback(0) /* Windows */, services => { @@ -55,13 +62,13 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri | Servizio | Ripiego | Chi lo sostituisce | |---|---|---| -| `IConnectionService` (`Connection/`) | `UnavailableConnectionService`: stato `BrowserUnavailable`, «Collegati» e «Scollega» rispondono 400 con un messaggio italiano | Server (vista remota) e Desktop (finestra WebView2): l'implementazione vera e `/api/vista` sono di quel lavoro | +| `IConnectionService` (`Connection/`) | `UnavailableConnectionService`: stato `BrowserUnavailable`, «Collegati» e «Scollega» rispondono 400 con un messaggio italiano | `Febe.App/BrowserConnectionService`, la stessa per le due vesti (in Windows porta in primo piano e nasconde la finestra «Browser di Febe»); `/api/vista` è della veste Docker | | `IConfigurationProblems` | `NoConfigurationProblems` (nessun problema) | Server: password mancante, cartelle non scrivibili… Se l'elenco non è vuoto l'interfaccia mostra solo la pagina di errore | | `IEngineSettingsControl` | `StoredEngineSettingsControl`: salva le impostazioni del motore nell'archivio | `new EngineHostSettingsControl(engineHost)`: le applica anche al motore che gira | | `IBrowserPreview` | `NoBrowserPreview` (nessuna anteprima) | Chi ha il browser: `GetLatestAsync` restituisce l'ultima schermata JPEG (`BrowserFrame`) con l'indirizzo | | `IIncidentHistory` | `StoredIncidentHistory` (dall'archivio) | Di solito nessuno | | `IAlertTestSender` (Core) | `TelegramNotAvailableYet`: nessun messaggio parte, la risposta lo dice | M8, l'invio vero dei messaggi Telegram | -| `IDataFolderChange` | `FixedDataFolder`: la cartella dei dati non si cambia dall'interfaccia | Desktop (M6): sposta la cartella al riavvio | +| `IDataFolderChange` | `FixedDataFolder`: la cartella dei dati non si cambia dall'interfaccia | Desktop: `DesktopDataFolderChange` registra la scelta e `DataFolderMove` sposta la cartella al prossimo avvio, con copia verificata (SHA-256) | | `ImportService` (Core) | `ImportHub` ne costruisce uno sulla libreria (Docker: solo sotto `FebeWebOptions.ImportRoot`, di serie `/importa`; desktop: qualsiasi cartella) | La composizione, se vuole opzioni diverse (ffmpeg, cartella sorgente) | - `ImportHub.LibrarySettingsChanged()` va chiamato quando cambiano cartella o schema dei nomi (lo fa già @@ -128,8 +135,8 @@ Ogni altro indirizzo senza estensione risponde con `index.html`; `/api/…` scon 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. +- `IConnectionService` lo registra la composizione (`Febe.App/BrowserConnectionService`, sul browser vero; con un + problema di configurazione `Febe.App/ProblemConnectionService`). 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, diff --git a/src/Febe.Web/wwwroot/js/pages/connection.js b/src/Febe.Web/wwwroot/js/pages/connection.js index f34bba9..5df7973 100644 --- a/src/Febe.Web/wwwroot/js/pages/connection.js +++ b/src/Febe.Web/wwwroot/js/pages/connection.js @@ -81,6 +81,8 @@ export async function mountConnection(page) { h('ol.passi-collegamento', (Array.isArray(steps) ? steps : []).map((s, i) => h('li', h('span.numero', String(i + 1)), h('div', h('b', s.titolo), h('p', s.testo)))))), passwordNote(windows), h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))), + // Windows: one engine per account (spec §5) said before the login too; Docker keeps mockup 10 as it is. + windows ? h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))) : null, message, h('div.molla'), h('div.bottoni-collegamento', diff --git a/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs b/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs new file mode 100644 index 0000000..b3a3207 --- /dev/null +++ b/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs @@ -0,0 +1,299 @@ +using System.Net; +using System.Text.Json; +using Febe.App; +using Febe.Core.Alerts; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Desktop.Core; +using Febe.Tests.Desktop.Support; +using Febe.Tests.Support; +using Microsoft.Extensions.DependencyInjection; + +namespace Febe.Tests.Desktop; + +/// +/// The Windows edition composed on Linux (spec §5 «I due involucri», §12, §13.1): the same as +/// Docker with the , and a fake only for what needs Windows (WebView2, registry, icon). +/// Never Instagram: the fake browser answers by itself. +/// +[TestClass] +public sealed class DesktopCompositionTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheInterfaceAnswersOnlyOnLoopbackWithTheTokenOfThisStart() + { + await using var bed = await DesktopTestBed.StartAsync(); + Assert.IsEmpty(bed.App.Problems); + Assert.AreEqual("127.0.0.1", bed.App.Address.Host); + Assert.AreNotEqual(8480, bed.App.Address.Port, "a port chosen at start-up"); + + // Without the token: refused, also for the pages. + foreach (var path in new[] { "/api/capabilities", "/api/accounts", "/" }) + { + using var anonymous = await bed.SendAsync(HttpMethod.Get, path, token: false); + Assert.AreEqual(HttpStatusCode.Unauthorized, anonymous.StatusCode, path); + } + + // The window opens /?gettone=… once: the token becomes an HttpOnly cookie and leaves the address. + var first = bed.Platform.FirstAddress(bed.App.Address); + StringAssert.StartsWith(first.Query, "?gettone="); + using (var opening = await bed.Client.GetAsync(first.PathAndQuery, TestContext.CancellationToken)) + { + Assert.AreEqual(HttpStatusCode.Redirect, opening.StatusCode); + Assert.AreEqual("/", opening.Headers.Location?.OriginalString); + var cookie = opening.Headers.GetValues("Set-Cookie").Single(); + StringAssert.Contains(cookie, "httponly"); + StringAssert.Contains(cookie, "samesite=strict"); + } + + // Another token (a page of another start, another program) is refused. + using (var wrong = await bed.Client.GetAsync("/?gettone=" + Febe.Web.Security.AccessToken.Create(), TestContext.CancellationToken)) + { + Assert.AreEqual(HttpStatusCode.Unauthorized, wrong.StatusCode); + } + + // DNS rebinding: a Host that is not 127.0.0.1/localhost is refused even with the token. + using (var request = new HttpRequestMessage(HttpMethod.Get, "/api/capabilities")) + { + request.Headers.Host = "attacco.example:" + bed.App.Address.Port; + request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, bed.Platform.AccessToken); + using var rebinding = await bed.Client.SendAsync(request, TestContext.CancellationToken); + Assert.AreEqual(HttpStatusCode.BadRequest, rebinding.StatusCode); + } + + // Commands from another origin are refused even with the token. + using (var request = new HttpRequestMessage(HttpMethod.Post, "/api/engine/pause")) + { + request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, bed.Platform.AccessToken); + request.Headers.TryAddWithoutValidation("Origin", "https://www.esempio.it"); + using var foreign = await bed.Client.SendAsync(request, TestContext.CancellationToken); + Assert.AreEqual(HttpStatusCode.Forbidden, foreign.StatusCode); + } + + var caps = await bed.JsonAsync(HttpMethod.Get, "/api/capabilities"); + Assert.AreEqual("desktop", caps.GetProperty("edition").GetString()); + Assert.AreEqual("token", caps.GetProperty("access").GetString()); + foreach (var flag in new[] { "showInFolder", "pickFolder", "autostart", "browserWindow", "notifications", "openUrlNative" }) + { + Assert.IsTrue(caps.GetProperty(flag).GetBoolean(), flag); + } + + Assert.IsFalse(caps.GetProperty("foldersReadOnly").GetBoolean()); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheBrowserWindowComesToTheFrontForTheLoginAndGoesOutOfViewAfterHoFinito() + { + await using var bed = await DesktopTestBed.StartAsync(); + await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), TestContext.CancellationToken); + var (settings, browser) = bed.Shell.Created.Single(); + Assert.AreEqual(BrowserHosting.Window, settings.Hosting, "the first attempt of S2 by default"); + Assert.AreEqual(Path.Combine(bed.Folders.DefaultDataFolder, "browser"), settings.ProfileDirectory, "Dati\\browser"); + Assert.AreEqual((1280, 900), (settings.Width, settings.Height)); + StringAssert.Contains(settings.AdditionalBrowserArguments, "CalculateNativeWinOcclusion"); + Assert.AreEqual(BrowserHosting.Window, bed.Platform.Hosting); + + var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection"); + Assert.AreEqual("notConnected", status.GetProperty("state").GetString()); + + // «Accedi a Instagram»: the login page in the browser window, which comes to the front; the engine is still. + using (var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", """{"openLogin":true}""")) + { + Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode); + } + + Assert.AreEqual(1, browser.Shown); + Assert.IsTrue(browser.UserIsDriving); + Assert.IsTrue(bed.App.Engine!.Services.Runtime.UserIsDriving, "the engine sees Alberto at the wheel"); + Assert.AreEqual("https://www.instagram.com/accounts/login/", browser.FakeCdp.Url, "the real login page (never opened here: the browser is a fake)"); + + // Alberto logs in by himself in the window; «Ho finito» checks the cookie and puts the window out of view. + browser.FakeCdp.LoggedIn = true; + var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); + Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString()); + Assert.IsGreaterThanOrEqualTo(1, browser.Hidden); + Assert.IsFalse(browser.UserIsDriving); + Assert.AreEqual("about:blank", browser.FakeCdp.Url, "back to the rest page"); + Assert.IsNotNull(bed.App.Tracker.LastUsedAt, "«Riprendi» knows the browser was used"); + Assert.IsNotNull(await bed.App.Database.Settings.GetInt64Async(BrowserConnectionService.FirstConnectionKey, TestContext.CancellationToken)); + Assert.AreEqual("connected", (await bed.JsonAsync(HttpMethod.Get, "/api/connection")).GetProperty("state").GetString()); + Assert.IsFalse(browser.FakeCdp.Methods.Contains("Network.setCookie"), "only the existence of the cookie is read"); + + // «Apri il browser» (Attività, red strip) and «Portalo in primo piano» (Collegamento). + await bed.JsonAsync(HttpMethod.Post, "/api/browser/show"); + Assert.AreEqual(2, browser.Shown); + using (var front = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", """{"openLogin":false}""")) + { + Assert.AreEqual(HttpStatusCode.NoContent, front.StatusCode); + } + + Assert.AreEqual(3, browser.Shown); + using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel")) + { + Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode); + } + + Assert.IsFalse(browser.UserIsDriving); + + // «Scollega»: the window goes away, the profile folder with the session is deleted, the browser starts empty. + var marker = Path.Combine(browser.ProfileDirectory, "Cookies"); + await File.WriteAllTextAsync(marker, "sessione", TestContext.CancellationToken); + using (var disconnect = await bed.SendAsync(HttpMethod.Post, "/api/connection/disconnect")) + { + Assert.AreEqual(HttpStatusCode.NoContent, disconnect.StatusCode); + } + + Assert.IsFalse(File.Exists(marker)); + Assert.AreEqual(1, browser.EmptiedProfiles); + Assert.AreEqual("notConnected", (await bed.JsonAsync(HttpMethod.Get, "/api/connection")).GetProperty("state").GetString()); + + // A profile that cannot be deleted is said in Italian; the engine starts again and the session is looked at again. + browser.FakeCdp.LoggedIn = true; + browser.ProfileLocked = true; + using (var locked = await bed.SendAsync(HttpMethod.Post, "/api/connection/disconnect")) + { + Assert.AreEqual(HttpStatusCode.BadRequest, locked.StatusCode); + using var problem = JsonDocument.Parse(await locked.Content.ReadAsStringAsync(TestContext.CancellationToken)); + StringAssert.Contains(problem.RootElement.GetProperty("message").GetString(), "non è riuscito del tutto"); + } + + Assert.IsTrue(bed.App.Engine.Services.Runtime.IsRunning, "the engine loop runs again"); + Assert.AreEqual("connected", (await bed.JsonAsync(HttpMethod.Get, "/api/connection")).GetProperty("state").GetString(), "never claimed disconnected"); + Assert.IsFalse(browser.UserIsDriving); + + await bed.StopAsync(); + Assert.IsTrue(browser.Disposed, "the browser is closed when Febe stops (S3: session on disk)"); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task FoldersAutostartAndTheDataFolderChangeGoThroughTheNativeShell() + { + await using var bed = await DesktopTestBed.StartAsync(); + var general = await bed.JsonAsync(HttpMethod.Get, "/api/settings/general"); + Assert.AreEqual(bed.Folders.DefaultLibraryFolder, general.GetProperty("library").GetProperty("path").GetString(), "Immagini\\Febe"); + Assert.AreEqual(bed.Folders.DefaultDataFolder, general.GetProperty("data").GetProperty("path").GetString(), "%LOCALAPPDATA%\\Febe"); + Assert.IsTrue(general.GetProperty("canChangeDataFolder").GetBoolean()); + Assert.IsFalse(general.GetProperty("autostart").GetBoolean()); + + // A new library folder: the next downloads go there at once, and the next start uses it. + var library = bed.Temp.Combine("Foto di Instagram"); + var saved = await bed.JsonAsync(HttpMethod.Put, "/api/settings/general", $$""" + {"libraryFolder":{{JsonSerializer.Serialize(library)}},"namingScheme":{{JsonSerializer.Serialize(NamingScheme.DefaultGeneral)}},"highlightScheme":{{JsonSerializer.Serialize(NamingScheme.DefaultHighlight)}},"setFileTime":true,"autostart":true,"keepInTray":true} + """); + Assert.AreEqual(library, saved.GetProperty("library").GetProperty("path").GetString()); + Assert.IsTrue(bed.Shell.NativeShell.Autostart, "«Avvia Febe all'accensione del computer»"); + var ingest = bed.App.Web.Services.GetRequiredService(); + Assert.AreEqual(library, ingest.Layout.Root); + + // «Cambia…» of the Data folder: recorded for the next start, nothing moves now. + var newData = bed.Temp.Combine("NuoviDati"); + var answer = await bed.JsonAsync(HttpMethod.Post, "/api/settings/data-folder", $$"""{"path":{{JsonSerializer.Serialize(newData)}}}"""); + StringAssert.Contains(answer.GetProperty("message").GetString(), "prossimo avvio"); + Assert.AreEqual(newData, bed.Locations.Pending); + Assert.IsFalse(Directory.Exists(newData)); + + // «Mostra nella cartella» and the folder picker go to the shell. + bed.Shell.NativeShell.FolderToPick = bed.Temp.Combine("scelta"); + var picked = await bed.JsonAsync(HttpMethod.Post, "/api/settings/pick-folder", """{"which":"library"}"""); + Assert.AreEqual(bed.Temp.Combine("scelta"), picked.GetProperty("path").GetString()); + + // The next start, after the move: the library chosen in Impostazioni is used. + await bed.StopAsync(); + var moved = DataFolderMove.ApplyPending(bed.Locations, bed.Folders.DefaultDataFolder); + Assert.AreEqual(DataFolderMoveOutcome.Moved, moved.Outcome, moved.Message); + Assert.IsTrue(File.Exists(Path.Combine(newData, "febe.sqlite"))); + await using var again = await DesktopTestBed.StartAsync(["--dati", newData]); + Assert.AreEqual(library, again.App.Library!.Root); + Assert.IsFalse((await again.JsonAsync(HttpMethod.Get, "/api/settings/general")).GetProperty("canChangeDataFolder").GetBoolean(), "with --dati the command line decides"); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheAlertsOfTheEngineBecomeWindowsNotifications() + { + await using var bed = await DesktopTestBed.StartAsync(); + var events = bed.App.Engine!.Services.Events; + var received = bed.Shell.Alerts.Received; + + await events.WriteAsync(EventSeverity.Error, EngineEventCodes.ChallengeStop, "Instagram ha chiesto una verifica: Febe si è fermato.", ct: TestContext.CancellationToken); + await events.WriteAsync(EventSeverity.Info, EngineEventCodes.SessionEnded, "Sessione finita.", ct: TestContext.CancellationToken); + await events.WriteAsync(EventSeverity.Success, EngineEventCodes.BackfillCompleted, "Storico di marta.prova completato.", ct: TestContext.CancellationToken); + await DesktopTestBed.WaitUntilAsync(() => received.Count >= 2, TimeSpan.FromSeconds(10), "due notifiche"); + var alerts = received.ToArray(); + Assert.AreEqual(AlertKind.Verification, alerts[0].Kind); + Assert.AreEqual("Instagram chiede una verifica", alerts[0].Title); + Assert.AreEqual(AlertKind.BackfillDone, alerts[1].Kind); + + // Alberto turns off «Storico completato» and then the Windows notifications: nothing more arrives. + var settings = AlertSettings.Default with { Events = AlertEvents.All with { BackfillDone = false } }; + await AlertSettingsStore.SaveAsync(bed.App.Database.Settings, settings, TestContext.CancellationToken); + await events.WriteAsync(EventSeverity.Success, EngineEventCodes.BackfillCompleted, "Storico di luca.prova completato.", ct: TestContext.CancellationToken); + await AlertSettingsStore.SaveAsync(bed.App.Database.Settings, settings with { WindowsNotifications = false }, TestContext.CancellationToken); + await events.WriteAsync(EventSeverity.Error, EngineEventCodes.DisconnectStop, "Sessione terminata.", ct: TestContext.CancellationToken); + await Task.Delay(500, TestContext.CancellationToken); + Assert.HasCount(2, received); + Assert.HasCount(1, bed.App.Alerts!.Channels); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task WithoutWebView2NothingStartsAndTheProblemIsKnown() + { + var shell = new FakeDesktopShell { RuntimeVersion = null }; + await using var bed = await DesktopTestBed.StartAsync(shell: shell); + Assert.AreEqual(DesktopStartupChecks.WebView2Missing, bed.App.Problems.Single().Code); + Assert.IsNull(bed.App.Browser); + Assert.IsNull(bed.App.Engine); + Assert.IsEmpty(shell.Created); + Assert.IsFalse(File.Exists(Path.Combine(bed.Folders.DefaultDataFolder, "febe.sqlite")), "nothing written in the Data folder"); + Assert.IsFalse(Directory.Exists(Path.Combine(bed.Folders.DefaultDataFolder, "registro"))); + var caps = await bed.JsonAsync(HttpMethod.Get, "/api/capabilities"); + Assert.AreEqual("webview2-assente", caps.GetProperty("problems")[0].GetProperty("code").GetString()); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheHostingOfS2IsChosenOnTheCommandLineKeptForTheNextStartsAndEdgeFallsBackWhenMissing() + { + using var temp = new TempFolder("desktop-s2"); + var locations = new MemoryLocationStore(); + await using (var composition = await DesktopTestBed.StartAsync(["--browser", "composizione"], temp: temp, locations: locations)) + { + Assert.AreEqual(BrowserHosting.Composition, composition.Shell.Created.Single().Settings.Hosting); + await composition.StopAsync(); + } + + await using (var kept = await DesktopTestBed.StartAsync(temp: temp, locations: locations)) + { + Assert.AreEqual(BrowserHosting.Composition, kept.Shell.Created.Single().Settings.Hosting, "stored in the settings"); + await kept.StopAsync(); + } + + // Edge chosen but not installed: the window of WebView2, with a warning in the log. + await using (var noEdge = await DesktopTestBed.StartAsync(["--browser", "edge"], temp: temp, locations: locations)) + { + Assert.AreEqual(BrowserHosting.Window, noEdge.Platform.Hosting); + Assert.AreEqual(BrowserHosting.Window, noEdge.Shell.Created.Single().Settings.Hosting); + await noEdge.StopAsync(); + } + + // Edge installed: Chromium's host on Edge, its profile inside Dati\browser, so «Scollega» deletes both. + var shell = new FakeDesktopShell { EdgePath = temp.Combine("Edge", "msedge.exe") }; + await using var edge = await DesktopTestBed.StartAsync(temp: temp, locations: locations, shell: shell); + Assert.AreEqual(BrowserHosting.Edge, edge.Platform.Hosting); + Assert.IsEmpty(shell.Created, "no WebView2 for the browser"); + var browser = (EdgeBrowser)edge.App.Browser!; + Assert.AreEqual(Path.Combine(edge.Folders.DefaultDataFolder, "browser", "edge"), browser.ProfileDirectory); + Assert.AreEqual(edge.Shell.EdgePath, browser.Inner.BrowserOptions.ExecutablePath); + Assert.IsNull(browser.Inner.BrowserOptions.Display, "a normal window on Windows, no Xvfb"); + await DesktopTestBed.WaitUntilAsync(() => browser.LastError is not null, TimeSpan.FromSeconds(10), "il tentativo di avviare Edge"); + Assert.IsFalse(browser.IsAvailable, "the fake msedge.exe does not exist: the browser is retried, nothing else breaks"); + } +} diff --git a/tests/Febe.Tests/Desktop/DesktopLogicTests.cs b/tests/Febe.Tests/Desktop/DesktopLogicTests.cs new file mode 100644 index 0000000..1e7998b --- /dev/null +++ b/tests/Febe.Tests/Desktop/DesktopLogicTests.cs @@ -0,0 +1,302 @@ +using Febe.Browser.Hosting; +using Febe.Core.Library; +using Febe.Desktop.Core; +using Febe.Tests.Desktop.Support; +using Febe.Tests.Support; +using Febe.Web.Api; + +namespace Febe.Tests.Desktop; + +/// +/// The parts of the Windows application that do not need Windows (spec §12): command line, single instance, start-up +/// checks, start with the computer, Edge for S2, the switches of S2, the move of the Data folder. +/// +[TestClass] +public sealed class DesktopLogicTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public void TheCommandLineIsReadAndWrongValuesAreRefusedInItalian() + { + Assert.IsTrue(DesktopCommandLine.TryParse([], out var plain, out _)); + Assert.IsFalse(plain.StartHidden); + Assert.IsNull(plain.Hosting); + Assert.IsNull(plain.DataFolder); + Assert.AreEqual("https://www.instagram.com/accounts/login/", plain.LoginUrl); + Assert.AreEqual("instagram", plain.Site.Name); + + var data = Path.Combine(Path.GetTempPath(), "febe-dati"); + var library = Path.Combine(Path.GetTempPath(), "febe-libreria"); + Assert.IsTrue(DesktopCommandLine.TryParse(["--nascosto", "--browser", "composizione", "--dati", data, "--sviluppo", "--libreria", library], out var options, out _)); + Assert.AreEqual(Path.GetFullPath(library), options.AppOptions(data, new DesktopFolders("a", "b")).LibraryFolder); + Assert.IsTrue(options.StartHidden); + Assert.AreEqual(BrowserHosting.Composition, options.Hosting); + Assert.AreEqual(Path.GetFullPath(data), options.DataFolder); + Assert.IsTrue(options.DeveloperTools); + + Assert.IsTrue(DesktopCommandLine.TryParse(["--sito-di-prova", "http://127.0.0.1:8481", "--accesso-di-prova", "--prima-sessione", "5", "--browser", "EDGE"], out var test, out _)); + Assert.AreEqual("http://127.0.0.1:8481/benvenuto", test.LoginUrl); + Assert.AreNotEqual("instagram", test.Site.Name); + Assert.AreEqual(TimeSpan.FromSeconds(5), test.FirstSessionDelay); + Assert.AreEqual(BrowserHosting.Edge, test.Hosting); + + foreach (var (args, fragment) in new (string[], string)[] + { + (["--browser", "nascosto"], "--browser"), + (["--dati", "relativo"], "--dati"), + (["--libreria"], "--libreria"), + (["--sito-di-prova", "https://www.instagram.com/"], "questo computer"), + (["--accesso-di-prova"], "--sito-di-prova"), + (["--prima-sessione", "0"], "--prima-sessione"), + (["--password", "x"], "Opzione sconosciuta"), + }) + { + Assert.IsFalse(DesktopCommandLine.TryParse(args, out _, out var problem), string.Join(' ', args)); + StringAssert.Contains(problem, fragment); + } + } + + [TestMethod] + public void TheHostingNamesAreItalianAndRoundTrip() + { + foreach (var hosting in Enum.GetValues()) + { + Assert.IsTrue(BrowserHostingNames.TryParse(BrowserHostingNames.Name(hosting), out var back)); + Assert.AreEqual(hosting, back); + } + + Assert.IsFalse(BrowserHostingNames.TryParse(null, out var fallback)); + Assert.AreEqual(BrowserHosting.Window, fallback, "the default of S2 is the first attempt"); + } + + [TestMethod] + public void TheDefaultFoldersAreLocalAppDataAndPictures() + { + var folders = new DesktopFolders(Path.Combine("C", "Users", "alberto", "AppData", "Local"), Path.Combine("C", "Users", "alberto", "Pictures")); + Assert.AreEqual(Path.Combine(folders.LocalAppData, "Febe"), folders.DefaultDataFolder); + Assert.AreEqual(Path.Combine(folders.Pictures, "Febe"), folders.DefaultLibraryFolder); + Assert.IsTrue(DesktopCommandLine.TryParse([], out var options, out _)); + var app = options.AppOptions(folders.DefaultDataFolder, folders); + Assert.IsTrue(app.LibraryFolderFromSettings, "the library chosen in Impostazioni wins over the default"); + Assert.IsNull(app.ImportFolder, "any folder can be imported on Windows"); + Assert.AreEqual(folders.DefaultLibraryFolder, app.LibraryFolder); + } + + [TestMethod] + public void OneInstancePerDataFolderAndTheMessagesBetweenLaunches() + { + var a = Path.Combine(Path.GetTempPath(), "febe", "dati"); + Assert.AreEqual(InstanceIdentity.For(a), InstanceIdentity.For(a + Path.DirectorySeparatorChar), "the same folder"); + Assert.AreEqual(InstanceIdentity.For(a), InstanceIdentity.For(a.ToUpperInvariant()), "whatever the case of the letters"); + Assert.AreNotEqual(InstanceIdentity.For(a), InstanceIdentity.For(a + "2"), "another account, another instance"); + StringAssert.StartsWith(InstanceIdentity.MutexName(a), @"Local\Febe-"); + Assert.AreEqual(21, InstanceIdentity.PipeName(a).Length); + + Assert.IsTrue(DesktopCommandLine.TryParse([], out var normal, out _)); + Assert.IsTrue(DesktopCommandLine.TryParse(["--nascosto"], out var hidden, out _)); + Assert.AreEqual(InstanceRequest.Show, InstanceMessages.Parse(InstanceMessages.For(normal))); + Assert.AreEqual(InstanceRequest.StayHidden, InstanceMessages.Parse(InstanceMessages.For(hidden))); + Assert.AreEqual(InstanceRequest.Show, InstanceMessages.Parse("FEBE1 mostra\n")); + foreach (var junk in new[] { null, string.Empty, "mostra", "FEBE2 mostra", "FEBE1 apri C:\\", new string('x', 500) }) + { + Assert.IsNull(InstanceMessages.Parse(junk), junk); + } + } + + [TestMethod] + public void WithoutWebView2TheProblemNamesTheOfficialPage() + { + using var temp = new TempFolder("desktop-controlli"); + var data = temp.Combine("dati"); + Assert.IsEmpty(DesktopStartupChecks.Run(data, () => "141.0.3537.71")); + + var problems = DesktopStartupChecks.Run(data, () => null); + var missing = problems.Single(); + Assert.AreEqual("webview2-assente", missing.Code); + StringAssert.Contains(missing.Remedy, "https://developer.microsoft.com/microsoft-edge/webview2/"); + StringAssert.Contains(missing.Message, "WebView2"); + + // The probe throws when the runtime is missing (WebView2RuntimeNotFoundException): same problem. + Assert.AreEqual("webview2-assente", DesktopStartupChecks.Run(data, () => throw new InvalidOperationException("nessun runtime")).Single().Code); + } + + [TestMethod] + public void ADataFolderOnANetworkShareOrNotWritableStopsTheEngine() + { + using var temp = new TempFolder("desktop-controlli"); + var file = temp.Combine("un-file"); + File.WriteAllText(file, "x"); + Assert.AreEqual("dati-non-scrivibili", DesktopStartupChecks.Run(file, () => "1.0").Single().Code); + + if (OperatingSystem.IsLinux()) + { + var share = temp.Combine("rete"); + var mounts = $"//nas/condivisa {share} cifs rw 0 0\n"; + var problems = DesktopStartupChecks.Run(share, () => null, new DataFolderCheck(() => mounts)); + CollectionAssert.AreEqual(new[] { "dati-in-rete", "webview2-assente" }, problems.Select(p => p.Code).ToArray()); + } + } + + [TestMethod] + public void StartWithTheComputerWritesTheQuotedExecutableAndRecognisesItsOwnValue() + { + var exe = Path.Combine(Path.GetTempPath(), "Programmi", "Febe", "Febe.exe"); + var command = Autostart.Command(exe); + Assert.AreEqual($"\"{exe}\" --nascosto", command); + Assert.IsTrue(Autostart.PointsTo(command, exe)); + Assert.IsTrue(Autostart.PointsTo(exe, exe), "a value without quotes"); + Assert.IsFalse(Autostart.PointsTo(Autostart.Command(exe + ".vecchio"), exe), "another copy of Febe"); + Assert.IsFalse(Autostart.PointsTo(null, exe)); + Assert.IsFalse(Autostart.PointsTo("\"senza fine", exe)); + Assert.ThrowsExactly(() => Autostart.Command("C:\\a\"b.exe")); + } + + [TestMethod] + public void EdgeIsFoundThroughAppPathsThenTheUsualFolders() + { + var candidates = EdgeLocator.Candidates("\"D:\\Edge\\msedge.exe\"", "C:\\Program Files (x86)", "C:\\Program Files", "C:\\Users\\a\\AppData\\Local"); + Assert.AreEqual("D:\\Edge\\msedge.exe", candidates[0]); + Assert.HasCount(4, candidates); + Assert.AreEqual(Path.Combine("C:\\Program Files (x86)", "Microsoft", "Edge", "Application", "msedge.exe"), candidates[1]); + + var exists = new HashSet([candidates[2]]); + Assert.AreEqual(candidates[2], EdgeLocator.Find(candidates, exists.Contains)); + Assert.IsNull(EdgeLocator.Find(candidates, _ => false)); + Assert.IsNull(EdgeLocator.Find(["C:\\Windows\\notepad.exe"], _ => true), "only msedge.exe"); + } + + [TestMethod] + public void TheSwitchesOfS2PassTheChecksOfRule2AndChangeNothingTheBrowserDeclares() + { + foreach (var argument in BrowserArguments.KeepPaintingOutOfView) + { + ChromiumCommandLine.EnsureAllowed(argument); + foreach (var declared in new[] { "user-agent", "lang", "headless", "automation", "proxy", "blink-features", "timezone", "fingerprint", "webdriver" }) + { + Assert.DoesNotContain(declared, argument, StringComparison.OrdinalIgnoreCase); + } + } + + Assert.AreEqual("--disable-features=CalculateNativeWinOcclusion --disable-backgrounding-occluded-windows", BrowserArguments.ForWebView2()); + + // Edge started as a process gets the same switches, after Febe's own (fixed port on 127.0.0.1, profile, size). + var line = ChromiumCommandLine.Build(new Febe.Core.Abstractions.BrowserOptions("profilo", 1280, 900, 9222), new ChromiumLaunchOptions { ExtraArguments = BrowserArguments.ForEdge() }); + CollectionAssert.IsSubsetOf(BrowserArguments.KeepPaintingOutOfView.ToList(), line.ToList()); + Assert.IsFalse(line.Any(a => a.StartsWith("--headless", StringComparison.Ordinal) || a.StartsWith("--enable-automation", StringComparison.Ordinal))); + } + + [TestMethod] + public void TheDataFolderMovesOnlyAfterEveryFileIsCopiedAndVerified() + { + using var temp = new TempFolder("desktop-sposta"); + var from = temp.Combine("vecchia"); + var to = temp.Combine("nuova", "Febe"); + Directory.CreateDirectory(Path.Combine(from, "browser", "Default")); + Directory.CreateDirectory(Path.Combine(from, "miniature", "ab")); + Directory.CreateDirectory(Path.Combine(from, "vuota")); + File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database"); + File.WriteAllText(Path.Combine(from, "browser", "Default", "Cookies"), "sessione"); + var big = new byte[3 * 1024 * 1024 + 17]; + new Random(4).NextBytes(big); + File.WriteAllBytes(Path.Combine(from, "miniature", "ab", "x.jpg"), big); + + var store = new MemoryLocationStore(); + Assert.AreEqual(DataFolderMoveOutcome.NotRequested, DataFolderMove.ApplyPending(store, from).Outcome); + + var change = new DesktopDataFolderChange(store, from, fixedByCommandLine: false); + Assert.IsTrue(change.CanChange); + var message = change.RequestChangeAsync(to, TestContext.CancellationToken).Result; + StringAssert.Contains(message, "prossimo avvio"); + Assert.AreEqual(Path.GetFullPath(to), store.Pending); + Assert.IsFalse(Directory.Exists(to), "nothing moves while Febe runs"); + + var reports = new List(); + var result = DataFolderMove.ApplyPending(store, from, new SyncProgress(reports.Add)); + Assert.AreEqual(DataFolderMoveOutcome.Moved, result.Outcome, result.Message); + Assert.AreEqual(Path.GetFullPath(to), result.DataFolder); + Assert.AreEqual(Path.GetFullPath(to), store.Current); + Assert.IsNull(store.Pending); + Assert.IsFalse(Directory.Exists(from), "the old folder, with a copy of the session, is gone"); + Assert.AreEqual("sessione", File.ReadAllText(Path.Combine(to, "browser", "Default", "Cookies"))); + CollectionAssert.AreEqual(big, File.ReadAllBytes(Path.Combine(to, "miniature", "ab", "x.jpg"))); + Assert.IsTrue(Directory.Exists(Path.Combine(to, "vuota")), "empty folders too"); + Assert.AreEqual(3, reports[^1].FilesTotal); + Assert.AreEqual(3, reports[^1].FilesDone); + } + + [TestMethod] + public void AFailedCopyLeavesTheOldFolderInUseAndRemovesThePartialCopy() + { + using var temp = new TempFolder("desktop-sposta"); + var from = temp.Combine("vecchia"); + Directory.CreateDirectory(from); + File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database"); + var to = temp.Combine("nuova"); + var store = new MemoryLocationStore { Pending = to }; + + // The target appears with a file before the start (someone used it): refused, nothing touched. + Directory.CreateDirectory(to); + File.WriteAllText(Path.Combine(to, "altro.txt"), "non di Febe"); + var refused = DataFolderMove.ApplyPending(store, from); + Assert.AreEqual(DataFolderMoveOutcome.Failed, refused.Outcome); + Assert.AreEqual(from, refused.DataFolder); + StringAssert.Contains(refused.Message, "vuota"); + Assert.IsNull(store.Pending); + Assert.IsNull(store.Current); + Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite"))); + Assert.IsTrue(File.Exists(Path.Combine(to, "altro.txt")), "a folder that is not Febe's is never emptied"); + + // A copy interrupted half way (the disk fills up after the first file): the old folder stays, the copy goes. + File.WriteAllText(Path.Combine(from, "secondo"), "y"); + var halfway = temp.Combine("quarta"); + store.Pending = halfway; + var interrupted = DataFolderMove.ApplyPending(store, from, new SyncProgress(_ => throw new IOException("disco pieno"))); + Assert.AreEqual(DataFolderMoveOutcome.Failed, interrupted.Outcome); + StringAssert.Contains(interrupted.Message, "disco pieno"); + Assert.IsFalse(Directory.Exists(halfway), "the partial copy is removed"); + Assert.IsNull(store.Current); + Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite"))); + + // A file the copy cannot read: the same. + if (OperatingSystem.IsLinux() && Environment.UserName != "root") + { + var locked = Path.Combine(from, "bloccato"); + File.WriteAllText(locked, "x"); + File.SetUnixFileMode(locked, UnixFileMode.None); + var target = temp.Combine("terza"); + store.Pending = target; + var failed = DataFolderMove.ApplyPending(store, from); + Assert.AreEqual(DataFolderMoveOutcome.Failed, failed.Outcome); + Assert.IsFalse(Directory.Exists(target), "the partial copy is removed"); + Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite"))); + File.SetUnixFileMode(locked, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + } + + [TestMethod] + public void TheNewDataFolderMustBeEmptyLocalAndOutsideTheCurrentOne() + { + using var temp = new TempFolder("desktop-sposta"); + var current = temp.Combine("dati"); + Directory.CreateDirectory(current); + Assert.IsNotNull(DataFolderMove.Validate(current, "relativa")); + Assert.IsNotNull(DataFolderMove.Validate(current, current)); + Assert.IsNotNull(DataFolderMove.Validate(current, Path.Combine(current, "dentro"))); + Assert.IsNotNull(DataFolderMove.Validate(Path.Combine(current, "sotto"), current)); + Assert.IsNull(DataFolderMove.Validate(current, temp.Combine("altrove"))); + Assert.IsFalse(Directory.Exists(temp.Combine("altrove")), "checking a choice does not leave a folder behind"); + + var fixedByCommandLine = new DesktopDataFolderChange(new MemoryLocationStore(), current, fixedByCommandLine: true); + Assert.IsFalse(fixedByCommandLine.CanChange); + Assert.ThrowsExactly(() => fixedByCommandLine.RequestChangeAsync(temp.Combine("altrove"), TestContext.CancellationToken).GetAwaiter().GetResult()); + var store = new MemoryLocationStore(); + Assert.ThrowsExactly(() => new DesktopDataFolderChange(store, current, false).RequestChangeAsync(Path.Combine(current, "x"), TestContext.CancellationToken).GetAwaiter().GetResult()); + Assert.IsNull(store.Pending); + } + + private sealed class SyncProgress(Action report) : IProgress + { + public void Report(DataFolderMoveProgress value) => report(value); + } +} diff --git a/tests/Febe.Tests/Desktop/IconTests.cs b/tests/Febe.Tests/Desktop/IconTests.cs new file mode 100644 index 0000000..48870b4 --- /dev/null +++ b/tests/Febe.Tests/Desktop/IconTests.cs @@ -0,0 +1,134 @@ +using System.Buffers.Binary; +using Febe.Desktop.Core; +using Febe.Tests.Desktop.Support; +using SkiaSharp; + +namespace Febe.Tests.Desktop; + +/// +/// The icon of the Windows application (spec §12, appendix C): the brand mark drawn with SkiaSharp and written by the +/// hand-made ICO writer, at 16, 24, 32, 48, 64, 128 and 256 pixels. The committed src/Febe.Desktop/Febe.ico must be +/// what the code draws: FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests writes it again. +/// +[TestClass] +public sealed class IconTests +{ + [TestMethod] + public void TheIconHasEverySizeDibBelow256AndPngAt256() + { + var ico = BrandMark.RenderIcon(); + var entries = IcoWriter.ReadDirectory(ico); + CollectionAssert.AreEqual(new[] { 16, 24, 32, 48, 64, 128, 256 }, entries.Select(e => e.Size).ToArray()); + Assert.IsTrue(entries.All(e => e.BitsPerPixel == 32)); + Assert.IsTrue(entries.Where(e => e.Size < 256).All(e => !e.IsPng), "DIB below 256"); + Assert.IsTrue(entries.Single(e => e.Size == 256).IsPng, "PNG at 256"); + + // Entries follow the directory and do not overlap. + var end = 6 + (16 * entries.Count); + foreach (var entry in entries.OrderBy(e => e.Offset)) + { + Assert.AreEqual(end, entry.Offset); + end += entry.Length; + } + + Assert.AreEqual(ico.Length, end); + + // A DIB has the doubled height of the XOR + AND images and the right length. + foreach (var entry in entries.Where(e => !e.IsPng)) + { + var header = ico.AsSpan(entry.Offset, 40); + Assert.AreEqual(40u, BinaryPrimitives.ReadUInt32LittleEndian(header)); + Assert.AreEqual(entry.Size, BinaryPrimitives.ReadInt32LittleEndian(header[4..])); + Assert.AreEqual(entry.Size * 2, BinaryPrimitives.ReadInt32LittleEndian(header[8..])); + var maskStride = ((entry.Size + 31) / 32) * 4; + Assert.AreEqual(40 + (entry.Size * entry.Size * 4) + (maskStride * entry.Size), entry.Length); + } + } + + [TestMethod] + public void EveryImageShowsTheMarkTransparentCornersAccentSquareWhiteMoon() + { + var ico = BrandMark.RenderIcon(); + foreach (var entry in IcoWriter.ReadDirectory(ico)) + { + using var image = IcoWriter.Decode(ico, entry); + var s = entry.Size; + Assert.AreEqual(0, image.GetPixel(0, 0).Alpha, $"{s}: transparent corner"); + Assert.AreEqual(0, image.GetPixel(s - 1, s - 1).Alpha, $"{s}: transparent corner"); + + // Inside the square, away from ring and moon (x=4/32, y=28/32): the accent colour #0F5C8C. + var accent = image.GetPixel(Scale(4, s), Scale(28, s)); + if (s >= 24) + { + AssertClose(new SKColor(0x0F, 0x5C, 0x8C, 0xFF), accent, 6, $"{s}: accent"); + } + + // The centre of the moon (23.2, 8.8) is white. + var moon = image.GetPixel(Scale(23.2, s), Scale(8.8, s)); + if (s >= 32) + { + AssertClose(SKColors.White, moon, 10, $"{s}: moon"); + } + + // The centre of the ring (14.5, 17.5) is the accent, not white: it is a ring, not a disc. + var hole = image.GetPixel(Scale(14.5, s), Scale(17.5, s)); + if (s >= 32) + { + AssertClose(new SKColor(0x0F, 0x5C, 0x8C, 0xFF), hole, 6, $"{s}: ring hole"); + } + } + } + + [TestMethod] + public void TheWriterRefusesImagesThatAreNotSquareOrTooLarge() + { + using var wide = new SKBitmap(32, 16); + using var huge = new SKBitmap(512, 512); + Assert.ThrowsExactly(() => IcoWriter.Write([wide])); + Assert.ThrowsExactly(() => IcoWriter.Write([huge])); + Assert.ThrowsExactly(() => IcoWriter.Write([])); + Assert.ThrowsExactly(() => IcoWriter.ReadDirectory([1, 2, 3, 4, 5, 6])); + } + + [TestMethod] + public void TheCommittedIconIsWhatTheCodeDraws() + { + var path = Repository.PathOf("src", "Febe.Desktop", "Febe.ico"); + var fresh = BrandMark.RenderIcon(); + if (Environment.GetEnvironmentVariable("FEBE_RIGENERA_ICONA") == "1") + { + File.WriteAllBytes(path, fresh); + } + + Assert.IsTrue(File.Exists(path), "src/Febe.Desktop/Febe.ico manca: FEBE_RIGENERA_ICONA=1 lo genera."); + var committed = File.ReadAllBytes(path); + var a = IcoWriter.ReadDirectory(committed); + var b = IcoWriter.ReadDirectory(fresh); + CollectionAssert.AreEqual(b.Select(e => e.Size).ToArray(), a.Select(e => e.Size).ToArray()); + + // Pixel by pixel, with a small tolerance (antialiasing may differ by a unit between SkiaSharp builds). + for (var i = 0; i < a.Count; i++) + { + using var left = IcoWriter.Decode(committed, a[i]); + using var right = IcoWriter.Decode(fresh, b[i]); + for (var y = 0; y < left.Height; y++) + { + for (var x = 0; x < left.Width; x++) + { + AssertClose(right.GetPixel(x, y), left.GetPixel(x, y), 3, $"{a[i].Size} px ({x},{y})"); + } + } + } + } + + private static int Scale(double coordinate, int size) => Math.Clamp((int)Math.Floor(coordinate * size / 32), 0, size - 1); + + private static void AssertClose(SKColor expected, SKColor actual, int tolerance, string what) + { + var ok = Math.Abs(expected.Red - actual.Red) <= tolerance + && Math.Abs(expected.Green - actual.Green) <= tolerance + && Math.Abs(expected.Blue - actual.Blue) <= tolerance + && Math.Abs(expected.Alpha - actual.Alpha) <= tolerance; + Assert.IsTrue(ok, $"{what}: atteso {expected}, trovato {actual}"); + } +} diff --git a/tests/Febe.Tests/Desktop/InstallerTests.cs b/tests/Febe.Tests/Desktop/InstallerTests.cs new file mode 100644 index 0000000..899e519 --- /dev/null +++ b/tests/Febe.Tests/Desktop/InstallerTests.cs @@ -0,0 +1,146 @@ +using System.Diagnostics; +using System.Text.RegularExpressions; +using Febe.Tests.Desktop.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Desktop; + +/// +/// The installer of Windows (spec §12, question 6 of §16): installer/febe.nsi compiles with makensis (a dry +/// compile with a stand-in Febe.exe; skipped where NSIS is not installed), installs per user without administrator +/// rights, registers its uninstaller in HKCU, and its uninstaller never deletes the Data folder or the library. +/// +[TestClass] +public sealed partial class InstallerTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheScriptCompilesWithMakensisWithoutWarnings() + { + var makensis = FindOnPath("makensis"); + if (makensis is null) + { + Assert.Inconclusive("makensis non è installato (apt-get install nsis): la prova del programma di installazione si salta."); + } + + var script = Repository.PathOf("installer", "febe.nsi"); + using var temp = new TempFolder("nsis"); + await File.WriteAllTextAsync(temp.Combine("Febe.exe"), "MZ finto per la prova", TestContext.CancellationToken); + var output = temp.Combine("Febe-Setup-0.0.1.exe"); + var start = new ProcessStartInfo(makensis) + { + WorkingDirectory = Path.GetDirectoryName(script)!, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var argument in new[] { "-V2", "-WX", "-INPUTCHARSET", "UTF8", "-DVERSION=0.0.1", "-DVERSIONE_FILE=0.0.1.0", $"-DSORGENTE={temp.Path}", $"-DUSCITA={output}", "febe.nsi" }) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start)!; + var stdout = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); + var stderr = process.StandardError.ReadToEndAsync(TestContext.CancellationToken); + await process.WaitForExitAsync(TestContext.CancellationToken); + Assert.AreEqual(0, process.ExitCode, $"makensis (avvisi = errori):\n{await stdout}\n{await stderr}"); + Assert.IsTrue(File.Exists(output)); + Assert.IsGreaterThan(100_000L, new FileInfo(output).Length); + + // Without the version the script refuses to compile: it always comes from the build. + using var noVersion = Process.Start(new ProcessStartInfo(makensis, ["-V1", $"-DSORGENTE={temp.Path}", $"-DUSCITA={temp.Combine("x.exe")}", "febe.nsi"]) + { + WorkingDirectory = Path.GetDirectoryName(script)!, + RedirectStandardOutput = true, + RedirectStandardError = true, + })!; + await noVersion.WaitForExitAsync(TestContext.CancellationToken); + Assert.AreNotEqual(0, noVersion.ExitCode); + } + + [TestMethod] + public void TheScriptInstallsPerUserAndItsUninstallerNeverTouchesTheData() + { + var text = File.ReadAllText(Repository.PathOf("installer", "febe.nsi")); + StringAssert.Contains(text, "Unicode true"); + StringAssert.Contains(text, "RequestExecutionLevel user"); + StringAssert.Contains(text, "InstallDir \"$LOCALAPPDATA\\Programs\\Febe\""); + StringAssert.Contains(text, "MUI_LANGUAGE \"Italian\""); + StringAssert.Contains(text, "$SMPROGRAMS\\Febe.lnk"); + StringAssert.Contains(text, "Section \"Collegamento sul desktop\""); + foreach (var value in new[] { "DisplayName", "DisplayVersion", "Publisher", "DisplayIcon", "UninstallString" }) + { + StringAssert.Contains(text, $"WriteRegStr HKCU \"${{CHIAVE_DISINSTALLA}}\" \"{value}\""); + } + + StringAssert.Contains(text, "\"DisplayVersion\" \"${VERSION}\""); + StringAssert.Contains(text, "\"Publisher\" \"${EDITORE}\""); + StringAssert.Contains(text, "!define EDITORE \"Alberto Balbo\""); + StringAssert.Contains(text, "EdgeUpdate\\Clients\\${WEBVIEW2_GUID}"); + StringAssert.Contains(text, "https://developer.microsoft.com/microsoft-edge/webview2/"); + Assert.DoesNotContain("HKLM\" \"${CHIAVE", text, "nothing written for every user"); + Assert.IsFalse(Regex.IsMatch(text, @"Write\w*\s+HKLM"), "no machine-wide registry"); + + // The uninstall section deletes only the program, its shortcuts and its registry entries. + var uninstall = text[text.IndexOf("Section \"Uninstall\"", StringComparison.Ordinal)..]; + uninstall = uninstall[..uninstall.IndexOf("SectionEnd", StringComparison.Ordinal)]; + foreach (Match removal in Removals().Matches(uninstall)) + { + var target = removal.Groups["target"].Value; + Assert.IsTrue( + target.StartsWith("$INSTDIR\\", StringComparison.Ordinal) || target == "$INSTDIR" + || target is "$SMPROGRAMS\\Febe.lnk" or "$DESKTOP\\Febe.lnk" or "$TEMP\\.net\\Febe", + $"the uninstaller removes «{target}»: only the program may go"); + } + + Assert.DoesNotContain("$LOCALAPPDATA\\Febe", uninstall.Replace("StrCpy $R8 \"$LOCALAPPDATA\\Febe\"", string.Empty, StringComparison.Ordinal), "never the Data folder"); + Assert.DoesNotContain("$PICTURES", uninstall, "never the library"); + Assert.DoesNotContain("MB_YESNO", uninstall, "it asks nothing about the data"); + StringAssert.Contains(uninstall, "DeleteRegValue HKCU \"${CHIAVE_AVVIO}\" \"Febe\"", "the start with the computer goes with the program"); + } + + [TestMethod] + public void TheBuildScriptIsValidBashAndProducesTheTwoFilesUnder100Mb() + { + var script = Repository.PathOf("installer", "costruisci.sh"); + var text = File.ReadAllText(script); + StringAssert.Contains(text, "set -euo pipefail"); + StringAssert.Contains(text, "-p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true"); + StringAssert.Contains(text, "Febe-Setup-$versione.exe"); + StringAssert.Contains(text, "Febe-$versione-portabile.zip"); + StringAssert.Contains(text, "100 * 1024 * 1024"); + Assert.DoesNotContain("\r\n", text, "Unix line ends: bash would choke on CR"); + + var bash = FindOnPath("bash"); + if (bash is null) + { + return; + } + + using var process = Process.Start(new ProcessStartInfo(bash, ["-n", script]) { RedirectStandardError = true })!; + var errors = process.StandardError.ReadToEnd(); + process.WaitForExit(); + Assert.AreEqual(0, process.ExitCode, errors); + } + + private static string? FindOnPath(string name) + { + foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + foreach (var candidate in new[] { name, name + ".exe" }) + { + var path = Path.Combine(folder, candidate); + if (File.Exists(path)) + { + return path; + } + } + } + + return null; + } + + [GeneratedRegex(@"^\s*(?:Delete|RMDir)(?:\s+/\w+)*\s+""(?[^""]+)""", RegexOptions.Multiline)] + private static partial Regex Removals(); +} diff --git a/tests/Febe.Tests/Desktop/SharedCompositionTests.cs b/tests/Febe.Tests/Desktop/SharedCompositionTests.cs new file mode 100644 index 0000000..bf95dd2 --- /dev/null +++ b/tests/Febe.Tests/Desktop/SharedCompositionTests.cs @@ -0,0 +1,86 @@ +using Febe.App; +using Febe.Core.Alerts; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Desktop; + +/// +/// Pieces of the shared composition () that both shells use: the alerts hook (spec §13.3) and the +/// library folder that changes while Febe runs (desktop, spec §4.7). The Docker composition on top of it is proved by +/// the Server tests (end-to-end with a real Chromium), unchanged. +/// +[TestClass] +public sealed class SharedCompositionTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public void TheEventsOfSpec13_3BecomeAlertsAndNothingElse() + { + var at = new DateTimeOffset(2026, 10, 13, 9, 0, 0, TimeSpan.Zero); + EventRecord Event(string code, string message = "testo") => new() { At = at, Severity = EventSeverity.Info, Code = code, Message = message }; + + var expected = new Dictionary + { + [EngineEventCodes.ChallengeStop] = AlertKind.Verification, + [EngineEventCodes.DisconnectStop] = AlertKind.Disconnection, + [EngineEventCodes.ThrottleStop] = AlertKind.Throttle, + [EngineEventCodes.ThrottleEnd] = AlertKind.Throttle, + [EngineEventCodes.Resumed] = AlertKind.Throttle, + [EngineEventCodes.BackfillCompleted] = AlertKind.BackfillDone, + [EngineEventCodes.FormatUnrecognized] = AlertKind.UnknownFormat, + [AlertRules.DiskLowCode] = AlertKind.DiskLow, + }; + foreach (var (code, kind) in expected) + { + var alert = AlertRules.FromEvent(Event(code)); + Assert.IsNotNull(alert, code); + Assert.AreEqual(kind, alert.Kind, code); + Assert.AreEqual(at, alert.At); + Assert.IsFalse(string.IsNullOrWhiteSpace(alert.Title)); + } + + foreach (var code in new[] { EngineEventCodes.SessionEnded, EngineEventCodes.BudgetReached, EngineEventCodes.Paused, "ricetta.ProfileCheck", "collegamento.primo" }) + { + Assert.IsNull(AlertRules.FromEvent(Event(code)), code); + } + + // A long line (the key structure of an unknown format) is cut for a notification. + var long_ = AlertRules.FromEvent(Event(EngineEventCodes.FormatUnrecognized, new string('k', 1000)))!; + Assert.IsLessThanOrEqualTo(240, long_.Message.Length); + + var none = new AlertEvents(false, false, false, false, false, false); + Assert.IsFalse(Enum.GetValues().Any(k => AlertRules.Wanted(k, none))); + Assert.IsTrue(Enum.GetValues().All(k => AlertRules.Wanted(k, AlertEvents.All))); + Assert.IsFalse(AlertRules.Wanted(AlertKind.Throttle, AlertEvents.All with { Throttle = false })); + } + + [TestMethod] + public async Task AChangedLibraryFolderTakesTheNextFilesWithoutMovingAnything() + { + using var temp = new TempFolder("cartella-libreria"); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var before = await library.SaveAsync(account, Make.Entry(account.Id, "1", Make.T0), [TestFile.Photo(1, 31)]); + var oldFile = library.Layout.FullPath(account, before.Media[0].RelativePath!); + Assert.IsTrue(File.Exists(oldFile)); + + // Impostazioni ▸ Generali ▸ «Cambia…» (desktop): the account with files keeps its folder, as the API does. + var newRoot = temp.Combine("nuova libreria"); + await library.Db.Accounts.UpdateAsync(account with { Folder = library.Layout.AccountFolder(account) }, TestContext.CancellationToken); + var other = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200")); + library.Ingest.UseLayout(new LibraryLayout(newRoot)); + Assert.AreEqual(newRoot, library.Ingest.Layout.Root); + + var fixedAccount = (await library.Db.Accounts.GetAsync(account.Id, TestContext.CancellationToken))!; + var again = await library.SaveAsync(fixedAccount, Make.Entry(account.Id, "2", Make.T0.AddDays(1)), [TestFile.Photo(1, 32)]); + var fresh = await library.SaveAsync(other, Make.Entry(other.Id, "3", Make.T0.AddDays(2)), [TestFile.Photo(1, 33)]); + + Assert.IsTrue(File.Exists(oldFile), "nothing moves (rule 12)"); + StringAssert.StartsWith(new LibraryLayout(newRoot).FullPath(fixedAccount, again.Media[0].RelativePath!), library.Layout.AccountFolder(account), "an account with files stays where it is"); + Assert.IsTrue(File.Exists(Path.Combine(newRoot, "luca.demo", fresh.Media[0].RelativePath!.Replace('/', Path.DirectorySeparatorChar))), "a new account goes to the new folder"); + } +} diff --git a/tests/Febe.Tests/Desktop/Support/DesktopTestBed.cs b/tests/Febe.Tests/Desktop/Support/DesktopTestBed.cs new file mode 100644 index 0000000..36ae8d9 --- /dev/null +++ b/tests/Febe.Tests/Desktop/Support/DesktopTestBed.cs @@ -0,0 +1,123 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Febe.App; +using Febe.Desktop.Core; +using Febe.Tests.Support; + +namespace Febe.Tests.Desktop.Support; + +/// +/// The Windows composition on Linux: the shared with the real +/// (token of this start, 127.0.0.1 on a port chosen at start-up, start-up checks, hosting of S2, native services) and +/// a fake of the Windows-only part (). Data and library in a temporary folder; the +/// interface is asked like the main window asks it, with the token and the Origin of the interface. +/// +internal sealed class DesktopTestBed : IAsyncDisposable +{ + private readonly bool _ownsTemp; + + private DesktopTestBed(TempFolder temp, bool ownsTemp, FakeDesktopShell shell, MemoryLocationStore locations, DesktopPlatform platform, FebeApp app) + { + Temp = temp; + _ownsTemp = ownsTemp; + Shell = shell; + Locations = locations; + Platform = platform; + App = app; + Client = new HttpClient(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false }) { BaseAddress = app.Address, Timeout = TimeSpan.FromSeconds(30) }; + } + + public TempFolder Temp { get; } + + public FakeDesktopShell Shell { get; } + + public MemoryLocationStore Locations { get; } + + public DesktopPlatform Platform { get; } + + public FebeApp App { get; } + + public HttpClient Client { get; } + + public DesktopFolders Folders => new(Temp.Combine("AppData", "Local"), Temp.Combine("Immagini")); + + /// The fake window «Browser di Febe» (null with a configuration problem or with Edge). + public FakeBrowser? Browser => App.Browser as FakeBrowser; + + public string Origin => $"{App.Address.Scheme}://{App.Address.Authority}"; + + public static async Task StartAsync(string[]? args = null, FakeDesktopShell? shell = null, TempFolder? temp = null, MemoryLocationStore? locations = null) + { + var ownsTemp = temp is null; + temp ??= new TempFolder("desktop"); + shell ??= new FakeDesktopShell(); + locations ??= new MemoryLocationStore(); + if (!DesktopCommandLine.TryParse(args ?? [], out var options, out var problem)) + { + throw new ArgumentException(problem); + } + + var folders = new DesktopFolders(temp.Combine("AppData", "Local"), temp.Combine("Immagini")); + var platform = new DesktopPlatform(options, shell, locations, dataFolderFixed: options.DataFolder is not null); + var app = await FebeApp.StartAsync(options.AppOptions(options.DataFolder ?? folders.DefaultDataFolder, folders), platform, new FebeAppHooks { ShutdownTimeout = TimeSpan.FromSeconds(1) }); + return new DesktopTestBed(temp, ownsTemp, shell, locations, platform, app); + } + + /// A request as the main window sends it: the token (here as the header the cookie stands for) and the Origin. + public async Task SendAsync(HttpMethod method, string path, string? json = null, bool token = true) + { + using var request = new HttpRequestMessage(method, path); + if (token) + { + request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, Platform.AccessToken); + } + + 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 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(); + } + + public static async Task WaitUntilAsync(Func condition, TimeSpan timeout, string what) + { + var deadline = DateTime.UtcNow + timeout; + while (!condition()) + { + if (DateTime.UtcNow > deadline) + { + Assert.Fail($"Tempo scaduto: {what}."); + } + + await Task.Delay(50); + } + } + + /// Stops the composition; the folders stay for a second start (dispose at the end). + public async ValueTask StopAsync() + { + Client.Dispose(); + await App.DisposeAsync(); + } + + /// Stops; deletes the temporary folder only when the bed created it (a shared one is the caller's). + public async ValueTask DisposeAsync() + { + await StopAsync(); + if (_ownsTemp) + { + Temp.Dispose(); + } + } +} diff --git a/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs new file mode 100644 index 0000000..623a99c --- /dev/null +++ b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs @@ -0,0 +1,261 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using System.Text.Json.Nodes; +using Febe.App; +using Febe.Browser.Cdp; +using Febe.Browser.Hosting; +using Febe.Core.Abstractions; +using Febe.Core.Alerts; +using Febe.Desktop.Core; +using Febe.Web.Native; + +namespace Febe.Tests.Desktop.Support; + +/// The Windows-only part of the desktop, faked: what the platform asks of it is recorded. +internal sealed class FakeDesktopShell : IDesktopShell +{ + public FakeNativeShell NativeShell { get; } = new(); + + public RecordingAlertChannel Alerts { get; } = new(); + + public INativeShell Native => NativeShell; + + public IAlertChannel? Notifications => Alerts; + + /// The WebView2 runtime this «Windows» has (null: missing). + public string? RuntimeVersion { get; set; } = "141.0.3537.71"; + + /// Where «Edge» is (null: not installed). + public string? EdgePath { get; set; } + + /// The browsers created, with the settings the platform gave them. + public ConcurrentQueue<(WebView2BrowserSettings Settings, FakeBrowser Browser)> Created { get; } = new(); + + public ConcurrentQueue ProcessWindows { get; } = new(); + + public string? WebView2Version() => RuntimeVersion; + + public IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context) + { + var browser = new FakeBrowser(settings.ProfileDirectory, settings.Width, settings.Height, context); + Created.Enqueue((settings, browser)); + return browser; + } + + public string? FindEdge() => EdgePath; + + public Task ShowProcessWindowAsync(int processId, CancellationToken ct) + { + ProcessWindows.Enqueue("mostra " + processId); + return Task.CompletedTask; + } + + public Task HideProcessWindowAsync(int processId, CancellationToken ct) + { + ProcessWindows.Enqueue("nascondi " + processId); + return Task.CompletedTask; + } +} + +/// Folder picker, explorer, default browser, notifications and autostart, faked. +internal sealed class FakeNativeShell : INativeShell +{ + public bool CanPickFolder => true; + + public bool CanShowInFolder => true; + + public bool CanOpenUrl => true; + + public bool CanNotify => true; + + public bool SupportsAutostart => true; + + public bool Autostart { get; private set; } + + public string? FolderToPick { get; set; } + + public ConcurrentQueue Shown { get; } = new(); + + public ConcurrentQueue Opened { get; } = new(); + + public ConcurrentQueue<(string Title, string Message)> Notified { get; } = new(); + + public Task PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult(FolderToPick); + + public Task ShowInFolderAsync(string fullPath, CancellationToken ct) + { + Shown.Enqueue(fullPath); + return Task.FromResult(true); + } + + public Task OpenUrlAsync(Uri address, CancellationToken ct) + { + Opened.Enqueue(address); + return Task.FromResult(true); + } + + public Task NotifyAsync(string title, string message, CancellationToken ct) + { + Notified.Enqueue((title, message)); + return Task.CompletedTask; + } + + public Task GetAutostartAsync(CancellationToken ct) => Task.FromResult(Autostart); + + public Task SetAutostartAsync(bool enabled, CancellationToken ct) + { + Autostart = enabled; + return Task.CompletedTask; + } +} + +/// The Windows notifications, recorded. +internal sealed class RecordingAlertChannel : IAlertChannel +{ + public ConcurrentQueue Received { get; } = new(); + + public bool IsEnabled(AlertSettings settings) => settings.WindowsNotifications; + + public Task SendAsync(FebeAlert alert, AlertSettings settings, CancellationToken ct) + { + Received.Enqueue(alert); + return Task.CompletedTask; + } +} + +/// +/// The window «Browser di Febe», faked: a CDP session that answers like a browser on a blank page, a session cookie +/// that exists once «Alberto» has logged in, and a record of every time the window came to the front or went away. +/// +internal sealed class FakeBrowser : IFebeBrowser +{ + private readonly FebePlatformContext _context; + private IDisposable? _lease; + + public FakeBrowser(string profileDirectory, int width, int height, FebePlatformContext context) + { + ProfileDirectory = profileDirectory; + WindowWidth = width; + WindowHeight = height; + _context = context; + } + + public FakeCdp FakeCdp { get; } = new(); + + public ICdpSession Cdp => FakeCdp; + + public UserDrivingGate UserDriving { get; } = new(); + + public bool UserIsDriving => UserDriving.IsDriving; + + public bool IsAvailable { get; private set; } + + public string? LastError => null; + + public string ProfileDirectory { get; } + + public int WindowWidth { get; } + + public int WindowHeight { get; } + + public int Shown { get; private set; } + + public int Hidden { get; private set; } + + public int EmptiedProfiles { get; private set; } + + public bool Disposed { get; private set; } + + public Task RunAsync(CancellationToken ct) + { + Directory.CreateDirectory(ProfileDirectory); + IsAvailable = true; + return Task.CompletedTask; + } + + public Task RestAsync(CancellationToken ct) => FakeCdp.NavigateAsync(CdpPageExtensions.RestUrl, ct); + + /// Like the real window: in front, Alberto is driving. + public Task ShowToUserAsync(CancellationToken ct) + { + Shown++; + _lease ??= UserDriving.Begin(); + _context.Tracker.MarkUsed(_context.Clock.Now); + return Task.CompletedTask; + } + + public Task HideFromUserAsync(CancellationToken ct) + { + Hidden++; + _lease?.Dispose(); + _lease = null; + return Task.CompletedTask; + } + + /// The next «Scollega» finds a file held by another process (Windows) and cannot delete the profile. + public bool ProfileLocked { get; set; } + + public Task RestartWithEmptyProfileAsync(CancellationToken ct) + { + if (ProfileLocked) + { + throw new IOException("Il file Cookies è in uso da un altro processo."); + } + + if (Directory.Exists(ProfileDirectory)) + { + Directory.Delete(ProfileDirectory, recursive: true); + } + + Directory.CreateDirectory(ProfileDirectory); + FakeCdp.LoggedIn = false; + EmptiedProfiles++; + return Task.CompletedTask; + } + + public ValueTask DisposeAsync() + { + Disposed = true; + IsAvailable = false; + return ValueTask.CompletedTask; + } +} + +/// A CDP session answering like a page: frame tree, navigation, the session cookie (name only). +internal sealed class FakeCdp : ICdpSession +{ + public bool LoggedIn { get; set; } + + public string Url { get; private set; } = "about:blank"; + + public ConcurrentQueue Methods { get; } = new(); + + public Task SendAsync(string method, object? parameters = null, CancellationToken ct = default) + { + CdpCommandPolicy.EnsureAllowed(method); + Methods.Enqueue(method); + JsonNode result = method switch + { + "Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = Url } } }, + "Page.navigate" => Navigate(parameters), + "Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }) : new JsonArray() }, + _ => new JsonObject(), + }; + return Task.FromResult(JsonDocument.Parse(result.ToJsonString()).RootElement.Clone()); + } + + public IDisposable On(string eventName, Action handler) => new Nothing(); + + private JsonObject Navigate(object? parameters) + { + Url = (parameters as JsonObject)?["url"]?.GetValue() ?? Url; + return new JsonObject { ["frameId"] = "F1" }; + } + + private sealed class Nothing : IDisposable + { + public void Dispose() + { + } + } +} diff --git a/tests/Febe.Tests/Desktop/Support/FakeDevTools.cs b/tests/Febe.Tests/Desktop/Support/FakeDevTools.cs new file mode 100644 index 0000000..0a3b8aa --- /dev/null +++ b/tests/Febe.Tests/Desktop/Support/FakeDevTools.cs @@ -0,0 +1,89 @@ +using System.Collections.Concurrent; +using Febe.Browser.Diagnostics; +using Febe.Browser.WebView2; + +namespace Febe.Tests.Desktop.Support; + +/// +/// A stand-in for the two WebView2 calls (CallDevToolsProtocolMethodAsync, GetDevToolsProtocolEventReceiver): +/// records what reaches «WebView2», answers with , and raises events like WebView2 does, on the +/// thread of the caller (WebView2's UI thread in the real application). +/// +internal sealed class FakeDevTools : IWebView2DevTools +{ + private readonly ConcurrentDictionary>> _receivers = new(StringComparer.Ordinal); + + /// Every call that reached «WebView2»: method and parameters as JSON. + public ConcurrentQueue<(string Method, string Json)> Calls { get; } = new(); + + /// The answer to a call (default: an empty result object). + public Func> Answer { get; set; } = (_, _) => Task.FromResult("{}"); + + /// How many event handlers are attached to «WebView2» right now, by event name. + public int Subscribed(string eventName) => _receivers.TryGetValue(eventName, out var list) ? list.Count : 0; + + /// Total subscriptions ever made (to see re-subscriptions after a new WebView). + public int SubscriptionsMade { get; private set; } + + public Task CallMethodAsync(string methodName, string parametersAsJson) + { + Calls.Enqueue((methodName, parametersAsJson)); + return Answer(methodName, parametersAsJson); + } + + public IDisposable Subscribe(string eventName, Action onEvent) + { + var list = _receivers.GetOrAdd(eventName, _ => []); + lock (list) + { + list.Add(onEvent); + } + + SubscriptionsMade++; + return new Removal(() => + { + lock (list) + { + list.Remove(onEvent); + } + }); + } + + /// «WebView2» receives a protocol event: ParameterObjectAsJson goes to the handlers. + public void Raise(string eventName, string parametersJson) + { + if (!_receivers.TryGetValue(eventName, out var list)) + { + return; + } + + Action[] handlers; + lock (list) + { + handlers = [.. list]; + } + + foreach (var handler in handlers) + { + handler(parametersJson); + } + } + + private sealed class Removal(Action remove) : IDisposable + { + private Action? _remove = remove; + + public void Dispose() => Interlocked.Exchange(ref _remove, null)?.Invoke(); + } +} + +/// Collects what the browser layer logs (to prove that only names get there). +internal sealed class RecordingBrowserLog : IBrowserLog +{ + public ConcurrentQueue Lines { get; } = new(); + + public void Write(BrowserLogLevel level, string message, Exception? exception = null) => + Lines.Enqueue($"{level} {message} {exception?.GetType().Name} {exception?.Message}"); + + public string All => string.Join('\n', Lines); +} diff --git a/tests/Febe.Tests/Desktop/Support/MemoryLocationStore.cs b/tests/Febe.Tests/Desktop/Support/MemoryLocationStore.cs new file mode 100644 index 0000000..81f1356 --- /dev/null +++ b/tests/Febe.Tests/Desktop/Support/MemoryLocationStore.cs @@ -0,0 +1,15 @@ +using Febe.Desktop.Core; + +namespace Febe.Tests.Desktop.Support; + +/// The registry values «CartellaDati» and «NuovaCartellaDati», in memory. +internal sealed class MemoryLocationStore : IDataFolderLocationStore +{ + public string? Current { get; set; } + + public string? Pending { get; set; } + + public void SetCurrent(string? folder) => Current = folder; + + public void SetPending(string? folder) => Pending = folder; +} diff --git a/tests/Febe.Tests/Desktop/Support/Repository.cs b/tests/Febe.Tests/Desktop/Support/Repository.cs new file mode 100644 index 0000000..069f95c --- /dev/null +++ b/tests/Febe.Tests/Desktop/Support/Repository.cs @@ -0,0 +1,31 @@ +namespace Febe.Tests.Desktop.Support; + +/// Files of the repository the desktop tests look at (the committed icon, the NSIS script). +internal static class Repository +{ + /// The folder with Febe.slnx, found from the test binaries upward; null outside a checkout. + public static string? Root() + { + for (var folder = new DirectoryInfo(AppContext.BaseDirectory); folder is not null; folder = folder.Parent) + { + if (File.Exists(Path.Combine(folder.FullName, "Febe.slnx"))) + { + return folder.FullName; + } + } + + return null; + } + + /// A file of the repository; the test is inconclusive when the checkout is not there. + public static string PathOf(params string[] parts) + { + var root = Root(); + if (root is null) + { + Assert.Inconclusive("Il repository non è accanto alle prove."); + } + + return Path.Combine([root, .. parts]); + } +} diff --git a/tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs b/tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs new file mode 100644 index 0000000..f8635f1 --- /dev/null +++ b/tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs @@ -0,0 +1,329 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using System.Text.Json.Nodes; +using Febe.Browser.Cdp; +using Febe.Browser.WebView2; +using Febe.Tests.Desktop.Support; + +namespace Febe.Tests.Desktop; + +/// +/// The CDP adapter of WebView2 (spec §6.1, Windows) with a fake of the two WebView2 calls: the same allowlist and +/// refusals as the Chromium client, JSON in and out, events routed in order to their handlers, names only in the log. +/// +[TestClass] +public sealed class WebView2CdpSessionTests +{ + private const string Secret = "segreto-che-non-deve-uscire"; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task AllowedCommandsReachWebView2AsJsonAndResultsComeBackAsElements() + { + var devTools = new FakeDevTools + { + Answer = (method, _) => Task.FromResult(method == "Page.getFrameTree" + ? """{"frameTree":{"frame":{"id":"F1","url":"about:blank"}}}""" + : "{}"), + }; + await using var session = new WebView2CdpSession(); + session.Attach(devTools); + + var tree = await session.SendAsync("Page.getFrameTree", ct: TestContext.CancellationToken); + Assert.AreEqual("F1", tree.GetProperty("frameTree").GetProperty("frame").GetProperty("id").GetString()); + Assert.AreEqual("about:blank", await session.GetMainFrameUrlAsync(TestContext.CancellationToken)); + + await session.SendAsync("Page.navigate", new JsonObject { ["url"] = "http://127.0.0.1:8481/" }, TestContext.CancellationToken); + await session.SendAsync("Input.dispatchMouseEvent", new { type = "mouseWheel", x = 10, y = 20, deltaX = 0, deltaY = 120 }, TestContext.CancellationToken); + await session.SendAsync("Page.enable", ct: TestContext.CancellationToken); + + var calls = devTools.Calls.ToArray(); + Assert.AreEqual("Page.navigate", calls[2].Method); + Assert.AreEqual("http://127.0.0.1:8481/", JsonNode.Parse(calls[2].Json)!["url"]!.GetValue()); + var mouse = JsonNode.Parse(calls[3].Json)!; + Assert.AreEqual("mouseWheel", mouse["type"]!.GetValue()); + Assert.AreEqual(120, mouse["deltaY"]!.GetValue()); + Assert.AreEqual("{}", calls[4].Json, "no parameters: an empty object, as WebView2 wants"); + } + + [TestMethod] + public async Task EveryCommandOutsideTheAllowlistIsRefusedBeforeWebView2() + { + var devTools = new FakeDevTools(); + await using var session = new WebView2CdpSession(); + session.Attach(devTools); + foreach (var method in new[] + { + "Network.setUserAgentOverride", "Network.setExtraHTTPHeaders", "Page.addScriptToEvaluateOnNewDocument", + "Emulation.setTimezoneOverride", "Emulation.setUserAgentOverride", "Fetch.enable", "Fetch.continueRequest", + "Target.createTarget", "Page.reload", "Runtime.callFunctionOn", "Network.setCookie", "Storage.getCookies", + "DOM.setAttributeValue", "Browser.close", + }) + { + var error = await Assert.ThrowsAsync(() => session.SendAsync(method, new { value = Secret }, TestContext.CancellationToken)); + Assert.AreEqual(method, error.Method); + Assert.DoesNotContain(Secret, error.Message); + } + + Assert.IsEmpty(devTools.Calls, "nothing refused ever reaches WebView2"); + + // Every command of the allowlist passes (Runtime.evaluate only read-only). + foreach (var method in CdpCommandPolicy.Allowed.Where(m => m != "Runtime.evaluate")) + { + await session.SendAsync(method, ct: TestContext.CancellationToken); + } + + Assert.HasCount(CdpCommandPolicy.Allowed.Count - 1, devTools.Calls); + } + + [TestMethod] + public async Task RuntimeEvaluateOnlyReadsThePage() + { + var devTools = new FakeDevTools { Answer = (_, _) => Task.FromResult("""{"result":{"type":"string","value":"complete"}}""") }; + await using var session = new WebView2CdpSession(); + session.Attach(devTools); + + var value = await session.EvaluateAsync("document.readyState", TestContext.CancellationToken); + Assert.AreEqual("complete", value.GetString()); + + foreach (var expression in new[] { "document.querySelector('a').click()", "window.scrollBy(0, 400)", "document.cookie", "fetch('/api')", "location = 'https://example.org'" }) + { + await Assert.ThrowsAsync(() => session.SendAsync("Runtime.evaluate", new JsonObject { ["expression"] = expression }, TestContext.CancellationToken)); + } + + Assert.HasCount(1, devTools.Calls, "only the read-only expression was sent"); + } + + [TestMethod] + public async Task EventsReachTheirHandlersInOrderOffTheCallersThreadAndStopWhenUnsubscribed() + { + var devTools = new FakeDevTools(); + await using var session = new WebView2CdpSession(); + session.Attach(devTools); + var received = new ConcurrentQueue<(string Handler, int N)>(); + var handlerThreads = new ConcurrentBag(); + using var first = session.On("Network.responseReceived", e => + { + handlerThreads.Add(Environment.CurrentManagedThreadId); + received.Enqueue(("a", e.GetProperty("n").GetInt32())); + }); + var second = session.On("Network.responseReceived", e => received.Enqueue(("b", e.GetProperty("n").GetInt32()))); + using var other = session.On("Page.frameNavigated", e => received.Enqueue(("nav", 0))); + Assert.AreEqual(1, devTools.Subscribed("Network.responseReceived"), "one WebView2 receiver per event name"); + + // WebView2 raises events on its UI thread: here a thread of its own, which no handler may run on. + var raisingThread = 0; + var ui = new Thread(() => + { + raisingThread = Environment.CurrentManagedThreadId; + for (var i = 1; i <= 50; i++) + { + devTools.Raise("Network.responseReceived", $$"""{"n":{{i}}}"""); + } + + devTools.Raise("Page.frameNavigated", """{"frame":{"id":"F1"}}"""); + devTools.Raise("Network.loadingFinished", """{"requestId":"1"}"""); // nobody listens + }); + ui.Start(); + ui.Join(); + await session.DrainAsync(); + + var a = received.Where(r => r.Handler == "a").Select(r => r.N).ToArray(); + CollectionAssert.AreEqual(Enumerable.Range(1, 50).ToArray(), a, "in order"); + Assert.AreEqual(50, received.Count(r => r.Handler == "b")); + Assert.AreEqual(1, received.Count(r => r.Handler == "nav")); + Assert.IsFalse(handlerThreads.Contains(raisingThread), "handlers never run on WebView2's (UI) thread"); + + second.Dispose(); + devTools.Raise("Network.responseReceived", """{"n":51}"""); + await session.DrainAsync(); + Assert.AreEqual(50, received.Count(r => r.Handler == "b"), "an unsubscribed handler gets nothing"); + Assert.AreEqual(51, received.Count(r => r.Handler == "a")); + + first.Dispose(); + Assert.AreEqual(0, devTools.Subscribed("Network.responseReceived"), "the last handler removes the WebView2 receiver"); + } + + [TestMethod] + public async Task AHandlerThatThrowsOrSendsACommandDoesNotStopTheOthers() + { + var devTools = new FakeDevTools { Answer = (_, _) => Task.FromResult("""{"body":"x","base64Encoded":false}""") }; + var log = new RecordingBrowserLog(); + await using var session = new WebView2CdpSession(log); + session.Attach(devTools); + var bodies = new ConcurrentQueue(); + using var bad = session.On("Network.loadingFinished", _ => throw new InvalidOperationException(Secret)); + + // The pattern of ResponseTap: the handler queues the command, it never blocks. + using var good = session.On("Network.loadingFinished", e => _ = Task.Run(async () => + { + var body = await session.SendAsync("Network.getResponseBody", new JsonObject { ["requestId"] = e.GetProperty("requestId").GetString() }); + bodies.Enqueue(body.GetProperty("body").GetString()!); + })); + devTools.Raise("Network.loadingFinished", """{"requestId":"7"}"""); + await session.DrainAsync(); + for (var i = 0; i < 50 && bodies.IsEmpty; i++) + { + await Task.Delay(20, TestContext.CancellationToken); + } + + Assert.AreEqual("x", bodies.Single()); + StringAssert.Contains(log.All, "Network.loadingFinished"); + } + + [TestMethod] + public async Task TheLogHasCommandAndEventNamesOnlyNeverParametersResultsOrErrorsText() + { + var log = new RecordingBrowserLog(); + var devTools = new FakeDevTools + { + Answer = (method, json) => method switch + { + "Network.getCookies" => Task.FromResult($$"""{"cookies":[{"name":"sessionid","value":"{{Secret}}"}]}"""), + + // WebView2 reports a protocol error as an exception whose message carries the error object (and here + // also the parameters, which must not get anywhere). + "Network.getResponseBody" => Task.FromException(new InvalidOperationException( + $$"""Errore 0x80004005 per {{json}}: {"code":-32000,"message":"No resource with given identifier found","data":"{{Secret}}"}""")), + _ => Task.FromResult("{}"), + }, + }; + await using var session = new WebView2CdpSession(log); + session.Attach(devTools); + + await session.SendAsync("Input.dispatchKeyEvent", new { type = "char", text = Secret }, TestContext.CancellationToken); + var cookies = await session.SendAsync("Network.getCookies", new { urls = new[] { "https://www.instagram.com/?x=" + Secret } }, TestContext.CancellationToken); + Assert.AreEqual("sessionid", cookies.GetProperty("cookies")[0].GetProperty("name").GetString()); + var error = await Assert.ThrowsAsync(() => session.SendAsync("Network.getResponseBody", new { requestId = Secret }, TestContext.CancellationToken)); + Assert.AreEqual(-32000, error.Code); + Assert.AreEqual("No resource with given identifier found", error.BrowserMessage); + Assert.DoesNotContain(Secret, error.Message, "only the code and the message of the protocol error"); + + using (session.On("Network.responseReceived", _ => throw new InvalidOperationException("gestore"))) + { + devTools.Raise("Network.responseReceived", $$$"""{"response":{"url":"https://cdn/{{{Secret}}}"}}"""); + await session.DrainAsync(); + } + + var all = log.All; + StringAssert.Contains(all, "Input.dispatchKeyEvent"); + StringAssert.Contains(all, "Network.getCookies"); + StringAssert.Contains(all, "Network.getResponseBody"); + StringAssert.Contains(all, "Network.responseReceived"); + Assert.DoesNotContain(Secret, all, "never parameters, results, events or error text in the log"); + Assert.DoesNotContain("instagram.com", all); + } + + [TestMethod] + public async Task AFailureWithoutAProtocolErrorKeepsOnlyItsCode() + { + var devTools = new FakeDevTools { Answer = (_, _) => Task.FromException(new InvalidOperationException("c:\\Users\\alberto " + Secret) { HResult = unchecked((int)0x8007139F) }) }; + await using var session = new WebView2CdpSession(); + session.Attach(devTools); + var error = await Assert.ThrowsAsync(() => session.SendAsync("Page.enable", ct: TestContext.CancellationToken)); + Assert.AreEqual(unchecked((int)0x8007139F), error.Code); + Assert.DoesNotContain(Secret, error.Message); + } + + [TestMethod] + public async Task WithoutAWebViewCommandsFailFastAndAClosingWebViewIsADisconnection() + { + await using var session = new WebView2CdpSession(); + await Assert.ThrowsAsync(() => session.SendAsync("Page.enable", ct: TestContext.CancellationToken)); + + // Policy first: a forbidden command is reported as such even without a WebView. + await Assert.ThrowsAsync(() => session.SendAsync("Emulation.setLocaleOverride", ct: TestContext.CancellationToken)); + + var devTools = new FakeDevTools { Answer = (_, _) => Task.FromException(new CdpDisconnectedException("chiuso")) }; + session.Attach(devTools); + await Assert.ThrowsAsync(() => session.SendAsync("Page.enable", ct: TestContext.CancellationToken)); + + session.Detach(); + Assert.IsFalse(session.IsAttached); + await Assert.ThrowsAsync(() => session.SendAsync("Page.enable", ct: TestContext.CancellationToken)); + } + + [TestMethod] + public async Task ACommandWithoutAnswerTimesOutAndCancellationIsHonoured() + { + var never = new TaskCompletionSource(); + var devTools = new FakeDevTools { Answer = (_, _) => never.Task }; + await using var session = new WebView2CdpSession(options: new WebView2CdpOptions(TimeSpan.FromMilliseconds(200))); + session.Attach(devTools); + var timeout = await Assert.ThrowsAsync(() => session.SendAsync("Page.enable", ct: TestContext.CancellationToken)); + StringAssert.Contains(timeout.Message, "Page.enable"); + + using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(50)); + await Assert.ThrowsAsync(() => session.SendAsync("Page.enable", ct: cancel.Token)); + } + + [TestMethod] + public async Task ANewWebViewKeepsTheSubscriptionsAndSaysItReconnected() + { + await using var session = new WebView2CdpSession(); + var reconnected = 0; + session.Reconnected += (_, _) => reconnected++; + var received = new ConcurrentQueue(); + using var subscription = session.On("Page.screencastFrame", e => received.Enqueue(e.GetProperty("data").GetString()!)); + + var first = new FakeDevTools(); + session.Attach(first); + Assert.AreEqual(0, reconnected, "the first WebView is not a reconnection"); + first.Raise("Page.screencastFrame", """{"data":"uno","sessionId":1}"""); + await session.DrainAsync(); + + // The browser process restarted («Scollega», crash): a new WebView, the same session object. + session.Detach(); + Assert.AreEqual(0, first.Subscribed("Page.screencastFrame"), "the old WebView's receivers are removed"); + var second = new FakeDevTools(); + session.Attach(second); + Assert.AreEqual(1, reconnected); + Assert.AreEqual(1, second.Subscribed("Page.screencastFrame"), "subscriptions survive"); + first.Raise("Page.screencastFrame", """{"data":"vecchio"}"""); + second.Raise("Page.screencastFrame", """{"data":"due","sessionId":2}"""); + await session.DrainAsync(); + CollectionAssert.AreEqual(new[] { "uno", "due" }, received.ToArray()); + } + + [TestMethod] + public void ProtocolErrorsAreReadFromTheMessageOfWebView2() + { + var error = WebView2CdpSession.ProtocolError("IO.read", new InvalidOperationException("""{"code":-32602,"message":"Invalid parameters","data":"handle: string value expected"}""")); + Assert.AreEqual(-32602, error.Code); + Assert.AreEqual("Invalid parameters", error.BrowserMessage); + Assert.AreEqual("IO.read", error.Method); + + var garbled = WebView2CdpSession.ProtocolError("IO.read", new InvalidOperationException("{ non è json }")); + Assert.AreEqual("errore di WebView2", garbled.BrowserMessage); + } + + [TestMethod] + public async Task UnreadableEventsAreSkippedAndLoggedByNameOnly() + { + var log = new RecordingBrowserLog(); + var devTools = new FakeDevTools(); + await using var session = new WebView2CdpSession(log); + session.Attach(devTools); + var good = 0; + using var subscription = session.On("Page.loadEventFired", _ => good++); + devTools.Raise("Page.loadEventFired", "{non json " + Secret); + devTools.Raise("Page.loadEventFired", """{"timestamp":1}"""); + await session.DrainAsync(); + Assert.AreEqual(1, good); + StringAssert.Contains(log.All, "Page.loadEventFired"); + Assert.DoesNotContain(Secret, log.All); + } + + [TestMethod] + public async Task ResultsAreSelfContainedElements() + { + var devTools = new FakeDevTools { Answer = (_, _) => Task.FromResult("""{"data":"AAEC","base64Encoded":true,"eof":true}""") }; + await using var session = new WebView2CdpSession(); + session.Attach(devTools); + var chunk = await session.SendAsync("IO.read", new { handle = "h" }, TestContext.CancellationToken); + GC.Collect(); + Assert.AreEqual(JsonValueKind.True, chunk.GetProperty("eof").ValueKind); + CollectionAssert.AreEqual(new byte[] { 0, 1, 2 }, Convert.FromBase64String(chunk.GetProperty("data").GetString()!)); + } +} diff --git a/tests/Febe.Tests/Febe.Tests.csproj b/tests/Febe.Tests/Febe.Tests.csproj index 2d87b85..cfa37cb 100644 --- a/tests/Febe.Tests/Febe.Tests.csproj +++ b/tests/Febe.Tests/Febe.Tests.csproj @@ -11,7 +11,9 @@ + + diff --git a/tests/Febe.Tests/Server/ServerEndToEndTests.cs b/tests/Febe.Tests/Server/ServerEndToEndTests.cs index 6193d70..98557d9 100644 --- a/tests/Febe.Tests/Server/ServerEndToEndTests.cs +++ b/tests/Febe.Tests/Server/ServerEndToEndTests.cs @@ -77,7 +77,7 @@ public sealed partial class ServerEndToEndTests 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.IsNotNull(await server.Database.Settings.GetInt64Async(Febe.App.BrowserConnectionService.FirstConnectionKey, ct), "first connection recorded"); Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State); // «Controlla ora». diff --git a/tests/Febe.Tests/Server/ServerOptionsTests.cs b/tests/Febe.Tests/Server/ServerOptionsTests.cs index 4216705..4ee4fbd 100644 --- a/tests/Febe.Tests/Server/ServerOptionsTests.cs +++ b/tests/Febe.Tests/Server/ServerOptionsTests.cs @@ -113,12 +113,12 @@ public sealed class ServerOptionsTests 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))); + var old = Path.Combine(folder, Febe.App.FebeLog.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)) + using (var log = new Febe.App.FebeLog(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")); @@ -126,14 +126,14 @@ public sealed class ServerOptionsTests log.Info("prova", "Il giorno dopo"); } - var first = File.ReadAllText(Path.Combine(folder, ServerLog.FileNameFor(new DateOnly(2026, 10, 13)))); + var first = File.ReadAllText(Path.Combine(folder, Febe.App.FebeLog.FileNameFor(new DateOnly(2026, 10, 13)))); Assert.DoesNotContain("SEGRETA", first); Assert.DoesNotContain("cdn.example", first); StringAssert.Contains(first, ""); StringAssert.Contains(first, "marta.prova"); StringAssert.Contains(first, "InvalidOperationException: riga uno "); Assert.DoesNotContain("riga due", first); - StringAssert.Contains(File.ReadAllText(Path.Combine(folder, ServerLog.FileNameFor(new DateOnly(2026, 10, 14)))), "Il giorno dopo"); + StringAssert.Contains(File.ReadAllText(Path.Combine(folder, Febe.App.FebeLog.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"); @@ -144,7 +144,7 @@ public sealed class ServerOptionsTests { 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)) + using (var log = new Febe.App.FebeLog(temp.Path, null, clock, maxBytesPerDay: 2000)) { for (var i = 0; i < 100; i++) { @@ -152,7 +152,7 @@ public sealed class ServerOptionsTests } } - var file = Path.Combine(temp.Path, ServerLog.FileNameFor(new DateOnly(2026, 10, 13))); + var file = Path.Combine(temp.Path, Febe.App.FebeLog.FileNameFor(new DateOnly(2026, 10, 13))); Assert.IsLessThan(2200L, new FileInfo(file).Length); StringAssert.Contains(File.ReadAllText(file), "troppo lungo"); }