makes get status work and adds debug logging of responses

This commit is contained in:
Philipp Häfelfinger 2022-10-07 13:43:19 +02:00
parent 3bf56c7ee7
commit 06dd6548cf
10 changed files with 150 additions and 11 deletions

View File

@ -1,23 +1,30 @@
using System.Text.Json;
using Flurl.Http.Testing; using Flurl.Http.Testing;
using Microsoft.Extensions.Logging.Abstractions;
namespace Piwigo.Client.Tests; namespace Piwigo.Client.Tests;
[TestFixture]
public class PiwigoClientTests public class PiwigoClientTests
{ {
private const string TestUri = "http://localhost:8080/ws.php?format=json";
private const string Username = "admin";
private const string Password = "admin";
private PiwigoClient _piwigoClient = null!; private PiwigoClient _piwigoClient = null!;
private HttpTest _httpTest = null!; private HttpTest? _httpTest;
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
_piwigoClient = new PiwigoClient(); _piwigoClient = new PiwigoClient(new NullLogger<PiwigoClient>());
_httpTest = new HttpTest(); _httpTest = new HttpTest();
} }
[TearDown] [TearDown]
public void TearDown() public void TearDown()
{ {
_httpTest.Dispose(); _httpTest?.Dispose();
} }
[Test] [Test]
@ -26,20 +33,45 @@ public class PiwigoClientTests
await LoginAsync(); await LoginAsync();
} }
[Test]
public async Task GetStatus_should_return_config()
{
await LoginAsync();
var expectedResponse = new PiwigoResponse<PiwigoStatus>
{
Status = "OK",
Result = new PiwigoStatus
{
Username = "admin",
Version = "12.0.0"
}
};
var jsonResponse = JsonSerializer.Serialize(expectedResponse);
_httpTest?.RespondWith(jsonResponse);
var status = await _piwigoClient.GetStatusAsync();
status.Should().NotBeNull();
status.Username.Should().Be("admin");
status.Version.Should().NotBeEmpty();
}
[Test] [Test]
public async Task Logout_should_set_IsLoggedIn_to_false() public async Task Logout_should_set_IsLoggedIn_to_false()
{ {
await LoginAsync(); await LoginAsync();
_httpTest.RespondWith("OK"); _httpTest?.RespondWith("OK");
await _piwigoClient.Logout(); await _piwigoClient.LogoutAsync();
_piwigoClient.IsLoggedIn.Should().BeFalse(); _piwigoClient.IsLoggedIn.Should().BeFalse();
} }
private async Task LoginAsync() private async Task LoginAsync()
{ {
_httpTest.RespondWith("OK", 200, cookies: new { pwg_id = "pwg_id" }); _httpTest?.RespondWith("{}", 200, cookies: new { pwg_id = "pwg_id" });
await _piwigoClient.LoginAsync(new Uri("http://localhost:8080/foo/bar/ws.php?format=json"), "admin", "admin"); await _piwigoClient.LoginAsync(new Uri(TestUri), Username, Password);
_piwigoClient.IsLoggedIn.Should().BeTrue(); _piwigoClient.IsLoggedIn.Should().BeTrue();
} }
} }

View File

@ -0,0 +1,14 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"System": "Warning",
"Microsoft": "Warning"
},
"Debug": {
"LogLevel": {
"Default": "Debug"
}
}
}
}

View File

@ -0,0 +1,3 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Piwigo.Client.Tests")]

View File

@ -5,5 +5,6 @@ public interface IPiwigoClient
bool IsLoggedIn { get; } bool IsLoggedIn { get; }
int ChunkSize { get; set; } int ChunkSize { get; set; }
Task LoginAsync(Uri uri, string username, string password); Task LoginAsync(Uri uri, string username, string password);
Task Logout(); Task LogoutAsync();
Task<PiwigoStatus> GetStatusAsync();
} }

View File

@ -1,7 +1,9 @@
using System.Diagnostics;
using System.Net; using System.Net;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Flurl; using Flurl;
using Flurl.Http; using Flurl.Http;
using Microsoft.Extensions.Logging;
namespace Piwigo.Client; namespace Piwigo.Client;
@ -11,7 +13,14 @@ public class PiwigoClient : IPiwigoClient
private string _piwigoBaseUri = null!; private string _piwigoBaseUri = null!;
public bool IsLoggedIn { get; private set; } public bool IsLoggedIn { get; private set; }
public int ChunkSize { get; set; } = 512; public int ChunkSize { get; set; } = 512;
private IFlurlRequest Request => _piwigoBaseUri.WithCookies(_cookies); private IFlurlRequest Request => _piwigoBaseUri.WithCookies(_cookies).ConfigureRequest(r => r.AfterCallAsync = LogResponse);
private readonly ILogger<PiwigoClient> _logger;
public PiwigoClient(ILogger<PiwigoClient> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task LoginAsync(Uri uri, string username, string password) public async Task LoginAsync(Uri uri, string username, string password)
{ {
@ -37,28 +46,43 @@ public class PiwigoClient : IPiwigoClient
_piwigoBaseUri = uri.AppendPathSegment("ws.php").SetQueryParam("format", "json"); _piwigoBaseUri = uri.AppendPathSegment("ws.php").SetQueryParam("format", "json");
_logger.LogInformation("Logging into {PiwigoBaseUri} using username {Username}", _piwigoBaseUri, username);
var response = await _piwigoBaseUri.WithCookies(out var cookieJar).PostMultipartAsync(c => var response = await _piwigoBaseUri.WithCookies(out var cookieJar).PostMultipartAsync(c =>
c.PiwigoLogin(username, password)); c.PiwigoLogin(username, password));
if (response.StatusCode != (int)HttpStatusCode.OK) if (response.StatusCode != (int)HttpStatusCode.OK)
{ {
_logger.LogError("Failed to log in {StatusCode}", response.StatusCode);
throw new PiwigoException($"Could not log in to {_piwigoBaseUri} using username {username}"); throw new PiwigoException($"Could not log in to {_piwigoBaseUri} using username {username}");
} }
_logger.LogInformation("Logging in succeeded");
_cookies = cookieJar; _cookies = cookieJar;
IsLoggedIn = true; IsLoggedIn = true;
} }
public async Task Logout() public async Task LogoutAsync()
{ {
EnsureLoggedIn(); EnsureLoggedIn();
_logger.LogInformation("Logging out from {Uri}", _piwigoBaseUri);
await Request.PostMultipartAsync(c => c.PiwigoLogout()); await Request.PostMultipartAsync(c => c.PiwigoLogout());
IsLoggedIn = false; IsLoggedIn = false;
_cookies.Clear(); _cookies.Clear();
} }
public async Task<PiwigoStatus> GetStatusAsync()
{
EnsureLoggedIn();
_logger.LogInformation("Getting status");
var response = await Request.PostMultipartAsync(c => c.PiwigoGetStatus());
var typedResponse = await response.GetJsonAsync<PiwigoResponse<PiwigoStatus>>();
return typedResponse.Result;
}
private void EnsureLoggedIn([CallerMemberName] string? callerName = null) private void EnsureLoggedIn([CallerMemberName] string? callerName = null)
{ {
if (!IsLoggedIn) if (!IsLoggedIn)
@ -66,4 +90,10 @@ public class PiwigoClient : IPiwigoClient
throw new InvalidOperationException($"Could not execute {callerName} as the client is not logged in."); throw new InvalidOperationException($"Could not execute {callerName} as the client is not logged in.");
} }
} }
private async Task LogResponse(FlurlCall call)
{
var responseString = await call.Response.GetStringAsync();
_logger.LogDebug("PiwigoResponse: {Response}", responseString);
}
} }

View File

@ -14,4 +14,9 @@ internal static class PiwigoMethods
{ {
return part.AddMethod("pwg.session.logout"); return part.AddMethod("pwg.session.logout");
} }
public static CapturedMultipartContent PiwigoGetStatus(this CapturedMultipartContent part)
{
return part.AddMethod("pwg.session.getStatus");
}
} }

View File

@ -0,0 +1,12 @@
using Newtonsoft.Json;
namespace Piwigo.Client;
internal class PiwigoResponse<T>
{
[JsonProperty("stat")]
public string? Status { get; init; }
[JsonProperty("result")]
public T Result { get; init; } = default!;
}

View File

@ -0,0 +1,39 @@
using Newtonsoft.Json;
namespace Piwigo.Client;
public class PiwigoStatus
{
[JsonProperty("username")]
public string? Username { get; init; }
[JsonProperty("status")]
public string? Status { get; init; }
[JsonProperty("theme")]
public string? Theme { get; init; }
[JsonProperty("language")]
public string? Language { get; init; }
[JsonProperty("pwg_token")]
public string? PwgToken { get; init; }
[JsonProperty("charset")]
public string? Charset { get; init; }
[JsonProperty("current_datetime")]
public string? CurrentDatetime { get; init; }
[JsonProperty("version")]
public string? Version { get; init; }
[JsonProperty("available_sizes")]
public string[]? AvailableSizes { get; init; }
[JsonProperty("upload_file_types")]
public string? UploadFileTypes { get; init; }
[JsonProperty("upload_form_chunk_size")]
public int UploadFormChunkSize { get; init; } = 512;
}

View File

@ -3,4 +3,7 @@
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_FOREACH/@EntryValue">Required</s:String> <s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_FOREACH/@EntryValue">Required</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_IFELSE/@EntryValue">Required</s:String> <s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_IFELSE/@EntryValue">Required</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_WHILE/@EntryValue">Required</s:String> <s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_WHILE/@EntryValue">Required</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_ACCESSOR_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_ACCESSORHOLDER_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_LIMIT/@EntryValue">180</s:Int64>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Piwigo/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary> <s:Boolean x:Key="/Default/UserDictionary/Words/=Piwigo/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>