← All source files

V12 / ea1357ad1734

ProjectBrowserSession.cs

Lilith/Core/Projects/ProjectBrowserSession.cs

Changed in this version
CS
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace Lilith.Core.Projects;

/// <summary>One visible browser for one explicitly approved qualification job.</summary>
internal sealed class ProjectBrowserSession : IDisposable
{
    private ChromeDriver? _driver;
    private ChromeDriverService? _service;
    internal Action<WebResearch.ResearchBrowserFrame>? Capture { get; set; }
    internal string Name { get; set; } = "project";
    internal ChromeDriver Get()
    {
        if (_driver is not null) return _driver;
        var options = WebResearch.BrowserResearchOptions.Load();
        string? directory = options.DriverDirectory;
        if (directory is null)
        {
            string cache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".cache/selenium/chromedriver");
            directory = Directory.Exists(cache) ? Directory.EnumerateFiles(cache, "chromedriver.exe", SearchOption.AllDirectories).OrderByDescending(File.GetLastWriteTimeUtc).Select(Path.GetDirectoryName).FirstOrDefault() : null;
        }
        if (directory is null) throw new IOException("Existing ChromeDriver required; nothing is downloaded.");
        var chrome = new ChromeOptions(); if (options.ChromeBinary is not null) chrome.BinaryLocation = options.ChromeBinary;
        chrome.AddArguments("--no-first-run", "--disable-background-networking"); chrome.SetLoggingPreference(OpenQA.Selenium.LogType.Browser, LogLevel.All);
        _service = ChromeDriverService.CreateDefaultService(directory); _service.HideCommandPromptWindow = true;
        _driver = new ChromeDriver(_service, chrome, TimeSpan.FromSeconds(10));
        _driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(10); return _driver;
    }
    public void Dispose()
    {
        bool opened = _driver is not null;
        try { _driver?.Dispose(); }
        finally
        {
            _service?.Dispose(); _driver = null; _service = null;
            if (opened) Capture?.Invoke(new(DateTimeOffset.UtcNow, "project://" + Name, null, Closed: true, Purpose: "Project testing"));
        }
    }
}