feat: улучшил обработку загрузки страницы
Create and publish a Docker image / Publish image (push) Successful in 10s

This commit is contained in:
serega404 committed 2026-10-12 14:13:51 +03:00
1 parent f5d5b0f68f
commit 2c4fccb22d
2 files changed
+31 -5

No files matched your search

+7 -4
View File
@@ -16,11 +16,14 @@ public static class MicrosoftLoginHelper
{
logger.LogInformation("Начало входа в Microsoft. Url: {LoginUrl}, пользователь: {Username}", loginUrl, username);
await page.GotoAsync(loginUrl, new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded });
// Готовность формы проверяем ниже по полям: сторонние скрипты могут задерживать DOMContentLoaded.
await page.GotoAsync(loginUrl, new PageGotoOptions { WaitUntil = WaitUntilState.Commit });
logger.LogDebug("Страница логина загружена, ожидаем переход на домен Microsoft.");
logger.LogDebug("Началась загрузка страницы логина, ожидаем переход на домен Microsoft.");
await page.WaitForURLAsync(new Regex("login\\.(microsoftonline|live)\\.com", RegexOptions.IgnoreCase), new PageWaitForURLOptions { Timeout = 60_000 });
// WaitForURL при уже совпавшем URL дополнительно ожидает событие загрузки страницы.
await page.WaitForFunctionAsync(@"() => /^login\.(microsoftonline|live)\.com$/i.test(location.hostname)",
options: new PageWaitForFunctionOptions { Timeout = 60_000 });
var useAnotherAccount = page.Locator("div#otherTile, #otherTileText, div[data-test-id='useAnotherAccount']").First;
try
@@ -35,7 +38,7 @@ public static class MicrosoftLoginHelper
}
var emailInput = page.Locator("input[name='loginfmt'], input#i0116");
await emailInput.WaitForAsync(new LocatorWaitForOptions { State = WaitForSelectorState.Visible, Timeout = 30_000 });
await emailInput.WaitForAsync(new LocatorWaitForOptions { State = WaitForSelectorState.Visible, Timeout = 60_000 });
logger.LogDebug("Поле ввода email найдено, вводим логин.");
await emailInput.FillAsync(username);
+24 -1
View File
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text.Json;
using Microsoft.Playwright;
@@ -50,6 +51,19 @@ public class MicrosoftAuthService(ILogger<MicrosoftAuthService> logger, IConfigu
ViewportSize = null
});
var page = await context.NewPageAsync();
var pendingRequests = new ConcurrentDictionary<IRequest, byte>();
EventHandler<IRequest> requestStarted = (_, request) => pendingRequests.TryAdd(request, 0);
EventHandler<IRequest> requestFinished = (sender, request) => pendingRequests.TryRemove(request, out _);
EventHandler<IRequest> requestFailed = (sender, request) =>
{
pendingRequests.TryRemove(request, out _);
if (request.Failure == "net::ERR_ABORTED") return;
logger.LogWarning("Ошибка загрузки ресурса браузером. Домен: {Host}, тип: {ResourceType}, причина: {Failure}",
new Uri(request.Url).Host, request.ResourceType, request.Failure);
};
page.Request += requestStarted;
page.RequestFinished += requestFinished;
page.RequestFailed += requestFailed;
try
{
@@ -80,11 +94,20 @@ public class MicrosoftAuthService(ILogger<MicrosoftAuthService> logger, IConfigu
}
catch (Exception ex) when (ex is not MicrosoftAuthInProgressException)
{
logger.LogError(ex, "Ошибка при получении JWT через Microsoft авторизацию");
logger.LogError(ex, "Ошибка при получении JWT через Microsoft авторизацию. Текущий домен браузера: {Host}",
page.Url == "about:blank" ? "about:blank" : new Uri(page.Url).Host);
if (!pendingRequests.IsEmpty)
{
var resources = pendingRequests.Keys.Select(request => $"{new Uri(request.Url).Host} ({request.ResourceType})").Distinct();
logger.LogWarning("Незавершенные запросы браузера: {Resources}", string.Join(", ", resources));
}
throw;
}
finally
{
page.Request -= requestStarted;
page.RequestFinished -= requestFinished;
page.RequestFailed -= requestFailed;
await context.CloseAsync();
await browser.CloseAsync();