80 lines
3.0 KiB
C#
80 lines
3.0 KiB
C#
using System.Collections.ObjectModel;
|
|
using Microsoft.Extensions.Logging;
|
|
using Piwigo.Client.Contract;
|
|
|
|
namespace Piwigo.Client;
|
|
|
|
internal static class DictionaryExtensions
|
|
{
|
|
public static IDictionary<string, string> AddIfValueNotNull(this IDictionary<string, string> dictionary, string key, string? value)
|
|
{
|
|
if (dictionary == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(dictionary));
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(key))
|
|
{
|
|
throw new ArgumentException("Value cannot be null or whitespace.", nameof(key));
|
|
}
|
|
|
|
if (value is not null)
|
|
{
|
|
dictionary.Add(key, value);
|
|
}
|
|
|
|
return dictionary;
|
|
}
|
|
}
|
|
|
|
public class CategoryApi : ICategoryApi
|
|
{
|
|
private readonly IPiwigoContext _context;
|
|
private readonly ILogger<CategoryApi> _logger;
|
|
|
|
public CategoryApi(IPiwigoContext context, ILogger<CategoryApi> logger)
|
|
{
|
|
_context = context ?? throw new ArgumentNullException(nameof(context));
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
}
|
|
|
|
public async Task<int> AddAsync(string name, int? parentId = null, string? comment = null, bool? visible = null, CategoryStatus? status = null, bool? commentable = null,
|
|
CategoryPosition? position = null)
|
|
{
|
|
var statusValue = status switch
|
|
{
|
|
CategoryStatus.Public => "public",
|
|
CategoryStatus.Private => "private",
|
|
null => null,
|
|
_ => throw new ArgumentOutOfRangeException(nameof(status), status, null)
|
|
};
|
|
|
|
var positionValue = position switch
|
|
{
|
|
CategoryPosition.First => "first",
|
|
CategoryPosition.Last => "last",
|
|
null => null,
|
|
_ => throw new ArgumentOutOfRangeException(nameof(position), position, null)
|
|
};
|
|
|
|
var formParams = new Dictionary<string, string> { { "name", name } };
|
|
formParams.AddIfValueNotNull("parent", parentId?.ToString()).AddIfValueNotNull("comment", comment).AddIfValueNotNull("visible", visible?.ToString())
|
|
.AddIfValueNotNull("status", statusValue).AddIfValueNotNull("commentable", visible?.ToString()).AddIfValueNotNull("position", positionValue);
|
|
|
|
var response = await _context.PostAsync<PiwigoResponse<AlbumAdded>>(_logger, "pwg.categories.add", formParams);
|
|
if (!response.Result.Id.HasValue)
|
|
{
|
|
throw new PiwigoException($"Could not create album {name}: {response.Result.Info}");
|
|
}
|
|
|
|
return response.Result.Id.Value;
|
|
}
|
|
|
|
public async Task<IReadOnlyCollection<PiwigoCategory>> GetAllAsync()
|
|
{
|
|
_logger.LogInformation("Getting all existing categories from server");
|
|
var formParams = new Dictionary<string, string> { { "recursive", "true" } };
|
|
var response = await _context.PostAsync<PiwigoResponse<PiwigoCategoryList>>(_logger, "pwg.categories.getList", formParams);
|
|
return new ReadOnlyCollection<PiwigoCategory>(response.Result.Categories);
|
|
}
|
|
} |