Загрузка данных
@DefaultServiceConfiguration(DefaultPlaywrightServiceConfiguration.class)
public class PlaywrightService implements Service {
private static final Logger LOGGER = LoggerFactory.getLogger(PlaywrightService.class);
private DefaultPlaywrightServiceConfiguration configuration;
private Playwright playwright;
private Browser browser;
private BrowserContext context;
private Page page;
private DevToolsManager devToolsManager;
private Environment environment;
private SelenoidUtils selenoidUtils = null;
public void init(@NotNull Environment environment) {
Preconditions.notNull(environment, "Environment must not be null");
this.environment = environment;
this.configuration = new DefaultPlaywrightServiceConfiguration();
}
public void init(@NotNull Environment environment, @NotNull ServiceConfiguration configuration) {
Preconditions.notNull(environment, "Environment must not be null");
Preconditions.notNull(configuration, "Service configuration must not be null");
this.environment = environment;
this.configuration = (DefaultPlaywrightServiceConfiguration)this.validate(configuration, DefaultPlaywrightServiceConfiguration.class);
}
public void beforeTest() {
this.setup();
}
public void afterTest() {
if (this.devToolsManager != null) {
LogsUtils.attachReport(this.devToolsManager, this.context);
} else {
LOGGER.warn("Нет возможности сохранить логи браузера.");
}
if (this.page != null) {
this.page.close();
}
if (this.context != null) {
this.context.close();
}
if (this.browser != null) {
this.browser.close();
}
if (this.playwright != null) {
this.playwright.close();
}
}
public Playwright getPlaywright() {
return this.playwright;
}
public Browser getBrowser() {
return this.browser;
}
public BrowserContext getBrowserContext() {
return this.context;
}
public Page getPage() {
return this.page;
}
public Download waitForDownload(Runnable runnable) {
return this.waitForDownload((Page.WaitForDownloadOptions)null, runnable);
}
public Download waitForDownload(@Nullable Page.WaitForDownloadOptions options, Runnable runnable) {
Download download = this.page.waitForDownload(options, runnable);
if (this.configuration.isRemote()) {
String fileName = download.suggestedFilename();
byte[] bytes = this.selenoidUtils.downloadSelenoidFile(fileName);
return new DownloadWrapper(download, bytes);
} else {
return download;
}
}
private void setup() {
LOGGER.info("Инициализация Playwright.");
this.playwright = Playwright.create(this.configuration.createOptions());
BrowserType browserType = (BrowserType)this.configuration.browserType().apply(this.playwright);
LOGGER.info("Выбран браузер {}.", browserType.name());
if (this.configuration.isRemote()) {
LOGGER.info("Инициализация контекста браузера для удалённого запуска.");
this.selenoidUtils = SelenoidUtils.createSession(this.configuration.selenoidCapabilities().toJson());
this.browser = browserType.connectOverCDP(this.selenoidUtils.getSocketUrl(), this.configuration.connectOverCDPOptions());
this.context = this.browser.newContext();
} else {
Map<String, Object> prefs = this.configuration.browserPreferences();
LOGGER.info("Инициализация контекста браузера для локального запуска.");
if ("chromium".equals(browserType.name())) {
BrowserType.LaunchPersistentContextOptions options = this.configuration.launchPersistentContextOptions();
Path profile = this.generateProfile(prefs);
this.context = browserType.launchPersistentContext(profile, options);
this.browser = this.context.browser();
} else {
BrowserType.LaunchOptions launchOptions = this.configuration.launchOptions();
launchOptions.setArgs(this.configuration.args());
launchOptions.setFirefoxUserPrefs(prefs);
this.browser = browserType.launch(launchOptions);
Browser.NewContextOptions contextOptions = this.configuration.newContextOptions();
this.context = this.browser.newContext(contextOptions);
}
}
LOGGER.info("Открытие базовой страницы.");
if (this.context.pages().isEmpty()) {
this.page = this.context.newPage();
} else {
this.page = (Page)this.context.pages().get(0);
}
try {
this.devToolsManager = DevToolsManager.create(this.context, this.page);
} catch (PlaywrightException var5) {
LOGGER.warn("Браузер не поддерживает CDP.");
}
this.page.navigate(this.configuration.getBaseUrl());
}
private Path generateProfile(Map<String, Object> prefs) {
try {
LOGGER.info("Создание профиля для Chromium браузера");
Path tempDirectory = Files.createTempDirectory("playwright-");
Path path = Files.createDirectories(tempDirectory.resolve("Default"));
Path prefsPath = path.resolve("Preferences");
Files.writeString(prefsPath, BrowserPreferenceUnwrapper.unwrap(prefs));
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
FileUtils.deleteDirectory(tempDirectory.toFile());
} catch (IOException e) {
LOGGER.warn("Ошибка при удалении временной директории", e);
}
}));
return tempDirectory;
} catch (IOException var5) {
throw ChromeProfileInitialization.exception("Не удалось создать профиль для браузера.");
}
}
}