55 lines
1.6 KiB
TypeScript
55 lines
1.6 KiB
TypeScript
import * as Playwright from "playwright";
|
|
import { chromium, devices } from "playwright";
|
|
import type { Database } from "./database";
|
|
import type { TPlatform } from "./platform";
|
|
|
|
export type Browser = {
|
|
loadBrowserContext(platform: TPlatform): Promise<Playwright.BrowserContext>;
|
|
saveBrowserContext(platform: TPlatform, ctx: BrowserContext): Promise<void>;
|
|
newContext: () => Promise<Playwright.BrowserContext>;
|
|
close: () => Promise<void>;
|
|
};
|
|
|
|
export type BrowserContext = Playwright.BrowserContext;
|
|
|
|
export async function createBrowser({
|
|
db,
|
|
headless = true,
|
|
}: {
|
|
db: Database;
|
|
headless?: boolean;
|
|
}): Promise<Browser> {
|
|
const { userAgent } = devices["Desktop Chrome"];
|
|
const browser = await chromium.launch({
|
|
headless,
|
|
args: ["--disable-blink-features=AutomationControlled"],
|
|
});
|
|
|
|
return {
|
|
async loadBrowserContext(
|
|
platform: TPlatform,
|
|
): Promise<Playwright.BrowserContext> {
|
|
const { secrets } = await db.get(
|
|
`select secrets from platforms where name = ?`,
|
|
platform,
|
|
);
|
|
|
|
const storageState = JSON.parse(secrets) ?? undefined;
|
|
const ctx = await browser.newContext({ storageState, userAgent });
|
|
return ctx;
|
|
},
|
|
async saveBrowserContext(
|
|
platform: TPlatform,
|
|
ctx: BrowserContext,
|
|
): Promise<void> {
|
|
const secrets = await ctx.storageState();
|
|
await db.run(
|
|
`update platforms set secrets = ? where name = ?`,
|
|
JSON.stringify(secrets),
|
|
platform,
|
|
);
|
|
},
|
|
newContext: () => browser.newContext(),
|
|
close: () => browser.close(),
|
|
};
|
|
}
|