WIP: upload file extension methods to make usages easier
All checks were successful
piwigodotnet/pipeline/head This commit looks good

This commit is contained in:
Philipp Häfelfinger 2022-11-16 00:22:55 +01:00
parent efaa7442c8
commit 326b76b54b
2 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1,16 @@
using System.Security.Cryptography;
namespace Piwigo.Client;
public static class FileInfoExtensions
{
public static async Task<string> CalculateMd5SumAsync(this FileInfo file, CancellationToken cancellationToken)
{
using var md5 = MD5.Create();
await using var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
var hash = await md5.ComputeHashAsync(stream, cancellationToken);
return BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
}
}

View File

@ -0,0 +1,49 @@
using Piwigo.Client.Images;
namespace Piwigo.Client;
public static class PiwigoClientExtensions
{
public static async Task<ImageUploaded> UploadImageAsync(this IPiwigoClient client, FileInfo imageToUpload, string? md5Sum, CancellationToken cancellationToken = default)
{
if (client == null)
{
throw new ArgumentNullException(nameof(client));
}
if (!imageToUpload.Exists)
{
throw new PiwigoException($"Could not find file {imageToUpload.FullName}");
}
var supportedFileTypes = await client.Session.GetSupportedFileTypes(cancellationToken);
if (!supportedFileTypes.Contains(imageToUpload.Extension.ToLower()))
{
throw new PiwigoException(
$"The file {imageToUpload.Name} has extension {imageToUpload.Extension} which is not supported by the connected piwigo server. Please use one of the following formats {string.Join(",", supportedFileTypes)}");
}
var uploadMd5 = md5Sum ?? await imageToUpload.CalculateMd5SumAsync(cancellationToken);
await UploadChunksAsync(client, imageToUpload, uploadMd5, cancellationToken);
return await client.Image.AddAsync(new ImageUpload(uploadMd5), cancellationToken);
}
private static async Task UploadChunksAsync(IPiwigoClient client, FileInfo imageToUpload, string uploadMd5, CancellationToken cancellationToken)
{
var chunkSizeInKiB = await client.Session.GetUploadChunkSizeAsync(cancellationToken);
await using var file = imageToUpload.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
var buffer = new byte[chunkSizeInKiB * 1024];
var totalChunks = (int)imageToUpload.Length / buffer.Length + 1;
var currentChunk = 0;
while (currentChunk < totalChunks)
{
var readBytes = await file.ReadAsync(buffer, cancellationToken);
await client.Image.AddChunkAsync(uploadMd5, currentChunk, buffer[..readBytes], cancellationToken);
currentChunk++;
}
}
}