Untitled

 avatar
unknown
plain_text
9 months ago
4.8 kB
15
Indexable
// Account chooser (nowe okno po "Authorize")
private static final By accountCard = By.cssSelector("[data-identifier],[data-email]");
private static final By accountClickable = By.cssSelector("[role='link'],[jsname][tabindex]");

// Jeśli chcesz wskazać konkretne konto – wpisz email; gdy null -> bierze pierwsze
@Nullable
private static final String PREFERRED_EMAIL = null;

/////////////////////////////////

public void handleAllPopupsIfPresent() {
  handlePopupIfPresent(authorizeButton, email, "Authorization");
  handleAccountChooserIfPresent(); // <—— NOWE: wybór konta w nowym oknie

  handlePopupIfPresent(grantAllowButton, grantConsentDialog, "Grant Consent");
  handlePopupIfPresent(acknowledgeButton, reviewDataAccessDialog, "Review Data Access");
}

//////////////////////

// Po "Authorize" czasem otwiera się nowe okno z wyborem konta Google.
// Ta metoda miękko to obsługuje: czeka na nowe okno, klika pierwsze (lub wskazane) konto i wraca.
private void handleAccountChooserIfPresent() {
  final String original = driver.getWindowHandle();
  final java.util.Set<String> before = driver.getWindowHandles();

  // 1) czekaj krótko na nowe okno; jeśli się nie pojawi – po prostu wyjdź
  try {
    new WebDriverWait(driver, Duration.ofSeconds(10))
        .until(ExpectedConditions.numberOfWindowsToBe(before.size() + 1));
  } catch (TimeoutException ignore) {
    logger.atInfo().log("Account chooser window not opened; continue.");
    return;
  }

  // 2) przełącz na nowe okno
  String popup = driver.getWindowHandles().stream()
      .filter(h -> !before.contains(h)).findFirst().orElse(null);
  if (popup == null) {
    logger.atInfo().log("No new window handle found for account chooser; continue.");
    return;
  }
  driver.switchTo().window(popup);

  try {
    // 3) upewnij się, że to chooser (URL/tytuł) – nie blokuje jeśli się nie zgadza
    try {
      new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.or(
          ExpectedConditions.urlContains("accounts.google.com"),
          ExpectedConditions.titleContains("Choose an account")
      ));
    } catch (TimeoutException ignore) { /* brak twardej blokady */ }

    WebElement card;

    // 4) znajdź kartę konta: preferowany e-mail lub pierwsza z listy
    if (PREFERRED_EMAIL != null) {
      card = new WebDriverWait(driver, Duration.ofSeconds(20))
          .until(d -> d.findElements(accountCard).stream()
              .filter(e -> {
                String id = Optional.ofNullable(e.getAttribute("data-identifier"))
                                    .orElse(e.getAttribute("data-email"));
                return PREFERRED_EMAIL.equalsIgnoreCase(id);
              })
              .findFirst().orElse(null));
      if (card == null) {
        logger.atInfo().log("Preferred email '%s' not found; falling back to first account.", PREFERRED_EMAIL);
      }
    } else {
      card = new WebDriverWait(driver, Duration.ofSeconds(20))
          .until(ExpectedConditions.presenceOfElementLocated(accountCard));
    }

    if (card == null) {
      logger.atInfo().log("No account card found in chooser; continue.");
      return;
    }

    // 5) kliknij najbliższy element „klikalny” (role='link') z fallbackami
    WebElement clickable;
    try {
      clickable = card.findElement(By.xpath("ancestor-or-self::*[@role='link'][1]"));
    } catch (NoSuchElementException e) {
      // fallback: szukaj klikalnego wewnątrz karty
      clickable = card.findElement(accountClickable);
    }

    // przewiń i klik
    ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView({block:'center'})", clickable);

    try {
      new WebDriverWait(driver, Duration.ofSeconds(10))
          .until(ExpectedConditions.elementToBeClickable(clickable));
      clickable.click();
      logger.atInfo().log("Clicked account in chooser window.");
    } catch (Exception e1) {
      try {
        new Actions(driver).moveToElement(clickable).pause(Duration.ofMillis(80)).click().perform();
        logger.atInfo().log("Clicked account via Actions.");
      } catch (Exception e2) {
        ((JavascriptExecutor) driver).executeScript(
            "const el=arguments[0].closest('[role=\"link\"]')||arguments[0]; el.click();", clickable);
        logger.atInfo().log("Clicked account via JS.");
      }
    }

    // opcjonalnie: poczekaj aż okno się zamknie lub zmieni się URL
    try {
      new WebDriverWait(driver, Duration.ofSeconds(5))
          .until(ExpectedConditions.numberOfWindowsToBe(before.size()));
    } catch (TimeoutException ignore) { /* nie wymagamy */ }

  } finally {
    // 6) zawsze wróć do głównego okna
    driver.switchTo().window(original);
  }
}
Editor is loading...
Leave a Comment