From 5affd9f061e75f6575a2fe6715f9e8757cfe87e8 Mon Sep 17 00:00:00 2001 From: "Emma [it/its]@Rory&" Date: Thu, 14 Dec 2023 07:20:46 +0100 Subject: Cleanup --- LibMatrix/RoomTypes/GenericRoom.cs | 74 +++++++++++++++++++------------------- LibMatrix/RoomTypes/SpaceRoom.cs | 4 +-- 2 files changed, 38 insertions(+), 40 deletions(-) (limited to 'LibMatrix/RoomTypes') diff --git a/LibMatrix/RoomTypes/GenericRoom.cs b/LibMatrix/RoomTypes/GenericRoom.cs index 9804e78..d067f9f 100644 --- a/LibMatrix/RoomTypes/GenericRoom.cs +++ b/LibMatrix/RoomTypes/GenericRoom.cs @@ -4,39 +4,39 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Web; using ArcaneLibs.Extensions; +using LibMatrix.EventTypes; using LibMatrix.EventTypes.Spec; using LibMatrix.EventTypes.Spec.State; -using LibMatrix.Extensions; +using LibMatrix.EventTypes.Spec.State.RoomInfo; using LibMatrix.Homeservers; -using LibMatrix.Interfaces; namespace LibMatrix.RoomTypes; public class GenericRoom { internal readonly AuthenticatedHomeserverGeneric Homeserver; - internal readonly MatrixHttpClient _httpClient; public GenericRoom(AuthenticatedHomeserverGeneric homeserver, string roomId) { if (string.IsNullOrWhiteSpace(roomId)) throw new ArgumentException("Room ID cannot be null or whitespace", nameof(roomId)); Homeserver = homeserver; - _httpClient = homeserver.ClientHttpClient; RoomId = roomId; - if (GetType() != typeof(SpaceRoom)) + // if (GetType() != typeof(SpaceRoom)) + if (GetType() == typeof(GenericRoom)) { AsSpace = new SpaceRoom(homeserver, RoomId); + } } public string RoomId { get; set; } public async IAsyncEnumerable GetFullStateAsync() { - var result = _httpClient.GetAsyncEnumerableFromJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state"); + var result = Homeserver.ClientHttpClient.GetAsyncEnumerableFromJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state"); await foreach (var resp in result) { yield return resp; } } public async Task> GetFullStateAsListAsync() { - return await _httpClient.GetFromJsonAsync>($"/_matrix/client/v3/rooms/{RoomId}/state"); + return await Homeserver.ClientHttpClient.GetFromJsonAsync>($"/_matrix/client/v3/rooms/{RoomId}/state"); } public async Task GetStateAsync(string type, string stateKey = "") { @@ -56,7 +56,7 @@ public class GenericRoom { return resp.Deserialize(); #else - var resp = await _httpClient.GetFromJsonAsync(url); + var resp = await Homeserver.ClientHttpClient.GetFromJsonAsync(url); return resp; #endif } @@ -85,8 +85,8 @@ public class GenericRoom { if (!string.IsNullOrWhiteSpace(from)) url += $"&from={from}"; if (limit is not null) url += $"&limit={limit}"; if (!string.IsNullOrWhiteSpace(filter)) url += $"&filter={filter}"; - var res = await _httpClient.GetFromJsonAsync(url); - return res ?? new MessagesResponse(); + var res = await Homeserver.ClientHttpClient.GetFromJsonAsync(url); + return res; } /// @@ -101,8 +101,8 @@ public class GenericRoom { concat.Add(resp); if (!includeState) resp.State.Clear(); - from = resp.End; if (resp.End is null) break; + from = resp.End; } concat.Reverse(); @@ -131,12 +131,12 @@ public class GenericRoom { resp.State.Clear(); limit -= resp.Chunk.Count + resp.State.Count; - from = resp.End; yield return resp; if (resp.End is null) { Console.WriteLine("End is null"); yield break; } + from = resp.End; } } @@ -148,19 +148,19 @@ public class GenericRoom { public async Task JoinAsync(string[]? homeservers = null, string? reason = null, bool checkIfAlreadyMember = true) { if (checkIfAlreadyMember) { try { - var ce = await GetCreateEventAsync(); - return new() { + _ = await GetCreateEventAsync(); + return new RoomIdResponse { RoomId = RoomId }; } catch { } //ignore } - var join_url = $"/_matrix/client/v3/join/{HttpUtility.UrlEncode(RoomId)}"; - Console.WriteLine($"Calling {join_url} with {homeservers?.Length ?? 0} via's..."); + var joinUrl = $"/_matrix/client/v3/join/{HttpUtility.UrlEncode(RoomId)}"; + Console.WriteLine($"Calling {joinUrl} 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 { + var fullJoinUrl = $"{joinUrl}?server_name=" + string.Join("&server_name=", homeservers); + var res = await Homeserver.ClientHttpClient.PostAsJsonAsync(fullJoinUrl, new { reason }); return await res.Content.ReadFromJsonAsync() ?? throw new Exception("Failed to join room?"); @@ -168,9 +168,9 @@ public class GenericRoom { public async IAsyncEnumerable GetMembersAsync(bool joinedOnly = true) { var sw = Stopwatch.StartNew(); - var res = await _httpClient.GetAsync($"/_matrix/client/v3/rooms/{RoomId}/members"); + var res = await Homeserver.ClientHttpClient.GetAsync($"/_matrix/client/v3/rooms/{RoomId}/members"); Console.WriteLine($"Members call responded in {sw.GetElapsedAndRestart()}"); - var resText = await res.Content.ReadAsStringAsync(); + // var resText = await res.Content.ReadAsStringAsync(); Console.WriteLine($"Members call response read in {sw.GetElapsedAndRestart()}"); var result = await JsonSerializer.DeserializeAsync(await res.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { TypeInfoResolver = ChunkedStateEventResponseSerializerContext.Default, @@ -188,7 +188,7 @@ public class GenericRoom { #region Utility shortcuts - public async Task SendMessageEventAsync(RoomMessageEventContent content) => + public async Task SendMessageEventAsync(RoomMessageEventContent content) => await SendTimelineEventAsync("m.room.message", content); public async Task?> GetAliasesAsync() { @@ -259,29 +259,29 @@ public class GenericRoom { #region Simple calls public async Task ForgetAsync() => - await _httpClient.PostAsync($"/_matrix/client/v3/rooms/{RoomId}/forget", null); + await Homeserver.ClientHttpClient.PostAsync($"/_matrix/client/v3/rooms/{RoomId}/forget", null); public async Task LeaveAsync(string? reason = null) => - await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/leave", new { + await Homeserver.ClientHttpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/leave", new { reason }); public async Task KickAsync(string userId, string? reason = null) => - await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/kick", + await Homeserver.ClientHttpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/kick", new UserIdAndReason { UserId = userId, Reason = reason }); public async Task BanAsync(string userId, string? reason = null) => - await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/ban", + await Homeserver.ClientHttpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/ban", new UserIdAndReason { UserId = userId, Reason = reason }); public async Task UnbanAsync(string userId) => - await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/unban", + await Homeserver.ClientHttpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/unban", new UserIdAndReason { UserId = userId }); public async Task InviteUserAsync(string userId, string? reason = null, bool skipExisting = true) { if (skipExisting && await GetStateAsync("m.room.member", userId) is not null) return; - await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/invite", new UserIdAndReason(userId, reason)); + await Homeserver.ClientHttpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/invite", new UserIdAndReason(userId, reason)); } #endregion @@ -289,19 +289,19 @@ public class GenericRoom { #region Events public async Task SendStateEventAsync(string eventType, object content) => - await (await _httpClient.PutAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state/{eventType}", content)) + await (await Homeserver.ClientHttpClient.PutAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state/{eventType}", content)) .Content.ReadFromJsonAsync(); public async Task SendStateEventAsync(string eventType, string stateKey, object content) => - await (await _httpClient.PutAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state/{eventType}/{stateKey}", content)) + await (await Homeserver.ClientHttpClient.PutAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state/{eventType}/{stateKey}", content)) .Content.ReadFromJsonAsync(); - public async Task SendTimelineEventAsync(string eventType, TimelineEventContent content) { - var res = await _httpClient.PutAsJsonAsync( + public async Task SendTimelineEventAsync(string eventType, TimelineEventContent content) { + var res = await Homeserver.ClientHttpClient.PutAsJsonAsync( $"/_matrix/client/v3/rooms/{RoomId}/send/{eventType}/" + Guid.NewGuid(), content, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }); - return await res.Content.ReadFromJsonAsync(); + return await res.Content.ReadFromJsonAsync() ?? throw new Exception("Failed to send event"); } public async Task SendFileAsync(string fileName, Stream fileStream, string messageType = "m.file", string contentType = "application/octet-stream") { @@ -320,7 +320,7 @@ public class GenericRoom { } public async Task GetRoomAccountDataAsync(string key) { - var res = await _httpClient.GetAsync($"/_matrix/client/v3/user/{Homeserver.UserId}/rooms/{RoomId}/account_data/{key}"); + var res = await Homeserver.ClientHttpClient.GetAsync($"/_matrix/client/v3/user/{Homeserver.UserId}/rooms/{RoomId}/account_data/{key}"); if (!res.IsSuccessStatusCode) { Console.WriteLine($"Failed to get room account data: {await res.Content.ReadAsStringAsync()}"); throw new InvalidDataException($"Failed to get room account data: {await res.Content.ReadAsStringAsync()}"); @@ -330,7 +330,7 @@ public class GenericRoom { } public async Task SetRoomAccountDataAsync(string key, object data) { - var res = await _httpClient.PutAsJsonAsync($"/_matrix/client/v3/user/{Homeserver.UserId}/rooms/{RoomId}/account_data/{key}", data); + var res = await Homeserver.ClientHttpClient.PutAsJsonAsync($"/_matrix/client/v3/user/{Homeserver.UserId}/rooms/{RoomId}/account_data/{key}", data); if (!res.IsSuccessStatusCode) { Console.WriteLine($"Failed to set room account data: {await res.Content.ReadAsStringAsync()}"); throw new InvalidDataException($"Failed to set room account data: {await res.Content.ReadAsStringAsync()}"); @@ -338,12 +338,12 @@ public class GenericRoom { } public async Task GetEventAsync(string eventId) { - return await _httpClient.GetFromJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/event/{eventId}"); + return await Homeserver.ClientHttpClient.GetFromJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/event/{eventId}"); } public async Task RedactEventAsync(string eventToRedact, string reason) { var data = new { reason }; - return (await (await _httpClient.PutAsJsonAsync( + return (await (await Homeserver.ClientHttpClient.PutAsJsonAsync( $"/_matrix/client/v3/rooms/{RoomId}/redact/{eventToRedact}/{Guid.NewGuid()}", data)).Content.ReadFromJsonAsync())!; } @@ -353,7 +353,7 @@ public class GenericRoom { public async Task>> GetMembersByHomeserverAsync(bool joinedOnly = true) { if (Homeserver is AuthenticatedHomeserverMxApiExtended mxaeHomeserver) - return await Homeserver.ClientHttpClient.GetFromJsonAsync>>( + return await mxaeHomeserver.ClientHttpClient.GetFromJsonAsync>>( $"/_matrix/client/v3/rooms/{RoomId}/members_by_homeserver?joined_only={joinedOnly}"); Dictionary> roomHomeservers = new(); var members = GetMembersAsync(); diff --git a/LibMatrix/RoomTypes/SpaceRoom.cs b/LibMatrix/RoomTypes/SpaceRoom.cs index da9fcf8..6ebd62f 100644 --- a/LibMatrix/RoomTypes/SpaceRoom.cs +++ b/LibMatrix/RoomTypes/SpaceRoom.cs @@ -4,10 +4,8 @@ using LibMatrix.Homeservers; namespace LibMatrix.RoomTypes; public class SpaceRoom(AuthenticatedHomeserverGeneric homeserver, string roomId) : GenericRoom(homeserver, roomId) { - private readonly GenericRoom _room; - public async IAsyncEnumerable GetChildrenAsync(bool includeRemoved = false) { - var rooms = new List(); + // var rooms = new List(); var state = GetFullStateAsync(); await foreach (var stateEvent in state) { if (stateEvent!.Type != "m.space.child") continue; -- cgit 1.4.1