about summary refs log tree commit diff
path: root/MatrixUtils.LibDMSpace/DMSpaceRoom.cs
blob: e2c8192fcaa532d22088a03995172b3fad2ffcf2 (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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
using System.Net;
using ArcaneLibs.Extensions;
using LibMatrix;
using LibMatrix.EventTypes.Spec.State;
using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Homeservers;
using LibMatrix.Responses;
using LibMatrix.RoomTypes;
using MatrixUtils.LibDMSpace.StateEvents;

namespace MatrixUtils.LibDMSpace;

public class DMSpaceRoom(AuthenticatedHomeserverGeneric homeserver, string roomId) : SpaceRoom(homeserver, roomId) {
    private readonly GenericRoom _room;

    // ReSharper disable once InconsistentNaming
    public async Task<DMSpaceInfo?> GetDMSpaceInfo() {
        return await GetStateOrNullAsync<DMSpaceInfo>(DMSpaceInfo.EventId);
    }

    public async Task<Dictionary<string, List<string>>?> ExportNativeDMs() {
        var state = GetFullStateAsync();
        var mdirect = new Dictionary<string, List<string>>();
        await foreach (var stateEvent in state) { }

        return mdirect;
    }

    public async Task ImportNativeDMs() {
        var dmSpaceInfo = await GetDMSpaceInfo();
        if (dmSpaceInfo is null) throw new NullReferenceException("DM Space is not configured!");
        if (dmSpaceInfo.LayerByUser)
            await ImportNativeDMsIntoLayers();
        else await ImportNativeDMsWithoutLayers();
    }

    public async Task<List<StateEventResponse>> GetAllActiveLayersAsync() {
        var state = await GetFullStateAsListAsync();
        return state.Where(x => x.Type == DMSpaceChildLayer.EventId && x.RawContent.ContainsKey("space_id")).ToList();
    }

#region Import Native DMs

    private async Task ImportNativeDMsWithoutLayers() {
        var mdirect = await homeserver.GetAccountDataAsync<Dictionary<string, List<string>>>("m.direct");
        foreach (var (userId, dmRooms) in mdirect) {
            foreach (var roomid in dmRooms) {
                var dri = new DMRoomInfo() {
                    AttributedUser = userId
                };
                await SendStateEventAsync(DMRoomInfo.EventId, roomid, dri);
                await AddChildAsync(Homeserver.GetRoom(roomid));
            }
        }
    }

    private async Task ImportNativeDMsIntoLayers() {
        var mdirect = await homeserver.GetAccountDataAsync<Dictionary<string, List<string>>>("m.direct");
        var layerTasks = mdirect.Select(async entry => {
            var (userId, dmRooms) = entry;
            DMSpaceChildLayer? layer = await GetStateOrNullAsync<DMSpaceChildLayer>(DMSpaceChildLayer.EventId, userId.UrlEncode()) ?? await CreateLayer(userId);
            return (entry, layer);
        }).ToAsyncEnumerable();

        await foreach (var ((userId, dmRooms), layer) in layerTasks) {
            var space = Homeserver.GetRoom(layer.SpaceId).AsSpace;
            foreach (var roomid in dmRooms) {
                var dri = new DMRoomInfo() {
                    AttributedUser = userId
                };
                await space.SendStateEventAsync(DMRoomInfo.EventId, roomid, dri);
                await space.AddChildAsync(Homeserver.GetRoom(roomid));
            }

            await UpdateLayer(layer, userId);
        }

        // ensure all spaces are linked
        Console.WriteLine("Ensuring all child layers are inside space...");
        var layerAssuranceTasks = (await GetFullStateAsListAsync())
            .Where(x => x.Type == DMSpaceChildLayer.EventId && (x.RawContent?.ContainsKey("space_id") ?? false))
            .Select(async layer => {
                var content = layer.TypedContent as DMSpaceChildLayer;
                var space = homeserver.GetRoom(content!.SpaceId);
                try {
                    var state = await space.GetFullStateAsListAsync();
                    if (!state.Any(e => e.Type == DMRoomInfo.EventId)) throw new Exception();
                }
                catch {
                    await homeserver.JoinRoomAsync(content!.SpaceId);
                }

                return AddChildAsync(space);
            });
        await Task.WhenAll(layerAssuranceTasks);
        Console.WriteLine("All child layers should be inside of space, if not, something went horribly wrong!");
    }

    private async Task<DMSpaceChildLayer> CreateLayer(string userId) {
        var childCreateRequest = CreateRoomRequest.CreatePrivate(homeserver, userId);
        childCreateRequest.CreationContent["type"] = "m.space";

        var layer = new DMSpaceChildLayer() {
            SpaceId = (await homeserver.CreateRoom(childCreateRequest)).RoomId
        };

        await SendStateEventAsync(DMSpaceChildLayer.EventId, userId[1..], layer);
        await AddChildAsync(Homeserver.GetRoom(layer.SpaceId));
        return layer;
    }

    private async Task UpdateLayerProfilesAsync() {
        var layers = await GetAllActiveLayersAsync();
        var getProfileTasks = layers.Select(async x => {
            UserProfileResponse? profile = null;
            try {
                return (x, profile);
            }
            catch {
                return (x, null);
            }

        }).ToAsyncEnumerable();
        await foreach (var (layer, profile) in getProfileTasks) {
            if (profile is null) continue;
            var layerContent = layer.TypedContent as DMSpaceChildLayer;
            var space = Homeserver.GetRoom(layerContent!.SpaceId).AsSpace;

            try {
                await space.SendStateEventAsync(RoomAvatarEventContent.EventId, "", new RoomAvatarEventContent() {
                    Url = layerContent.OverrideAvatar ?? profile?.AvatarUrl
                });
                await space.SendStateEventAsync(RoomNameEventContent.EventId, "", new RoomNameEventContent() {
                    Name = layerContent.OverrideName ?? profile?.DisplayName ?? "@" + layer.StateKey.UrlDecode()
                });
            }
            catch (MatrixException e) {
                Console.WriteLine("Failed to update space: {0}", e);
            }
        }
    }

    private async Task UpdateLayer(DMSpaceChildLayer layer, string mxid) {
        UserProfileResponse? profile = null;
        var space = Homeserver.GetRoom(layer.SpaceId).AsSpace;

        if (string.IsNullOrWhiteSpace(layer.OverrideAvatar) || string.IsNullOrWhiteSpace(layer.OverrideName)) {
            try {
                profile = await homeserver.GetProfileAsync(mxid);
            }
            catch (MatrixException e) {
                // if (e.ErrorCode != "M_NOT_FOUND") throw;
                Console.Error.WriteLine(e);
            }
        }

        try {
            await space.SendStateEventAsync(RoomAvatarEventContent.EventId, "", new RoomAvatarEventContent() {
                Url = layer.OverrideAvatar ?? profile?.AvatarUrl
            });
            await space.SendStateEventAsync(RoomNameEventContent.EventId, "", new RoomNameEventContent() {
                Name = layer.OverrideName ?? profile?.DisplayName ?? mxid
            });
        }
        catch (MatrixException e) {
            Console.WriteLine("Failed to update space: {0}", e);
        }
    }

    public async Task DisbandDMSpace() {
        var state = await GetFullStateAsListAsync();
        var leaveTasks = state.Select(async x => {
            if (x.Type != DMSpaceChildLayer.EventId) return;
            var content = x.TypedContent as DMSpaceChildLayer;
            if (content?.SpaceId is null) return;
            var space = homeserver.GetRoom(content.SpaceId);
            try {
                await space.LeaveAsync();
            }
            catch {
                // might not be in room, doesnt matter
            }
        });

        await LeaveAsync();

        await Task.WhenAll(leaveTasks);
    }

#endregion
}