69 lines
2.0 KiB
C#
69 lines
2.0 KiB
C#
using System.Net;
|
|
using System.Runtime.CompilerServices;
|
|
using Flurl;
|
|
using Flurl.Http;
|
|
|
|
namespace Piwigo.Client;
|
|
|
|
public class PiwigoClient : IPiwigoClient
|
|
{
|
|
private CookieJar _cookies = new();
|
|
private string _piwigoBaseUri = null!;
|
|
public bool IsLoggedIn { get; private set; }
|
|
public int ChunkSize { get; set; } = 512;
|
|
private IFlurlRequest Request => _piwigoBaseUri.WithCookies(_cookies);
|
|
|
|
public async Task LoginAsync(Uri uri, string username, string password)
|
|
{
|
|
if (uri == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(uri));
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(username))
|
|
{
|
|
throw new ArgumentException("Value cannot be null or whitespace.", nameof(username));
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(password))
|
|
{
|
|
throw new ArgumentException("Value cannot be null or whitespace.", nameof(password));
|
|
}
|
|
|
|
if (IsLoggedIn)
|
|
{
|
|
throw new PiwigoException("The client is already logged in. Create a new instance or log out first!");
|
|
}
|
|
|
|
_piwigoBaseUri = uri.AppendPathSegment("ws.php").SetQueryParam("format", "json");
|
|
|
|
var response = await _piwigoBaseUri.WithCookies(out var cookieJar).PostMultipartAsync(c =>
|
|
c.PiwigoLogin(username, password));
|
|
|
|
if (response.StatusCode != (int)HttpStatusCode.OK)
|
|
{
|
|
throw new PiwigoException($"Could not log in to {_piwigoBaseUri} using username {username}");
|
|
}
|
|
|
|
_cookies = cookieJar;
|
|
IsLoggedIn = true;
|
|
}
|
|
|
|
public async Task Logout()
|
|
{
|
|
EnsureLoggedIn();
|
|
|
|
await Request.PostMultipartAsync(c => c.PiwigoLogout());
|
|
|
|
IsLoggedIn = false;
|
|
_cookies.Clear();
|
|
}
|
|
|
|
private void EnsureLoggedIn([CallerMemberName] string? callerName = null)
|
|
{
|
|
if (!IsLoggedIn)
|
|
{
|
|
throw new InvalidOperationException($"Could not execute {callerName} as the client is not logged in.");
|
|
}
|
|
}
|
|
} |