From 03f1669d98e1fad81bc4832900ae149ac6510ebc Mon Sep 17 00:00:00 2001 From: Rory& Date: Mon, 29 Jul 2024 22:45:36 +0200 Subject: Initial commit --- ModerationClient/Services/FileStorageProvider.cs | 54 ++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 ModerationClient/Services/FileStorageProvider.cs (limited to 'ModerationClient/Services/FileStorageProvider.cs') diff --git a/ModerationClient/Services/FileStorageProvider.cs b/ModerationClient/Services/FileStorageProvider.cs new file mode 100644 index 0000000..3658369 --- /dev/null +++ b/ModerationClient/Services/FileStorageProvider.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; +using ArcaneLibs.Extensions; +using LibMatrix.Extensions; +using LibMatrix.Interfaces.Services; +using Microsoft.Extensions.Logging; + +namespace MatrixUtils.Abstractions; + +public class FileStorageProvider : IStorageProvider { + private readonly ILogger _logger; + + public string TargetPath { get; } + + /// + /// Creates a new instance of . + /// + /// + public FileStorageProvider(string targetPath) { + // new Logger(new LoggerFactory()).LogInformation("test"); + Console.WriteLine($"Initialised FileStorageProvider with path {targetPath}"); + TargetPath = targetPath; + if (!Directory.Exists(targetPath)) { + Directory.CreateDirectory(targetPath); + } + } + + public async Task SaveObjectAsync(string key, T value) => await File.WriteAllTextAsync(Path.Join(TargetPath, key), value?.ToJson()); + + [RequiresUnreferencedCode("This API uses reflection to deserialize JSON")] + public async Task LoadObjectAsync(string key) => JsonSerializer.Deserialize(await File.ReadAllTextAsync(Path.Join(TargetPath, key))); + + public Task ObjectExistsAsync(string key) => Task.FromResult(File.Exists(Path.Join(TargetPath, key))); + + public Task> GetAllKeysAsync() => Task.FromResult(Directory.GetFiles(TargetPath).Select(Path.GetFileName).ToList()); + + public Task DeleteObjectAsync(string key) { + File.Delete(Path.Join(TargetPath, key)); + return Task.CompletedTask; + } + + public async Task SaveStreamAsync(string key, Stream stream) { + Directory.CreateDirectory(Path.GetDirectoryName(Path.Join(TargetPath, key)) ?? throw new InvalidOperationException()); + await using var fileStream = File.Create(Path.Join(TargetPath, key)); + await stream.CopyToAsync(fileStream); + } + + public Task LoadStreamAsync(string key) => Task.FromResult(File.Exists(Path.Join(TargetPath, key)) ? File.OpenRead(Path.Join(TargetPath, key)) : null); +} -- cgit 1.5.1