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; } }