Skip to content

Commit

Permalink
Добавляет заглушку для логгера
Browse files Browse the repository at this point in the history
  • Loading branch information
inyutin-maxim committed Sep 11, 2023
1 parent f7a3334 commit 2d08df5
Show file tree
Hide file tree
Showing 8 changed files with 201 additions and 62 deletions.
6 changes: 0 additions & 6 deletions VkNet/Abstractions/Core/IVkApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using VkNet.Abstractions.Authorization;
using VkNet.Abstractions.Core;
using VkNet.Enums;
using VkNet.Utils;

namespace VkNet.Abstractions;

Expand All @@ -19,11 +18,6 @@ public interface IVkApi : IDisposable, IVkApiAuthAsync, IVkApiCategories, IVkApi
/// </summary>
int RequestsPerSecond { get; set; }

/// <summary>
/// Браузер.
/// </summary>
IBrowser Browser { get; set; }

/// <summary>
/// Поток авторизации
/// </summary>
Expand Down
43 changes: 32 additions & 11 deletions VkNet/Infrastructure/Authorization/ImplicitFlow/ImplicitFlow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ public class ImplicitFlow : IImplicitFlow
/// <summary>
/// Логгер
/// </summary>
[CanBeNull]
private readonly ILogger<ImplicitFlow> _logger;
private readonly ILogger _logger;

/// <summary>
/// Менеджер версий VkApi
Expand All @@ -36,7 +35,7 @@ public class ImplicitFlow : IImplicitFlow
private readonly IVkAuthorization<ImplicitFlowPageType> _vkAuthorization;

/// <inheritdoc cref="ImplicitFlow"/>
public ImplicitFlow([CanBeNull] ILogger<ImplicitFlow> logger,
public ImplicitFlow(ILogger logger,
IVkApiVersionManager versionManager,
IAuthorizationFormFactory authorizationFormsFactory,
IVkAuthorization<ImplicitFlowPageType> vkAuthorization)
Expand All @@ -50,10 +49,17 @@ public ImplicitFlow([CanBeNull] ILogger<ImplicitFlow> logger,
/// <inheritdoc />
public async Task<AuthorizationResult> AuthorizeAsync(CancellationToken token = default)
{
_logger?.LogDebug("Валидация данных");
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Валидация данных");
}

ValidateAuthorizationParameters();

_logger?.LogDebug("Шаг 1. Открытие диалога авторизации");
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Шаг 1. Открытие диалога авторизации");
}

var authorizeUrlResult = CreateAuthorizeUrl();

Expand Down Expand Up @@ -85,7 +91,7 @@ public Uri CreateAuthorizeUrl(ulong clientId, ulong scope, Display display, stri
"Используйте перегрузку Url CreateAuthorizeUrl();\nПараметры авторизации должны быть уставленны вызовом void SetAuthorizationParams(IApiAuthParams authorizationParams);")]
public Uri CreateAuthorizeUrl()
{
_logger?.LogDebug("Построение url для авторизации");
_logger.LogDebug("Построение url для авторизации");

const string url = "https://oauth.vk.com/authorize?";

Expand Down Expand Up @@ -140,39 +146,54 @@ private async Task<AuthorizationResult> NextStepAsync(AuthorizationFormResult fo
case ImplicitFlowPageType.Error:

{
_logger?.LogError("При авторизации произошла ошибка");
if (_logger.IsEnabled(LogLevel.Error))
{
_logger.LogError("При авторизации произошла ошибка");
}

throw new VkAuthorizationException("При авторизации произошла ошибка.");
}

case ImplicitFlowPageType.LoginPassword:

{
_logger?.LogDebug("Неверный логин или пароль");
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Неверный логин или пароль");
}

throw new VkAuthorizationException("Неверный логин или пароль.");
}

case ImplicitFlowPageType.Captcha:

{
_logger?.LogDebug("Капча");
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Капча");
}

break;
}

case ImplicitFlowPageType.TwoFactor:

{
_logger?.LogDebug("Двухфакторная авторизация");
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Двухфакторная авторизация");
}

break;
}

case ImplicitFlowPageType.Consent:

{
_logger?.LogDebug("Страница подтверждения доступа к скоупам");
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Страница подтверждения доступа к скоупам");
}

break;
}
Expand Down
29 changes: 29 additions & 0 deletions VkNet/Infrastructure/NullLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System;
using Microsoft.Extensions.Logging;

namespace VkNet.Infrastructure;

/// <summary>
/// Minimalistic logger that does nothing.
/// </summary>
public class NullLogger : ILogger
{
/// <summary>
/// Returns an instance of <see cref="NullLogger" />.
/// </summary>
/// <returns> An instance of <see cref="NullLogger" />. </returns>
public static readonly NullLogger Instance = new();

/// <inheritdoc />
public IDisposable BeginScope<TState>(TState state)
where TState : notnull => NullScope.Instance;

/// <inheritdoc />
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, System.Exception exception,
Func<TState, System.Exception, string> formatter)
{
}

/// <inheritdoc />
public bool IsEnabled(LogLevel logLevel) => false;
}
23 changes: 23 additions & 0 deletions VkNet/Infrastructure/NullScope.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;

namespace VkNet.Infrastructure;

/// <summary>
/// An empty scope without any logic
/// </summary>
internal sealed class NullScope : IDisposable
{
/// <summary>
/// Initializes a new instance of the
/// </summary>
public static NullScope Instance { get; } = new();

private NullScope()
{
}

/// <inheritdoc />
public void Dispose()
{
}
}
14 changes: 10 additions & 4 deletions VkNet/Utils/CaptchaHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ public class CaptchaHandler : ICaptchaHandler
{
private readonly ICaptchaSolver _captchaSolver;

private readonly ILogger<CaptchaHandler> _logger;
private readonly ILogger _logger;

/// <inheritdoc cref="CaptchaHandler"/>
public CaptchaHandler(ILogger<CaptchaHandler> logger, ICaptchaSolver captchaSolver)
public CaptchaHandler(ILogger logger, ICaptchaSolver captchaSolver)
{
_logger = logger;
_captchaSolver = captchaSolver;
Expand Down Expand Up @@ -58,7 +58,10 @@ public T Perform<T>(Func<ulong?, string, T> action)
return result;
}

_logger?.LogError("Капча ни разу не была распознана верно");
if (_logger.IsEnabled(LogLevel.Error))
{
_logger.LogError("Капча ни разу не была распознана верно");
}

throw new CaptchaNeededException(new()
{
Expand All @@ -71,7 +74,10 @@ private void RepeatSolveCaptchaAsync(CaptchaNeededException captchaNeededExcepti
ref ulong? captchaSidTemp,
ref string captchaKeyTemp)
{
_logger?.LogWarning("Повторная обработка капчи");
if (_logger.IsEnabled(LogLevel.Warning))
{
_logger.LogWarning("Повторная обработка капчи");
}

if (numberOfRemainingAttemptsToSolveCaptcha < MaxCaptchaRecognitionCount)
{
Expand Down
16 changes: 12 additions & 4 deletions VkNet/Utils/RestClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ namespace VkNet.Utils;
[Serializable]
public sealed class RestClient : IRestClient
{
private readonly ILogger<RestClient> _logger;
private readonly ILogger _logger;

/// <inheritdoc cref="RestClient"/>
public RestClient(HttpClient httpClient, ILogger<RestClient> logger)
public RestClient(HttpClient httpClient, ILogger logger)
{
HttpClient = httpClient;
_logger = logger;
Expand All @@ -46,7 +46,10 @@ public Task<HttpResponse<string>> GetAsync(Uri uri, IEnumerable<KeyValuePair<str
{
var url = Url.Combine(uri.ToString(), Url.QueryFrom(parameters.ToArray()));

_logger?.LogDebug("GET request: {Url}", url);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("GET request: {Url}", url);
}

return CallAsync(() => HttpClient.GetAsync(new Uri(url), token), encoding, token);
}
Expand Down Expand Up @@ -103,7 +106,12 @@ private async Task<HttpResponse<string>> CallAsync(Func<Task<HttpResponseMessage
#endif

var content = encoding.GetString(bytes, 0, bytes.Length);
_logger?.LogDebug("Response:{NewLine}{PrettyJson}", Environment.NewLine, Utilities.PrettyPrintJson(content));

if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Response:{NewLine}{PrettyJson}", Environment.NewLine, Utilities.PrettyPrintJson(content));
}

var requestUri = response.RequestMessage?.RequestUri;

return response.IsSuccessStatusCode
Expand Down
4 changes: 2 additions & 2 deletions VkNet/Utils/TypeHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using VkNet.Abstractions.Authorization;
using VkNet.Abstractions.Core;
using VkNet.Abstractions.Utils;
Expand All @@ -30,7 +29,7 @@ public static void RegisterDefaultDependencies(this IServiceCollection container
{
container.TryAddSingleton<INeedValidationHandler, NeedValidationHandler>();
container.TryAddSingleton<HttpClient>();
container.TryAddSingleton(typeof(ILogger<>), typeof(NullLogger<>));
container.TryAddSingleton<ILogger>(_ => NullLogger.Instance);
container.TryAddSingleton<IRestClient, RestClient>();
container.TryAddSingleton<IWebProxy>(_ => null);
container.TryAddSingleton<IVkApiVersionManager, VkApiVersionManager>();
Expand All @@ -50,6 +49,7 @@ public static void RegisterDefaultDependencies(this IServiceCollection container
/// <typeparam name="T"> Тип ответа </typeparam>
/// <returns> Результат выполнения функции. </returns>
public static Task<T> TryInvokeMethodAsync<T>(Func<T> func, CancellationToken token = default) => Task.Run(func, token);

/// <summary>
/// Попытаться асинхронно выполнить метод.
/// </summary>
Expand Down
Loading

0 comments on commit 2d08df5

Please sign in to comment.