about summary refs log tree commit diff
path: root/Tests/LibMatrix.HomeserverEmulator/Services/PaginationTokenResolverService.cs
blob: 0128ba69b998ace4724c7d0a7c83f6c0f68a9d18 (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
namespace LibMatrix.HomeserverEmulator.Services;

public class PaginationTokenResolverService(ILogger<PaginationTokenResolverService> logger, RoomStore roomStore, UserStore userStore) {
    public async Task<long?> ResolveTokenToTimestamp(string token) {
        logger.LogTrace("ResolveTokenToTimestamp({token})", token);
        if (token.StartsWith('$')) {
            //we have an event ID
            foreach (var room in roomStore._rooms) {
                var evt = await ResolveTokenToEvent(token, room);
                if (evt is not null) return evt.OriginServerTs;
            }

            // event not found
            throw new NotImplementedException();
        }
        else {
            // we have a sync token 
            foreach (var user in userStore._users) {
                foreach (var (_, session) in user.AccessTokens) {
                    if (!session.SyncStates.TryGetValue(token, out var syncState)) continue;
                    long? maxTs = 0;
                    foreach (var room in syncState.RoomPositions) {
                        var roomObj = roomStore.GetRoomById(room.Key);
                        if (roomObj is null)
                            continue;
                        var ts = roomObj.Timeline.Last().OriginServerTs;
                        if (ts > maxTs) maxTs = ts;
                    }

                    return maxTs;
                }
            }

            throw new NotImplementedException();
        }
    }

    public async Task<StateEventResponse?> ResolveTokenToEvent(string token, RoomStore.Room room) {
        if (token.StartsWith('$')) {
            //we have an event ID
            logger.LogTrace("ResolveTokenToEvent(EventId({token}), Room({room})): searching for event...", token, room.RoomId);

            var evt = room.Timeline.SingleOrDefault(x => x.EventId == token);
            if (evt is not null) return evt;
            logger.LogTrace("ResolveTokenToEvent({token}, Room({room})): event not in requested room...", token, room.RoomId);
            return null;
        }
        else {
            // we have a sync token
            logger.LogTrace("ResolveTokenToEvent(SyncToken({token}), Room({room}))", token, room.RoomId);
            throw new NotImplementedException();
        }
    }
}