about summary refs log tree commit diff
path: root/OsuFederatedBeatmapApi/Services/FederatedBeatmapApiBot.cs
blob: 04d64ad388cad4aad946611f6fe5b34f245dc0de (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
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) {
        Directory.GetFiles("bot_data/cache").ToList().ForEach(File.Delete);

        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.UserId);
                }

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

        foreach (var inviteTask in admins.Select(x=>accountDataService.ControlRoom.InviteUserAsync(x))) await inviteTask;
        foreach (var inviteTask in admins.Select(x=>accountDataService.LogRoom.InviteUserAsync(x))) await inviteTask;

        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!");
    }
}