Files
Mimante/tools/Mimante.Schermate/Cdp/CdpClient.cs
T
Alby96andClaude Opus 5.5 88c16568fb
verifica / controlli (push) Successful in 47s
verifica / prove (push) Successful in 2m27s
verifica / immagine (push) Canceled after 7m51s
Niente più browser nel bot: la sessione di Bidoo si incolla da Chrome (#36)
I cookie di accesso di Bidoo (__stattrb, PHPSESSID) sono HttpOnly: nessuno script o copia della pagina
li vede, quindi non esiste un modo più semplice degli strumenti per sviluppatori. Lì Chrome ha già
«Copia come cURL», che porta cookie e User-Agent in un colpo. Per questo, come deciso da Alberto, il
browser del bot se ne va.

- Session/SessionPaste riconosce da solo cURL (bash e cmd, -b o -H cookie, -A o -H user-agent),
  «Copia come PowerShell», intestazioni della richiesta (anche nome e valore su righe diverse), la riga
  Cookie, righe della tabella dei cookie e il solo valore di __stattrb; rifiuta un testo senza il
  cookie di accesso. Lo User-Agent del testo vale più di quello del campo.
- La pagina Browser diventa «Accesso a Bidoo» (#/accesso, #/browser ci porta): riquadro da incollare,
  istruzioni per Chrome, stato della sessione.
- Via AssistedLogin, i comandi login.* e i messaggi login.frame/login.state; via chromium e
  fonts-liberation dall'immagine, e prova-immagine.sh controlla che Chromium non ci sia. All'avvio il
  bot cancella /config/browser, il profilo della 1.x con una copia dei cookie.
- Il client CDP e l'avvio di Chromium passano in tools/Mimante.Schermate, che usa Chrome o Edge del PC.
- ADR 0017 (supera la 0003; la 0010 resta per la base Debian), README, architettura, guida, docker.md,
  stato e CHANGELOG aggiornati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:36:47 +01:00

179 lines
7.1 KiB
C#

using System.Collections.Concurrent;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Mimante.Schermate.Cdp;
/// <summary>Un errore restituito da Chromium a un comando CDP.</summary>
public sealed class CdpException(string method, string message) : Exception($"{method}: {message}");
/// <summary>Il canale verso Chromium: in produzione un WebSocket, nei test una coda in memoria.</summary>
public interface ICdpTransport : IAsyncDisposable
{
Task SendAsync(string json, CancellationToken ct);
/// <summary>Il prossimo messaggio intero; null quando il canale si chiude.</summary>
Task<string?> ReceiveAsync(CancellationToken ct);
}
/// <summary>
/// Client del Chrome DevTools Protocol scritto a mano, per le schermate: JSON-RPC su
/// WebSocket, <c>id</c> incrementale, mappa delle risposte in attesa, eventi con
/// <c>sessionId</c> (sessioni piatte, <c>Target.attachToTarget</c> con <c>flatten: true</c>).
/// Niente Playwright: servono una decina di comandi.
/// </summary>
public sealed class CdpClient : IAsyncDisposable
{
private readonly ICdpTransport _transport;
private readonly ConcurrentDictionary<int, (string Method, TaskCompletionSource<JsonElement> Tcs)> _pending = new();
private readonly CancellationTokenSource _cts = new();
private readonly Task _reader;
private int _nextId;
/// <summary>Un evento: metodo, parametri, sessione (null = browser).</summary>
public event Action<string, JsonElement, string?>? Event;
/// <summary>Il canale si è chiuso (Chromium uscito).</summary>
public event Action? Closed;
public CdpClient(ICdpTransport transport)
{
_transport = transport;
_reader = Task.Run(() => ReadLoopAsync(_cts.Token));
}
public static async Task<CdpClient> ConnectAsync(Uri endpoint, CancellationToken ct)
{
var ws = new ClientWebSocket();
ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(20);
await ws.ConnectAsync(endpoint, ct).ConfigureAwait(false);
return new CdpClient(new WebSocketCdpTransport(ws));
}
public bool IsClosed { get; private set; }
/// <summary>Un comando; la risposta è il campo <c>result</c>. Un <c>error</c> diventa <see cref="CdpException"/>.</summary>
public async Task<JsonElement> SendAsync(string method, object? parameters = null, string? sessionId = null,
CancellationToken ct = default, TimeSpan? timeout = null)
{
if (IsClosed) throw new CdpException(method, "browser chiuso");
var id = Interlocked.Increment(ref _nextId);
var tcs = new TaskCompletionSource<JsonElement>(TaskCreationOptions.RunContinuationsAsynchronously);
_pending[id] = (method, tcs);
var message = new JsonObject { ["id"] = id, ["method"] = method };
if (parameters != null) message["params"] = JsonSerializer.SerializeToNode(parameters);
if (sessionId != null) message["sessionId"] = sessionId;
try
{
await _transport.SendAsync(message.ToJsonString(), ct).ConfigureAwait(false);
return await tcs.Task.WaitAsync(timeout ?? TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
throw new CdpException(method, "nessuna risposta dal browser");
}
finally
{
_pending.TryRemove(id, out _);
}
}
/// <summary>Un comando di cui non interessa la risposta (conferme dei frame, input).</summary>
public void Post(string method, object? parameters = null, string? sessionId = null) =>
_ = SendAsync(method, parameters, sessionId).ContinueWith(t => _ = t.Exception, TaskScheduler.Default);
private async Task ReadLoopAsync(CancellationToken ct)
{
try
{
while (!ct.IsCancellationRequested)
{
var text = await _transport.ReceiveAsync(ct).ConfigureAwait(false);
if (text == null) break;
Handle(text);
}
}
catch (OperationCanceledException) { }
catch (WebSocketException) { }
finally
{
IsClosed = true;
foreach (var (_, p) in _pending) p.Tcs.TrySetException(new CdpException(p.Method, "browser chiuso"));
_pending.Clear();
Closed?.Invoke();
}
}
/// <summary>Smista un messaggio in arrivo: risposta a un comando o evento.</summary>
internal void Handle(string text)
{
using var doc = JsonDocument.Parse(text);
var root = doc.RootElement;
if (root.TryGetProperty("id", out var idEl) && idEl.TryGetInt32(out var id))
{
if (!_pending.TryGetValue(id, out var p)) return;
if (root.TryGetProperty("error", out var err))
p.Tcs.TrySetException(new CdpException(p.Method, err.TryGetProperty("message", out var msg) ? msg.GetString() ?? "errore" : "errore"));
else
p.Tcs.TrySetResult(root.TryGetProperty("result", out var result) ? result.Clone() : default);
return;
}
if (root.TryGetProperty("method", out var method))
{
var session = root.TryGetProperty("sessionId", out var s) ? s.GetString() : null;
var parameters = root.TryGetProperty("params", out var pr) ? pr.Clone() : default;
try { Event?.Invoke(method.GetString() ?? "", parameters, session); }
catch { /* un gestore rotto non chiude il canale */ }
}
}
public async ValueTask DisposeAsync()
{
await _cts.CancelAsync().ConfigureAwait(false);
await _transport.DisposeAsync().ConfigureAwait(false);
try { await _reader.WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); } catch { }
_cts.Dispose();
}
}
/// <summary>Il WebSocket di Chromium (<c>ws://127.0.0.1:porta/devtools/browser/…</c>).</summary>
internal sealed class WebSocketCdpTransport(ClientWebSocket ws) : ICdpTransport
{
private readonly SemaphoreSlim _sendGate = new(1, 1);
public async Task SendAsync(string json, CancellationToken ct)
{
await _sendGate.WaitAsync(ct).ConfigureAwait(false);
try { await ws.SendAsync(Encoding.UTF8.GetBytes(json), WebSocketMessageType.Text, true, ct).ConfigureAwait(false); }
finally { _sendGate.Release(); }
}
public async Task<string?> ReceiveAsync(CancellationToken ct)
{
var buffer = new byte[64 * 1024];
using var ms = new MemoryStream();
while (true)
{
var r = await ws.ReceiveAsync(buffer, ct).ConfigureAwait(false);
if (r.MessageType == WebSocketMessageType.Close) return null;
ms.Write(buffer, 0, r.Count);
if (r.EndOfMessage) return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
}
}
public async ValueTask DisposeAsync()
{
if (ws.State == WebSocketState.Open)
{
try { await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "fine", CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); }
catch { }
}
ws.Dispose();
}
}