Files
Febe/src/Febe.Web/wwwroot/js/pages/connection.js
T
Alby96andClaude Opus 5.5 2fc4b40c41
verifica / controlli (push) Successful in 24s
verifica / prove (push) Failing after 41m21s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped
Docker: lasciare la pagina del browser copia la sessione (#36, S4b, risposta 1)
In Docker lasciare la pagina «Browser» o la vista remota di Collegamento mentre
Alberto guida (un'altra pagina, la scheda chiusa, il collegamento perso) valeva
«Annulla» e la sessione non si copiava. Ora è come chiudere la finestra del
browser su Windows: `cancel` con `pageLeft` va a LeavePageAsync, la vista
remota chiusa dalla sua pagina lo dice alla connessione, e se per 5 secondi
non si apre un'altra vista né arriva un `begin` (una pagina ricaricata) il
controllo del permesso copia la sessione con CopyOnLetGoAsync, solo da una
pagina del sito che non sia di accesso o di verifica, poi rilascia il permesso
e il motore rimette il browser a riposo. Il pulsante «Annulla» continua a non
copiare; Windows non cambia.

Prove nuove per la copia lasciando la pagina, la ricarica che non è lasciare,
la pagina di accesso, la vista sostituita o chiusa da Febe; guida, protocollo
e una riga in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:52:51 +01:00

384 lines
17 KiB
JavaScript

// Collegamento a Instagram (mockup 10, spec §4.1, §10.3). Docker: the large remote view of the server's browser with
// the steps «Come collegarti», the note that the password goes only to Instagram (keys pass through the server without
// being recorded), the risk note, Annulla and «Ho finito». Windows: the browser is the separate window «Browser di
// Febe» and the large area says so, with «Portalo in primo piano». When connected: the account, «Usa il browser» and
// «Scollega» with its confirmation. While Alberto uses the browser the engine is still. With the raccolta «richieste»
// (issue #36, S4b) the page also shows the saved session in counts and names (never values), the choice for an
// incomplete copy, and «Serve «Ho finito»» when the browser is connected but the copy is missing.
import { api } from '../core/api.js';
import { caps } from '../core/context.js';
import { h, icon, fill } from '../core/dom.js';
import { engineState, refreshEngine } from '../core/engine.js';
import { navigate } from '../core/shell.js';
import { t } from '../core/text.js';
import { avatar, confirmDialog, label, radio, showError, toast } from '../core/ui.js';
import { remoteView } from './remote-view.js';
const STATE_KIND = { notConnected: 'ambra', connected: 'verde', copyMissing: 'ambra', verificationRequired: 'rosso', browserUnavailable: '' };
/** True while the engine waits for «Riprendi» (the stop strip of a verification or a disconnection). */
function waitsForResume(state) {
const banner = state && state.snapshot && state.snapshot.banner;
return Boolean(banner && banner.needsResume);
}
// The last «give the browser back» sent by a page that was left: the next «begin» waits for it, so that the server
// never sees the new page's begin before the old page's release.
let releasing = Promise.resolve();
/** Starts using the browser (the engine is still); with openLogin the real login page is loaded. */
export async function beginDriving(openLogin) {
await releasing;
try {
await api('/api/connection/begin', { method: 'POST', body: { openLogin } });
return true;
} catch (error) {
showError(error);
return false;
}
}
/**
* The browser as a page uses it (spec §4.1, §10.3: the engine is still only while Alberto uses the browser). begin()
* takes it; «Ho finito», «Annulla» and «Scollega» give it back on the server, and the page calls settled(). Leaving the
* page in any other way — another page, a reload, closing the tab — gives it back too: in Docker like closing the
* window on Windows, not like «Annulla» (answer of 25 November 2026: if no view opens again within a moment, the
* server copies the session and the engine may work again; a reload opens the view again); on Windows the window
* «Browser di Febe» stays as it is, on screen until Alberto closes it (issue #52), and only the page's hold ends.
*/
export function drivingLease(page) {
let held = false;
const release = (keepalive) => {
if (!held) return;
held = false;
releasing = api('/api/connection/cancel', { method: 'POST', body: { pageLeft: true }, keepalive }).then(() => {}, () => {});
};
const onHide = () => release(true);
window.addEventListener('pagehide', onHide);
page.onLeave(() => {
window.removeEventListener('pagehide', onHide);
release(false);
});
return {
/** Takes the browser (nothing when the page was already left). */
begin(openLogin) {
if (page.signal.aborted) return Promise.resolve(false);
held = true;
return beginDriving(openLogin);
},
/** The server already gave the browser back («Ho finito», «Annulla», «Scollega»). */
settled() {
held = false;
},
};
}
/** The area that replaces the remote view on Windows: the browser is its own window. */
export function windowPanel() {
return h('div.vista.vista-finestra',
h('div.vista-segnaposto',
icon('app-window', 'l'),
h('h2', t('impostazioni.collegamento.finestra')),
h('p', t('impostazioni.collegamento.finestraTesto')),
h('button.btn.primo', { type: 'button', onclick: () => beginDriving(false) }, icon('app-window', 's'), t('impostazioni.collegamento.primoPiano'))));
}
/** «Ho finito»: Febe checks the session and hides the browser. Returns the answer of the server. */
export async function finishDriving() {
try {
const result = await api('/api/connection/finish', { method: 'POST' });
refreshEngine();
return result;
} catch (error) {
showError(error);
return null;
}
}
export async function mountConnection(page) {
page.back(t('pagine.impostazioni'), '/impostazioni');
page.title(t('impostazioni.collegamento.titolo'));
const stateLabel = h('span');
page.head.insertBefore(stateLabel, page.head.children[1] || null);
const left = h('div.collega-sinistra');
const right = h('div.collega-destra');
fill(page.body, h('div.pagina-collegamento', left, right));
const windows = caps().browserWindow;
const lease = drivingLease(page);
// The remote view drawn now (Docker): open, it keeps the engine still, so it closes as soon as it is not shown.
let view = null;
// «Ho finito» went well but the engine still waits for «Riprendi» (verification or disconnection); stopSeen: the
// engine was seen stopped since then, so the end of the stop is «Riprendi».
let waitingResume = false;
let stopSeen = false;
function closeView() {
if (view) view.close();
view = null;
}
let status = await api('/api/connection', { signal: page.signal });
async function draw() {
fill(stateLabel, label(t(`impostazioni.collegamento.stati.${status.state}`), STATE_KIND[status.state] || ''));
if (status.state === 'connected') drawConnected();
else if (status.state === 'browserUnavailable') drawUnavailable();
else if (status.state === 'copyMissing') drawLogin({ copyMissing: true });
else drawLogin();
}
// After «Riprendi» (in the red strip of this page) the page shows the connection as it is now. It never takes the
// browser again by itself: still waiting for the verification, the panel stays.
page.onEngine((state) => {
if (!waitingResume) return;
if (waitsForResume(state)) {
stopSeen = true;
return;
}
if (!stopSeen) return;
waitingResume = false;
api('/api/connection', { signal: page.signal }).then((answer) => {
status = answer;
if (status.state !== 'verificationRequired') {
draw();
return;
}
waitingResume = true;
stopSeen = false;
}).catch(showError);
});
// ------------------------------------------------------------------------------------------- login or verification
function drawLogin({ copyMissing = false } = {}) {
const verification = status.state === 'verificationRequired';
// Connected but without the copy for the requests: the start page (the site's home), never the login page.
const login = !verification && !copyMissing;
waitingResume = false;
closeView();
lease.begin(login);
if (windows) {
fill(left, windowPanel());
} else {
view = remoteView(page, { url: status.currentUrl, login });
fill(left, view.element);
}
const steps = t(windows ? 'impostazioni.collegamento.passiWindows' : 'impostazioni.collegamento.passi');
const message = h('div', { 'aria-live': 'polite' });
fill(right,
verification
? h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', h('b', t('impostazioni.collegamento.verificaTitolo')), ' ', t('impostazioni.collegamento.verificaTesto')))
: copyMissing
? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', h('b', t('impostazioni.collegamento.copiaMancanteTitolo')), ' ', t('impostazioni.collegamento.copiaMancanteTesto')))
: h('div',
h('h2.sez', t('impostazioni.collegamento.come')),
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,
copyMissing ? savedSessionBox(status.savedSession, page) : null,
message,
h('div.molla'),
h('div.bottoni-collegamento',
h('button.btn.grande', { type: 'button', onclick: cancel }, t('impostazioni.collegamento.annulla')),
h('button.btn.primo.grande', { type: 'button', onclick: () => finish(message) }, t('impostazioni.collegamento.hoFinito'))));
}
async function cancel() {
try {
await api('/api/connection/cancel', { method: 'POST' });
lease.settled();
} catch (error) {
showError(error);
}
navigate('/impostazioni');
}
async function finish(message) {
const result = await finishDriving();
if (!result) return;
// «Ho finito» gives the browser back on the server whatever the answer.
lease.settled();
if (result.connected) {
toast(result.message);
closeView();
status = await api('/api/connection', { signal: page.signal });
// Still stopped for the verification: «Riprendi» is next, the browser is not taken again.
if (status.state === 'verificationRequired') drawFinished(result.message);
else draw();
} else {
fill(message, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', result.message)));
}
}
/** After «Ho finito» during a verification: what is left is «Riprendi»; the browser can be opened again. */
function drawFinished(text) {
waitingResume = true;
stopSeen = waitsForResume(engineState());
closeView();
fill(left, h('div.vista.vista-finestra', h('div.vista-segnaposto',
icon('circle-check', 'l'),
h('h2', t('impostazioni.collegamento.finitoTitolo')),
h('p', text),
h('button.btn.riapri-browser', { type: 'button', onclick: () => drawLogin() }, icon('app-window', 's'), t('impostazioni.collegamento.riapri')))));
fill(right,
passwordNote(windows),
h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))));
}
// ------------------------------------------------------------------------------------------- connected
function drawConnected() {
waitingResume = false;
closeView();
// Before the first round the name of the account is not known yet: «Collegato» and «Nome non ancora noto», never «@».
const nome = status.username || '';
const sotto = nome ? status.displayName : t('stato.accountDaLeggere');
fill(left, h('div.pannello.collegato',
h('div.chi-collegato', avatar(nome, 'g'),
h('div', h('h2', nome ? t('impostazioni.collegamento.collegatoCome', { nome }) : t('stato.collegato')), sotto ? h('span.muto', sotto) : null)),
h('p', t('impostazioni.collegamento.collegatoTesto')),
h('div.azioni-collegato',
h('button.btn', { type: 'button', onclick: useBrowser }, icon('app-window', 's'), t('impostazioni.collegamento.usaBrowser')),
h('button.btn.pericolo', { type: 'button', onclick: disconnect }, icon('log-out', 's'), t('impostazioni.collegamento.scollega'))),
h('p.aiuto.piccolo', t('impostazioni.collegamento.usaBrowserTesto'))));
fill(right,
passwordNote(windows),
h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))),
h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))),
savedSessionBox(status.savedSession, page));
}
async function useBrowser() {
if (windows) {
await beginDriving(false);
} else {
navigate('/browser');
}
}
async function disconnect() {
const choice = await confirmDialog({
title: t('impostazioni.collegamento.scollegaTitolo'),
text: t('impostazioni.collegamento.scollegaTesto'),
buttons: [
{ label: t('comune.annulla'), value: 'no', kind: 'nudo', autofocus: true },
{ label: t('impostazioni.collegamento.usaPrima'), value: 'browser', kind: '' },
{ label: t('impostazioni.collegamento.scollegaConferma'), value: 'yes', kind: 'pericolo' },
],
});
if (choice === 'browser') {
useBrowser();
return;
}
if (choice !== 'yes') return;
try {
await api('/api/connection/disconnect', { method: 'POST' });
lease.settled();
toast(t('impostazioni.collegamento.scollegato'));
refreshEngine();
status = await api('/api/connection', { signal: page.signal });
draw();
} catch (error) {
showError(error);
}
}
// ------------------------------------------------------------------------------------------- unavailable
function drawUnavailable() {
waitingResume = false;
closeView();
fill(left, h('div.vista.vista-finestra', h('div.vista-segnaposto',
icon('octagon-alert', 'l'),
h('h2', t('impostazioni.collegamento.nonDisponibileTitolo')),
h('p', t('impostazioni.collegamento.nonDisponibileTesto')))));
fill(right, passwordNote(windows), h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))));
}
await draw();
}
/**
* The saved session of the raccolta «richieste» (issue #36, S4b): when it was copied, the values and doc_id present
* and the names of the missing ones — counts and names only, the server never sends a value — and the choice for an
* incomplete copy. Nothing without a saved session in this start («pagine»).
*/
export function savedSessionBox(saved, page) {
if (!saved) return null;
const k = (key, vars) => t(`impostazioni.collegamento.salvata.${key}`, vars);
const lines = [];
if (saved.state === 'present') {
if (saved.copiedAt) {
const when = new Date(saved.copiedAt).toLocaleString('it-IT', { dateStyle: 'medium', timeStyle: 'short' });
lines.push(h('p', k('copiata', { quando: when })));
}
lines.push(h('p.muto', [
k('valori', { presenti: String(saved.valuesPresent), attesi: String(saved.valuesExpected) }),
k('docId', { presenti: String(saved.docIdsPresent), attesi: String(saved.docIdsExpected) }),
k('cookie', { n: String(saved.cookies) }),
].join(' ')));
const missing = [...(saved.missingValues || []), ...(saved.missingDocIds || [])];
if (missing.length) lines.push(h('p', k('mancano', { nomi: missing.join(', ') })));
lines.push(saved.neededMissing
? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', k('servono', { n: String(saved.neededMissing) })))
: h('p', k('completa')));
} else {
lines.push(h('p', k(saved.state === 'unreadable' ? 'illeggibile' : 'nessuna')));
}
// Neither choice is shown as chosen, and neither can be picked, until the server says which one is stored: the page
// never claims a choice the next copy will not follow. Once Alberto picks one, a late answer no longer changes it;
// a choice the server did not save goes back to the one before.
let saved = null;
let chosen = false;
const show = (value) => {
keep.input.checked = value === 'tieni-completa';
replace.input.checked = value === 'sostituisci';
};
const choose = async (value) => {
chosen = true;
const before = saved;
try {
const settings = await api('/api/connection/settings', { method: 'PUT', body: { incompleteCopy: value } });
saved = settings && settings.incompleteCopy ? settings.incompleteCopy : value;
unknown.hidden = true;
toast(k('salvato'));
} catch (error) {
show(before);
showError(error);
}
};
const replace = radio({ name: 'copia-incompleta', value: 'sostituisci', onchange: choose, labelNode: h('span', h('b', k('sostituisci')), h('small', k('sostituisciAiuto'))) });
const keep = radio({ name: 'copia-incompleta', value: 'tieni-completa', onchange: choose, labelNode: h('span', h('b', k('tieni')), h('small', k('tieniAiuto'))) });
const unknown = h('p.aiuto.piccolo.scelta-ignota', { hidden: true }, k('sceltaIgnota'));
for (const choice of [replace, keep]) choice.input.disabled = true;
api('/api/connection/settings', { signal: page && page.signal }).then((settings) => {
if (chosen) return;
saved = settings.incompleteCopy;
show(saved);
}).catch(() => {
if (page && page.signal && page.signal.aborted) return; // the page was left
if (!chosen) unknown.hidden = false;
}).finally(() => {
if (page && page.signal && page.signal.aborted) return;
for (const choice of [replace, keep]) choice.input.disabled = false;
});
return h('div.pannello.sessione-salvata',
h('h2.sez', k('titolo')),
...lines,
h('p.aiuto.piccolo', k('nota')),
h('h3.sez', k('incompleta')),
h('div.scelte', { role: 'radiogroup', 'aria-label': k('incompleta') }, replace, keep),
unknown);
}
/** «La password va solo a Instagram», with the true wording of each shell (spec §10.3). */
export function passwordNote(windows) {
return h('div.avviso.nota-password', icon('shield-check', 's'),
h('span', h('b', t('impostazioni.collegamento.passwordTitolo')), ' ', t(windows ? 'impostazioni.collegamento.passwordWindows' : 'impostazioni.collegamento.passwordDocker')));
}
export default {
mount: (page) => mountConnection(page),
};