67 lines
2.4 KiB
C#
67 lines
2.4 KiB
C#
using System.Net;
|
|
using Flurl.Http;
|
|
using Microsoft.Extensions.Logging;
|
|
using Piwigo.Client.Contract;
|
|
|
|
namespace Piwigo.Client;
|
|
|
|
internal class SessionApi : ISessionApi
|
|
{
|
|
private readonly IPiwigoContext _context;
|
|
private readonly ILogger<SessionApi> _logger;
|
|
|
|
public SessionApi(IPiwigoContext context, ILogger<SessionApi> logger)
|
|
{
|
|
_context = context ?? throw new ArgumentNullException(nameof(context));
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
}
|
|
|
|
public async Task LogoutAsync()
|
|
{
|
|
_logger.LogInformation("Logging out from {Uri}", _context.Config.BaseUri);
|
|
await _context.ConfigureRequest(_logger).PostMultipartAsync(c => c.AddMethod("pwg.session.logout"));
|
|
_context.LoggedOut();
|
|
}
|
|
|
|
public async Task LoginAsync()
|
|
{
|
|
var userName = _context.Config.UserName;
|
|
if (string.IsNullOrWhiteSpace(userName))
|
|
{
|
|
throw new ArgumentException("Value cannot be null or whitespace.", nameof(userName));
|
|
}
|
|
|
|
var password = _context.Config.Password;
|
|
if (string.IsNullOrWhiteSpace(password))
|
|
{
|
|
throw new ArgumentException("Value cannot be null or whitespace.", nameof(password));
|
|
}
|
|
|
|
if (_context.IsLoggedIn)
|
|
{
|
|
throw new PiwigoException("The client is already logged in. Create a new instance or log out first!");
|
|
}
|
|
|
|
_logger.LogInformation("Logging into {PiwigoBaseUri} using username {Username}", _context.Config.BaseUri, userName);
|
|
|
|
var response = await _context.ConfigureRequest(_logger, false).PostMultipartAsync(c =>
|
|
c.AddMethod("pwg.session.login").AddString("username", userName).AddString("password", password));
|
|
|
|
if (response.StatusCode != (int)HttpStatusCode.OK)
|
|
{
|
|
_logger.LogError("Failed to log in {StatusCode}", response.StatusCode);
|
|
throw new PiwigoException($"Could not log in to {_context.Config.BaseUri} using username {userName}");
|
|
}
|
|
|
|
_logger.LogInformation("Logging in succeeded");
|
|
_context.LoggedIn();
|
|
}
|
|
|
|
public async Task<PiwigoStatus> GetStatusAsync()
|
|
{
|
|
_logger.LogInformation("Getting status");
|
|
var response = await _context.ConfigureRequest(_logger).PostMultipartAsync(c => c.AddMethod("pwg.session.getStatus"));
|
|
var typedResponse = await response.GetJsonAsync<PiwigoResponse<PiwigoStatus>>();
|
|
return typedResponse.Result;
|
|
}
|
|
} |