Files
Febe/src/Febe.App/LiveBrowserPreview.cs
T

73 lines
2.5 KiB
C#

using Febe.Browser.Cdp;
using Febe.Browser.RemoteView;
using Febe.Core.Abstractions;
using Febe.Web.Engine;
namespace Febe.App;
/// <summary>
/// Preview of the browser for the Attività page (mockup 06): one still frame taken with Page.captureScreenshot when the
/// page asks, at most every few seconds. Reading what the browser shows is not an action toward the site. On the empty
/// rest page there is nothing to show. The same in both shells.
/// </summary>
public sealed class LiveBrowserPreview(IFebeBrowser browser, IClock clock) : IBrowserPreview
{
private static readonly TimeSpan MinimumAge = TimeSpan.FromSeconds(4);
private readonly SemaphoreSlim _gate = new(1, 1);
private BrowserFrame? _last;
public async Task<BrowserFrame?> GetLatestAsync(CancellationToken ct)
{
if (!browser.IsAvailable)
{
return null;
}
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
var now = clock.Now;
if (_last is { } cached && now - cached.At < MinimumAge)
{
return cached;
}
var url = await browser.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
if (string.IsNullOrEmpty(url) || url.StartsWith("about:", StringComparison.OrdinalIgnoreCase))
{
_last = null;
return null;
}
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)
{
return null;
}
finally
{
_gate.Release();
}
}
}
/// <summary>Addresses as Febe may show them.</summary>
public static class Addresses
{
/// <summary>The address without query string or fragment (they may carry tokens).</summary>
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;
}
}