about summary refs log tree commit diff
path: root/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminApiClient.cs
blob: 4d8a577604351913ee6e241dc8f2cfcd371e34c7 (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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using ArcaneLibs.Extensions;
using LibMatrix.Filters;
using LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Filters;
using LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
using LibMatrix.Responses;

namespace LibMatrix.Homeservers.ImplementationDetails.Synapse;

public class SynapseAdminApiClient(AuthenticatedHomeserverSynapse authenticatedHomeserver) {
    // https://github.com/element-hq/synapse/tree/develop/docs/admin_api
    // https://github.com/element-hq/synapse/tree/develop/docs/usage/administration/admin_api

#region Rooms

    public async IAsyncEnumerable<SynapseAdminRoomListResult.SynapseAdminRoomListResultRoom> SearchRoomsAsync(int limit = int.MaxValue, int chunkLimit = 250,
        string orderBy = "name", string dir = "f", string? searchTerm = null, SynapseAdminLocalRoomQueryFilter? localFilter = null) {
        SynapseAdminRoomListResult? res = null;
        var i = 0;
        int? totalRooms = null;
        do {
            var url = $"/_synapse/admin/v1/rooms?limit={Math.Min(limit, chunkLimit)}&dir={dir}&order_by={orderBy}";
            if (!string.IsNullOrEmpty(searchTerm)) url += $"&search_term={searchTerm}";

            if (res?.NextBatch is not null) url += $"&from={res.NextBatch}";

            Console.WriteLine($"--- ADMIN Querying Room List with URL: {url} - Already have {i} items... ---");

            res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRoomListResult>(url);
            totalRooms ??= res.TotalRooms;
            Console.WriteLine(res.ToJson(false));
            foreach (var room in res.Rooms) {
                if (localFilter is not null) {
                    if (!room.RoomId.Contains(localFilter.RoomIdContains)) {
                        totalRooms--;
                        continue;
                    }

                    if (!room.Name?.Contains(localFilter.NameContains) == true) {
                        totalRooms--;
                        continue;
                    }

                    if (!room.CanonicalAlias?.Contains(localFilter.CanonicalAliasContains) == true) {
                        totalRooms--;
                        continue;
                    }

                    if (!room.Version.Contains(localFilter.VersionContains)) {
                        totalRooms--;
                        continue;
                    }

                    if (!room.Creator.Contains(localFilter.CreatorContains)) {
                        totalRooms--;
                        continue;
                    }

                    if (!room.Encryption?.Contains(localFilter.EncryptionContains) == true) {
                        totalRooms--;
                        continue;
                    }

                    if (!room.JoinRules?.Contains(localFilter.JoinRulesContains) == true) {
                        totalRooms--;
                        continue;
                    }

                    if (!room.GuestAccess?.Contains(localFilter.GuestAccessContains) == true) {
                        totalRooms--;
                        continue;
                    }

                    if (!room.HistoryVisibility?.Contains(localFilter.HistoryVisibilityContains) == true) {
                        totalRooms--;
                        continue;
                    }

                    if (localFilter.CheckFederation && room.Federatable != localFilter.Federatable) {
                        totalRooms--;
                        continue;
                    }

                    if (localFilter.CheckPublic && room.Public != localFilter.Public) {
                        totalRooms--;
                        continue;
                    }

                    if (room.JoinedMembers < localFilter.JoinedMembersGreaterThan || room.JoinedMembers > localFilter.JoinedMembersLessThan) {
                        totalRooms--;
                        continue;
                    }

                    if (room.JoinedLocalMembers < localFilter.JoinedLocalMembersGreaterThan || room.JoinedLocalMembers > localFilter.JoinedLocalMembersLessThan) {
                        totalRooms--;
                        continue;
                    }
                }
                // if (contentSearch is not null && !string.IsNullOrEmpty(contentSearch) &&
                //     !(
                //         room.Name?.Contains(contentSearch, StringComparison.InvariantCultureIgnoreCase) == true ||
                //         room.CanonicalAlias?.Contains(contentSearch, StringComparison.InvariantCultureIgnoreCase) == true ||
                //         room.Creator?.Contains(contentSearch, StringComparison.InvariantCultureIgnoreCase) == true
                //     )
                //    ) {
                //     totalRooms--;
                //     continue;
                // }

                i++;
                yield return room;
            }
        } while (i < Math.Min(limit, totalRooms ?? limit));
    }

#endregion

#region Users

    public async IAsyncEnumerable<SynapseAdminUserListResult.SynapseAdminUserListResultUser> SearchUsersAsync(int limit = int.MaxValue, int chunkLimit = 250,
        SynapseAdminLocalUserQueryFilter? localFilter = null) {
        // TODO: implement filters
        string? from = null;
        while (limit > 0) {
            var url = new Uri("/_synapse/admin/v3/users", UriKind.Relative);
            url = url.AddQuery("limit", Math.Min(limit, chunkLimit).ToString());
            if (!string.IsNullOrWhiteSpace(from)) url = url.AddQuery("from", from);
            Console.WriteLine($"--- ADMIN Querying User List with URL: {url} ---");
            // TODO: implement URI methods in http client
            var res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminUserListResult>(url.ToString());
            foreach (var user in res.Users) {
                limit--;
                yield return user;
            }

            if (string.IsNullOrWhiteSpace(res.NextToken)) break;
            from = res.NextToken;
        }
    }

    public async Task<LoginResponse> LoginUserAsync(string userId, TimeSpan expireAfter) {
        var url = new Uri($"/_synapse/admin/v1/users/{userId.UrlEncode()}/login", UriKind.Relative);
        url.AddQuery("valid_until_ms", DateTimeOffset.UtcNow.Add(expireAfter).ToUnixTimeMilliseconds().ToString());
        var resp = await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync<JsonObject>(url.ToString(), new());
        var loginResp = await resp.Content.ReadFromJsonAsync<LoginResponse>();
        loginResp.UserId = userId; // Synapse only returns the access token
        return loginResp;
    }

#endregion

#region Reports

    public async IAsyncEnumerable<SynapseAdminEventReportListResult.SynapseAdminEventReportListResultReport> GetEventReportsAsync(int limit = int.MaxValue, int chunkLimit = 250,
        string dir = "f", SynapseAdminLocalEventReportQueryFilter? filter = null) {
        // TODO: implement filters
        string? from = null;
        while (limit > 0) {
            var url = new Uri("/_synapse/admin/v1/event_reports", UriKind.Relative);
            url = url.AddQuery("limit", Math.Min(limit, chunkLimit).ToString());
            if (!string.IsNullOrWhiteSpace(from)) url = url.AddQuery("from", from);
            Console.WriteLine($"--- ADMIN Querying Reports with URL: {url} ---");
            var res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminEventReportListResult>(url.ToString());
            foreach (var report in res.Reports) {
                limit--;
                yield return report;
            }

            if (string.IsNullOrWhiteSpace(res.NextToken)) break;
            from = res.NextToken;
        }
    }

    public async Task<SynapseAdminEventReportListResult.SynapseAdminEventReportListResultReportWithDetails> GetEventReportDetailsAsync(string reportId) {
        var url = new Uri($"/_synapse/admin/v1/event_reports/{reportId.UrlEncode()}", UriKind.Relative);
        return await authenticatedHomeserver.ClientHttpClient
            .GetFromJsonAsync<SynapseAdminEventReportListResult.SynapseAdminEventReportListResultReportWithDetails>(url.ToString());
    }

    // Utility function to get details straight away
    public async IAsyncEnumerable<SynapseAdminEventReportListResult.SynapseAdminEventReportListResultReportWithDetails> GetEventReportsWithDetailsAsync(int limit = int.MaxValue,
        int chunkLimit = 250, string dir = "f", SynapseAdminLocalEventReportQueryFilter? filter = null) {
        Queue<Task<SynapseAdminEventReportListResult.SynapseAdminEventReportListResultReportWithDetails>> tasks = [];
        await foreach (var report in GetEventReportsAsync(limit, chunkLimit, dir, filter)) {
            tasks.Enqueue(GetEventReportDetailsAsync(report.Id));
            while (tasks.Peek().IsCompleted) yield return await tasks.Dequeue(); // early return if possible
        }

        while (tasks.Count > 0) yield return await tasks.Dequeue();
    }

    public async Task DeleteEventReportAsync(string reportId) {
        var url = new Uri($"/_synapse/admin/v1/event_reports/{reportId.UrlEncode()}", UriKind.Relative);
        await authenticatedHomeserver.ClientHttpClient.DeleteAsync(url.ToString());
    }

#endregion

#region Background Updates

    public async Task<bool> GetBackgroundUpdatesEnabledAsync() {
        var url = new Uri("/_synapse/admin/v1/background_updates/enabled", UriKind.Relative);
        // The return type is technically wrong, but includes the field we want.
        var resp = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminBackgroundUpdateStatusResponse>(url.ToString());
        return resp.Enabled;
    }

    public async Task<bool> SetBackgroundUpdatesEnabledAsync(bool enabled) {
        var url = new Uri("/_synapse/admin/v1/background_updates/enabled", UriKind.Relative);
        // The used types are technically wrong, but include the field we want.
        var resp = await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync<JsonObject>(url.ToString(), new JsonObject {
            ["enabled"] = enabled
        });
        var json = await resp.Content.ReadFromJsonAsync<SynapseAdminBackgroundUpdateStatusResponse>();
        return json!.Enabled;
    }

    public async Task<SynapseAdminBackgroundUpdateStatusResponse> GetBackgroundUpdatesStatusAsync() {
        var url = new Uri("/_synapse/admin/v1/background_updates/status", UriKind.Relative);
        return await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminBackgroundUpdateStatusResponse>(url.ToString());
    }

    /// <summary>
    /// Run a background job
    /// </summary>
    /// <param name="jobName">One of "populate_stats_process_rooms" or "regenerate_directory"</param>
    public async Task RunBackgroundJobsAsync(string jobName) {
        var url = new Uri("/_synapse/admin/v1/background_updates/run", UriKind.Relative);
        await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync(url.ToString(), new JsonObject() {
            ["job_name"] = jobName
        });
    }

#endregion

#region Federation

    public async IAsyncEnumerable<SynapseAdminDestinationListResult.SynapseAdminDestinationListResultDestination> GetFederationDestinationsAsync(int limit = int.MaxValue,
        int chunkLimit = 250) {
        string? from = null;
        while (limit > 0) {
            var url = new Uri("/_synapse/admin/v1/federation/destinations", UriKind.Relative);
            url = url.AddQuery("limit", Math.Min(limit, chunkLimit).ToString());
            if (!string.IsNullOrWhiteSpace(from)) url = url.AddQuery("from", from);
            Console.WriteLine($"--- ADMIN Querying Federation Destinations with URL: {url} ---");
            var res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminDestinationListResult>(url.ToString());
            foreach (var dest in res.Destinations) {
                limit--;
                yield return dest;
            }
        }
    }

    public async Task<SynapseAdminDestinationListResult.SynapseAdminDestinationListResultDestination> GetFederationDestinationDetailsAsync(string destination) {
        var url = new Uri($"/_synapse/admin/v1/federation/destinations/{destination}", UriKind.Relative);
        return await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminDestinationListResult.SynapseAdminDestinationListResultDestination>(url.ToString());
    }

    public async IAsyncEnumerable<SynapseAdminDestinationRoomListResult.SynapseAdminDestinationRoomListResultRoom> GetFederationDestinationRoomsAsync(string destination,
        int limit = int.MaxValue, int chunkLimit = 250) {
        string? from = null;
        while (limit > 0) {
            var url = new Uri($"/_synapse/admin/v1/federation/destinations/{destination}/rooms", UriKind.Relative);
            url = url.AddQuery("limit", Math.Min(limit, chunkLimit).ToString());
            if (!string.IsNullOrWhiteSpace(from)) url = url.AddQuery("from", from);
            Console.WriteLine($"--- ADMIN Querying Federation Destination Rooms with URL: {url} ---");
            var res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminDestinationRoomListResult>(url.ToString());
            foreach (var room in res.Rooms) {
                limit--;
                yield return room;
            }
        }
    }

    public async Task ResetFederationConnectionTimeoutAsync(string destination) {
        await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync($"/_synapse/admin/v1/federation/destinations/{destination}/reset_connection", new JsonObject());
    }

#endregion

#region Registration Tokens

    // does not support pagination
    public async Task<List<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken>> GetRegistrationTokensAsync() {
        var url = new Uri("/_synapse/admin/v1/registration_tokens", UriKind.Relative);
        var resp = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRegistrationTokenListResult>(url.ToString());
        return resp.RegistrationTokens;
    }

    public async Task<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken> GetRegistrationTokenAsync(string token) {
        var url = new Uri($"/_synapse/admin/v1/registration_tokens/{token.UrlEncode()}", UriKind.Relative);
        var resp =
            await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken>(url.ToString());
        return resp;
    }

    public async Task<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken> CreateRegistrationTokenAsync(
        SynapseAdminRegistrationTokenCreateRequest request) {
        var url = new Uri("/_synapse/admin/v1/", UriKind.Relative);
        var resp = await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync(url.ToString(), request);
        var token = await resp.Content.ReadFromJsonAsync<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken>();
        return token!;
    }

    public async Task<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken> UpdateRegistrationTokenAsync(string token,
        SynapseAdminRegistrationTokenUpdateRequest request) {
        var url = new Uri($"/_synapse/admin/v1/registration_tokens/{token.UrlEncode()}", UriKind.Relative);
        var resp = await authenticatedHomeserver.ClientHttpClient.PutAsJsonAsync(url.ToString(), request);
        return await resp.Content.ReadFromJsonAsync<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken>();
    }

    public async Task DeleteRegistrationTokenAsync(string token) {
        var url = new Uri($"/_synapse/admin/v1/registration_tokens/{token.UrlEncode()}", UriKind.Relative);
        await authenticatedHomeserver.ClientHttpClient.DeleteAsync(url.ToString());
    }

#endregion

#region Account Validity

    // Does anyone even use this?
    // README: https://github.com/matrix-org/synapse/issues/15271
    // -> Don't implement unless requested, if not for this feature almost never being used.

#endregion

#region Experimental Features

    public async Task<Dictionary<string, bool>> GetExperimentalFeaturesAsync(string userId) {
        var url = new Uri($"/_synapse/admin/v1/experimental_features/{userId.UrlEncode()}", UriKind.Relative);
        var resp = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<JsonObject>(url.ToString());
        return resp["features"]!.GetValue<Dictionary<string, bool>>();
    }

    public async Task SetExperimentalFeaturesAsync(string userId, Dictionary<string, bool> features) {
        var url = new Uri($"/_synapse/admin/v1/experimental_features/{userId.UrlEncode()}", UriKind.Relative);
        await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync<JsonObject>(url.ToString(), new JsonObject {
            ["features"] = JsonSerializer.Deserialize<JsonObject>(features.ToJson())
        });
    }

#endregion

#region Media

    public async Task<SynapseAdminRoomMediaListResult> GetRoomMediaAsync(string roomId) {
        var url = new Uri($"/_synapse/admin/v1/rooms/{roomId.UrlEncode()}/media", UriKind.Relative);
        return await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRoomMediaListResult>(url.ToString());
    }

    // This is in the user admin API section
    // public async IAsyncEnumerable<SynapseAdminRoomMediaListResult>

#endregion
}