about summary refs log tree commit diff
path: root/MatrixAntiDmSpam/PolicyListFetcher.cs
blob: 723550f2387966860df508a5226ec2d57e9ba72e (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
using LibMatrix.Filters;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
using LibMatrix.RoomTypes;

namespace MatrixAntiDmSpam;

public class PolicyListFetcher(ILogger<PolicyListFetcher> logger, AntiDmSpamConfiguration config, AuthenticatedHomeserverGeneric homeserver, PolicyStore policyStore)
    : IHostedService {
    private CancellationTokenSource _cts = new();

    public async Task StartAsync(CancellationToken cancellationToken) {
        // _ = Enumerable.Range(0, 10_000_000).Select(x => {
        //     policyStore.AllPolicies.Add(Guid.NewGuid().ToString(), new UserPolicyRuleEventContent() {
        //         Entity = Guid.NewGuid().ToString() + x,
        //         Reason = "meow " + x,
        //         Recommendation = "m.ban"
        //     });
        //     return 0;
        // }).ToList();

        logger.LogInformation("Starting policy list fetcher");
        await EnsurePolicyListsJoined();
        _ = SyncPolicyLists();
    }

    public async Task StopAsync(CancellationToken cancellationToken) {
        logger.LogInformation("Stopping policy list fetcher");
        await _cts.CancelAsync();
    }

    private async Task EnsurePolicyListsJoined() {
        var joinedRooms = await homeserver.GetJoinedRooms();
        var expectedPolicyRooms = config.PolicyLists;
        var missingRooms = expectedPolicyRooms.Where(room => !joinedRooms.Any(r => r.RoomId == room.RoomId)).ToList();

        await Task.WhenAll(missingRooms.Select(async room => {
            logger.LogInformation("Joining policy list room {}", room.RoomId);
            await homeserver.GetRoom(room.RoomId).JoinAsync(room.Vias);
        }).ToList());
    }

    private async Task SyncPolicyLists() {
        var syncHelper = new SyncHelper(homeserver, logger) {
            Timeout = 30_000,
            MinimumDelay = TimeSpan.FromSeconds(3),
            FilterId = (await homeserver.UploadFilterAsync(new SyncFilter() {
                AccountData = SyncFilter.EventFilter.Empty,
                Presence = SyncFilter.EventFilter.Empty,
                Room = new SyncFilter.RoomFilter {
                    AccountData = SyncFilter.RoomFilter.StateFilter.Empty,
                    Ephemeral = SyncFilter.RoomFilter.StateFilter.Empty,
                    State = new SyncFilter.RoomFilter.StateFilter(types: PolicyRoom.SpecPolicyEventTypes.ToList()),
                    Timeline = new SyncFilter.RoomFilter.StateFilter(types: PolicyRoom.SpecPolicyEventTypes.ToList()),
                    Rooms = config.PolicyLists.Select(x => x.RoomId).ToList(),
                    IncludeLeave = false
                }
            })).FilterId
        };

        await foreach (var syncResponse in syncHelper.EnumerateSyncAsync(_cts.Token)) {
            if (_cts.IsCancellationRequested) return;

            if (syncResponse is { Rooms.Join.Count: > 0 }) {
                foreach (var (roomId, data) in syncResponse.Rooms.Join) {
                    if (!config.PolicyLists.Any(x => x.RoomId == roomId)) continue;

                    if (data.State?.Events is null)
                        data.State = new() { Events = [] };

                    if (data.Timeline is { Events.Count: > 0 }) {
                        data.State.Events.AddRange(data.Timeline.Events);
                        data.Timeline = null;
                    }
                }

                var newPolicies = syncResponse.Rooms!.Join!.SelectMany(x => x.Value.State!.Events!)
                    .Where(x => PolicyRoom.SpecPolicyEventTypes.Contains(x.Type))
                    .ToList();

                logger.LogWarning("Received non-empty sync response with {}/{}/{} rooms, resulting in {} policies", syncResponse.Rooms?.Join?.Count,
                    syncResponse.Rooms?.Invite?.Count,
                    syncResponse.Rooms?.Leave?.Count, newPolicies.Count);

                await policyStore.AddPoliciesAsync(newPolicies);
            }
        }
    }
}