about summary refs log tree commit diff
path: root/ExampleBots/MediaModeratorPoC/Bot/MediaModBot.cs
blob: 1b379c778831a5d031f6caeac0c052a694124438 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
using ArcaneLibs.Extensions;
using LibMatrix;
using LibMatrix.Homeservers;
using LibMatrix.Responses;
using LibMatrix.RoomTypes;
using LibMatrix.Services;
using LibMatrix.StateEventTypes.Spec;
using MediaModeratorPoC.Bot.AccountData;
using MediaModeratorPoC.Bot.Interfaces;
using MediaModeratorPoC.Bot.StateEventTypes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace MediaModeratorPoC.Bot;

public class MediaModBot : IHostedService {
    private readonly HomeserverProviderService _homeserverProviderService;
    private readonly ILogger<MediaModBot> _logger;
    private readonly MediaModBotConfiguration _configuration;
    private readonly IEnumerable<ICommand> _commands;

    private GenericRoom PolicyRoom;

    public MediaModBot(HomeserverProviderService homeserverProviderService, ILogger<MediaModBot> logger,
        MediaModBotConfiguration configuration, IServiceProvider services) {
        logger.LogInformation("MRUBot hosted service instantiated!");
        _homeserverProviderService = homeserverProviderService;
        _logger = logger;
        _configuration = configuration;
        _logger.LogInformation("Getting commands...");
        _commands = services.GetServices<ICommand>();
        _logger.LogInformation("Got {} commands!", _commands.Count());
    }

    /// <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>
    [SuppressMessage("ReSharper", "FunctionNeverReturns")]
    public async Task StartAsync(CancellationToken cancellationToken) {
        Directory.GetFiles("bot_data/cache").ToList().ForEach(File.Delete);
        AuthenticatedHomeserverGeneric hs;
        try {
            hs = await _homeserverProviderService.GetAuthenticatedWithToken(_configuration.Homeserver,
                _configuration.AccessToken);
        }
        catch (Exception e) {
            _logger.LogError("{}", e.Message);
            throw;
        }

        BotData botData;

        try {
            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());
                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;
            creationContent.CreationContent["type"] = "gay.rory.media_moderator_poc.control_room";

            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() {
                    JoinRule = "knock_restricted",
                    Allow = new() {
                        new JoinRulesEventData.AllowEntry() {
                            Type = "m.room_membership",
                            RoomId = botData.ControlRoom
                        }
                    }
                }
            });

            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;

            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;

            await hs.SetAccountData("gay.rory.media_moderator_poc_data", botData);
        }

        PolicyRoom = await hs.GetRoom(botData.PolicyRoom);

        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}");
            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 => {
            _logger.LogInformation(
                "Got timeline event in {}: {}", @event.RoomId, @event.ToJson(indent: true, ignoreNull: true));

            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" } && 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.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!"
                            });
                    }
                }
            }
        });
        await hs.SyncHelper.RunSyncLoop(cancellationToken: cancellationToken);
    }

    /// <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 Task StopAsync(CancellationToken cancellationToken) {
        _logger.LogInformation("Shutting down bot!");
        return Task.CompletedTask;
    }


    private async Task<bool> CheckMedia(StateEventResponse @event) {
        var stateList = PolicyRoom.GetFullStateAsync();
        await foreach (var state in stateList) {
            if(state.Type != "gay.rory.media_moderator_poc.rule.media") continue;
            var rule = state.TypedContent as MediaPolicyStateEventData;
            rule.Entity = rule.Entity.Replace("\\*", ".*").Replace("\\?", ".");
            var regex = new Regex(rule.Entity);
            if (regex.IsMatch(@event.RawContent["url"].GetValue<string>())) {
                _logger.LogInformation("{url} matched rule {rule}", @event.RawContent["url"], rule.ToJson(ignoreNull: true));
                return true;
            }
        }
        return false;
    }
}