From 8579db2c9099630b6a268015d586db73435032f0 Mon Sep 17 00:00:00 2001 From: Rory& Date: Fri, 23 Feb 2024 12:31:43 +0100 Subject: Changes --- Services/ModerationBotRoomProvider.cs | 76 +++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Services/ModerationBotRoomProvider.cs (limited to 'Services/ModerationBotRoomProvider.cs') diff --git a/Services/ModerationBotRoomProvider.cs b/Services/ModerationBotRoomProvider.cs new file mode 100644 index 0000000..d4a200f --- /dev/null +++ b/Services/ModerationBotRoomProvider.cs @@ -0,0 +1,76 @@ +using System.Diagnostics.CodeAnalysis; +using LibMatrix.Homeservers; +using LibMatrix.Responses; +using LibMatrix.RoomTypes; +using ModerationBot.AccountData; + +namespace ModerationBot.Services; + +public class ModerationBotRoomProvider(AuthenticatedHomeserverGeneric hs, ModerationBotConfiguration cfg) { + private BotData? _botData; + + public BotData? BotData { + get { + if (BotDataExpiry >= DateTime.UtcNow) return _botData; + Console.WriteLine("BotData expired!"); + return null; + } + set { + _botData = value; + Console.WriteLine("BotData updated!"); + BotDataExpiry = DateTime.UtcNow.AddMinutes(5); + } + } + + private DateTime BotDataExpiry { get; set; } + + [MemberNotNull(nameof(BotData))] + private async Task GetBotDataAsync() { + try { + BotData ??= await hs.GetAccountDataAsync(BotData.EventId); + } + catch (Exception e) { + Console.WriteLine(e); + await hs.SetAccountDataAsync(BotData.EventId, new BotData()); + return await GetBotDataAsync(); + } + + if (BotData == null) + throw new NullReferenceException("BotData is null!"); + + return BotData; + } + + public async Task GetControlRoomAsync() { + var botData = await GetBotDataAsync(); + if (botData.ControlRoom == null) { + var createRoomRequest = CreateRoomRequest.CreatePrivate(hs, "Rory&::ModerationBot - Control Room"); + createRoomRequest.Invite = cfg.Admins; + var newRoom = await hs.CreateRoom(createRoomRequest, true, true, true); + BotData.ControlRoom = newRoom.RoomId; + await hs.SetAccountDataAsync(BotData.EventId, BotData); + } + + return hs.GetRoom(BotData.ControlRoom!); + } + + public async Task GetLogRoomAsync() { + var botData = await GetBotDataAsync(); + if (botData.LogRoom == null) { + var controlRoom = await GetControlRoomAsync(); + var createRoomRequest = CreateRoomRequest.CreatePrivate(hs, "Rory&::ModerationBot - Log Room"); + createRoomRequest.Invite = (await controlRoom.GetMembersListAsync()).Select(x=>x.StateKey).ToList(); + var newRoom = await hs.CreateRoom(createRoomRequest, true, true, true); + BotData.LogRoom = newRoom.RoomId; + await hs.SetAccountDataAsync(BotData.EventId, BotData); + } + + return hs.GetRoom(BotData.LogRoom!); + } + + public async Task GetDefaultPolicyRoomAsync() { + var botData = await GetBotDataAsync(); + + return string.IsNullOrWhiteSpace(botData.DefaultPolicyRoom) ? null : hs.GetRoom(BotData.DefaultPolicyRoom!); + } +} \ No newline at end of file -- cgit 1.5.1