about summary refs log tree commit diff
path: root/OsuFederatedBeatmapApi/Services/FederatedBeatmapApiBot.cs
blob: 2aaf45c7700f3c4b3514bc37d87afde5da74f170 (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
using ArcaneLibs.Extensions;
using LibMatrix.EventTypes.Spec;
using LibMatrix.EventTypes.Spec.State;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
using LibMatrix.Services;
using LibMatrix.Utilities.Bot.Interfaces;

namespace OsuFederatedBeatmapApi.Services;

public class FederatedBeatmapApiBot(AuthenticatedHomeserverGeneric hs,
    ILogger<FederatedBeatmapApiBot> logger,
    FederatedBeatmapApiBotConfiguration configuration,
    HomeserverResolverService hsResolver,
    FederatedBeatmapApiBotAccountDataService accountDataService) : IHostedService {
    private readonly IEnumerable<ICommand> _commands;

    private Task _listenerTask;

    /// <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) {
        if (Directory.Exists("bot_data/cache"))
            Directory.GetFiles("bot_data/cache").ToList().ForEach(File.Delete);

        logger.LogInformation("Logged in as {}", hs.UserId);
        await accountDataService.LoadAccountDataAsync();
        var syncHelper = new SyncHelper(hs);

        List<string> admins = new();

#pragma warning disable CS4014 // We don't care if this doesn't wait
        Task.Run(async () => {
            while (!cancellationToken.IsCancellationRequested) {
                var controlRoomMembers = accountDataService.ControlRoom.GetMembersAsync();
                await foreach (var member in controlRoomMembers) {
                    if ((member.TypedContent as RoomMemberEventContent)?
                        .Membership == "join")
                        admins.Add(member.StateKey);
                }

                var pls = await accountDataService.OwnBeatmapRepositoryRoom.GetPowerLevelsAsync();
                var ownPl = pls.GetUserPowerLevel(hs.UserId);

                if (!pls.UserHasPermission(hs.UserId, RoomPowerLevelEventContent.EventId)) {
                    accountDataService.LogRoom.SendMessageEventAsync(
                        MessageFormatter.FormatError(
                            $"I don't have permission to send power level updates in " +
                            $"{MessageFormatter.HtmlFormatMention(accountDataService.OwnBeatmapRepositoryRoom.RoomId, "my own beatmap repository")}!"));
                }
                else {
                    foreach (var admin in admins) {
                        if (pls.GetUserPowerLevel(admin) < ownPl - 1) {
                            logger.LogInformation("Raising powerlevel of {} in {} to {}", admin, accountDataService.OwnBeatmapRepositoryRoom.RoomId, ownPl - 1);
                            pls.SetUserPowerLevel(admin, ownPl - 1);
                            await accountDataService.OwnBeatmapRepositoryRoom.SendStateEventAsync(
                                RoomPowerLevelEventContent.EventId, pls);
                        }
                    }
                }

                await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken);
            }
        }, cancellationToken);
#pragma warning restore CS4014

        await accountDataService.ControlRoom.InviteUsersAsync(configuration.Admins, "You are marked as an administrator in the bot configuration!");
        await accountDataService.LogRoom.InviteUsersAsync(configuration.Admins, "You are marked as an administrator in the bot configuration!");
        await accountDataService.OwnBeatmapRepositoryRoom.InviteUsersAsync(configuration.Admins, "You are marked as an administrator in the bot configuration!");

        syncHelper.InviteReceivedHandlers.Add(async Task (args) => {
            var inviteEvent =
                args.Value.InviteState.Events.FirstOrDefault(x =>
                    x.Type == "m.room.member" && x.StateKey == hs.UserId);
            logger.LogInformation("Got invite to {RoomId} by {Sender} with reason: {Reason}", args.Key, inviteEvent!.Sender,
                (inviteEvent.TypedContent as RoomMemberEventContent)!.Reason);
            if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent!.Sender.EndsWith(":conduit.rory.gay") || admins.Contains(inviteEvent.Sender)) {
                try {
                    var senderProfile = await hs.GetProfileAsync(inviteEvent.Sender);
                    await hs.GetRoom(args.Key).JoinAsync(reason: $"I was invited by {senderProfile.DisplayName ?? inviteEvent.Sender}!");
                }
                catch (Exception e) {
                    logger.LogError("{}", e.ToString());
                    await hs.GetRoom(args.Key).LeaveAsync(reason: "I was unable to join the room: " + e);
                }
            }
        });

        syncHelper.TimelineEventHandlers.Add(async @event => {
            var room = 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 accountDataService.ControlRoom.SendMessageEventAsync(
                    MessageFormatter.FormatException($"Exception handling event {MessageFormatter.HtmlFormatMention(room.RoomId)}", e));
                await accountDataService.LogRoom.SendMessageEventAsync(
                    MessageFormatter.FormatException($"Exception handling event {MessageFormatter.HtmlFormatMention(room.RoomId)}", e));
                await using var stream = new MemoryStream(e.ToString().AsBytes().ToArray());
                await accountDataService.ControlRoom.SendFileAsync("error.log.cs", stream);
                await accountDataService.LogRoom.SendFileAsync("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!");
    }
}