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

namespace MatrixAntiDmSpam;

public class PolicyListFetcher(ILogger<PolicyListFetcher> logger, AntiDmSpamConfiguration config, AuthenticatedHomeserverGeneric homeserver, PolicyStore policyStore)
    : IHostedService {
    public async Task StartAsync(CancellationToken cancellationToken) {
        logger.LogInformation("Starting policy list fetcher");
        await EnsurePolicyListsJoined();
        await LoadPolicyLists();
    }

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

    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();

        foreach (var room in missingRooms) {
            logger.LogInformation("Joining policy list room {}", room.RoomId);
            await homeserver.GetRoom(room.RoomId).JoinAsync(room.Vias);
        }
    }

    private async Task LoadPolicyLists() {
        foreach (var room in config.PolicyLists) {
            var sw = Stopwatch.StartNew();
            var count = await LoadPolicyList(homeserver.GetRoom(room.RoomId).AsPolicyRoom());
            logger.LogInformation("Loaded policy list {} ({}) in {}, with {} policies", room.Name, room.RoomId, sw.Elapsed, count);
        }
    }

    private async Task<int> LoadPolicyList(PolicyRoom room) {
        var policies = room.GetPoliciesAsync().ToBlockingEnumerable().ToList();
        await policyStore.AddPolicies(policies);
        return policies.Count();
    }
}