about summary refs log tree commit diff
path: root/MatrixUtils.Web/Pages/User/DMManager.razor
blob: 80bf3b22b1dc3f1c46ef420005526e98e64e7d18 (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
@page "/User/DirectMessages"
@using LibMatrix.EventTypes.Spec.State
@using LibMatrix.Responses
@using MatrixUtils.Abstractions
@using LibMatrix
<h3>Direct Messages</h3>
<hr/>

@foreach (var (targetUser, rooms) in DMRooms) {
    <div>
        <InlineUserItem User="targetUser"></InlineUserItem>
        @foreach (var room in rooms) {
            <RoomListItem RoomInfo="room" LoadData="true"></RoomListItem>
        }
    </div>
}

@code {
    private string? _status;
    private AuthenticatedHomeserverGeneric? Homeserver { get; set; }
    private Dictionary<UserProfileResponse, List<RoomInfo>> DMRooms { get; set; } = new();

    public string? Status {
        get => _status;
        set {
            _status = value;
            StateHasChanged();
        }
    }

    protected override async Task OnInitializedAsync() {
        Homeserver = await RMUStorage.GetCurrentSessionOrNavigate();
        if (Homeserver is null) return;
        Status = "Loading global profile...";
        if (Homeserver.WhoAmI?.UserId is null) return;

        Status = "Loading DM list from account data...";
        var dms = await Homeserver.GetAccountDataAsync<Dictionary<string, List<string>>>("m.direct");
        DMRooms.Clear();
        var userTasks = dms.Select(async kv => {
            var (userId, rooms) = kv;
            var roomList = new List<RoomInfo>();
            UserProfileResponse? profile = null;
            try {
                profile = await Homeserver.GetProfileAsync(userId);
            }
            catch (MatrixException e) {
                if (e is { ErrorCode: "M_UNKNOWN" }) profile = new UserProfileResponse() { DisplayName = $"{userId}: {e.Error}" };
            }

            foreach (var room in rooms) {
                var roomInfo = new RoomInfo(Homeserver.GetRoom(room));
                roomList.Add(roomInfo);
                roomInfo.StateEvents.Add(new() {
                    Type = RoomNameEventContent.EventId,
                    TypedContent = new RoomNameEventContent() {
                        Name = await Homeserver.GetRoom(room).GetNameOrFallbackAsync(4)
                    },
                    RoomId = room, Sender = null, EventId = null
                });
            }

            DMRooms.Add(profile ?? new() { DisplayName = userId }, roomList);
            StateHasChanged();
        }).ToList();
        
        await Task.WhenAll(userTasks);
        await Task.Delay(500);

        StateHasChanged();
        Status = null;

        await base.OnInitializedAsync();
    }

}