about summary refs log tree commit diff
diff options
context:
space:
mode:
authorTheArcaneBrony <myrainbowdash949@gmail.com>2023-10-11 15:52:28 +0200
committerTheArcaneBrony <myrainbowdash949@gmail.com>2023-10-11 15:52:28 +0200
commita98f16f1aaa72aa68278420a61d8ce897639416f (patch)
tree959044674e30b9fe16dc909e8e44af1483c99bc8
parentFix bug with event sending, make initial sync detection deterministic (diff)
downloadLibMatrix-bak-a98f16f1aaa72aa68278420a61d8ce897639416f.tar.xz
Added options to skip inviting already invited/joined/left users, added option to join room if it already exists when trying to create
-rw-r--r--LibMatrix/Extensions/HttpClientExtensions.cs9
-rw-r--r--LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs46
-rw-r--r--LibMatrix/RoomTypes/GenericRoom.cs8
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<HttpResponseMessage> PostAsJsonAsync<T>([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<WhoAmIResponse> 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<GenericRoom> CreateRoom(CreateRoomRequest creationEvent) {
+    public virtual async Task<GenericRoom> 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<JsonObject>())!["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<EventIdResponse>())!;
     }
 
-    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<RoomMemberEventContent>("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<string> users) {
-        var tasks = users.Select(x=>InviteUserAsync(x)).ToList();
+    public async Task InviteUsersAsync(IEnumerable<string> users, string? reason = null, bool skipExisting = true) {
+        var tasks = users.Select(x => InviteUserAsync(x, reason, skipExisting)).ToList();
         await Task.WhenAll(tasks);
     }
 }