BotSharp/src/Plugins/BotSharp.Plugin.WebDriver/Drivers/PlaywrightDriver/PlaywrightInstance.cs

101 lines
2.6 KiB
C#
Raw Normal View History

using System.IO;
2024-01-03 19:40:41 +00:00
namespace BotSharp.Plugin.WebDriver.Drivers.PlaywrightDriver;
2024-01-03 04:43:37 +00:00
public class PlaywrightInstance : IDisposable
{
IPlaywright _playwright;
Dictionary<string, IBrowserContext> _contexts = new Dictionary<string, IBrowserContext>();
2024-01-03 04:43:37 +00:00
public IPage GetPage(string id)
2024-02-06 05:05:52 +00:00
{
InitInstance(id).Wait();
return _contexts[id].Pages.LastOrDefault();
2024-02-06 05:05:52 +00:00
}
2024-01-03 04:43:37 +00:00
public async Task InitInstance(string id)
2024-01-06 03:24:13 +00:00
{
if (_playwright == null)
{
_playwright = await Playwright.CreateAsync();
}
await InitContext(id);
}
public async Task InitContext(string id)
{
if (_contexts.ContainsKey(id))
return;
2024-03-22 19:06:20 +00:00
#if DEBUG
2024-03-08 13:17:36 +00:00
string tempFolderPath = $"{Path.GetTempPath()}\\playwright";
2024-03-22 19:06:20 +00:00
#else
string tempFolderPath = $"{Path.GetTempPath()}\\playwright\\{id}";
#endif
_contexts[id] = await _playwright.Chromium.LaunchPersistentContextAsync(tempFolderPath, new BrowserTypeLaunchPersistentContextOptions
{
2024-02-24 16:15:26 +00:00
#if DEBUG
Headless = false,
#else
2024-02-15 21:01:22 +00:00
Headless = true,
2024-02-24 16:15:26 +00:00
#endif
Channel = "chrome",
IgnoreDefaultArgs = new[]
2024-01-06 03:24:13 +00:00
{
2024-02-06 20:42:35 +00:00
"--disable-infobars"
2024-02-05 04:22:43 +00:00
},
Args = new[]
{
2024-02-06 20:42:35 +00:00
"--disable-infobars",
// "--start-maximized"
2024-01-06 22:24:22 +00:00
}
});
2024-02-02 04:16:57 +00:00
_contexts[id].Page += async (sender, e) =>
{
e.Close += async (sender, e) =>
{
Serilog.Log.Information($"Page is closed: {e.Url}");
};
Serilog.Log.Information($"New page is created: {e.Url}");
await e.SetViewportSizeAsync(1280, 800);
};
_contexts[id].Close += async (sender, e) =>
{
Serilog.Log.Warning($"Playwright browser context is closed");
_contexts.Remove(id);
};
}
public async Task<IPage> NewPage(string id)
{
await InitContext(id);
return await _contexts[id].NewPageAsync();
}
public async Task Wait(string id)
{
if (_contexts.ContainsKey(id))
{
2024-02-15 21:55:50 +00:00
var page = _contexts[id].Pages.Last();
await page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
await page.WaitForLoadStateAsync(LoadState.NetworkIdle);
}
2024-02-12 21:49:18 +00:00
await Task.Delay(100);
}
public async Task Close(string id)
{
if (_contexts.ContainsKey(id))
{
await _contexts[id].CloseAsync();
2024-01-06 03:24:13 +00:00
}
}
2024-01-03 04:43:37 +00:00
public void Dispose()
{
_contexts.Clear();
2024-01-03 04:43:37 +00:00
_playwright.Dispose();
}
}