54 lines
1.6 KiB
C#
54 lines
1.6 KiB
C#
|
using Flurl.Http;
|
||
|
using Microsoft.Extensions.Logging;
|
||
|
|
||
|
namespace Piwigo.Client;
|
||
|
|
||
|
public class PiwigoContext : IPiwigoContext
|
||
|
{
|
||
|
private readonly CookieJar _cookies = new();
|
||
|
private readonly ILogger<PiwigoContext> _logger;
|
||
|
|
||
|
public PiwigoContext(IPiwigoConfiguration configuration, ILogger<PiwigoContext> logger)
|
||
|
{
|
||
|
Config = configuration ?? throw new ArgumentNullException(nameof(configuration));
|
||
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||
|
}
|
||
|
|
||
|
public IPiwigoConfiguration Config { get; }
|
||
|
|
||
|
public bool IsLoggedIn { get; private set; }
|
||
|
|
||
|
public IFlurlRequest ConfigureRequest(ILogger logger, bool requireLogin = true)
|
||
|
{
|
||
|
if (logger == null)
|
||
|
{
|
||
|
throw new ArgumentNullException(nameof(logger));
|
||
|
}
|
||
|
|
||
|
if (requireLogin && !IsLoggedIn)
|
||
|
{
|
||
|
throw new InvalidOperationException("User is not logged in. Ensure login is called before accessing any piwigo methods");
|
||
|
}
|
||
|
|
||
|
return Config.BaseUri.WithCookies(_cookies).ConfigureRequest(r => r.AfterCallAsync = call => LogResponse(call, logger));
|
||
|
}
|
||
|
|
||
|
public void LoggedOut()
|
||
|
{
|
||
|
_logger.LogInformation("logged out, clearing cookies");
|
||
|
IsLoggedIn = false;
|
||
|
_cookies.Clear();
|
||
|
}
|
||
|
|
||
|
public void LoggedIn()
|
||
|
{
|
||
|
_logger.LogInformation("logged in");
|
||
|
IsLoggedIn = true;
|
||
|
}
|
||
|
|
||
|
private static async Task LogResponse(FlurlCall call, ILogger logger)
|
||
|
{
|
||
|
var responseString = await call.Response.GetStringAsync();
|
||
|
logger.LogDebug("PiwigoResponse: {Response}", responseString);
|
||
|
}
|
||
|
}
|