diff options
author | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-09-15 09:50:45 +0200 |
---|---|---|
committer | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-09-15 09:50:45 +0200 |
commit | 6bd02248ccfbcb46960a6f39eaad23888d190eb5 (patch) | |
tree | 110578f31b6f9f70a7a1edab32fb3a34d6ad4f1a | |
parent | Media moderator PoC works, abstract command handling to library (diff) | |
download | LibMatrix-bak-6bd02248ccfbcb46960a6f39eaad23888d190eb5.tar.xz |
Some refactoring
68 files changed, 870 insertions, 288 deletions
diff --git a/.gitignore b/.gitignore index 5350fd3..625aad4 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ matrix-sync.json /patches/ MatrixRoomUtils.Bot/bot_data/ appsettings.Local*.json +appservice.yaml +appservice.json 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<bool> 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 = $"<pre class=\"language-csharp\">\n{msg}\n</pre>", + 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 = $"<pre class=\"language-csharp\">\n{msg}\n</pre>", + // // 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 @@ <PropertyGroup> <OutputType>Exe</OutputType> - <TargetFramework>net8.0</TargetFramework> + <TargetFramework>net7.0</TargetFramework> <LangVersion>preview</LangVersion> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> @@ -22,7 +22,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0-preview.7.23375.6" /> + <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" /> </ItemGroup> <ItemGroup> <Content Include="appsettings*.json"> 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<ServerRoomSizeCalulator>(); + // services.AddHostedService<ServerRoomSizeCalulator>(); services.AddHostedService<MRUBot>(); }).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<MediaModBot> _logger; - private readonly MediaModBotConfiguration _configuration; - private readonly HomeserverResolverService _hsResolver; +public class MediaModBot(AuthenticatedHomeserverGeneric hs, ILogger<MediaModBot> logger, MediaModBotConfiguration configuration, + HomeserverResolverService hsResolver) : IHostedService { private readonly IEnumerable<ICommand> _commands; private Task _listenerTask; @@ -33,20 +30,11 @@ public class MediaModBot : IHostedService { private GenericRoom _logRoom; private GenericRoom _controlRoom; - public MediaModBot(AuthenticatedHomeserverGeneric hs, ILogger<MediaModBot> logger, - MediaModBotConfiguration configuration, HomeserverResolverService hsResolver) { - logger.LogInformation("{} instantiated!", this.GetType().Name); - _hs = hs; - _logger = logger; - _configuration = configuration; - _hsResolver = hsResolver; - } - /// <summary>Triggered when the application host is ready to start the service.</summary> /// <param name="cancellationToken">Indicates that the start process has been aborted.</param> 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<BotData>("gay.rory.media_moderator_poc_data"); + botData = await hs.GetAccountData<BotData>("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<string> 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" + $"<font color=\"#FF0000\">User {MessageFormatter.HtmlFormatMention(@event.Sender)} posted a banned image <a href=\"{message.Url}\">{message.Url}</a></font>" }); 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 { // </span> // </blockquote> 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 { /// <summary>Triggered when the application host is performing a graceful shutdown.</summary> /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param> public async Task StopAsync(CancellationToken cancellationToken) { - _logger.LogInformation("Shutting down bot!"); + logger.LogInformation("Shutting down bot!"); } private async Task<StateEventResponse?> CheckMedia(StateEventResponse @event) { @@ -277,67 +266,66 @@ public class MediaModBot : IHostedService { var hashAlgo = SHA3_256.Create(); var mxcUri = @event.RawContent["url"].GetValue<string>(); - 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<string>())) { - _logger.LogInformation("{url} matched rule {rule}", @event.RawContent["url"], rule.ToJson(ignoreNull: true)); + if (regex.IsMatch(@event.RawContent["url"]!.GetValue<string>())) { + 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 { /// <summary> /// This is an MXC URI, hashed with SHA3-256. /// </summary> 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<string> 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<bool> 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<BotData>("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<PluralContactBot> logger, LibMatrixBotConfiguration botConfiguration, + PluralContactBotConfiguration configuration, + HomeserverResolverService hsResolver) : IHostedService { + private readonly IEnumerable<ICommand> _commands; + + private Task _listenerTask; + + private GenericRoom? _logRoom; + + /// <summary>Triggered when the application host is ready to start the service.</summary> + /// <param name="cancellationToken">Indicates that the start process has been aborted.</param> + 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<SystemData>($"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); + } + }); + } + + /// <summary>Triggered when the application host is performing a graceful shutdown.</summary> + /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param> + 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 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net8.0</TargetFramework> + <LangVersion>preview</LangVersion> + <ImplicitUsings>enable</ImplicitUsings> + <Nullable>enable</Nullable> + <PublishAot>false</PublishAot> + <InvariantGlobalization>true</InvariantGlobalization> + <!-- <PublishTrimmed>true</PublishTrimmed>--> + <!-- <PublishReadyToRun>true</PublishReadyToRun>--> + <!-- <PublishSingleFile>true</PublishSingleFile>--> + <!-- <PublishReadyToRunShowWarnings>true</PublishReadyToRunShowWarnings>--> + <!-- <PublishTrimmedShowLinkerSizeComparison>true</PublishTrimmedShowLinkerSizeComparison>--> + <!-- <PublishTrimmedShowLinkerSizeComparisonWarnings>true</PublishTrimmedShowLinkerSizeComparisonWarnings>--> + </PropertyGroup> + + <ItemGroup> + <!-- <ProjectReference Include="..\..\..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj" />--> + <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj" /> + <ProjectReference Include="..\..\Utilities\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj" /> + </ItemGroup> + + <ItemGroup> + <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0-preview.7.23375.6" /> + </ItemGroup> + <ItemGroup> + <Content Include="appsettings*.json"> + <CopyToOutputDirectory>Always</CopyToOutputDirectory> + </Content> + </ItemGroup> + <ItemGroup> + <Folder Include="Bot\StateEventTypes\" /> + </ItemGroup> +</Project> 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<string>() { "matrix" } +}; + +if(File.Exists("appservice.json")) + asConfig = JsonSerializer.Deserialize<AppServiceConfiguration>(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<TieredStorageService>(x => + new TieredStorageService( + cacheStorageProvider: new FileStorageProvider("bot_data/cache/"), + dataStorageProvider: new FileStorageProvider("bot_data/data/") + ) + ); + services.AddSingleton<PluralContactBotConfiguration>(); + services.AddSingleton<AppServiceConfiguration>(); + + services.AddRoryLibMatrixServices(); + services.AddBot(withCommands: true); + + services.AddHostedService<PluralContactBot>(); +}).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" + } + } +} diff --git a/LibMatrix/Extensions/HttpClientExtensions.cs b/LibMatrix/Extensions/HttpClientExtensions.cs index d4017ed..31ae650 100644 --- a/LibMatrix/Extensions/HttpClientExtensions.cs +++ b/LibMatrix/Extensions/HttpClientExtensions.cs @@ -2,6 +2,7 @@ using System.Diagnostics; using System.Net.Http.Headers; using System.Reflection; using System.Text.Json; +using ArcaneLibs.Extensions; namespace LibMatrix.Extensions; @@ -20,13 +21,18 @@ public static class HttpClientExtensions { } public class MatrixHttpClient : HttpClient { + internal string? AssertedUserId { get; set; } + public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + if (request.RequestUri is null) throw new NullReferenceException("RequestUri is null"); + if (AssertedUserId is not null) request.RequestUri = request.RequestUri.AddQuery("user_id", AssertedUserId); + Console.WriteLine($"Sending request to {request.RequestUri}"); try { - var WebAssemblyEnableStreamingResponseKey = + var webAssemblyEnableStreamingResponseKey = new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse"); - request.Options.Set(WebAssemblyEnableStreamingResponseKey, true); + request.Options.Set(webAssemblyEnableStreamingResponseKey, true); } catch (Exception e) { Console.WriteLine("Failed to set browser response streaming:"); @@ -50,7 +56,6 @@ public class MatrixHttpClient : HttpClient { typeof(HttpRequestMessage).GetField("_sendStatus", BindingFlags.NonPublic | BindingFlags.Instance) ?.SetValue(request, 0); return await SendAsync(request, cancellationToken); - } // GetFromJsonAsync diff --git a/LibMatrix/Filters/SyncFilter.cs b/LibMatrix/Filters/SyncFilter.cs index c907f6b..e3e8164 100644 --- a/LibMatrix/Filters/SyncFilter.cs +++ b/LibMatrix/Filters/SyncFilter.cs @@ -1,3 +1,4 @@ +using System.Reflection.Metadata; using System.Text.Json.Serialization; namespace LibMatrix.Filters; @@ -25,42 +26,58 @@ public class SyncFilter { [JsonPropertyName("timeline")] public StateFilter? Timeline { get; set; } - - public class StateFilter : EventFilter { + public class StateFilter(bool? containsUrl = null, bool? includeRedundantMembers = null, bool? lazyLoadMembers = null, List<string>? rooms = null, + List<string>? notRooms = null, bool? unreadThreadNotifications = null, + //base ctor + int? limit = null, List<string>? types = null, List<string>? notTypes = null, List<string>? senders = null, List<string>? notSenders = null + ) : EventFilter(limit: limit, types: types, notTypes: notTypes, senders: senders, notSenders: notSenders) { [JsonPropertyName("contains_url")] - public bool? ContainsUrl { get; set; } + public bool? ContainsUrl { get; set; } = containsUrl; [JsonPropertyName("include_redundant_members")] - public bool? IncludeRedundantMembers { get; set; } + public bool? IncludeRedundantMembers { get; set; } = includeRedundantMembers; [JsonPropertyName("lazy_load_members")] - public bool? LazyLoadMembers { get; set; } + public bool? LazyLoadMembers { get; set; } = lazyLoadMembers; [JsonPropertyName("rooms")] - public List<string>? Rooms { get; set; } + public List<string>? Rooms { get; set; } = rooms; [JsonPropertyName("not_rooms")] - public List<string>? NotRooms { get; set; } + public List<string>? NotRooms { get; set; } = notRooms; [JsonPropertyName("unread_thread_notifications")] - public bool? UnreadThreadNotifications { get; set; } + public bool? UnreadThreadNotifications { get; set; } = unreadThreadNotifications; } } - public class EventFilter { + public class EventFilter(int? limit = null, List<string>? types = null, List<string>? notTypes = null, List<string>? senders = null, List<string>? notSenders = null) { [JsonPropertyName("limit")] - public int? Limit { get; set; } + public int? Limit { get; set; } = limit; [JsonPropertyName("types")] - public List<string>? Types { get; set; } + public List<string>? Types { get; set; } = types; [JsonPropertyName("not_types")] - public List<string>? NotTypes { get; set; } + public List<string>? NotTypes { get; set; } = notTypes; [JsonPropertyName("senders")] - public List<string>? Senders { get; set; } + public List<string>? Senders { get; set; } = senders; [JsonPropertyName("not_senders")] - public List<string>? NotSenders { get; set; } + public List<string>? NotSenders { get; set; } = notSenders; } } + +public static class ExampleFilters { + public static readonly SyncFilter Limit1Filter = new() { + Presence = new(limit: 1), + Room = new() { + AccountData = new(limit: 1), + Ephemeral = new(limit: 1), + State = new(limit: 1), + Timeline = new(limit: 1), + }, + AccountData = new(limit: 1) + }; +} diff --git a/LibMatrix/Helpers/MessageFormatter.cs b/LibMatrix/Helpers/MessageFormatter.cs index ff0a00f..37d7004 100644 --- a/LibMatrix/Helpers/MessageFormatter.cs +++ b/LibMatrix/Helpers/MessageFormatter.cs @@ -4,30 +4,30 @@ using LibMatrix.StateEventTypes.Spec; namespace LibMatrix.Helpers; public static class MessageFormatter { - public static RoomMessageEventData FormatError(string error) { - return new RoomMessageEventData(body: error, messageType: "m.text") { + public static RoomMessageEventContent FormatError(string error) { + return new RoomMessageEventContent(body: error, messageType: "m.text") { FormattedBody = $"<font color=\"#FF0000\">{error}: {error}</font>", Format = "org.matrix.custom.html" }; } - public static RoomMessageEventData FormatException(string error, Exception e) { - return new RoomMessageEventData(body: $"{error}: {e.Message}", messageType: "m.text") { + public static RoomMessageEventContent FormatException(string error, Exception e) { + return new RoomMessageEventContent(body: $"{error}: {e.Message}", messageType: "m.text") { FormattedBody = $"<font color=\"#FF0000\">{error}: <pre>{e.Message}</pre>" + $"</font>", Format = "org.matrix.custom.html" }; } - public static RoomMessageEventData FormatSuccess(string text) { - return new RoomMessageEventData(body: text, messageType: "m.text") { + public static RoomMessageEventContent FormatSuccess(string text) { + return new RoomMessageEventContent(body: text, messageType: "m.text") { FormattedBody = $"<font color=\"#00FF00\">{text}</font>", Format = "org.matrix.custom.html" }; } - public static RoomMessageEventData FormatSuccessJson(string text, object data) { - return new RoomMessageEventData(body: text, messageType: "m.text") { + public static RoomMessageEventContent FormatSuccessJson(string text, object data) { + return new RoomMessageEventContent(body: text, messageType: "m.text") { FormattedBody = $"<font color=\"#00FF00\">{text}: <pre>{data.ToJson(ignoreNull: true)}</pre></font>", Format = "org.matrix.custom.html" }; diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs index 0b3201c..a280c54 100644 --- a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs +++ b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs @@ -2,6 +2,7 @@ using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; +using ArcaneLibs.Extensions; using LibMatrix.Extensions; using LibMatrix.Helpers; using LibMatrix.Responses; @@ -14,21 +15,18 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer { public AuthenticatedHomeserverGeneric(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) : base(canonicalHomeServerDomain) { Storage = storage; AccessToken = accessToken.Trim(); - HomeServerDomain = canonicalHomeServerDomain.Trim(); SyncHelper = new SyncHelper(this, storage); - _httpClient = new MatrixHttpClient(); } - public TieredStorageService Storage { get; set; } - public SyncHelper SyncHelper { get; init; } - public WhoAmIResponse WhoAmI { get; set; } = null!; - public string UserId => WhoAmI.UserId; - public string AccessToken { get; set; } + public virtual TieredStorageService Storage { get; set; } + public virtual SyncHelper SyncHelper { get; init; } + public virtual WhoAmIResponse WhoAmI { get; set; } = null!; + public virtual string UserId => WhoAmI.UserId; + public virtual string AccessToken { get; set; } + public virtual Task<GenericRoom> GetRoom(string roomId) => Task.FromResult<GenericRoom>(new(this, roomId)); - public Task<GenericRoom> GetRoom(string roomId) => Task.FromResult<GenericRoom>(new(this, roomId)); - - public async Task<List<GenericRoom>> GetJoinedRooms() { + public virtual async Task<List<GenericRoom>> GetJoinedRooms() { var roomQuery = await _httpClient.GetAsync("/_matrix/client/v3/joined_rooms"); var roomsJson = await roomQuery.Content.ReadFromJsonAsync<JsonElement>(); @@ -39,7 +37,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer { return rooms; } - public async Task<string> UploadFile(string fileName, Stream fileStream, string contentType = "application/octet-stream") { + public virtual async Task<string> UploadFile(string fileName, Stream fileStream, string contentType = "application/octet-stream") { var res = await _httpClient.PostAsync($"/_matrix/media/v3/upload?filename={fileName}", new StreamContent(fileStream)); if (!res.IsSuccessStatusCode) { Console.WriteLine($"Failed to upload file: {await res.Content.ReadAsStringAsync()}"); @@ -50,7 +48,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer { return resJson.GetProperty("content_uri").GetString()!; } - public async Task<GenericRoom> CreateRoom(CreateRoomRequest creationEvent) { + public virtual async Task<GenericRoom> CreateRoom(CreateRoomRequest creationEvent) { creationEvent.CreationContent["creator"] = UserId; var res = await _httpClient.PostAsJsonAsync("/_matrix/client/v3/createRoom", creationEvent, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull @@ -60,12 +58,36 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer { throw new InvalidDataException($"Failed to create room: {await res.Content.ReadAsStringAsync()}"); } - return await GetRoom((await res.Content.ReadFromJsonAsync<JsonObject>())!["room_id"]!.ToString()); + var room = await GetRoom((await res.Content.ReadFromJsonAsync<JsonObject>())!["room_id"]!.ToString()); + + foreach (var user in creationEvent.Invite) { + await room.InviteUser(user); + } + + return room; + } + +#region Utility Functions + public virtual async IAsyncEnumerable<GenericRoom> GetJoinedRoomsByType(string type) { + var rooms = await GetJoinedRooms(); + var tasks = rooms.Select(async room => { + var roomType = await room.GetRoomType(); + if (roomType == type) { + return room; + } + + return null; + }).ToAsyncEnumerable(); + + await foreach (var result in tasks) { + if (result is not null) yield return result; + } } +#endregion #region Account Data - public async Task<T> GetAccountData<T>(string key) { + public virtual async Task<T> GetAccountData<T>(string key) { // var res = await _httpClient.GetAsync($"/_matrix/client/v3/user/{UserId}/account_data/{key}"); // if (!res.IsSuccessStatusCode) { // Console.WriteLine($"Failed to get account data: {await res.Content.ReadAsStringAsync()}"); @@ -76,7 +98,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer { return await _httpClient.GetFromJsonAsync<T>($"/_matrix/client/v3/user/{UserId}/account_data/{key}"); } - public async Task SetAccountData(string key, object data) { + public virtual async Task SetAccountData(string key, object data) { var res = await _httpClient.PutAsJsonAsync($"/_matrix/client/v3/user/{UserId}/account_data/{key}", data); if (!res.IsSuccessStatusCode) { Console.WriteLine($"Failed to set account data: {await res.Content.ReadAsStringAsync()}"); diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs index 8ffcfaf..e44d727 100644 --- a/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs +++ b/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs @@ -4,11 +4,5 @@ using LibMatrix.Services; namespace LibMatrix.Homeservers; -public class AuthenticatedHomeserverMxApiExtended : AuthenticatedHomeserverGeneric { - public AuthenticatedHomeserverMxApiExtended(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) : base(storage, canonicalHomeServerDomain, accessToken) { - AccessToken = accessToken.Trim(); - HomeServerDomain = canonicalHomeServerDomain.Trim(); - SyncHelper = new SyncHelper(this, storage); - _httpClient = new MatrixHttpClient(); - } -} +public class AuthenticatedHomeserverMxApiExtended(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) : AuthenticatedHomeserverGeneric(storage, canonicalHomeServerDomain, + accessToken); diff --git a/LibMatrix/Homeservers/RemoteHomeServer.cs b/LibMatrix/Homeservers/RemoteHomeServer.cs index 923986d..caed397 100644 --- a/LibMatrix/Homeservers/RemoteHomeServer.cs +++ b/LibMatrix/Homeservers/RemoteHomeServer.cs @@ -5,28 +5,24 @@ using LibMatrix.StateEventTypes.Spec; namespace LibMatrix.Homeservers; -public class RemoteHomeServer { - public RemoteHomeServer(string canonicalHomeServerDomain) { - HomeServerDomain = canonicalHomeServerDomain; - _httpClient = new MatrixHttpClient(); - _httpClient.Timeout = TimeSpan.FromSeconds(5); - } +public class RemoteHomeServer(string canonicalHomeServerDomain) { + // _httpClient.Timeout = TimeSpan.FromSeconds(5); private Dictionary<string, object> _profileCache { get; set; } = new(); - public string HomeServerDomain { get; set; } + public string HomeServerDomain { get; } = canonicalHomeServerDomain.Trim(); public string FullHomeServerDomain { get; set; } - public MatrixHttpClient _httpClient { get; set; } + public MatrixHttpClient _httpClient { get; set; } = new(); - public async Task<ProfileResponseEventData> GetProfile(string mxid) { + public async Task<ProfileResponseEventContent> GetProfile(string mxid) { if(mxid is null) throw new ArgumentNullException(nameof(mxid)); if (_profileCache.TryGetValue(mxid, out var value)) { if (value is SemaphoreSlim s) await s.WaitAsync(); - if (value is ProfileResponseEventData p) return p; + if (value is ProfileResponseEventContent p) return p; } _profileCache[mxid] = new SemaphoreSlim(1); var resp = await _httpClient.GetAsync($"/_matrix/client/v3/profile/{mxid}"); - var data = await resp.Content.ReadFromJsonAsync<ProfileResponseEventData>(); + var data = await resp.Content.ReadFromJsonAsync<ProfileResponseEventContent>(); if (!resp.IsSuccessStatusCode) Console.WriteLine("Profile: " + data); _profileCache[mxid] = data; diff --git a/LibMatrix/Interfaces/IStateEventType.cs b/LibMatrix/Interfaces/IStateEventType.cs index 13a0d05..f2e4a3b 100644 --- a/LibMatrix/Interfaces/IStateEventType.cs +++ b/LibMatrix/Interfaces/IStateEventType.cs @@ -1,3 +1,23 @@ +using System.Text.Json.Serialization; + namespace LibMatrix.Interfaces; -public interface IStateEventType { } +public abstract class EventContent { + [JsonPropertyName("m.relates_to")] + public virtual MessageRelatesTo? RelatesTo { get; set; } + + [JsonPropertyName("m.new_content")] + public virtual EventContent? NewContent { get; set; } + + public abstract class MessageRelatesTo { + [JsonPropertyName("m.in_reply_to")] + public EventInReplyTo? InReplyTo { get; set; } + + + + public abstract class EventInReplyTo { + [JsonPropertyName("event_id")] + public string EventId { get; set; } + } + } +} diff --git a/LibMatrix/LibMatrix.csproj b/LibMatrix/LibMatrix.csproj index 709e079..805695b 100644 --- a/LibMatrix/LibMatrix.csproj +++ b/LibMatrix/LibMatrix.csproj @@ -8,12 +8,22 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0"/> + <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1"/> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj" /> + <ProjectReference Condition="Exists('..\..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj')" Include="..\..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj"/> + <!-- This is dangerous, but eases development since locking the version will drift out of sync without noticing, + which causes build errors due to missing functions. + Using the NuGet version in development is annoying due to delays between pushing and being able to consume. + If you want to use a time-appropriate version of the library, recursively clone https://git.rory.gay/matrix/MatrixRoomUtils.git + instead, since this will be locked by the MatrixRoomUtils project, which contains both LibMatrix and ArcaneLibs as a submodule. --> + <PackageReference Condition="!Exists('..\..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj')" Include="ArcaneLibs" Version="*-preview*"/> </ItemGroup> - + + <Target Name="ArcaneLibsNugetWarning" AfterTargets="AfterBuild"> + <Warning Text="ArcaneLibs is being referenced from NuGet, which is dangerous. Please read the warning in LibMatrix.csproj!" Condition="!Exists('..\..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj')"/> + </Target> + </Project> diff --git a/LibMatrix/Responses/CreateRoomRequest.cs b/LibMatrix/Responses/CreateRoomRequest.cs index 24c9ae0..82a4b12 100644 --- a/LibMatrix/Responses/CreateRoomRequest.cs +++ b/LibMatrix/Responses/CreateRoomRequest.cs @@ -4,6 +4,7 @@ using System.Text.Json.Serialization; using System.Text.RegularExpressions; using LibMatrix.Helpers; using LibMatrix.Homeservers; +using LibMatrix.Interfaces; using LibMatrix.StateEventTypes.Spec; namespace LibMatrix.Responses; @@ -33,7 +34,7 @@ public class CreateRoomRequest { public string Visibility { get; set; } = null!; [JsonPropertyName("power_level_content_override")] - public RoomPowerLevelEventData PowerLevelContentOverride { get; set; } = null!; + public RoomPowerLevelEventContent PowerLevelContentOverride { get; set; } = null!; [JsonPropertyName("creation_content")] public JsonObject CreationContent { get; set; } = new(); @@ -52,7 +53,7 @@ public class CreateRoomRequest { InitialState.Add(stateEvent = new StateEvent { Type = event_type, StateKey = event_key, - TypedContent = Activator.CreateInstance( + TypedContent = (EventContent)Activator.CreateInstance( StateEvent.KnownStateEventTypes.FirstOrDefault(x => x.GetCustomAttributes<MatrixEventAttribute>()? .Any(y => y.EventName == event_type) ?? false) ?? typeof(object) diff --git a/LibMatrix/RoomTypes/GenericRoom.cs b/LibMatrix/RoomTypes/GenericRoom.cs index 4c784ce..146b5dd 100644 --- a/LibMatrix/RoomTypes/GenericRoom.cs +++ b/LibMatrix/RoomTypes/GenericRoom.cs @@ -85,7 +85,7 @@ public class GenericRoom { // TODO: should we even error handle here? public async Task<string> GetNameAsync() { try { - var res = await GetStateAsync<RoomNameEventData>("m.room.name"); + var res = await GetStateAsync<RoomNameEventContent>("m.room.name"); return res?.Name ?? RoomId; } catch (MatrixException e) { @@ -108,7 +108,7 @@ public class GenericRoom { // var res = GetFullStateAsync(); // await foreach (var member in res) { // if (member?.Type != "m.room.member") continue; - // if (joinedOnly && (member.TypedContent as RoomMemberEventData)?.Membership is not "join") continue; + // if (joinedOnly && (member.TypedContent as RoomMemberEventContent)?.Membership is not "join") continue; // yield return member; // } var res = await _httpClient.GetAsync($"/_matrix/client/v3/rooms/{RoomId}/members"); @@ -116,7 +116,7 @@ public class GenericRoom { JsonSerializer.DeserializeAsyncEnumerable<StateEventResponse>(await res.Content.ReadAsStreamAsync()); await foreach (var resp in result) { if (resp?.Type != "m.room.member") continue; - if (joinedOnly && (resp.TypedContent as RoomMemberEventData)?.Membership is not "join") continue; + if (joinedOnly && (resp.TypedContent as RoomMemberEventContent)?.Membership is not "join") continue; yield return resp; } } @@ -124,38 +124,38 @@ public class GenericRoom { #region Utility shortcuts public async Task<List<string>> GetAliasesAsync() { - var res = await GetStateAsync<RoomAliasEventData>("m.room.aliases"); + var res = await GetStateAsync<RoomAliasEventContent>("m.room.aliases"); return res.Aliases; } - public async Task<CanonicalAliasEventData?> GetCanonicalAliasAsync() => - await GetStateAsync<CanonicalAliasEventData>("m.room.canonical_alias"); + public async Task<CanonicalAliasEventContent?> GetCanonicalAliasAsync() => + await GetStateAsync<CanonicalAliasEventContent>("m.room.canonical_alias"); - public async Task<RoomTopicEventData?> GetTopicAsync() => - await GetStateAsync<RoomTopicEventData>("m.room.topic"); + public async Task<RoomTopicEventContent?> GetTopicAsync() => + await GetStateAsync<RoomTopicEventContent>("m.room.topic"); - public async Task<RoomAvatarEventData?> GetAvatarUrlAsync() => - await GetStateAsync<RoomAvatarEventData>("m.room.avatar"); + public async Task<RoomAvatarEventContent?> GetAvatarUrlAsync() => + await GetStateAsync<RoomAvatarEventContent>("m.room.avatar"); - public async Task<JoinRulesEventData> GetJoinRuleAsync() => - await GetStateAsync<JoinRulesEventData>("m.room.join_rules"); + public async Task<JoinRulesEventContent> GetJoinRuleAsync() => + await GetStateAsync<JoinRulesEventContent>("m.room.join_rules"); - public async Task<HistoryVisibilityEventData?> GetHistoryVisibilityAsync() => - await GetStateAsync<HistoryVisibilityEventData>("m.room.history_visibility"); + public async Task<HistoryVisibilityEventContent?> GetHistoryVisibilityAsync() => + await GetStateAsync<HistoryVisibilityEventContent>("m.room.history_visibility"); - public async Task<GuestAccessEventData?> GetGuestAccessAsync() => - await GetStateAsync<GuestAccessEventData>("m.room.guest_access"); + public async Task<GuestAccessEventContent?> GetGuestAccessAsync() => + await GetStateAsync<GuestAccessEventContent>("m.room.guest_access"); - public async Task<RoomCreateEventData> GetCreateEventAsync() => - await GetStateAsync<RoomCreateEventData>("m.room.create"); + public async Task<RoomCreateEventContent> GetCreateEventAsync() => + await GetStateAsync<RoomCreateEventContent>("m.room.create"); public async Task<string?> GetRoomType() { - var res = await GetStateAsync<RoomCreateEventData>("m.room.create"); + var res = await GetStateAsync<RoomCreateEventContent>("m.room.create"); return res.Type; } - public async Task<RoomPowerLevelEventData?> GetPowerLevelsAsync() => - await GetStateAsync<RoomPowerLevelEventData>("m.room.power_levels"); + public async Task<RoomPowerLevelEventContent?> GetPowerLevelsAsync() => + await GetStateAsync<RoomPowerLevelEventContent>("m.room.power_levels"); #endregion @@ -187,7 +187,7 @@ public class GenericRoom { await (await _httpClient.PutAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state/{eventType}/{stateKey}", content)) .Content.ReadFromJsonAsync<EventIdResponse>(); - public async Task<EventIdResponse> SendMessageEventAsync(string eventType, RoomMessageEventData content) { + public async Task<EventIdResponse> SendMessageEventAsync(string eventType, RoomMessageEventContent content) { var res = await _httpClient.PutAsJsonAsync( $"/_matrix/client/v3/rooms/{RoomId}/send/{eventType}/" + Guid.NewGuid(), content, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull @@ -239,4 +239,8 @@ public class GenericRoom { return (await (await _httpClient.PutAsJsonAsync( $"/_matrix/client/v3/rooms/{RoomId}/redact/{eventToRedact}/{Guid.NewGuid()}", data)).Content.ReadFromJsonAsync<EventIdResponse>())!; } + + public async Task InviteUser(string userId, string? reason = null) { + await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/invite", new UserIdAndReason(userId, reason)); + } } diff --git a/LibMatrix/RoomTypes/SpaceRoom.cs b/LibMatrix/RoomTypes/SpaceRoom.cs index e1e9879..0a4447a 100644 --- a/LibMatrix/RoomTypes/SpaceRoom.cs +++ b/LibMatrix/RoomTypes/SpaceRoom.cs @@ -12,7 +12,7 @@ public class SpaceRoom : GenericRoom { } private static SemaphoreSlim _semaphore = new(1, 1); - public async IAsyncEnumerable<GenericRoom> GetRoomsAsync(bool includeRemoved = false) { + public async IAsyncEnumerable<GenericRoom> GetChildrenAsync(bool includeRemoved = false) { await _semaphore.WaitAsync(); var rooms = new List<GenericRoom>(); var state = GetFullStateAsync(); diff --git a/LibMatrix/StateEvent.cs b/LibMatrix/StateEvent.cs index 175d706..9ca9141 100644 --- a/LibMatrix/StateEvent.cs +++ b/LibMatrix/StateEvent.cs @@ -6,28 +6,41 @@ using ArcaneLibs; using ArcaneLibs.Extensions; using LibMatrix.Helpers; using LibMatrix.Interfaces; +using LibMatrix.StateEventTypes; namespace LibMatrix; public class StateEvent { - public static List<Type> KnownStateEventTypes = - new ClassCollector<IStateEventType>().ResolveFromAllAccessibleAssemblies(); + public static readonly List<Type> KnownStateEventTypes = + new ClassCollector<EventContent>().ResolveFromAllAccessibleAssemblies(); + + public static readonly Dictionary<string, Type> KnownStateEventTypesByName = KnownStateEventTypes.Aggregate( + new Dictionary<string, Type>(), + (dict, type) => { + var attrs = type.GetCustomAttributes<MatrixEventAttribute>(); + foreach (var attr in attrs) { + dict[attr.EventName] = type; + } + + return dict; + }); public static Type GetStateEventType(string type) { if (type == "m.receipt") { return typeof(Dictionary<string, JsonObject>); } - var eventType = KnownStateEventTypes.FirstOrDefault(x => - x.GetCustomAttributes<MatrixEventAttribute>()?.Any(y => y.EventName == type) ?? false); + // var eventType = KnownStateEventTypes.FirstOrDefault(x => + // x.GetCustomAttributes<MatrixEventAttribute>()?.Any(y => y.EventName == type) ?? false); + var eventType = KnownStateEventTypesByName.GetValueOrDefault(type); - return eventType ?? typeof(object); + return eventType ?? typeof(UnknownEventContent); } - public object TypedContent { + public EventContent TypedContent { get { try { - return RawContent.Deserialize(GetType)!; + return (EventContent) RawContent.Deserialize(GetType)!; } catch (JsonException e) { Console.WriteLine(e); @@ -42,19 +55,8 @@ public class StateEvent { [JsonPropertyName("state_key")] public string StateKey { get; set; } = ""; - private string _type; - [JsonPropertyName("type")] - public string Type { - get => _type; - set { - _type = value; - // if (RawContent is not null && this is StateEventResponse stateEventResponse) { - // if (File.Exists($"unknown_state_events/{Type}/{stateEventResponse.EventId}.json")) return; - // var x = GetType.Name; - // } - } - } + public string Type { get; set; } [JsonPropertyName("replaces_state")] public string? ReplacesState { get; set; } @@ -79,7 +81,7 @@ public class StateEvent { var type = GetStateEventType(Type); //special handling for some types - // if (type == typeof(RoomEmotesEventData)) { + // if (type == typeof(RoomEmotesEventContent)) { // RawContent["emote"] = RawContent["emote"]?.AsObject() ?? new JsonObject(); // } // diff --git a/LibMatrix/StateEventTypes/Common/MjolnirShortcodeEventData.cs b/LibMatrix/StateEventTypes/Common/MjolnirShortcodeEventData.cs index 7a4b3f3..ff11be7 100644 --- a/LibMatrix/StateEventTypes/Common/MjolnirShortcodeEventData.cs +++ b/LibMatrix/StateEventTypes/Common/MjolnirShortcodeEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Common; [MatrixEvent(EventName = "org.matrix.mjolnir.shortcode")] -public class MjolnirShortcodeEventData : IStateEventType { +public class MjolnirShortcodeEventContent : EventContent { [JsonPropertyName("shortcode")] public string? Shortcode { get; set; } } diff --git a/LibMatrix/StateEventTypes/Common/RoomEmotesEventData.cs b/LibMatrix/StateEventTypes/Common/RoomEmotesEventData.cs index ad65b0f..a056eda 100644 --- a/LibMatrix/StateEventTypes/Common/RoomEmotesEventData.cs +++ b/LibMatrix/StateEventTypes/Common/RoomEmotesEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Common; [MatrixEvent(EventName = "im.ponies.room_emotes")] -public class RoomEmotesEventData : IStateEventType { +public class RoomEmotesEventContent : EventContent { [JsonPropertyName("emoticons")] public Dictionary<string, EmoticonData>? Emoticons { get; set; } diff --git a/LibMatrix/StateEventTypes/Spec/CanonicalAliasEventData.cs b/LibMatrix/StateEventTypes/Spec/CanonicalAliasEventContent.cs index 269bd6d..7a0e84c 100644 --- a/LibMatrix/StateEventTypes/Spec/CanonicalAliasEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/CanonicalAliasEventContent.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.canonical_alias")] -public class CanonicalAliasEventData : IStateEventType { +public class CanonicalAliasEventContent : EventContent { [JsonPropertyName("alias")] public string? Alias { get; set; } [JsonPropertyName("alt_aliases")] diff --git a/LibMatrix/StateEventTypes/Spec/GuestAccessEventData.cs b/LibMatrix/StateEventTypes/Spec/GuestAccessEventData.cs index 7ba3428..0709b86 100644 --- a/LibMatrix/StateEventTypes/Spec/GuestAccessEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/GuestAccessEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.guest_access")] -public class GuestAccessEventData : IStateEventType { +public class GuestAccessEventContent : EventContent { [JsonPropertyName("guest_access")] public string GuestAccess { get; set; } diff --git a/LibMatrix/StateEventTypes/Spec/HistoryVisibilityEventData.cs b/LibMatrix/StateEventTypes/Spec/HistoryVisibilityEventData.cs index deca7c8..b19dd32 100644 --- a/LibMatrix/StateEventTypes/Spec/HistoryVisibilityEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/HistoryVisibilityEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.history_visibility")] -public class HistoryVisibilityEventData : IStateEventType { +public class HistoryVisibilityEventContent : EventContent { [JsonPropertyName("history_visibility")] public string HistoryVisibility { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/JoinRulesEventData.cs b/LibMatrix/StateEventTypes/Spec/JoinRulesEventData.cs index b64c1dd..8c0772f 100644 --- a/LibMatrix/StateEventTypes/Spec/JoinRulesEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/JoinRulesEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.join_rules")] -public class JoinRulesEventData : IStateEventType { +public class JoinRulesEventContent : EventContent { private static string Public = "public"; private static string Invite = "invite"; private static string Knock = "knock"; diff --git a/LibMatrix/StateEventTypes/Spec/PolicyRuleStateEventData.cs b/LibMatrix/StateEventTypes/Spec/PolicyRuleStateEventData.cs index 2e66bd9..539e371 100644 --- a/LibMatrix/StateEventTypes/Spec/PolicyRuleStateEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/PolicyRuleStateEventData.cs @@ -7,7 +7,7 @@ namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.policy.rule.user")] [MatrixEvent(EventName = "m.policy.rule.server")] [MatrixEvent(EventName = "org.matrix.mjolnir.rule.server")] -public class PolicyRuleStateEventData : IStateEventType { +public class PolicyRuleEventContent : EventContent { /// <summary> /// Entity this ban applies to, can use * and ? as globs. /// </summary> diff --git a/LibMatrix/StateEventTypes/Spec/PresenceStateEventData.cs b/LibMatrix/StateEventTypes/Spec/PresenceStateEventData.cs index 5167502..b897ff0 100644 --- a/LibMatrix/StateEventTypes/Spec/PresenceStateEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/PresenceStateEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.presence")] -public class PresenceStateEventData : IStateEventType { +public class PresenceEventContent : EventContent { [JsonPropertyName("presence")] public string Presence { get; set; } [JsonPropertyName("last_active_ago")] diff --git a/LibMatrix/StateEventTypes/Spec/ProfileResponseEventData.cs b/LibMatrix/StateEventTypes/Spec/ProfileResponseEventData.cs index 14449e0..9b4f1d0 100644 --- a/LibMatrix/StateEventTypes/Spec/ProfileResponseEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/ProfileResponseEventData.cs @@ -3,7 +3,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; -public class ProfileResponseEventData : IStateEventType { +public class ProfileResponseEventContent : EventContent { [JsonPropertyName("avatar_url")] public string? AvatarUrl { get; set; } diff --git a/LibMatrix/StateEventTypes/Spec/RoomAliasEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomAliasEventData.cs index 3f2c39e..d3960a1 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomAliasEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomAliasEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.alias")] -public class RoomAliasEventData : IStateEventType { +public class RoomAliasEventContent : EventContent { [JsonPropertyName("aliases")] public List<string>? Aliases { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/RoomAvatarEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomAvatarEventData.cs index f71e1fb..e2263c8 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomAvatarEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomAvatarEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.avatar")] -public class RoomAvatarEventData : IStateEventType { +public class RoomAvatarEventContent : EventContent { [JsonPropertyName("url")] public string? Url { get; set; } diff --git a/LibMatrix/StateEventTypes/Spec/RoomCreateEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomCreateEventData.cs index 31f9411..22df784 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomCreateEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomCreateEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.create")] -public class RoomCreateEventData : IStateEventType { +public class RoomCreateEventContent : EventContent { [JsonPropertyName("room_version")] public string? RoomVersion { get; set; } [JsonPropertyName("creator")] diff --git a/LibMatrix/StateEventTypes/Spec/RoomEncryptionEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomEncryptionEventData.cs index 9673dcc..1d5ec2c 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomEncryptionEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomEncryptionEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.encryption")] -public class RoomEncryptionEventData : IStateEventType { +public class RoomEncryptionEventContent : EventContent { [JsonPropertyName("algorithm")] public string? Algorithm { get; set; } [JsonPropertyName("rotation_period_ms")] diff --git a/LibMatrix/StateEventTypes/Spec/RoomMemberEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomMemberEventData.cs index c99aa8d..a9d4710 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomMemberEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomMemberEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.member")] -public class RoomMemberEventData : IStateEventType { +public class RoomMemberEventContent : EventContent { [JsonPropertyName("reason")] public string? Reason { get; set; } diff --git a/LibMatrix/StateEventTypes/Spec/RoomMessageEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomMessageEventData.cs index d13c273..a15efe8 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomMessageEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomMessageEventData.cs @@ -6,19 +6,12 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.message")] -public class RoomMessageEventData : IStateEventType { - public RoomMessageEventData() { } - - public RoomMessageEventData(string messageType, string body) { +public class RoomMessageEventContent : EventContent { + public RoomMessageEventContent(string? messageType = "m.notice", string? body = null) { MessageType = messageType; Body = body; } - public RoomMessageEventData(string body) : this() { - Body = body; - MessageType = "m.notice"; - } - [JsonPropertyName("body")] public string Body { get; set; } @@ -31,22 +24,9 @@ public class RoomMessageEventData : IStateEventType { [JsonPropertyName("format")] public string Format { get; set; } - [JsonPropertyName("m.relates_to")] - public MessageRelatesTo? RelatesTo { get; set; } - /// <summary> /// Media URI for this message, if any /// </summary> [JsonPropertyName("url")] public string? Url { get; set; } - - public class MessageRelatesTo { - [JsonPropertyName("m.in_reply_to")] - public MessageInReplyTo? InReplyTo { get; set; } - - public class MessageInReplyTo { - [JsonPropertyName("event_id")] - public string EventId { get; set; } - } - } } diff --git a/LibMatrix/StateEventTypes/Spec/RoomNameEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomNameEventData.cs index e04f0dc..3002102 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomNameEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomNameEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.name")] -public class RoomNameEventData : IStateEventType { +public class RoomNameEventContent : EventContent { [JsonPropertyName("name")] public string? Name { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/RoomPinnedEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomPinnedEventData.cs index bb78aeb..16144bc 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomPinnedEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomPinnedEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.pinned_events")] -public class RoomPinnedEventData : IStateEventType { +public class RoomPinnedEventContent : EventContent { [JsonPropertyName("pinned")] public string[]? PinnedEvents { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/RoomPowerLevelEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomPowerLevelEventData.cs index b4f7d53..960c198 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomPowerLevelEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomPowerLevelEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.power_levels")] -public class RoomPowerLevelEventData : IStateEventType { +public class RoomPowerLevelEventContent : EventContent { [JsonPropertyName("ban")] public long Ban { get; set; } // = 50; diff --git a/LibMatrix/StateEventTypes/Spec/RoomTopicEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomTopicEventData.cs index c3deb98..61d1a01 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomTopicEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomTopicEventData.cs @@ -6,7 +6,7 @@ namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.topic")] [MatrixEvent(EventName = "org.matrix.msc3765.topic", Legacy = true)] -public class RoomTopicEventData : IStateEventType { +public class RoomTopicEventContent : EventContent { [JsonPropertyName("topic")] public string? Topic { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/RoomTypingEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomTypingEventData.cs index 3812c46..e935cb2 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomTypingEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomTypingEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.typing")] -public class RoomTypingEventData : IStateEventType { +public class RoomTypingEventContent : EventContent { [JsonPropertyName("user_ids")] public string[]? UserIds { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/ServerACLEventData.cs b/LibMatrix/StateEventTypes/Spec/ServerACLEventData.cs index d00b464..031d113 100644 --- a/LibMatrix/StateEventTypes/Spec/ServerACLEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/ServerACLEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.server_acl")] -public class ServerACLEventData : IStateEventType { +public class ServerACLEventContent : EventContent { [JsonPropertyName("allow")] public List<string> Allow { get; set; } // = null!; diff --git a/LibMatrix/StateEventTypes/Spec/SpaceChildEventData.cs b/LibMatrix/StateEventTypes/Spec/SpaceChildEventData.cs index e8c6d18..80fc771 100644 --- a/LibMatrix/StateEventTypes/Spec/SpaceChildEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/SpaceChildEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.space.child")] -public class SpaceChildEventData : IStateEventType { +public class SpaceChildEventContent : EventContent { [JsonPropertyName("auto_join")] public bool? AutoJoin { get; set; } [JsonPropertyName("via")] diff --git a/LibMatrix/StateEventTypes/Spec/SpaceParentEventData.cs b/LibMatrix/StateEventTypes/Spec/SpaceParentEventData.cs index ebd083e..1bc89ab 100644 --- a/LibMatrix/StateEventTypes/Spec/SpaceParentEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/SpaceParentEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.space.parent")] -public class SpaceParentEventData : IStateEventType { +public class SpaceParentEventContent : EventContent { [JsonPropertyName("via")] public string[]? Via { get; set; } diff --git a/LibMatrix/StateEventTypes/UnknownStateEventData.cs b/LibMatrix/StateEventTypes/UnknownStateEventData.cs new file mode 100644 index 0000000..59d8fd4 --- /dev/null +++ b/LibMatrix/StateEventTypes/UnknownStateEventData.cs @@ -0,0 +1,7 @@ +using LibMatrix.Interfaces; + +namespace LibMatrix.StateEventTypes; + +public class UnknownEventContent : EventContent { + +} diff --git a/LibMatrix/UserIdAndReason.cs b/LibMatrix/UserIdAndReason.cs index a0c2acd..09dc461 100644 --- a/LibMatrix/UserIdAndReason.cs +++ b/LibMatrix/UserIdAndReason.cs @@ -2,9 +2,10 @@ using System.Text.Json.Serialization; namespace LibMatrix; -internal class UserIdAndReason { +internal class UserIdAndReason(string? userId = null, string? reason = null) { [JsonPropertyName("user_id")] - public string UserId { get; set; } + public string UserId { get; set; } = userId; + [JsonPropertyName("reason")] - public string? Reason { get; set; } + public string? Reason { get; set; } = reason; } diff --git a/Tests/LibMatrix.Tests/GlobalUsings.cs b/Tests/LibMatrix.Tests/GlobalUsings.cs new file mode 100644 index 0000000..8c927eb --- /dev/null +++ b/Tests/LibMatrix.Tests/GlobalUsings.cs @@ -0,0 +1 @@ +global using Xunit; \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj b/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj new file mode 100644 index 0000000..ad9b2fa --- /dev/null +++ b/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj @@ -0,0 +1,32 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>net7.0</TargetFramework> + <ImplicitUsings>enable</ImplicitUsings> + <Nullable>enable</Nullable> + + <IsPackable>false</IsPackable> + <IsTestProject>true</IsTestProject> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0"/> + <PackageReference Include="xunit" Version="2.4.2"/> + <PackageReference Include="Xunit.Microsoft.DependencyInjection" Version="7.0.6"/> + <PackageReference Include="Xunit.DependencyInjection" Version="8.8.2" /> + <PackageReference Include="Xunit.DependencyInjection.Logging" Version="8.1.0" /> + <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5"> + <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + <PackageReference Include="coverlet.collector" Version="3.2.0"> + <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj" /> + </ItemGroup> + +</Project> diff --git a/Tests/LibMatrix.Tests/ResolverTest.cs b/Tests/LibMatrix.Tests/ResolverTest.cs new file mode 100644 index 0000000..b1191fe --- /dev/null +++ b/Tests/LibMatrix.Tests/ResolverTest.cs @@ -0,0 +1,10 @@ +using LibMatrix.Services; + +namespace LibMatrix.Tests; + +public class ResolverTest { + [Fact] + public void ResolveServer() { + + } +} diff --git a/Utilities/LibMatrix.Utilities.Bot/AppServiceConfiguration.cs b/Utilities/LibMatrix.Utilities.Bot/AppServiceConfiguration.cs new file mode 100644 index 0000000..4de139e --- /dev/null +++ b/Utilities/LibMatrix.Utilities.Bot/AppServiceConfiguration.cs @@ -0,0 +1,87 @@ +namespace PluralContactBotPoC; + +public class AppServiceConfiguration { + public string Id { get; set; } = null!; + public string? Url { get; set; } = null!; + public string SenderLocalpart { get; set; } = null!; + public string AppserviceToken { get; set; } = null!; + public string HomeserverToken { get; set; } = null!; + public List<string>? Protocols { get; set; } = null!; + public bool? RateLimited { get; set; } = null!; + + public AppserviceNamespaces Namespaces { get; set; } = null!; + + public class AppserviceNamespaces { + public List<AppserviceNamespace>? Users { get; set; } = null; + public List<AppserviceNamespace>? Aliases { get; set; } = null; + public List<AppserviceNamespace>? Rooms { get; set; } = null; + + public class AppserviceNamespace { + public bool Exclusive { get; set; } + public string Regex { get; set; } = null!; + } + } + + /// <summary> + /// Please dont look at code, it's horrifying but works + /// </summary> + /// <returns></returns> + public string ToYaml() { + var yaml = $""" + id: "{Id ?? throw new NullReferenceException("Id is null")}" + url: {(Url is null ? "null" : $"\"{Url}\"")} + as_token: "{AppserviceToken ?? throw new NullReferenceException("AppserviceToken is null")}" + hs_token: "{HomeserverToken ?? throw new NullReferenceException("HomeserverToken is null")}" + sender_localpart: "{SenderLocalpart ?? throw new NullReferenceException("SenderLocalpart is null")}" + + """; + + if (Protocols is not null && Protocols.Count > 0) + yaml += $""" + protocols: + - "{Protocols[0] ?? throw new NullReferenceException("Protocols[0] is null")}" + """; + else + yaml += "protocols: []"; + yaml += "\n"; + if (RateLimited is not null) + yaml += $"rate_limited: {RateLimited!.ToString().ToLower()}\n"; + else + yaml += "rate_limited: false\n"; + + yaml += "namespaces: \n"; + + if (Namespaces.Users is null || Namespaces.Users.Count == 0) + yaml += " users: []"; + else + Namespaces.Users.ForEach(x => + yaml += $""" + users: + - exclusive: {x.Exclusive.ToString().ToLower()} + regex: "{x.Regex ?? throw new NullReferenceException("x.Regex is null")}" + """); + yaml += "\n"; + + if (Namespaces.Aliases is null || Namespaces.Aliases.Count == 0) + yaml += " aliases: []"; + else + Namespaces.Aliases.ForEach(x => + yaml += $""" + aliases: + - exclusive: {x.Exclusive.ToString().ToLower()} + regex: "{x.Regex ?? throw new NullReferenceException("x.Regex is null")}" + """); + yaml += "\n"; + if (Namespaces.Rooms is null || Namespaces.Rooms.Count == 0) + yaml += " rooms: []"; + else + Namespaces.Rooms.ForEach(x => + yaml += $""" + rooms: + - exclusive: {x.Exclusive.ToString().ToLower()} + regex: "{x.Regex ?? throw new NullReferenceException("x.Regex is null")}" + """); + + return yaml; + } +} diff --git a/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs b/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs index 42cdb6c..a13f1bd 100644 --- a/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs +++ b/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs @@ -22,7 +22,7 @@ public static class BotCommandInstaller { return services; } - public static IServiceCollection AddBot(this IServiceCollection services, bool withCommands = true) { + public static IServiceCollection AddBot(this IServiceCollection services, bool withCommands = true, bool isAppservice = false) { services.AddSingleton<LibMatrixBotConfiguration>(); services.AddScoped<AuthenticatedHomeserverGeneric>(x => { diff --git a/Utilities/LibMatrix.Utilities.Bot/Commands/HelpCommand.cs b/Utilities/LibMatrix.Utilities.Bot/Commands/HelpCommand.cs index c975c8b..de033ef 100644 --- a/Utilities/LibMatrix.Utilities.Bot/Commands/HelpCommand.cs +++ b/Utilities/LibMatrix.Utilities.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(messageType: "m.notice", body: sb.ToString())); + await ctx.Room.SendMessageEventAsync("m.room.message", new RoomMessageEventContent(messageType: "m.notice", body: sb.ToString())); } } diff --git a/Utilities/LibMatrix.Utilities.Bot/Commands/PingCommand.cs b/Utilities/LibMatrix.Utilities.Bot/Commands/PingCommand.cs index e7f3b10..b008be9 100644 --- a/Utilities/LibMatrix.Utilities.Bot/Commands/PingCommand.cs +++ b/Utilities/LibMatrix.Utilities.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/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs b/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs index 0ad3e09..bdb93d5 100644 --- a/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs +++ b/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs @@ -1,3 +1,4 @@ +using LibMatrix; using LibMatrix.Homeservers; using LibMatrix.Responses; using LibMatrix.RoomTypes; @@ -10,7 +11,7 @@ public class CommandContext { public StateEventResponse MessageEvent { get; set; } public string MessageContentWithoutReply => - (MessageEvent.TypedContent as RoomMessageEventData)! + (MessageEvent.TypedContent as RoomMessageEventContent)! .Body.Split('\n') .SkipWhile(x => x.StartsWith(">")) .Aggregate((x, y) => $"{x}\n{y}"); @@ -18,4 +19,6 @@ public class CommandContext { public string CommandName => MessageContentWithoutReply.Split(' ')[0][1..]; public string[] Args => MessageContentWithoutReply.Split(' ')[1..]; public AuthenticatedHomeserverGeneric Homeserver { get; set; } + + public async Task<EventIdResponse> Reply(string eventType, RoomMessageEventContent content) => await Room.SendMessageEventAsync(eventType, content); } diff --git a/Utilities/LibMatrix.Utilities.Bot/LibMatrixBotConfiguration.cs b/Utilities/LibMatrix.Utilities.Bot/LibMatrixBotConfiguration.cs index 118b4df..27ce06b 100644 --- a/Utilities/LibMatrix.Utilities.Bot/LibMatrixBotConfiguration.cs +++ b/Utilities/LibMatrix.Utilities.Bot/LibMatrixBotConfiguration.cs @@ -7,4 +7,5 @@ public class LibMatrixBotConfiguration { public string Homeserver { get; set; } = ""; public string AccessToken { get; set; } = ""; public string Prefix { get; set; } = "?"; + public string? LogRoom { get; set; } } diff --git a/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs b/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs index d5e7dd6..df702f4 100644 --- a/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs +++ b/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs @@ -1,3 +1,4 @@ +using LibMatrix.Helpers; using LibMatrix.Homeservers; using LibMatrix.StateEventTypes.Spec; using MediaModeratorPoC.Bot.Interfaces; @@ -37,34 +38,47 @@ public class CommandListenerHostedService : IHostedService { private async Task? Run(CancellationToken cancellationToken) { _logger.LogInformation("Starting command listener!"); _hs.SyncHelper.TimelineEventHandlers.Add(async @event => { - var room = await _hs.GetRoom(@event.RoomId); - // _logger.LogInformation(eventResponse.ToJson(indent: false)); - if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventData message }) { - if (message is { MessageType: "m.text" }) { - var messageContentWithoutReply = message.Body.Split('\n', StringSplitOptions.RemoveEmptyEntries).SkipWhile(x=>x.StartsWith(">")).Aggregate((x, y) => $"{x}\n{y}"); - if (messageContentWithoutReply.StartsWith(_config.Prefix)) { - var command = _commands.FirstOrDefault(x => x.Name == messageContentWithoutReply.Split(' ')[0][_config.Prefix.Length..]); - if (command == null) { - await room.SendMessageEventAsync("m.room.message", - new RoomMessageEventData(messageType: "m.notice", body: "Command not found!")); - return; - } + try { + var room = await _hs.GetRoom(@event.RoomId); + // _logger.LogInformation(eventResponse.ToJson(indent: false)); + if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message }) { + if (message is { MessageType: "m.text" }) { + var messageContentWithoutReply = + message.Body.Split('\n', StringSplitOptions.RemoveEmptyEntries).SkipWhile(x => x.StartsWith(">")).Aggregate((x, y) => $"{x}\n{y}"); + if (messageContentWithoutReply.StartsWith(_config.Prefix)) { + var command = _commands.FirstOrDefault(x => x.Name == messageContentWithoutReply.Split(' ')[0][_config.Prefix.Length..]); + if (command == null) { + await room.SendMessageEventAsync("m.room.message", + new RoomMessageEventContent(messageType: "m.notice", body: "Command not found!")); + return; + } - var ctx = new CommandContext { - Room = room, - MessageEvent = @event, - Homeserver = _hs - }; - if (await command.CanInvoke(ctx)) { - await command.Invoke(ctx); - } - else { - await room.SendMessageEventAsync("m.room.message", - new RoomMessageEventData(messageType: "m.notice", body: "You do not have permission to run this command!")); + var ctx = new CommandContext { + Room = room, + MessageEvent = @event, + Homeserver = _hs + }; + + if (await command.CanInvoke(ctx)) { + try { + await command.Invoke(ctx); + } + catch (Exception e) { + await room.SendMessageEventAsync("m.room.message", + MessageFormatter.FormatException("An error occurred during the execution of this command", e)); + } + } + else { + await room.SendMessageEventAsync("m.room.message", + new RoomMessageEventContent(messageType: "m.notice", body: "You do not have permission to run this command!")); + } } } } } + catch (Exception e) { + _logger.LogError(e, "Error in command listener!"); + } }); await _hs.SyncHelper.RunSyncLoop(cancellationToken: cancellationToken); } |