From a98f16f1aaa72aa68278420a61d8ce897639416f Mon Sep 17 00:00:00 2001 From: TheArcaneBrony Date: Wed, 11 Oct 2023 15:52:28 +0200 Subject: Added options to skip inviting already invited/joined/left users, added option to join room if it already exists when trying to create --- LibMatrix/Extensions/HttpClientExtensions.cs | 9 +++++ .../Homeservers/AuthenticatedHomeserverGeneric.cs | 46 ++++++++++++++-------- LibMatrix/RoomTypes/GenericRoom.cs | 8 ++-- 3 files changed, 44 insertions(+), 19 deletions(-) diff --git a/LibMatrix/Extensions/HttpClientExtensions.cs b/LibMatrix/Extensions/HttpClientExtensions.cs index 6f1eab6..2faf0d5 100644 --- a/LibMatrix/Extensions/HttpClientExtensions.cs +++ b/LibMatrix/Extensions/HttpClientExtensions.cs @@ -98,4 +98,13 @@ public class MatrixHttpClient : HttpClient { Encoding.UTF8, "application/json"); return await SendAsync(request, cancellationToken); } + + public async Task PostAsJsonAsync([StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, T value, JsonSerializerOptions? options = null, + CancellationToken cancellationToken = default) { + var request = new HttpRequestMessage(HttpMethod.Post, requestUri); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + request.Content = new StringContent(JsonSerializer.Serialize(value, value.GetType(), options ?? new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }), + Encoding.UTF8, "application/json"); + return await SendAsync(request, cancellationToken); + } } diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs index c78b799..1da34d5 100644 --- a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs +++ b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs @@ -4,6 +4,7 @@ using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using ArcaneLibs.Extensions; +using LibMatrix.EventTypes.Spec.State; using LibMatrix.Responses; using LibMatrix.RoomTypes; using LibMatrix.Services; @@ -27,20 +28,20 @@ public class AuthenticatedHomeserverGeneric(string baseUrl, string accessToken) } // Activator.CreateInstance(baseUrl, accessToken) { - // _httpClient = new() { - // BaseAddress = new Uri(await new HomeserverResolverService().ResolveHomeserverFromWellKnown(baseUrl) - // ?? throw new InvalidOperationException("Failed to resolve homeserver")), - // Timeout = TimeSpan.FromMinutes(15), - // DefaultRequestHeaders = { - // Authorization = new AuthenticationHeaderValue("Bearer", accessToken) - // } - // } - // }; - + // _httpClient = new() { + // BaseAddress = new Uri(await new HomeserverResolverService().ResolveHomeserverFromWellKnown(baseUrl) + // ?? throw new InvalidOperationException("Failed to resolve homeserver")), + // Timeout = TimeSpan.FromMinutes(15), + // DefaultRequestHeaders = { + // Authorization = new AuthenticationHeaderValue("Bearer", accessToken) + // } + // } + // }; public WhoAmIResponse? WhoAmI { get; set; } public string? UserId => WhoAmI?.UserId; public string? UserLocalpart => UserId?.Split(":")[0][1..]; + public string? ServerName => UserId?.Split(":", 2)[1]; // public virtual async Task WhoAmI() { // if (_whoAmI is not null) return _whoAmI; @@ -77,7 +78,24 @@ public class AuthenticatedHomeserverGeneric(string baseUrl, string accessToken) return resJson.GetProperty("content_uri").GetString()!; } - public virtual async Task CreateRoom(CreateRoomRequest creationEvent) { + public virtual async Task CreateRoom(CreateRoomRequest creationEvent, bool returnExistingIfAliasExists = false, bool joinIfAliasExists = false, + bool inviteIfAliasExists = false) { + if (returnExistingIfAliasExists) { + var aliasRes = await ResolveRoomAliasAsync($"#{creationEvent.RoomAliasName}:{ServerName}"); + if (aliasRes is not null) { + var existingRoom = GetRoom(aliasRes.RoomId); + if (joinIfAliasExists) { + await existingRoom.JoinAsync(); + } + + if (inviteIfAliasExists) { + await existingRoom.InviteUsersAsync(creationEvent.Invite ?? new()); + } + + return existingRoom; + } + } + creationEvent.CreationContent["creator"] = WhoAmI.UserId; var res = await _httpClient.PostAsJsonAsync("/_matrix/client/v3/createRoom", creationEvent, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull @@ -90,9 +108,7 @@ public class AuthenticatedHomeserverGeneric(string baseUrl, string accessToken) var room = GetRoom((await res.Content.ReadFromJsonAsync())!["room_id"]!.ToString()); if (creationEvent.Invite is not null) - foreach (var user in creationEvent.Invite) { - await room.InviteUserAsync(user); - } + await room.InviteUsersAsync(creationEvent.Invite ?? new()); return room; } @@ -147,6 +163,4 @@ public class AuthenticatedHomeserverGeneric(string baseUrl, string accessToken) } #endregion - - } diff --git a/LibMatrix/RoomTypes/GenericRoom.cs b/LibMatrix/RoomTypes/GenericRoom.cs index 37006af..1c0633c 100644 --- a/LibMatrix/RoomTypes/GenericRoom.cs +++ b/LibMatrix/RoomTypes/GenericRoom.cs @@ -232,7 +232,9 @@ public class GenericRoom { $"/_matrix/client/v3/rooms/{RoomId}/redact/{eventToRedact}/{Guid.NewGuid()}", data)).Content.ReadFromJsonAsync())!; } - public async Task InviteUserAsync(string userId, string? reason = null) { + 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)); } @@ -265,8 +267,8 @@ public class GenericRoom { #endregion - public async Task InviteUsersAsync(IEnumerable users) { - var tasks = users.Select(x=>InviteUserAsync(x)).ToList(); + public async Task InviteUsersAsync(IEnumerable users, string? reason = null, bool skipExisting = true) { + var tasks = users.Select(x => InviteUserAsync(x, reason, skipExisting)).ToList(); await Task.WhenAll(tasks); } } -- cgit 1.4.1