2023-07-09 16:32:14 +03:00
|
|
|
using System.Collections.Concurrent;
|
|
|
|
using System.Text.Json;
|
2023-07-18 15:25:02 +03:00
|
|
|
using System.Text.Json.Nodes;
|
2023-07-09 16:32:14 +03:00
|
|
|
using Microsoft.Extensions.Hosting;
|
2023-08-22 10:44:05 +03:00
|
|
|
using Microsoft.Extensions.Logging;
|
2023-09-30 16:58:32 +03:00
|
|
|
using Octobot.Data;
|
2023-07-09 16:32:14 +03:00
|
|
|
using Remora.Rest.Core;
|
|
|
|
|
2023-09-30 16:58:32 +03:00
|
|
|
namespace Octobot.Services;
|
2023-07-09 16:32:14 +03:00
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Handles saving, loading, initializing and providing <see cref="GuildData" />.
|
|
|
|
/// </summary>
|
2023-12-20 20:08:56 +03:00
|
|
|
public sealed class GuildDataService : BackgroundService
|
2023-08-02 23:51:16 +03:00
|
|
|
{
|
2023-07-09 16:32:14 +03:00
|
|
|
private readonly ConcurrentDictionary<Snowflake, GuildData> _datas = new();
|
2023-08-22 10:44:05 +03:00
|
|
|
private readonly ILogger<GuildDataService> _logger;
|
2023-07-09 16:32:14 +03:00
|
|
|
|
2023-12-20 20:08:56 +03:00
|
|
|
public GuildDataService(ILogger<GuildDataService> logger)
|
2023-08-02 23:51:16 +03:00
|
|
|
{
|
2023-08-22 10:44:05 +03:00
|
|
|
_logger = logger;
|
2023-07-09 16:32:14 +03:00
|
|
|
}
|
|
|
|
|
2023-12-20 20:08:56 +03:00
|
|
|
public override Task StopAsync(CancellationToken ct)
|
2023-08-02 23:51:16 +03:00
|
|
|
{
|
2023-12-20 20:08:56 +03:00
|
|
|
base.StopAsync(ct);
|
|
|
|
return SaveAsync(ct);
|
2023-07-09 16:32:14 +03:00
|
|
|
}
|
|
|
|
|
2023-12-20 20:08:56 +03:00
|
|
|
private Task SaveAsync(CancellationToken ct)
|
2023-08-02 23:51:16 +03:00
|
|
|
{
|
2023-07-09 16:32:14 +03:00
|
|
|
var tasks = new List<Task>();
|
2023-09-12 16:28:46 +03:00
|
|
|
var datas = _datas.Values.ToArray();
|
2023-10-26 18:14:27 +03:00
|
|
|
foreach (var data in datas.Where(data => !data.DataLoadFailed))
|
2023-08-02 23:51:16 +03:00
|
|
|
{
|
2023-10-26 18:14:27 +03:00
|
|
|
tasks.Add(SerializeObjectSafelyAsync(data.Settings, data.SettingsPath, ct));
|
|
|
|
tasks.Add(SerializeObjectSafelyAsync(data.ScheduledEvents, data.ScheduledEventsPath, ct));
|
2023-07-09 16:32:14 +03:00
|
|
|
|
2023-09-12 16:28:46 +03:00
|
|
|
var memberDatas = data.MemberData.Values.ToArray();
|
2023-10-26 18:14:27 +03:00
|
|
|
tasks.AddRange(memberDatas.Select(memberData =>
|
|
|
|
SerializeObjectSafelyAsync(memberData, $"{data.MemberDataPath}/{memberData.Id}.json", ct)));
|
2023-07-09 16:32:14 +03:00
|
|
|
}
|
|
|
|
|
2023-12-05 22:24:55 +03:00
|
|
|
return Task.WhenAll(tasks);
|
2023-07-09 16:32:14 +03:00
|
|
|
}
|
|
|
|
|
2023-10-26 18:14:27 +03:00
|
|
|
private static async Task SerializeObjectSafelyAsync<T>(T obj, string path, CancellationToken ct)
|
|
|
|
{
|
|
|
|
var tempFilePath = path + ".tmp";
|
|
|
|
await using (var tempFileStream = File.Create(tempFilePath))
|
|
|
|
{
|
|
|
|
await JsonSerializer.SerializeAsync(tempFileStream, obj, cancellationToken: ct);
|
|
|
|
}
|
|
|
|
|
|
|
|
File.Copy(tempFilePath, path, true);
|
|
|
|
File.Delete(tempFilePath);
|
|
|
|
}
|
|
|
|
|
2023-12-20 20:08:56 +03:00
|
|
|
protected override async Task ExecuteAsync(CancellationToken ct)
|
|
|
|
{
|
|
|
|
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
|
|
|
|
|
|
|
|
while (await timer.WaitForNextTickAsync(ct))
|
|
|
|
{
|
|
|
|
await SaveAsync(ct);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-02 23:51:16 +03:00
|
|
|
public async Task<GuildData> GetData(Snowflake guildId, CancellationToken ct = default)
|
|
|
|
{
|
2023-07-09 16:32:14 +03:00
|
|
|
return _datas.TryGetValue(guildId, out var data) ? data : await InitializeData(guildId, ct);
|
|
|
|
}
|
|
|
|
|
2023-08-02 23:51:16 +03:00
|
|
|
private async Task<GuildData> InitializeData(Snowflake guildId, CancellationToken ct = default)
|
|
|
|
{
|
2023-09-22 15:33:14 +03:00
|
|
|
var path = $"GuildData/{guildId}";
|
|
|
|
var memberDataPath = $"{path}/MemberData";
|
|
|
|
var settingsPath = $"{path}/Settings.json";
|
|
|
|
var scheduledEventsPath = $"{path}/ScheduledEvents.json";
|
|
|
|
|
|
|
|
MigrateGuildData(guildId, path);
|
|
|
|
|
|
|
|
Directory.CreateDirectory(path);
|
2023-08-02 23:51:16 +03:00
|
|
|
|
|
|
|
if (!File.Exists(settingsPath))
|
|
|
|
{
|
|
|
|
await File.WriteAllTextAsync(settingsPath, "{}", ct);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!File.Exists(scheduledEventsPath))
|
|
|
|
{
|
|
|
|
await File.WriteAllTextAsync(scheduledEventsPath, "{}", ct);
|
|
|
|
}
|
2023-07-09 16:32:14 +03:00
|
|
|
|
2023-10-26 18:14:27 +03:00
|
|
|
var dataLoadFailed = false;
|
|
|
|
|
2023-07-18 15:25:02 +03:00
|
|
|
await using var settingsStream = File.OpenRead(settingsPath);
|
2023-10-26 18:14:27 +03:00
|
|
|
JsonNode? jsonSettings = null;
|
|
|
|
try
|
|
|
|
{
|
2023-11-22 12:27:55 +03:00
|
|
|
jsonSettings = await JsonNode.ParseAsync(settingsStream, cancellationToken: ct);
|
2023-10-26 18:14:27 +03:00
|
|
|
}
|
|
|
|
catch (Exception e)
|
|
|
|
{
|
|
|
|
_logger.LogError(e, "Guild settings load failed: {Path}", settingsPath);
|
|
|
|
dataLoadFailed = true;
|
|
|
|
}
|
2023-07-09 16:32:14 +03:00
|
|
|
|
|
|
|
await using var eventsStream = File.OpenRead(scheduledEventsPath);
|
2023-10-26 18:14:27 +03:00
|
|
|
Dictionary<ulong, ScheduledEventData>? events = null;
|
|
|
|
try
|
|
|
|
{
|
|
|
|
events = await JsonSerializer.DeserializeAsync<Dictionary<ulong, ScheduledEventData>>(
|
2023-07-09 16:32:14 +03:00
|
|
|
eventsStream, cancellationToken: ct);
|
2023-10-26 18:14:27 +03:00
|
|
|
}
|
|
|
|
catch (Exception e)
|
|
|
|
{
|
|
|
|
_logger.LogError(e, "Guild scheduled events load failed: {Path}", scheduledEventsPath);
|
|
|
|
dataLoadFailed = true;
|
|
|
|
}
|
2023-07-09 16:32:14 +03:00
|
|
|
|
|
|
|
var memberData = new Dictionary<ulong, MemberData>();
|
2023-08-04 16:52:54 +03:00
|
|
|
foreach (var dataFileInfo in Directory.CreateDirectory(memberDataPath).GetFiles())
|
2023-08-02 23:51:16 +03:00
|
|
|
{
|
2023-08-04 16:52:54 +03:00
|
|
|
await using var dataStream = dataFileInfo.OpenRead();
|
2023-10-26 18:14:27 +03:00
|
|
|
MemberData? data;
|
|
|
|
try
|
|
|
|
{
|
|
|
|
data = await JsonSerializer.DeserializeAsync<MemberData>(dataStream, cancellationToken: ct);
|
|
|
|
}
|
|
|
|
catch (Exception e)
|
|
|
|
{
|
|
|
|
_logger.LogError(e, "Member data load failed: {MemberDataPath}/{FileName}", memberDataPath,
|
|
|
|
dataFileInfo.Name);
|
|
|
|
dataLoadFailed = true;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2023-08-02 23:51:16 +03:00
|
|
|
if (data is null)
|
|
|
|
{
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2023-07-09 16:32:14 +03:00
|
|
|
memberData.Add(data.Id, data);
|
|
|
|
}
|
|
|
|
|
|
|
|
var finalData = new GuildData(
|
2023-07-18 15:25:02 +03:00
|
|
|
jsonSettings ?? new JsonObject(), settingsPath,
|
2023-08-22 10:44:05 +03:00
|
|
|
events ?? new Dictionary<ulong, ScheduledEventData>(), scheduledEventsPath,
|
2023-10-26 18:14:27 +03:00
|
|
|
memberData, memberDataPath,
|
|
|
|
dataLoadFailed);
|
2023-08-04 16:52:54 +03:00
|
|
|
|
|
|
|
_datas.TryAdd(guildId, finalData);
|
2023-08-02 23:51:16 +03:00
|
|
|
|
2023-07-09 16:32:14 +03:00
|
|
|
return finalData;
|
|
|
|
}
|
|
|
|
|
2023-09-22 15:33:14 +03:00
|
|
|
private void MigrateGuildData(Snowflake guildId, string newPath)
|
|
|
|
{
|
|
|
|
var oldPath = $"{guildId}";
|
|
|
|
|
|
|
|
if (Directory.Exists(oldPath))
|
|
|
|
{
|
|
|
|
Directory.CreateDirectory($"{newPath}/..");
|
|
|
|
Directory.Move(oldPath, newPath);
|
|
|
|
|
2023-10-26 18:14:27 +03:00
|
|
|
_logger.LogInformation("Moved guild data to separate folder: \"{OldPath}\" -> \"{NewPath}\"", oldPath,
|
|
|
|
newPath);
|
2023-09-22 15:33:14 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-02 23:51:16 +03:00
|
|
|
public async Task<JsonNode> GetSettings(Snowflake guildId, CancellationToken ct = default)
|
|
|
|
{
|
2023-07-18 15:25:02 +03:00
|
|
|
return (await GetData(guildId, ct)).Settings;
|
2023-07-09 16:32:14 +03:00
|
|
|
}
|
|
|
|
|
2023-08-02 23:51:16 +03:00
|
|
|
public ICollection<Snowflake> GetGuildIds()
|
|
|
|
{
|
2023-07-09 16:32:14 +03:00
|
|
|
return _datas.Keys;
|
|
|
|
}
|
2023-10-04 15:58:56 +03:00
|
|
|
|
|
|
|
public bool UnloadGuildData(Snowflake id)
|
|
|
|
{
|
|
|
|
return _datas.TryRemove(id, out _);
|
|
|
|
}
|
2023-07-09 16:32:14 +03:00
|
|
|
}
|