2022-07-21 01:55:08 +00:00
|
|
|
|
using Newtonsoft.Json;
|
2022-03-29 05:03:01 +00:00
|
|
|
|
using RegexBot.Common;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
|
|
|
|
|
namespace RegexBot.Services.ModuleState;
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Implements per-module storage and retrieval of guild-specific state data, most typically but not limited to configuration data.
|
|
|
|
|
/// To that end, this service handles loading and validation of per-guild configuration files.
|
|
|
|
|
/// </summary>
|
|
|
|
|
class ModuleStateService : Service {
|
|
|
|
|
private readonly object _storageLock = new();
|
|
|
|
|
private readonly Dictionary<ulong, EntityList> _moderators;
|
|
|
|
|
private readonly Dictionary<ulong, Dictionary<Type, object?>> _stateData;
|
|
|
|
|
|
|
|
|
|
public ModuleStateService(RegexbotClient bot) : base(bot) {
|
|
|
|
|
_moderators = new();
|
|
|
|
|
_stateData = new();
|
|
|
|
|
|
|
|
|
|
bot.DiscordClient.GuildAvailable += RefreshGuildState;
|
|
|
|
|
bot.DiscordClient.JoinedGuild += RefreshGuildState;
|
|
|
|
|
bot.DiscordClient.LeftGuild += RemoveGuildData;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task RefreshGuildState(SocketGuild arg) {
|
2022-07-28 21:08:23 +00:00
|
|
|
|
if (await ProcessConfiguration(arg)) Log($"Configuration refreshed for '{arg.Name}'.");
|
2022-03-29 05:03:01 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private Task RemoveGuildData(SocketGuild arg) {
|
|
|
|
|
lock (_storageLock) {
|
|
|
|
|
_stateData.Remove(arg.Id);
|
|
|
|
|
_moderators.Remove(arg.Id);
|
|
|
|
|
}
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Hooked
|
|
|
|
|
public T? DoGetStateObj<T>(ulong guildId, Type t) {
|
|
|
|
|
lock (_storageLock) {
|
|
|
|
|
if (_stateData.ContainsKey(guildId) && _stateData[guildId].ContainsKey(t)) {
|
|
|
|
|
// Leave handling of potential InvalidCastException to caller.
|
|
|
|
|
return (T?)_stateData[guildId][t];
|
|
|
|
|
}
|
|
|
|
|
return default;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Hooked
|
|
|
|
|
public EntityList DoGetModlist(ulong guildId) {
|
|
|
|
|
lock (_storageLock) {
|
|
|
|
|
if (_moderators.TryGetValue(guildId, out var mods)) return mods;
|
|
|
|
|
else return new EntityList();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Configuration is loaded from database, and appropriate sections dispatched to their
|
|
|
|
|
/// respective methods for further processing.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <remarks>
|
|
|
|
|
/// This takes an all-or-nothing approach. Should there be a single issue in processing
|
|
|
|
|
/// configuration, all existing state data is kept.
|
|
|
|
|
/// </remarks>
|
2022-07-28 21:08:23 +00:00
|
|
|
|
private async Task<bool> ProcessConfiguration(SocketGuild guild) {
|
|
|
|
|
var jstr = await LoadConfigFile(guild);
|
2022-03-29 05:03:01 +00:00
|
|
|
|
JObject guildConf;
|
|
|
|
|
try {
|
|
|
|
|
var tok = JToken.Parse(jstr);
|
|
|
|
|
if (tok.Type == JTokenType.Object) {
|
|
|
|
|
guildConf = (JObject)tok;
|
|
|
|
|
} else {
|
|
|
|
|
throw new InvalidCastException("Configuration is not valid JSON.");
|
|
|
|
|
}
|
|
|
|
|
} catch (Exception ex) when (ex is JsonReaderException or InvalidCastException) {
|
2022-07-28 21:08:23 +00:00
|
|
|
|
Log($"Error loading configuration for server ID {guild.Id}: {ex.Message}");
|
2022-03-29 05:03:01 +00:00
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Load moderator list
|
|
|
|
|
var mods = new EntityList(guildConf["Moderators"]!, true);
|
|
|
|
|
|
|
|
|
|
// Create guild state objects for all existing modules
|
|
|
|
|
var newStates = new Dictionary<Type, object?>();
|
2022-05-20 00:03:03 +00:00
|
|
|
|
foreach (var module in BotClient.Modules) {
|
|
|
|
|
var t = module.GetType();
|
2022-03-29 05:03:01 +00:00
|
|
|
|
try {
|
2022-07-28 21:08:23 +00:00
|
|
|
|
var state = await module.CreateGuildStateAsync(guild.Id, guildConf[module.Name]!);
|
2022-05-20 00:03:03 +00:00
|
|
|
|
newStates.Add(t, state);
|
2022-03-29 05:03:01 +00:00
|
|
|
|
} catch (ModuleLoadException ex) {
|
2022-07-28 21:08:23 +00:00
|
|
|
|
Log($"{guild.Id}: Error reading configuration regarding {module.Name}: {ex.Message}");
|
2022-05-20 00:03:03 +00:00
|
|
|
|
return false;
|
|
|
|
|
} catch (Exception ex) when (ex is not ModuleLoadException) {
|
|
|
|
|
Log("Unhandled exception while initializing guild state for module:\n" +
|
|
|
|
|
$"Module: {module.Name} | " +
|
2022-07-28 21:08:23 +00:00
|
|
|
|
$"Guild: {guild.Id} ({BotClient.DiscordClient.GetGuild(guild.Id)?.Name ?? "unknown name"})\n" +
|
2022-07-28 02:23:49 +00:00
|
|
|
|
$"```\n{ex}\n```");
|
2022-03-29 05:03:01 +00:00
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
lock (_storageLock) {
|
2022-07-28 21:08:23 +00:00
|
|
|
|
_moderators[guild.Id] = mods;
|
|
|
|
|
_stateData[guild.Id] = newStates;
|
2022-03-29 05:03:01 +00:00
|
|
|
|
}
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2022-07-28 21:08:23 +00:00
|
|
|
|
private async Task<string> LoadConfigFile(SocketGuild guild) {
|
2022-03-29 05:03:01 +00:00
|
|
|
|
// Per-guild configuration exists under `config/(guild ID).json`
|
|
|
|
|
var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly()!.Location) +
|
|
|
|
|
Path.DirectorySeparatorChar + "config" + Path.DirectorySeparatorChar;
|
|
|
|
|
if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);
|
2022-07-28 21:08:23 +00:00
|
|
|
|
var path = basePath + guild.Id + ".json";
|
2022-03-29 05:03:01 +00:00
|
|
|
|
if (File.Exists(path)) {
|
|
|
|
|
return await File.ReadAllTextAsync(path);
|
2022-07-28 21:08:23 +00:00
|
|
|
|
} else { // Write default configuration to new file
|
|
|
|
|
string fileContents;
|
|
|
|
|
using (var resStream = Assembly.GetExecutingAssembly()
|
|
|
|
|
.GetManifestResourceStream($"{nameof(RegexBot)}.DefaultGuildConfig.json")!) {
|
|
|
|
|
using var readin = new StreamReader(resStream, encoding: System.Text.Encoding.UTF8);
|
|
|
|
|
fileContents = readin.ReadToEnd();
|
|
|
|
|
}
|
|
|
|
|
var userex = BotClient.DiscordClient.CurrentUser;
|
|
|
|
|
fileContents = fileContents.Replace("SERVER NAME", guild.Name).Replace("MODERATOR", $"@{userex.Id}::{userex.Username}");
|
|
|
|
|
using (var newFile = File.OpenWrite(path)) {
|
|
|
|
|
var w = new StreamWriter(newFile);
|
|
|
|
|
w.Write(fileContents);
|
|
|
|
|
w.Flush();
|
|
|
|
|
w.Close();
|
|
|
|
|
}
|
|
|
|
|
Log($"Created initial configuration file in config{Path.DirectorySeparatorChar}{guild.Id}.json");
|
|
|
|
|
return await LoadConfigFile(guild);
|
2022-03-29 05:03:01 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|