about summary refs log tree commit diff
path: root/MatrixRoomUtils.Core/RoomTypes/GenericRoom.cs
blob: 8dc30d1fc6494d9877292656e5dbd8b26a83bedb (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
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Web;
using MatrixRoomUtils.Core.Extensions;
using MatrixRoomUtils.Core.RoomTypes;

namespace MatrixRoomUtils.Core;

public class GenericRoom {
    internal readonly AuthenticatedHomeServer _homeServer;
    internal readonly HttpClient _httpClient;

    public GenericRoom(AuthenticatedHomeServer homeServer, string roomId) {
        _homeServer = homeServer;
        _httpClient = homeServer._httpClient;
        RoomId = roomId;
        if (GetType() != typeof(SpaceRoom))
            AsSpace = new SpaceRoom(homeServer, RoomId);
    }

    public string RoomId { get; set; }

    public async Task<JsonElement?> GetStateAsync(string type, string stateKey = "", bool logOnFailure = true) {
        var url = $"/_matrix/client/v3/rooms/{RoomId}/state";
        if (!string.IsNullOrEmpty(type)) url += $"/{type}";
        if (!string.IsNullOrEmpty(stateKey)) url += $"/{stateKey}";

        var res = await _httpClient.GetAsync(url);
        if (!res.IsSuccessStatusCode) {
            if (logOnFailure) Console.WriteLine($"{RoomId}/{stateKey}/{type} - got status: {res.StatusCode}");
            return null;
        }

        var result = await res.Content.ReadFromJsonAsync<JsonElement>();
        return result;
    }

    public async Task<T?> GetStateAsync<T>(string type, string stateKey = "", bool logOnFailure = false) {
        var res = await GetStateAsync(type, stateKey, logOnFailure);
        if (res == null) return default;
        return res.Value.Deserialize<T>();
    }

    public async Task<MessagesResponse> GetMessagesAsync(string from = "", int limit = 10, string dir = "b",
        string filter = "") {
        var url = $"/_matrix/client/v3/rooms/{RoomId}/messages?from={from}&limit={limit}&dir={dir}";
        if (!string.IsNullOrEmpty(filter)) url += $"&filter={filter}";
        var res = await _httpClient.GetAsync(url);
        if (!res.IsSuccessStatusCode) {
            Console.WriteLine($"Failed to get messages for {RoomId} - got status: {res.StatusCode}");
            throw new Exception($"Failed to get messages for {RoomId} - got status: {res.StatusCode}");
        }

        var result = await res.Content.ReadFromJsonAsync<MessagesResponse>();
        return result ?? new MessagesResponse();
    }

    public async Task<string> GetNameAsync() {
        var res = await GetStateAsync("m.room.name");
        if (!res.HasValue) {
            Console.WriteLine($"Room {RoomId} has no name!");
            return RoomId;
        }

        var resn = res?.TryGetProperty("name", out var name) ?? false ? name.GetString() ?? RoomId : RoomId;
        //Console.WriteLine($"Got name: {resn}");
        return resn;
    }

    public async Task JoinAsync(string[]? homeservers = null, string? reason = null) {
        var join_url = $"/_matrix/client/v3/join/{HttpUtility.UrlEncode(RoomId)}";
        Console.WriteLine($"Calling {join_url} with {homeservers?.Length ?? 0} via's...");
        if (homeservers == null || homeservers.Length == 0) homeservers = new[] { RoomId.Split(':')[1] };
        var fullJoinUrl = $"{join_url}?server_name=" + string.Join("&server_name=", homeservers);
        var res = await _httpClient.PostAsJsonAsync(fullJoinUrl, new {
            reason
        });
    }

    public async Task<List<string>> GetMembersAsync(bool joinedOnly = true) {
        var res = await GetStateAsync("");
        if (!res.HasValue) return new List<string>();
        var members = new List<string>();
        foreach (var member in res.Value.EnumerateArray()) {
            if (member.GetProperty("type").GetString() != "m.room.member") continue;
            if (joinedOnly && member.GetProperty("content").GetProperty("membership").GetString() != "join") continue;
            var memberId = member.GetProperty("state_key").GetString();
            members.Add(
                memberId ?? throw new InvalidOperationException("Event type was member but state key was null!"));
        }

        return members;
    }

    public async Task<List<string>> GetAliasesAsync() {
        var res = await GetStateAsync("m.room.aliases");
        if (!res.HasValue) return new List<string>();
        var aliases = new List<string>();
        foreach (var alias in res.Value.GetProperty("aliases").EnumerateArray()) aliases.Add(alias.GetString() ?? "");

        return aliases;
    }

    public async Task<string> GetCanonicalAliasAsync() {
        var res = await GetStateAsync("m.room.canonical_alias");
        if (!res.HasValue) return "";
        return res.Value.GetProperty("alias").GetString() ?? "";
    }

    public async Task<string> GetTopicAsync() {
        var res = await GetStateAsync("m.room.topic");
        if (!res.HasValue) return "";
        return res.Value.GetProperty("topic").GetString() ?? "";
    }

    public async Task<string> GetAvatarUrlAsync() {
        var res = await GetStateAsync("m.room.avatar");
        if (!res.HasValue) return "";
        return res.Value.GetProperty("url").GetString() ?? "";
    }

    public async Task<JoinRulesEventData> GetJoinRuleAsync() {
        var res = await GetStateAsync("m.room.join_rules");
        if (!res.HasValue) return new JoinRulesEventData();
        return res.Value.Deserialize<JoinRulesEventData>() ?? new JoinRulesEventData();
    }

    public async Task<string> GetHistoryVisibilityAsync() {
        var res = await GetStateAsync("m.room.history_visibility");
        if (!res.HasValue) return "";
        return res.Value.GetProperty("history_visibility").GetString() ?? "";
    }

    public async Task<string> GetGuestAccessAsync() {
        var res = await GetStateAsync("m.room.guest_access");
        if (!res.HasValue) return "";
        return res.Value.GetProperty("guest_access").GetString() ?? "";
    }

    public async Task<CreateEvent> GetCreateEventAsync() {
        var res = await GetStateAsync("m.room.create");
        if (!res.HasValue) return new CreateEvent();

        res.FindExtraJsonElementFields(typeof(CreateEvent));

        return res.Value.Deserialize<CreateEvent>() ?? new CreateEvent();
    }

    public async Task<string?> GetRoomType() {
        var res = await GetStateAsync("m.room.create");
        if (!res.HasValue) return null;
        if (res.Value.TryGetProperty("type", out var type)) return type.GetString();
        return null;
    }

    public async Task ForgetAsync() {
        var res = await _httpClient.PostAsync($"/_matrix/client/v3/rooms/{RoomId}/forget", null);
        if (!res.IsSuccessStatusCode) {
            Console.WriteLine($"Failed to forget room {RoomId} - got status: {res.StatusCode}");
            throw new Exception($"Failed to forget room {RoomId} - got status: {res.StatusCode}");
        }
    }

    public async Task LeaveAsync(string? reason = null) {
        var res = await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/leave", new {
            reason
        });
        if (!res.IsSuccessStatusCode) {
            Console.WriteLine($"Failed to leave room {RoomId} - got status: {res.StatusCode}");
            throw new Exception($"Failed to leave room {RoomId} - got status: {res.StatusCode}");
        }
    }

    public async Task KickAsync(string userId, string? reason = null) {
        var res = await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/kick",
            new UserIdAndReason() { UserId = userId, Reason = reason });
        if (!res.IsSuccessStatusCode) {
            Console.WriteLine($"Failed to kick {userId} from room {RoomId} - got status: {res.StatusCode}");
            throw new Exception($"Failed to kick {userId} from room {RoomId} - got status: {res.StatusCode}");
        }
    }

    public async Task BanAsync(string userId, string? reason = null) {
        var res = await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/ban",
            new UserIdAndReason() { UserId = userId, Reason = reason });
        if (!res.IsSuccessStatusCode) {
            Console.WriteLine($"Failed to ban {userId} from room {RoomId} - got status: {res.StatusCode}");
            throw new Exception($"Failed to ban {userId} from room {RoomId} - got status: {res.StatusCode}");
        }
    }

    public async Task UnbanAsync(string userId) {
        var res = await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/unban",
            new UserIdAndReason() { UserId = userId });
        if (!res.IsSuccessStatusCode) {
            Console.WriteLine($"Failed to unban {userId} from room {RoomId} - got status: {res.StatusCode}");
            throw new Exception($"Failed to unban {userId} from room {RoomId} - got status: {res.StatusCode}");
        }
    }

    public async Task<EventIdResponse> SendStateEventAsync(string eventType, object content) {
        var res = await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state/{eventType}", content);
        if (!res.IsSuccessStatusCode) {
            Console.WriteLine(
                $"Failed to send state event {eventType} to room {RoomId} - got status: {res.StatusCode}");
            throw new Exception(
                $"Failed to send state event {eventType} to room {RoomId} - got status: {res.StatusCode}");
        }

        return await res.Content.ReadFromJsonAsync<EventIdResponse>();
    }

    public async Task<EventIdResponse> SendMessageEventAsync(string eventType, MessageEventData content) {
        var url = $"/_matrix/client/v3/rooms/{RoomId}/send/{eventType}/" + Guid.NewGuid();
        var res = await _httpClient.PutAsJsonAsync(url, content);
        if (!res.IsSuccessStatusCode) {
            Console.WriteLine($"Failed to send event {eventType} to room {RoomId} - got status: {res.StatusCode}");
            throw new Exception($"Failed to send event {eventType} to room {RoomId} - got status: {res.StatusCode}");
        }

        var resu = await res.Content.ReadFromJsonAsync<EventIdResponse>();

        return resu;
    }

    public async Task<EventIdResponse> SendFileAsync(string eventType, string fileName, Stream fileStream) {
        var url = $"/_matrix/client/v3/rooms/{RoomId}/send/{eventType}/" + Guid.NewGuid();
        var content = new MultipartFormDataContent();
        content.Add(new StreamContent(fileStream), "file", fileName);
        var res = await _httpClient.PutAsync(url, content);
        if (!res.IsSuccessStatusCode) {
            Console.WriteLine($"Failed to send event {eventType} to room {RoomId} - got status: {res.StatusCode}");
            throw new Exception($"Failed to send event {eventType} to room {RoomId} - got status: {res.StatusCode}");
        }

        var resu = await res.Content.ReadFromJsonAsync<EventIdResponse>();

        return resu;
    }

    public readonly SpaceRoom AsSpace;
}