From 6bd02248ccfbcb46960a6f39eaad23888d190eb5 Mon Sep 17 00:00:00 2001 From: TheArcaneBrony Date: Fri, 15 Sep 2023 09:50:45 +0200 Subject: Some refactoring --- .../Bot/Commands/CmdCommand.cs | 60 +++++++--- .../Bot/Commands/HelpCommand.cs | 2 +- .../Bot/Commands/PingCommand.cs | 2 +- .../Bot/Interfaces/CommandContext.cs | 4 +- ExampleBots/LibMatrix.ExampleBot/Bot/MRUBot.cs | 8 +- .../LibMatrix.ExampleBot.csproj | 4 +- ExampleBots/LibMatrix.ExampleBot/Program.cs | 2 +- .../Bot/Commands/BanMediaCommand.cs | 14 +-- ExampleBots/MediaModeratorPoC/Bot/MediaModBot.cs | 126 ++++++++++----------- .../StateEventTypes/MediaPolicyStateEventData.cs | 2 +- .../PluralContactBotPoC/Bot/AccountData/BotData.cs | 16 +++ .../Bot/AccountData/SystemData.cs | 15 +++ .../Bot/Commands/CreateSystemCommand.cs | 57 ++++++++++ .../PluralContactBotPoC/Bot/PluralContactBot.cs | 99 ++++++++++++++++ .../Bot/PluralContactBotConfiguration.cs | 9 ++ .../PluralContactBotPoC/PluralContactBotPoC.csproj | 36 ++++++ ExampleBots/PluralContactBotPoC/Program.cs | 75 ++++++++++++ .../Properties/launchSettings.json | 26 +++++ .../appsettings.Development.json | 17 +++ ExampleBots/PluralContactBotPoC/appsettings.json | 9 ++ 20 files changed, 478 insertions(+), 105 deletions(-) create mode 100644 ExampleBots/PluralContactBotPoC/Bot/AccountData/BotData.cs create mode 100644 ExampleBots/PluralContactBotPoC/Bot/AccountData/SystemData.cs create mode 100644 ExampleBots/PluralContactBotPoC/Bot/Commands/CreateSystemCommand.cs create mode 100644 ExampleBots/PluralContactBotPoC/Bot/PluralContactBot.cs create mode 100644 ExampleBots/PluralContactBotPoC/Bot/PluralContactBotConfiguration.cs create mode 100644 ExampleBots/PluralContactBotPoC/PluralContactBotPoC.csproj create mode 100644 ExampleBots/PluralContactBotPoC/Program.cs create mode 100644 ExampleBots/PluralContactBotPoC/Properties/launchSettings.json create mode 100644 ExampleBots/PluralContactBotPoC/appsettings.Development.json create mode 100644 ExampleBots/PluralContactBotPoC/appsettings.json (limited to 'ExampleBots') diff --git a/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/CmdCommand.cs b/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/CmdCommand.cs index efedbba..5b2828e 100644 --- a/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/CmdCommand.cs +++ b/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/CmdCommand.cs @@ -1,3 +1,4 @@ +using ArcaneLibs.Extensions; using LibMatrix.ExampleBot.Bot.Interfaces; using LibMatrix.StateEventTypes.Spec; @@ -8,7 +9,7 @@ public class CmdCommand : ICommand { public string Description => "Runs a command on the host system"; public Task CanInvoke(CommandContext ctx) { - return Task.FromResult(ctx.MessageEvent.Sender.EndsWith(":rory.gay")); + return Task.FromResult(ctx.MessageEvent.Sender.EndsWith(":rory.gay") || ctx.MessageEvent.Sender.EndsWith(":conduit.rory.gay")); } public async Task Invoke(CommandContext ctx) { @@ -17,28 +18,55 @@ public class CmdCommand : ICommand { cmd = cmd.Trim(); cmd += "\""; - await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventData(body: $"Command being executed: `{cmd}`")); + await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventContent(body: $"Command being executed: `{cmd}`")); - var output = ArcaneLibs.Util.GetCommandOutputSync( - Environment.OSVersion.Platform == PlatformID.Unix ? "/bin/sh" : "cmd.exe", - (Environment.OSVersion.Platform == PlatformID.Unix ? "-c " : "/c ") + cmd) - .Replace("`", "\\`") - .Split("\n").ToList(); - foreach (var _out in output) Console.WriteLine($"{_out.Length:0000} {_out}"); + var output = ArcaneLibs.Util.GetCommandOutputAsync( + Environment.OSVersion.Platform == PlatformID.Unix ? "/bin/sh" : "cmd.exe", + (Environment.OSVersion.Platform == PlatformID.Unix ? "-c " : "/c ") + cmd); + // .Replace("`", "\\`") + // .Split("\n").ToList(); var msg = ""; - while (output.Count > 0) { - Console.WriteLine("Adding: " + output[0]); - msg += output[0] + "\n"; - output.RemoveAt(0); - if ((output.Count > 0 && (msg + output[0]).Length > 64000) || output.Count == 0) { - await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventData { - FormattedBody = $"```ansi\n{msg}\n```", - // Body = Markdig.Markdown.ToHtml(msg), + EventIdResponse? msgId = await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventContent { + FormattedBody = $"Waiting for command output...", + Body = msg.RemoveAnsi(), + Format = "m.notice" + }); + + var lastSendTask = Task.CompletedTask; + await foreach (var @out in output) { + Console.WriteLine($"{@out.Length:0000} {@out}"); + msg += @out + "\n"; + if (lastSendTask.IsCompleted) + lastSendTask = ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventContent { + FormattedBody = $"
\n{msg}\n
", + Body = msg.RemoveAnsi(), Format = "org.matrix.custom.html" }); + if (msg.Length > 31000) { + await lastSendTask; + msgId = await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventContent { + FormattedBody = $"Waiting for command output...", + Body = msg.RemoveAnsi(), + Format = "m.notice" + }); msg = ""; } } + + // while (output.Count > 0) { + // Console.WriteLine("Adding: " + output[0]); + // msg += output[0] + "\n"; + // output.RemoveAt(0); + // if ((output.Count > 0 && (msg + output[0]).Length > 31500) || output.Count == 0) { + // await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventContent { + // FormattedBody = $"
\n{msg}\n
", + // // Body = Markdig.Markdown.ToHtml(msg), + // Body = msg.RemoveAnsi(), + // Format = "org.matrix.custom.html" + // }); + // msg = ""; + // } + // } } } diff --git a/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/HelpCommand.cs b/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/HelpCommand.cs index 09c4e3f..c750130 100644 --- a/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/HelpCommand.cs +++ b/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/HelpCommand.cs @@ -17,6 +17,6 @@ public class HelpCommand(IServiceProvider services) : ICommand { sb.AppendLine($"- {command.Name}: {command.Description}"); } - await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventData(body: sb.ToString())); + await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventContent(body: sb.ToString())); } } diff --git a/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/PingCommand.cs b/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/PingCommand.cs index f70cd78..a261a59 100644 --- a/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/PingCommand.cs +++ b/ExampleBots/LibMatrix.ExampleBot/Bot/Commands/PingCommand.cs @@ -8,6 +8,6 @@ public class PingCommand : ICommand { public string Description { get; } = "Pong!"; public async Task Invoke(CommandContext ctx) { - await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventData(body: "pong!")); + await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventContent(body: "pong!")); } } diff --git a/ExampleBots/LibMatrix.ExampleBot/Bot/Interfaces/CommandContext.cs b/ExampleBots/LibMatrix.ExampleBot/Bot/Interfaces/CommandContext.cs index ec61a1e..3715cb6 100644 --- a/ExampleBots/LibMatrix.ExampleBot/Bot/Interfaces/CommandContext.cs +++ b/ExampleBots/LibMatrix.ExampleBot/Bot/Interfaces/CommandContext.cs @@ -7,6 +7,6 @@ namespace LibMatrix.ExampleBot.Bot.Interfaces; public class CommandContext { public GenericRoom Room { get; set; } public StateEventResponse MessageEvent { get; set; } - public string CommandName => (MessageEvent.TypedContent as RoomMessageEventData).Body.Split(' ')[0][1..]; - public string[] Args => (MessageEvent.TypedContent as RoomMessageEventData).Body.Split(' ')[1..]; + public string CommandName => (MessageEvent.TypedContent as RoomMessageEventContent).Body.Split(' ')[0][1..]; + public string[] Args => (MessageEvent.TypedContent as RoomMessageEventContent).Body.Split(' ')[1..]; } diff --git a/ExampleBots/LibMatrix.ExampleBot/Bot/MRUBot.cs b/ExampleBots/LibMatrix.ExampleBot/Bot/MRUBot.cs index 3f69d90..0b4e2ba 100644 --- a/ExampleBots/LibMatrix.ExampleBot/Bot/MRUBot.cs +++ b/ExampleBots/LibMatrix.ExampleBot/Bot/MRUBot.cs @@ -58,7 +58,7 @@ public class MRUBot : IHostedService { args.Value.InviteState.Events.FirstOrDefault(x => x.Type == "m.room.member" && x.StateKey == hs.WhoAmI.UserId); _logger.LogInformation( - $"Got invite to {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventData).Reason}"); + $"Got invite to {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventContent).Reason}"); if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent.Sender == "@mxidupwitch:the-apothecary.club") { try { var senderProfile = await hs.GetProfile(inviteEvent.Sender); @@ -76,12 +76,12 @@ public class MRUBot : IHostedService { var room = await hs.GetRoom(@event.RoomId); // _logger.LogInformation(eventResponse.ToJson(indent: false)); - if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventData message }) { + if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message }) { if (message is { MessageType: "m.text" } && message.Body.StartsWith(_configuration.Prefix)) { var command = _commands.FirstOrDefault(x => x.Name == message.Body.Split(' ')[0][_configuration.Prefix.Length..]); if (command == null) { await room.SendMessageEventAsync("m.room.message", - new RoomMessageEventData(messageType: "m.text", body: "Command not found!")); + new RoomMessageEventContent(messageType: "m.text", body: "Command not found!")); return; } @@ -94,7 +94,7 @@ public class MRUBot : IHostedService { } else { await room.SendMessageEventAsync("m.room.message", - new RoomMessageEventData(messageType: "m.text", body: "You do not have permission to run this command!")); + new RoomMessageEventContent(messageType: "m.text", body: "You do not have permission to run this command!")); } } } diff --git a/ExampleBots/LibMatrix.ExampleBot/LibMatrix.ExampleBot.csproj b/ExampleBots/LibMatrix.ExampleBot/LibMatrix.ExampleBot.csproj index 13cbb15..30ea1e5 100644 --- a/ExampleBots/LibMatrix.ExampleBot/LibMatrix.ExampleBot.csproj +++ b/ExampleBots/LibMatrix.ExampleBot/LibMatrix.ExampleBot.csproj @@ -2,7 +2,7 @@ Exe - net8.0 + net7.0 preview enable enable @@ -22,7 +22,7 @@ - + diff --git a/ExampleBots/LibMatrix.ExampleBot/Program.cs b/ExampleBots/LibMatrix.ExampleBot/Program.cs index 0378ec9..ef40ecb 100644 --- a/ExampleBots/LibMatrix.ExampleBot/Program.cs +++ b/ExampleBots/LibMatrix.ExampleBot/Program.cs @@ -25,7 +25,7 @@ var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => { services.AddScoped(typeof(ICommand), commandClass); } - services.AddHostedService(); + // services.AddHostedService(); services.AddHostedService(); }).UseConsoleLifetime().Build(); diff --git a/ExampleBots/MediaModeratorPoC/Bot/Commands/BanMediaCommand.cs b/ExampleBots/MediaModeratorPoC/Bot/Commands/BanMediaCommand.cs index 90de136..4642007 100644 --- a/ExampleBots/MediaModeratorPoC/Bot/Commands/BanMediaCommand.cs +++ b/ExampleBots/MediaModeratorPoC/Bot/Commands/BanMediaCommand.cs @@ -22,7 +22,7 @@ public class BanMediaCommand(IServiceProvider services, HomeserverProviderServic if (!isAdmin) { // await ctx.Reply("You do not have permission to use this command!"); await (await ctx.Homeserver.GetRoom(botData.LogRoom!)).SendMessageEventAsync("m.room.message", - new RoomMessageEventData(body: $"User {ctx.MessageEvent.Sender} tried to use command {Name} but does not have permission!", messageType: "m.text")); + new RoomMessageEventContent(body: $"User {ctx.MessageEvent.Sender} tried to use command {Name} but does not have permission!", messageType: "m.text")); } return isAdmin; @@ -34,11 +34,11 @@ public class BanMediaCommand(IServiceProvider services, HomeserverProviderServic var logRoom = await ctx.Homeserver.GetRoom(botData.LogRoom ?? botData.ControlRoom); //check if reply - var messageContent = ctx.MessageEvent.TypedContent as RoomMessageEventData; + var messageContent = ctx.MessageEvent.TypedContent as RoomMessageEventContent; if (messageContent?.RelatesTo is { InReplyTo: not null }) { try { await logRoom.SendMessageEventAsync("m.room.message", - new RoomMessageEventData( + new RoomMessageEventContent( body: $"User {MessageFormatter.HtmlFormatMention(ctx.MessageEvent.Sender)} is trying to ban media {messageContent!.RelatesTo!.InReplyTo!.EventId}", messageType: "m.text")); @@ -58,10 +58,8 @@ public class BanMediaCommand(IServiceProvider services, HomeserverProviderServic return; } - - //hash file - var mxcUri = (repliedMessage.TypedContent as RoomMessageEventData).Url!; + var mxcUri = (repliedMessage.TypedContent as RoomMessageEventContent).Url!; var resolvedUri = await hsResolver.ResolveMediaUri(mxcUri.Split('/')[2], mxcUri); var hashAlgo = SHA3_256.Create(); var uriHash = hashAlgo.ComputeHash(mxcUri.AsBytes().ToArray()); @@ -85,8 +83,8 @@ public class BanMediaCommand(IServiceProvider services, HomeserverProviderServic } } - MediaPolicyStateEventData policy; - await policyRoom.SendStateEventAsync("gay.rory.media_moderator_poc.rule.media", Guid.NewGuid().ToString(), policy = new MediaPolicyStateEventData { + MediaPolicyEventContent policy; + await policyRoom.SendStateEventAsync("gay.rory.media_moderator_poc.rule.media", Guid.NewGuid().ToString(), policy = new MediaPolicyEventContent { Entity = uriHash, FileHash = fileHash, Reason = string.Join(' ', ctx.Args[1..]), diff --git a/ExampleBots/MediaModeratorPoC/Bot/MediaModBot.cs b/ExampleBots/MediaModeratorPoC/Bot/MediaModBot.cs index 81aecc7..7104114 100644 --- a/ExampleBots/MediaModeratorPoC/Bot/MediaModBot.cs +++ b/ExampleBots/MediaModeratorPoC/Bot/MediaModBot.cs @@ -20,11 +20,8 @@ using Microsoft.Extensions.Logging; namespace MediaModeratorPoC.Bot; -public class MediaModBot : IHostedService { - private readonly AuthenticatedHomeserverGeneric _hs; - private readonly ILogger _logger; - private readonly MediaModBotConfiguration _configuration; - private readonly HomeserverResolverService _hsResolver; +public class MediaModBot(AuthenticatedHomeserverGeneric hs, ILogger logger, MediaModBotConfiguration configuration, + HomeserverResolverService hsResolver) : IHostedService { private readonly IEnumerable _commands; private Task _listenerTask; @@ -33,20 +30,11 @@ public class MediaModBot : IHostedService { private GenericRoom _logRoom; private GenericRoom _controlRoom; - public MediaModBot(AuthenticatedHomeserverGeneric hs, ILogger logger, - MediaModBotConfiguration configuration, HomeserverResolverService hsResolver) { - logger.LogInformation("{} instantiated!", this.GetType().Name); - _hs = hs; - _logger = logger; - _configuration = configuration; - _hsResolver = hsResolver; - } - /// Triggered when the application host is ready to start the service. /// Indicates that the start process has been aborted. public async Task StartAsync(CancellationToken cancellationToken) { _listenerTask = Run(cancellationToken); - _logger.LogInformation("Bot started!"); + logger.LogInformation("Bot started!"); } private async Task Run(CancellationToken cancellationToken) { @@ -55,29 +43,29 @@ public class MediaModBot : IHostedService { BotData botData; try { - botData = await _hs.GetAccountData("gay.rory.media_moderator_poc_data"); + botData = await hs.GetAccountData("gay.rory.media_moderator_poc_data"); } catch (Exception e) { if (e is not MatrixException { ErrorCode: "M_NOT_FOUND" }) { - _logger.LogError("{}", e.ToString()); + logger.LogError("{}", e.ToString()); throw; } botData = new BotData(); - var creationContent = CreateRoomRequest.CreatePrivate(_hs, name: "Media Moderator PoC - Control room", roomAliasName: "media-moderator-poc-control-room"); - creationContent.Invite = _configuration.Admins; + var creationContent = CreateRoomRequest.CreatePrivate(hs, name: "Media Moderator PoC - Control room", roomAliasName: "media-moderator-poc-control-room"); + creationContent.Invite = configuration.Admins; creationContent.CreationContent["type"] = "gay.rory.media_moderator_poc.control_room"; - botData.ControlRoom = (await _hs.CreateRoom(creationContent)).RoomId; + botData.ControlRoom = (await hs.CreateRoom(creationContent)).RoomId; //set access rules to allow joining via control room creationContent.InitialState.Add(new StateEvent { Type = "m.room.join_rules", StateKey = "", - TypedContent = new JoinRulesEventData { + TypedContent = new JoinRulesEventContent { JoinRule = "knock_restricted", Allow = new() { - new JoinRulesEventData.AllowEntry { + new JoinRulesEventContent.AllowEntry { Type = "m.room_membership", RoomId = botData.ControlRoom } @@ -88,19 +76,19 @@ public class MediaModBot : IHostedService { creationContent.Name = "Media Moderator PoC - Log room"; creationContent.RoomAliasName = "media-moderator-poc-log-room"; creationContent.CreationContent["type"] = "gay.rory.media_moderator_poc.log_room"; - botData.LogRoom = (await _hs.CreateRoom(creationContent)).RoomId; + botData.LogRoom = (await hs.CreateRoom(creationContent)).RoomId; creationContent.Name = "Media Moderator PoC - Policy room"; creationContent.RoomAliasName = "media-moderator-poc-policy-room"; creationContent.CreationContent["type"] = "gay.rory.media_moderator_poc.policy_room"; - botData.PolicyRoom = (await _hs.CreateRoom(creationContent)).RoomId; + botData.PolicyRoom = (await hs.CreateRoom(creationContent)).RoomId; - await _hs.SetAccountData("gay.rory.media_moderator_poc_data", botData); + await hs.SetAccountData("gay.rory.media_moderator_poc_data", botData); } - _policyRoom = await _hs.GetRoom(botData.PolicyRoom ?? botData.ControlRoom); - _logRoom = await _hs.GetRoom(botData.LogRoom ?? botData.ControlRoom); - _controlRoom = await _hs.GetRoom(botData.ControlRoom); + _policyRoom = await hs.GetRoom(botData.PolicyRoom ?? botData.ControlRoom); + _logRoom = await hs.GetRoom(botData.LogRoom ?? botData.ControlRoom); + _controlRoom = await hs.GetRoom(botData.ControlRoom); List admins = new(); @@ -109,7 +97,7 @@ public class MediaModBot : IHostedService { while (!cancellationToken.IsCancellationRequested) { var controlRoomMembers = _controlRoom.GetMembersAsync(); await foreach (var member in controlRoomMembers) { - if ((member.TypedContent as RoomMemberEventData).Membership == "join") admins.Add(member.UserId); + if ((member.TypedContent as RoomMemberEventContent).Membership == "join") admins.Add(member.UserId); } await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken); @@ -117,39 +105,39 @@ public class MediaModBot : IHostedService { }, cancellationToken); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed - _hs.SyncHelper.InviteReceivedHandlers.Add(async Task (args) => { + hs.SyncHelper.InviteReceivedHandlers.Add(async Task (args) => { var inviteEvent = args.Value.InviteState.Events.FirstOrDefault(x => - x.Type == "m.room.member" && x.StateKey == _hs.WhoAmI.UserId); - _logger.LogInformation( - $"Got invite to {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventData).Reason}"); + x.Type == "m.room.member" && x.StateKey == hs.WhoAmI.UserId); + logger.LogInformation( + $"Got invite to {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventContent).Reason}"); if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent.Sender.EndsWith(":conduit.rory.gay")) { try { - var senderProfile = await _hs.GetProfile(inviteEvent.Sender); - await (await _hs.GetRoom(args.Key)).JoinAsync(reason: $"I was invited by {senderProfile.DisplayName ?? inviteEvent.Sender}!"); + var senderProfile = await hs.GetProfile(inviteEvent.Sender); + await (await hs.GetRoom(args.Key)).JoinAsync(reason: $"I was invited by {senderProfile.DisplayName ?? inviteEvent.Sender}!"); } catch (Exception e) { - _logger.LogError("{}", e.ToString()); - await (await _hs.GetRoom(args.Key)).LeaveAsync(reason: "I was unable to join the room: " + e); + logger.LogError("{}", e.ToString()); + await (await hs.GetRoom(args.Key)).LeaveAsync(reason: "I was unable to join the room: " + e); } } }); - _hs.SyncHelper.TimelineEventHandlers.Add(async @event => { - var room = await _hs.GetRoom(@event.RoomId); + hs.SyncHelper.TimelineEventHandlers.Add(async @event => { + var room = await hs.GetRoom(@event.RoomId); try { - _logger.LogInformation( + logger.LogInformation( "Got timeline event in {}: {}", @event.RoomId, @event.ToJson(indent: true, ignoreNull: true)); - if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventData message }) { + if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message }) { if (message is { MessageType: "m.image" }) { //check media var matchedPolicy = await CheckMedia(@event); if (matchedPolicy is null) return; - var matchedpolicyData = matchedPolicy.TypedContent as MediaPolicyStateEventData; + var matchedpolicyData = matchedPolicy.TypedContent as MediaPolicyEventContent; var recommendation = matchedpolicyData.Recommendation; await _logRoom.SendMessageEventAsync("m.room.message", - new RoomMessageEventData( + new RoomMessageEventContent( body: $"User {MessageFormatter.HtmlFormatMention(@event.Sender)} posted an image in {MessageFormatter.HtmlFormatMention(room.RoomId)} that matched rule {matchedPolicy.StateKey}, applying action {matchedpolicyData.Recommendation}, as described in rule: {matchedPolicy.RawContent!.ToJson(ignoreNull: true)}", messageType: "m.text") { @@ -160,17 +148,18 @@ public class MediaModBot : IHostedService { switch (recommendation) { case "warn_admins": { await _controlRoom.SendMessageEventAsync("m.room.message", - new RoomMessageEventData(body: $"{string.Join(' ', admins)}\nUser {MessageFormatter.HtmlFormatMention(@event.Sender)} posted a banned image {message.Url}", + new RoomMessageEventContent( + body: $"{string.Join(' ', admins)}\nUser {MessageFormatter.HtmlFormatMention(@event.Sender)} posted a banned image {message.Url}", messageType: "m.text") { Format = "org.matrix.custom.html", - FormattedBody = $"{string.Join(' ', admins.Select(u=>MessageFormatter.HtmlFormatMention(u)))}\n" + + FormattedBody = $"{string.Join(' ', admins.Select(u => MessageFormatter.HtmlFormatMention(u)))}\n" + $"User {MessageFormatter.HtmlFormatMention(@event.Sender)} posted a banned image {message.Url}" }); break; } case "warn": { await room.SendMessageEventAsync("m.room.message", - new RoomMessageEventData( + new RoomMessageEventContent( body: $"Please be careful when posting this image: {matchedpolicyData.Reason}", messageType: "m.text") { Format = "org.matrix.custom.html", @@ -196,7 +185,7 @@ public class MediaModBot : IHostedService { // // await room.SendMessageEventAsync("m.room.message", - new RoomMessageEventData( + new RoomMessageEventContent( body: $"Please be careful when posting this image: {matchedpolicyData.Reason}, I have spoilered it for you:", messageType: "m.text") { @@ -206,7 +195,7 @@ public class MediaModBot : IHostedService { }); var imageUrl = message.Url; await room.SendMessageEventAsync("m.room.message", - new RoomMessageEventData(body: $"CN: {imageUrl}", + new RoomMessageEventContent(body: $"CN: {imageUrl}", messageType: "m.text") { Format = "org.matrix.custom.html", FormattedBody = $""" @@ -254,7 +243,7 @@ public class MediaModBot : IHostedService { } } catch (Exception e) { - _logger.LogError("{}", e.ToString()); + logger.LogError("{}", e.ToString()); await _controlRoom.SendMessageEventAsync("m.room.message", MessageFormatter.FormatException($"Unable to ban user in {MessageFormatter.HtmlFormatMention(room.RoomId)}", e)); await _logRoom.SendMessageEventAsync("m.room.message", @@ -269,7 +258,7 @@ public class MediaModBot : IHostedService { /// Triggered when the application host is performing a graceful shutdown. /// Indicates that the shutdown process should no longer be graceful. public async Task StopAsync(CancellationToken cancellationToken) { - _logger.LogInformation("Shutting down bot!"); + logger.LogInformation("Shutting down bot!"); } private async Task CheckMedia(StateEventResponse @event) { @@ -277,67 +266,66 @@ public class MediaModBot : IHostedService { var hashAlgo = SHA3_256.Create(); var mxcUri = @event.RawContent["url"].GetValue(); - var resolvedUri = await _hsResolver.ResolveMediaUri(mxcUri.Split('/')[2], mxcUri); + var resolvedUri = await hsResolver.ResolveMediaUri(mxcUri.Split('/')[2], mxcUri); var uriHash = hashAlgo.ComputeHash(mxcUri.AsBytes().ToArray()); byte[]? fileHash = null; try { - fileHash = await hashAlgo.ComputeHashAsync(await _hs._httpClient.GetStreamAsync(resolvedUri)); + fileHash = await hashAlgo.ComputeHashAsync(await hs._httpClient.GetStreamAsync(resolvedUri)); } catch (Exception ex) { await _logRoom.SendMessageEventAsync("m.room.message", - MessageFormatter.FormatException($"Error calculating file hash for {mxcUri} via {mxcUri.Split('/')[2]} ({resolvedUri}), retrying via {_hs.HomeServerDomain}...", + MessageFormatter.FormatException($"Error calculating file hash for {mxcUri} via {mxcUri.Split('/')[2]} ({resolvedUri}), retrying via {hs.HomeServerDomain}...", ex)); try { - resolvedUri = await _hsResolver.ResolveMediaUri(_hs.HomeServerDomain, mxcUri); - fileHash = await hashAlgo.ComputeHashAsync(await _hs._httpClient.GetStreamAsync(resolvedUri)); + resolvedUri = await hsResolver.ResolveMediaUri(hs.HomeServerDomain, mxcUri); + fileHash = await hashAlgo.ComputeHashAsync(await hs._httpClient.GetStreamAsync(resolvedUri)); } catch (Exception ex2) { await _logRoom.SendMessageEventAsync("m.room.message", - MessageFormatter.FormatException($"Error calculating file hash via {_hs.HomeServerDomain} ({resolvedUri})!", ex2)); + MessageFormatter.FormatException($"Error calculating file hash via {hs.HomeServerDomain} ({resolvedUri})!", ex2)); } } - _logger.LogInformation("Checking media {url} with hash {hash}", resolvedUri, fileHash); + logger.LogInformation("Checking media {url} with hash {hash}", resolvedUri, fileHash); await foreach (var state in stateList) { if (state.Type != "gay.rory.media_moderator_poc.rule.media" && state.Type != "gay.rory.media_moderator_poc.rule.server") continue; if (!state.RawContent.ContainsKey("entity")) { - _logger.LogWarning("Rule {rule} has no entity, this event was probably redacted!", state.StateKey); + logger.LogWarning("Rule {rule} has no entity, this event was probably redacted!", state.StateKey); continue; } - _logger.LogInformation("Checking rule {rule}: {data}", state.StateKey, state.TypedContent.ToJson(ignoreNull: true, indent: false)); - var rule = state.TypedContent as MediaPolicyStateEventData; + + logger.LogInformation("Checking rule {rule}: {data}", state.StateKey, state.TypedContent.ToJson(ignoreNull: true, indent: false)); + var rule = state.TypedContent as MediaPolicyEventContent; if (state.Type == "gay.rory.media_moderator_poc.rule.server" && rule.ServerEntity is not null) { rule.ServerEntity = rule.ServerEntity.Replace("\\*", ".*").Replace("\\?", "."); var regex = new Regex($"mxc://({rule.ServerEntity})/.*", RegexOptions.Compiled | RegexOptions.IgnoreCase); - if (regex.IsMatch(@event.RawContent["url"].GetValue())) { - _logger.LogInformation("{url} matched rule {rule}", @event.RawContent["url"], rule.ToJson(ignoreNull: true)); + if (regex.IsMatch(@event.RawContent["url"]!.GetValue())) { + logger.LogInformation("{url} matched rule {rule}", @event.RawContent["url"], rule.ToJson(ignoreNull: true)); return state; } } if (rule.Entity is not null && uriHash.SequenceEqual(rule.Entity)) { - _logger.LogInformation("{url} matched rule {rule} by uri hash", @event.RawContent["url"], rule.ToJson(ignoreNull: true)); + logger.LogInformation("{url} matched rule {rule} by uri hash", @event.RawContent["url"], rule.ToJson(ignoreNull: true)); return state; } - _logger.LogInformation("uri hash {uriHash} did not match rule's {ruleUriHash}", Convert.ToBase64String(uriHash), Convert.ToBase64String(rule.Entity)); + logger.LogInformation("uri hash {uriHash} did not match rule's {ruleUriHash}", Convert.ToBase64String(uriHash), Convert.ToBase64String(rule.Entity)); if (rule.FileHash is not null && fileHash is not null && rule.FileHash.SequenceEqual(fileHash)) { - _logger.LogInformation("{url} matched rule {rule} by file hash", @event.RawContent["url"], rule.ToJson(ignoreNull: true)); + logger.LogInformation("{url} matched rule {rule} by file hash", @event.RawContent["url"], rule.ToJson(ignoreNull: true)); return state; } - _logger.LogInformation("file hash {fileHash} did not match rule's {ruleFileHash}", Convert.ToBase64String(fileHash), Convert.ToBase64String(rule.FileHash)); - + logger.LogInformation("file hash {fileHash} did not match rule's {ruleFileHash}", Convert.ToBase64String(fileHash), Convert.ToBase64String(rule.FileHash)); //check pixels every 10% of the way through the image using ImageSharp // var image = Image.Load(await _hs._httpClient.GetStreamAsync(resolvedUri)); } - - _logger.LogInformation("{url} did not match any rules", @event.RawContent["url"]); + logger.LogInformation("{url} did not match any rules", @event.RawContent["url"]); return null; } diff --git a/ExampleBots/MediaModeratorPoC/Bot/StateEventTypes/MediaPolicyStateEventData.cs b/ExampleBots/MediaModeratorPoC/Bot/StateEventTypes/MediaPolicyStateEventData.cs index f37d33c..6686a37 100644 --- a/ExampleBots/MediaModeratorPoC/Bot/StateEventTypes/MediaPolicyStateEventData.cs +++ b/ExampleBots/MediaModeratorPoC/Bot/StateEventTypes/MediaPolicyStateEventData.cs @@ -6,7 +6,7 @@ namespace MediaModeratorPoC.Bot.StateEventTypes; [MatrixEvent(EventName = "gay.rory.media_moderator_poc.rule.homeserver")] [MatrixEvent(EventName = "gay.rory.media_moderator_poc.rule.media")] -public class MediaPolicyStateEventData : IStateEventType { +public class MediaPolicyEventContent : EventContent { /// /// This is an MXC URI, hashed with SHA3-256. /// diff --git a/ExampleBots/PluralContactBotPoC/Bot/AccountData/BotData.cs b/ExampleBots/PluralContactBotPoC/Bot/AccountData/BotData.cs new file mode 100644 index 0000000..9477488 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Bot/AccountData/BotData.cs @@ -0,0 +1,16 @@ +using System.Text.Json.Serialization; +using LibMatrix.Helpers; +using LibMatrix.Interfaces; + +namespace PluralContactBotPoC.Bot.AccountData; +[MatrixEvent(EventName = "gay.rory.plural_contact_bot.bot_config")] +public class BotData : EventContent { + [JsonPropertyName("control_room")] + public string ControlRoom { get; set; } = ""; + + [JsonPropertyName("log_room")] + public string? LogRoom { get; set; } = ""; + + [JsonPropertyName("policy_room")] + public string? PolicyRoom { get; set; } = ""; +} diff --git a/ExampleBots/PluralContactBotPoC/Bot/AccountData/SystemData.cs b/ExampleBots/PluralContactBotPoC/Bot/AccountData/SystemData.cs new file mode 100644 index 0000000..5edfc0e --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Bot/AccountData/SystemData.cs @@ -0,0 +1,15 @@ +using System.Text.Json.Serialization; +using LibMatrix.Helpers; +using LibMatrix.Interfaces; + +namespace PluralContactBotPoC.Bot.StateEventTypes; + +[MatrixEvent(EventName = "gay.rory.plural_contact_bot.system_data")] +public class SystemData : EventContent { + [JsonPropertyName("control_room")] + public string ControlRoom { get; set; } = null!; + [JsonPropertyName("system_members")] + public List Members { get; set; } = new(); + [JsonPropertyName("dm_space")] + public string? DmSpace { get; set; } +} diff --git a/ExampleBots/PluralContactBotPoC/Bot/Commands/CreateSystemCommand.cs b/ExampleBots/PluralContactBotPoC/Bot/Commands/CreateSystemCommand.cs new file mode 100644 index 0000000..5da4f5e --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Bot/Commands/CreateSystemCommand.cs @@ -0,0 +1,57 @@ +using LibMatrix; +using LibMatrix.Helpers; +using LibMatrix.Services; +using LibMatrix.StateEventTypes.Spec; +using MediaModeratorPoC.Bot.Interfaces; +using PluralContactBotPoC.Bot.AccountData; +using PluralContactBotPoC.Bot.StateEventTypes; + +namespace PluralContactBotPoC.Bot.Commands; + +public class CreateSystemCommand(IServiceProvider services, HomeserverProviderService hsProvider, HomeserverResolverService hsResolver) : ICommand { + public string Name { get; } = "createsystem"; + public string Description { get; } = "Create a new system"; + + public async Task CanInvoke(CommandContext ctx) { + return true; + } + + public async Task Invoke(CommandContext ctx) { + if (ctx.Args.Length != 1) { + await ctx.Reply("m.notice", MessageFormatter.FormatError("Only one argument is allowed: system name!")); + return; + } + + var sysName = ctx.Args[0]; + try { + try { + await ctx.Homeserver.GetAccountData("gay.rory.plural_contact_bot.system_data"); + await ctx.Reply("m.notice", MessageFormatter.FormatError($"System {sysName} already exists!")); + } + catch (MatrixException e) { + if (e is { ErrorCode: "M_NOT_FOUND" }) { + var sysData = new SystemData() { + ControlRoom = ctx.Room.RoomId, + Members = new(), + }; + + var state = ctx.Room.GetMembersAsync(); + await foreach (var member in state) { + sysData.Members.Add(member.UserId); + } + + await ctx.Room.SendStateEventAsync("m.room.name", new RoomNameEventContent() { + Name = sysName + " control room" + }); + + return; + } + + throw; + } + } + catch (Exception e) { + await ctx.Reply("m.notice", MessageFormatter.FormatException("Something went wrong!", e)); + } + } +} diff --git a/ExampleBots/PluralContactBotPoC/Bot/PluralContactBot.cs b/ExampleBots/PluralContactBotPoC/Bot/PluralContactBot.cs new file mode 100644 index 0000000..2136b42 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Bot/PluralContactBot.cs @@ -0,0 +1,99 @@ +using System.Text; +using ArcaneLibs.Extensions; +using LibMatrix.Helpers; +using LibMatrix.Homeservers; +using LibMatrix.RoomTypes; +using LibMatrix.Services; +using LibMatrix.StateEventTypes.Spec; +using LibMatrix.Utilities.Bot; +using MediaModeratorPoC.Bot.Interfaces; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using PluralContactBotPoC.Bot.AccountData; +using PluralContactBotPoC.Bot.StateEventTypes; + +namespace PluralContactBotPoC.Bot; + +public class PluralContactBot(AuthenticatedHomeserverGeneric hs, ILogger logger, LibMatrixBotConfiguration botConfiguration, + PluralContactBotConfiguration configuration, + HomeserverResolverService hsResolver) : IHostedService { + private readonly IEnumerable _commands; + + private Task _listenerTask; + + private GenericRoom? _logRoom; + + /// Triggered when the application host is ready to start the service. + /// Indicates that the start process has been aborted. + public async Task StartAsync(CancellationToken cancellationToken) { + _listenerTask = Run(cancellationToken); + logger.LogInformation("Bot started!"); + } + + private async Task Run(CancellationToken cancellationToken) { + Directory.GetFiles("bot_data/cache").ToList().ForEach(File.Delete); + + BotData botData; + + _logRoom = await hs.GetRoom(botConfiguration.LogRoom); + + hs.SyncHelper.InviteReceivedHandlers.Add(async Task (args) => { + var inviteEvent = + args.Value.InviteState.Events.FirstOrDefault(x => + x.Type == "m.room.member" && x.StateKey == hs.WhoAmI.UserId); + logger.LogInformation("Got invite to {} by {} with reason: {}", args.Key, inviteEvent.Sender, (inviteEvent.TypedContent as RoomMemberEventContent).Reason); + + try { + var accountData = await hs.GetAccountData($"gay.rory.plural_contact_bot.system_data#{inviteEvent.StateKey}"); + if (accountData.Members.Contains(inviteEvent.Sender)) { + await (await hs.GetRoom(args.Key)).JoinAsync(reason: "I was invited by a system member!"); + + await _logRoom.SendMessageEventAsync("m.room.message", + MessageFormatter.FormatSuccess( + $"I was invited by a system member ({MessageFormatter.HtmlFormatMention(inviteEvent.Sender)}) to {MessageFormatter.HtmlFormatMention(args.Key)}")); + + return; + } + } + catch (Exception e) { + await _logRoom.SendMessageEventAsync("m.room.message", + MessageFormatter.FormatException( + $"Exception handling event {inviteEvent.EventId} by {inviteEvent.Sender} in {MessageFormatter.HtmlFormatMention(inviteEvent.RoomId)}", e)); + } + + if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent.Sender.EndsWith(":conduit.rory.gay")) { + try { + var senderProfile = await hs.GetProfile(inviteEvent.Sender); + await (await hs.GetRoom(args.Key)).JoinAsync(reason: $"I was invited by {senderProfile.DisplayName ?? inviteEvent.Sender}!"); + } + catch (Exception e) { + logger.LogError("{}", e.ToString()); + await (await hs.GetRoom(args.Key)).LeaveAsync(reason: "I was unable to join the room: " + e); + } + } + }); + + hs.SyncHelper.TimelineEventHandlers.Add(async @event => { + var room = await hs.GetRoom(@event.RoomId); + try { + logger.LogInformation( + "Got timeline event in {}: {}", @event.RoomId, @event.ToJson(indent: true, ignoreNull: true)); + + if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message }) { } + } + catch (Exception e) { + logger.LogError("{}", e.ToString()); + await _logRoom.SendMessageEventAsync("m.room.message", + MessageFormatter.FormatException($"Exception handling event {@event.EventId} by {@event.Sender} in {MessageFormatter.HtmlFormatMention(room.RoomId)}", e)); + await using var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.ToString())); + await _logRoom.SendFileAsync("m.file", "error.log.cs", stream); + } + }); + } + + /// Triggered when the application host is performing a graceful shutdown. + /// Indicates that the shutdown process should no longer be graceful. + public async Task StopAsync(CancellationToken cancellationToken) { + logger.LogInformation("Shutting down bot!"); + } +} diff --git a/ExampleBots/PluralContactBotPoC/Bot/PluralContactBotConfiguration.cs b/ExampleBots/PluralContactBotPoC/Bot/PluralContactBotConfiguration.cs new file mode 100644 index 0000000..f5c21af --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Bot/PluralContactBotConfiguration.cs @@ -0,0 +1,9 @@ +using Microsoft.Extensions.Configuration; + +namespace PluralContactBotPoC.Bot; + +public class PluralContactBotConfiguration { + public PluralContactBotConfiguration(IConfiguration config) => config.GetRequiredSection("PluralContactBot").Bind(this); + + // public string +} diff --git a/ExampleBots/PluralContactBotPoC/PluralContactBotPoC.csproj b/ExampleBots/PluralContactBotPoC/PluralContactBotPoC.csproj new file mode 100644 index 0000000..cd549f9 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/PluralContactBotPoC.csproj @@ -0,0 +1,36 @@ + + + + Exe + net8.0 + preview + enable + enable + false + true + + + + + + + + + + + + + + + + + + + + Always + + + + + + diff --git a/ExampleBots/PluralContactBotPoC/Program.cs b/ExampleBots/PluralContactBotPoC/Program.cs new file mode 100644 index 0000000..b2e041e --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Program.cs @@ -0,0 +1,75 @@ +// See https://aka.ms/new-console-template for more information + +using System.Text.Json; +using System.Text.Json.Serialization; +using ArcaneLibs.Extensions; +using LibMatrix.Services; +using LibMatrix.Utilities.Bot; +using MediaModeratorPoC.Bot; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using PluralContactBotPoC; +using PluralContactBotPoC.Bot; + +Console.WriteLine("Hello, World!"); + +var randomBytes = new byte[32]; +Random.Shared.NextBytes(randomBytes); +var ASToken = Convert.ToBase64String(randomBytes); +Random.Shared.NextBytes(randomBytes); +var HSToken = Convert.ToBase64String(randomBytes); + +var asConfig = new AppServiceConfiguration() { + Id = "plural_contact_bot", + Url = null, + SenderLocalpart = "plural_contact_bot", + AppserviceToken = ASToken, + HomeserverToken = HSToken, + Namespaces = new() { + Users = new() { + new() { + Exclusive = false, + Regex = "@.*" + } + }, + Aliases = new() { + new() { + Exclusive = false, + Regex = "#.*" + } + }, + Rooms = new() { + new() { + Exclusive = false, + Regex = "!.*" + } + } + }, + RateLimited = false, + Protocols = new List() { "matrix" } +}; + +if(File.Exists("appservice.json")) + asConfig = JsonSerializer.Deserialize(File.ReadAllText("appservice.json"))!; + +File.WriteAllText("appservice.yaml", asConfig.ToYaml()); +File.WriteAllText("appservice.json", asConfig.ToJson()); +Environment.Exit(0); + +var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => { + services.AddScoped(x => + new TieredStorageService( + cacheStorageProvider: new FileStorageProvider("bot_data/cache/"), + dataStorageProvider: new FileStorageProvider("bot_data/data/") + ) + ); + services.AddSingleton(); + services.AddSingleton(); + + services.AddRoryLibMatrixServices(); + services.AddBot(withCommands: true); + + services.AddHostedService(); +}).UseConsoleLifetime().Build(); + +await host.RunAsync(); diff --git a/ExampleBots/PluralContactBotPoC/Properties/launchSettings.json b/ExampleBots/PluralContactBotPoC/Properties/launchSettings.json new file mode 100644 index 0000000..997e294 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/Properties/launchSettings.json @@ -0,0 +1,26 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "profiles": { + "Default": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + + } + }, + "Development": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + "DOTNET_ENVIRONMENT": "Development" + } + }, + "Local config": { + "commandName": "Project", + "dotnetRunMessages": true, + "environmentVariables": { + "DOTNET_ENVIRONMENT": "Local" + } + } + } +} diff --git a/ExampleBots/PluralContactBotPoC/appsettings.Development.json b/ExampleBots/PluralContactBotPoC/appsettings.Development.json new file mode 100644 index 0000000..93dc0e6 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/appsettings.Development.json @@ -0,0 +1,17 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + }, + "LibMatrixBot": { + // The homeserver to connect to + "Homeserver": "rory.gay", + // The access token to use + "AccessToken": "syt_xxxxxxxxxxxxxxxxx", + // The command prefix + "Prefix": "?" + } +} diff --git a/ExampleBots/PluralContactBotPoC/appsettings.json b/ExampleBots/PluralContactBotPoC/appsettings.json new file mode 100644 index 0000000..6ba02f3 --- /dev/null +++ b/ExampleBots/PluralContactBotPoC/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} -- cgit 1.4.1