← All source files

V16 / 6df58cd3ed86

EdgeDriverLocator.cs

Interfaces/Gui/LilithDesktop/EdgeDriverLocator.cs

Changed in this version
CS
using System.IO.Compression;
using System.Runtime.InteropServices;

namespace Lilith.Desktop;

internal static class EdgeDriverLocator
{
    internal static async Task<string> ResolveAsync(string repo,string version)
    {
        if(!System.Text.RegularExpressions.Regex.IsMatch(version,@"^\d+\.\d+\.\d+\.\d+$"))throw new InvalidDataException("Invalid WebView2 runtime version.");
        string platform=RuntimeInformation.OSArchitecture==Architecture.Arm64?"arm64":"win64";
        string cache=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),".cache","selenium","msedgedriver",platform,version,"msedgedriver.exe");
        if(File.Exists(cache))return cache;
        string folder=Path.Combine(repo,"Admin","Build","DesktopDriver",version);
        string target=Path.Combine(folder,"msedgedriver.exe");if(File.Exists(target))return target;
        using var http=new HttpClient{Timeout=TimeSpan.FromSeconds(60)};
        // Microsoft distributes a version-matched driver separately from WebView2.
        using var response=await http.GetAsync($"https://msedgedriver.microsoft.com/{version}/edgedriver_{platform}.zip",HttpCompletionOption.ResponseHeadersRead);
        response.EnsureSuccessStatusCode();
        if(response.Content.Headers.ContentLength>50000000)throw new IOException("Unexpected driver archive size.");
        var bytes=await response.Content.ReadAsByteArrayAsync();if(bytes.Length>50000000)throw new IOException("Unexpected driver archive size.");
        using var zip=new ZipArchive(new MemoryStream(bytes));
        var executable=zip.GetEntry("msedgedriver.exe")??throw new IOException("Microsoft archive did not contain Edge WebDriver.");
        if(executable.Length>100000000)throw new IOException("Unexpected driver size.");
        Directory.CreateDirectory(folder);string pending=target+".pending";
        executable.ExtractToFile(pending,true);File.Move(pending,target,true);return target;
    }
}