about summary refs log tree commit diff
path: root/MatrixAntiDmSpam.Core/ReportManager.cs
blob: b52ecb7813cf06fdc441fe4e5a3dcb09499b17a9 (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
using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;
using ArcaneLibs.Extensions;
using LibMatrix;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
using LibMatrix.RoomTypes;
using LibMatrix.Utilities.Bot.Interfaces;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace MatrixAntiDmSpam.Core;

public class ReportManager(
    ILogger<ReportManager> logger,
    AntiDmSpamConfiguration config,
    InviteManager inviteManager,
    AuthenticatedHomeserverGeneric homeserver) : IHostedService {
    private readonly GenericRoom? _logRoom = string.IsNullOrWhiteSpace(config.LogRoom) ? null : homeserver.GetRoom(config.LogRoom);

    public async Task StartAsync(CancellationToken cancellationToken) {
        if (config.ReportBlockedInvites) {
            inviteManager.OnBeforeInviteRejected.Add(ReportRejectedInvite);
        }
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;

    private async Task ReportRejectedInvite(RoomInviteContext invite, StateEventResponse policyEvent) {
        logger.LogInformation("Reporting rejected invite to {}", homeserver.ServerName);

        var reportContent = "MatrixAntiDmSpam[fmt=v1] | " + new ReportContent {
            Reason = "Invite rejected due to matching policy",
            RoomName = await invite.TryGetRoomNameAsync(),
            Inviter = await invite.TryGetInviterNameAsync(),
            InviteEvent = invite.MemberEvent,
            PolicyEvent = policyEvent,
            RoomId = invite.RoomId,
        }.ToJson();

        logger.LogError(reportContent);

        try {
            await homeserver.ReportRoomEventAsync(invite.RoomId, invite.MemberEvent.EventId!, reportContent, score: 50);
            var successMessage = new MessageBuilder()
                .WithColoredBody("#00FF00", $"Successfully reported {invite.MemberEvent.EventId} to {homeserver.ServerName}!")
                .Build();

            if (_logRoom != null)
                await _logRoom.SendMessageEventAsync(successMessage);
        }
        catch {
            // ignored, we're not expecting this to work on spec compliant homeservers
        }

        try {
            await homeserver.ReportRoomAsync(invite.RoomId, reportContent);
            var successMessage = new MessageBuilder()
                .WithColoredBody("#00FF00", $"Successfully reported {invite.RoomId} to {homeserver.ServerName}!")
                .Build();

            if (_logRoom != null)
                await _logRoom.SendMessageEventAsync(successMessage);
        }
        catch (Exception e) {
            logger.LogError("Failed to report room {roomId}: {exception}", invite.RoomId, e);
        }

        try {
            await homeserver.ReportUserAsync(invite.MemberEvent.Sender!, reportContent);
            var successMessage = new MessageBuilder()
                .WithColoredBody("#00FF00", $"Successfully reported {invite.MemberEvent.Sender} to {homeserver.ServerName}!")
                .Build();

            if (_logRoom != null)
                await _logRoom.SendMessageEventAsync(successMessage);
        }
        catch (Exception e) {
            logger.LogError("Failed to report user {userId}: {exception}", invite.MemberEvent.Sender, e);
        }
    }

    [SuppressMessage("ReSharper", "UnusedMember.Local", Justification = "Used for JSON serialization")]
    [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local", Justification = "Used for JSON serialization")]
    private class ReportContent {
        [JsonPropertyName("report_id")]
        public Guid ReportId { get; set; } = Guid.NewGuid();

        [JsonPropertyName("room_id")]
        public required string RoomId { get; set; }

        [JsonPropertyName("reason")]
        public required string Reason { get; set; }

        [JsonPropertyName("inviter")]
        public required string Inviter { get; set; }

        [JsonPropertyName("room_name")]
        public required string RoomName { get; set; }

        [JsonPropertyName("invite_event")]
        public required StateEventResponse InviteEvent { get; set; }

        [JsonPropertyName("policy_event")]
        public required StateEventResponse PolicyEvent { get; set; }
    }
}