void.cat/VoidCat/Services/Files/LocalDiskFileMetadataStore.cs

73 lines
2.0 KiB
C#
Raw Normal View History

2022-02-08 18:20:59 +00:00
using Newtonsoft.Json;
using VoidCat.Model;
using VoidCat.Model.Exceptions;
2022-02-16 16:33:00 +00:00
using VoidCat.Services.Abstractions;
2022-02-08 18:20:59 +00:00
2022-02-22 14:20:31 +00:00
namespace VoidCat.Services.Files;
2022-02-08 18:20:59 +00:00
public class LocalDiskFileMetadataStore : IFileMetadataStore
{
2022-02-17 22:10:37 +00:00
private const string MetadataDir = "metadata-v3";
2022-02-22 14:20:31 +00:00
private readonly ILogger<LocalDiskFileMetadataStore> _logger;
2022-02-08 18:20:59 +00:00
private readonly VoidSettings _settings;
2022-02-22 14:20:31 +00:00
public LocalDiskFileMetadataStore(VoidSettings settings, ILogger<LocalDiskFileMetadataStore> logger)
2022-02-08 18:20:59 +00:00
{
_settings = settings;
2022-02-22 14:20:31 +00:00
_logger = logger;
2022-02-08 18:20:59 +00:00
var metaPath = Path.Combine(_settings.DataDirectory, MetadataDir);
if (!Directory.Exists(metaPath))
{
Directory.CreateDirectory(metaPath);
}
}
2022-02-22 14:20:31 +00:00
2022-02-27 13:54:25 +00:00
public ValueTask<TMeta?> Get<TMeta>(Guid id) where TMeta : VoidFileMeta
2022-02-08 18:20:59 +00:00
{
2022-02-27 13:54:25 +00:00
return GetMeta<TMeta>(id);
2022-02-08 18:20:59 +00:00
}
2022-02-22 14:20:31 +00:00
2022-02-17 15:52:49 +00:00
public async ValueTask Set(Guid id, SecretVoidFileMeta meta)
2022-02-08 18:20:59 +00:00
{
2022-02-17 15:52:49 +00:00
var path = MapMeta(id);
2022-02-08 18:20:59 +00:00
var json = JsonConvert.SerializeObject(meta);
2022-02-16 16:33:00 +00:00
await File.WriteAllTextAsync(path, json);
2022-02-08 18:20:59 +00:00
}
2022-02-22 14:20:31 +00:00
2022-02-17 15:52:49 +00:00
public async ValueTask Update(Guid id, SecretVoidFileMeta patch)
2022-02-08 18:20:59 +00:00
{
2022-02-27 13:54:25 +00:00
var oldMeta = await Get<SecretVoidFileMeta>(id);
2022-02-17 15:52:49 +00:00
if (oldMeta?.EditSecret != patch.EditSecret)
2022-02-08 18:20:59 +00:00
{
throw new VoidNotAllowedException("Edit secret incorrect");
}
2022-02-17 15:52:49 +00:00
await Set(id, patch);
2022-02-08 18:20:59 +00:00
}
2022-02-22 14:20:31 +00:00
public ValueTask Delete(Guid id)
{
var path = MapMeta(id);
if (File.Exists(path))
{
_logger.LogInformation("Deleting metadata file {Path}", path);
File.Delete(path);
}
return ValueTask.CompletedTask;
}
2022-02-17 22:48:34 +00:00
private async ValueTask<TMeta?> GetMeta<TMeta>(Guid id)
{
var path = MapMeta(id);
if (!File.Exists(path)) return default;
var json = await File.ReadAllTextAsync(path);
return JsonConvert.DeserializeObject<TMeta>(json);
}
2022-02-22 14:20:31 +00:00
2022-02-08 18:20:59 +00:00
private string MapMeta(Guid id) =>
Path.ChangeExtension(Path.Join(_settings.DataDirectory, MetadataDir, id.ToString()), ".json");
2022-02-27 13:54:25 +00:00
}