From 6bd02248ccfbcb46960a6f39eaad23888d190eb5 Mon Sep 17 00:00:00 2001 From: TheArcaneBrony Date: Fri, 15 Sep 2023 09:50:45 +0200 Subject: Some refactoring --- LibMatrix/Extensions/HttpClientExtensions.cs | 11 +++-- LibMatrix/Filters/SyncFilter.cs | 45 +++++++++++++------ LibMatrix/Helpers/MessageFormatter.cs | 16 +++---- .../Homeservers/AuthenticatedHomeserverGeneric.cs | 52 +++++++++++++++------- .../AuthenticatedHomeserverMxApiExtended.cs | 10 +---- LibMatrix/Homeservers/RemoteHomeServer.cs | 18 +++----- LibMatrix/Interfaces/IStateEventType.cs | 22 ++++++++- LibMatrix/LibMatrix.csproj | 18 ++++++-- LibMatrix/Responses/CreateRoomRequest.cs | 5 ++- LibMatrix/RoomTypes/GenericRoom.cs | 48 +++++++++++--------- LibMatrix/RoomTypes/SpaceRoom.cs | 2 +- LibMatrix/StateEvent.cs | 42 ++++++++--------- .../Common/MjolnirShortcodeEventData.cs | 2 +- .../StateEventTypes/Common/RoomEmotesEventData.cs | 2 +- .../Spec/CanonicalAliasEventContent.cs | 13 ++++++ .../Spec/CanonicalAliasEventData.cs | 13 ------ .../StateEventTypes/Spec/GuestAccessEventData.cs | 2 +- .../Spec/HistoryVisibilityEventData.cs | 2 +- .../StateEventTypes/Spec/JoinRulesEventData.cs | 2 +- .../Spec/PolicyRuleStateEventData.cs | 2 +- .../StateEventTypes/Spec/PresenceStateEventData.cs | 2 +- .../Spec/ProfileResponseEventData.cs | 2 +- .../StateEventTypes/Spec/RoomAliasEventData.cs | 2 +- .../StateEventTypes/Spec/RoomAvatarEventData.cs | 2 +- .../StateEventTypes/Spec/RoomCreateEventData.cs | 2 +- .../Spec/RoomEncryptionEventData.cs | 2 +- .../StateEventTypes/Spec/RoomMemberEventData.cs | 2 +- .../StateEventTypes/Spec/RoomMessageEventData.cs | 24 +--------- .../StateEventTypes/Spec/RoomNameEventData.cs | 2 +- .../StateEventTypes/Spec/RoomPinnedEventData.cs | 2 +- .../Spec/RoomPowerLevelEventData.cs | 2 +- .../StateEventTypes/Spec/RoomTopicEventData.cs | 2 +- .../StateEventTypes/Spec/RoomTypingEventData.cs | 2 +- .../StateEventTypes/Spec/ServerACLEventData.cs | 2 +- .../StateEventTypes/Spec/SpaceChildEventData.cs | 2 +- .../StateEventTypes/Spec/SpaceParentEventData.cs | 2 +- LibMatrix/StateEventTypes/UnknownStateEventData.cs | 7 +++ LibMatrix/UserIdAndReason.cs | 7 +-- 38 files changed, 227 insertions(+), 168 deletions(-) create mode 100644 LibMatrix/StateEventTypes/Spec/CanonicalAliasEventContent.cs delete mode 100644 LibMatrix/StateEventTypes/Spec/CanonicalAliasEventData.cs create mode 100644 LibMatrix/StateEventTypes/UnknownStateEventData.cs (limited to 'LibMatrix') diff --git a/LibMatrix/Extensions/HttpClientExtensions.cs b/LibMatrix/Extensions/HttpClientExtensions.cs index d4017ed..31ae650 100644 --- a/LibMatrix/Extensions/HttpClientExtensions.cs +++ b/LibMatrix/Extensions/HttpClientExtensions.cs @@ -2,6 +2,7 @@ using System.Diagnostics; using System.Net.Http.Headers; using System.Reflection; using System.Text.Json; +using ArcaneLibs.Extensions; namespace LibMatrix.Extensions; @@ -20,13 +21,18 @@ public static class HttpClientExtensions { } public class MatrixHttpClient : HttpClient { + internal string? AssertedUserId { get; set; } + public override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + if (request.RequestUri is null) throw new NullReferenceException("RequestUri is null"); + if (AssertedUserId is not null) request.RequestUri = request.RequestUri.AddQuery("user_id", AssertedUserId); + Console.WriteLine($"Sending request to {request.RequestUri}"); try { - var WebAssemblyEnableStreamingResponseKey = + var webAssemblyEnableStreamingResponseKey = new HttpRequestOptionsKey("WebAssemblyEnableStreamingResponse"); - request.Options.Set(WebAssemblyEnableStreamingResponseKey, true); + request.Options.Set(webAssemblyEnableStreamingResponseKey, true); } catch (Exception e) { Console.WriteLine("Failed to set browser response streaming:"); @@ -50,7 +56,6 @@ public class MatrixHttpClient : HttpClient { typeof(HttpRequestMessage).GetField("_sendStatus", BindingFlags.NonPublic | BindingFlags.Instance) ?.SetValue(request, 0); return await SendAsync(request, cancellationToken); - } // GetFromJsonAsync diff --git a/LibMatrix/Filters/SyncFilter.cs b/LibMatrix/Filters/SyncFilter.cs index c907f6b..e3e8164 100644 --- a/LibMatrix/Filters/SyncFilter.cs +++ b/LibMatrix/Filters/SyncFilter.cs @@ -1,3 +1,4 @@ +using System.Reflection.Metadata; using System.Text.Json.Serialization; namespace LibMatrix.Filters; @@ -25,42 +26,58 @@ public class SyncFilter { [JsonPropertyName("timeline")] public StateFilter? Timeline { get; set; } - - public class StateFilter : EventFilter { + public class StateFilter(bool? containsUrl = null, bool? includeRedundantMembers = null, bool? lazyLoadMembers = null, List? rooms = null, + List? notRooms = null, bool? unreadThreadNotifications = null, + //base ctor + int? limit = null, List? types = null, List? notTypes = null, List? senders = null, List? notSenders = null + ) : EventFilter(limit: limit, types: types, notTypes: notTypes, senders: senders, notSenders: notSenders) { [JsonPropertyName("contains_url")] - public bool? ContainsUrl { get; set; } + public bool? ContainsUrl { get; set; } = containsUrl; [JsonPropertyName("include_redundant_members")] - public bool? IncludeRedundantMembers { get; set; } + public bool? IncludeRedundantMembers { get; set; } = includeRedundantMembers; [JsonPropertyName("lazy_load_members")] - public bool? LazyLoadMembers { get; set; } + public bool? LazyLoadMembers { get; set; } = lazyLoadMembers; [JsonPropertyName("rooms")] - public List? Rooms { get; set; } + public List? Rooms { get; set; } = rooms; [JsonPropertyName("not_rooms")] - public List? NotRooms { get; set; } + public List? NotRooms { get; set; } = notRooms; [JsonPropertyName("unread_thread_notifications")] - public bool? UnreadThreadNotifications { get; set; } + public bool? UnreadThreadNotifications { get; set; } = unreadThreadNotifications; } } - public class EventFilter { + public class EventFilter(int? limit = null, List? types = null, List? notTypes = null, List? senders = null, List? notSenders = null) { [JsonPropertyName("limit")] - public int? Limit { get; set; } + public int? Limit { get; set; } = limit; [JsonPropertyName("types")] - public List? Types { get; set; } + public List? Types { get; set; } = types; [JsonPropertyName("not_types")] - public List? NotTypes { get; set; } + public List? NotTypes { get; set; } = notTypes; [JsonPropertyName("senders")] - public List? Senders { get; set; } + public List? Senders { get; set; } = senders; [JsonPropertyName("not_senders")] - public List? NotSenders { get; set; } + public List? NotSenders { get; set; } = notSenders; } } + +public static class ExampleFilters { + public static readonly SyncFilter Limit1Filter = new() { + Presence = new(limit: 1), + Room = new() { + AccountData = new(limit: 1), + Ephemeral = new(limit: 1), + State = new(limit: 1), + Timeline = new(limit: 1), + }, + AccountData = new(limit: 1) + }; +} diff --git a/LibMatrix/Helpers/MessageFormatter.cs b/LibMatrix/Helpers/MessageFormatter.cs index ff0a00f..37d7004 100644 --- a/LibMatrix/Helpers/MessageFormatter.cs +++ b/LibMatrix/Helpers/MessageFormatter.cs @@ -4,30 +4,30 @@ using LibMatrix.StateEventTypes.Spec; namespace LibMatrix.Helpers; public static class MessageFormatter { - public static RoomMessageEventData FormatError(string error) { - return new RoomMessageEventData(body: error, messageType: "m.text") { + public static RoomMessageEventContent FormatError(string error) { + return new RoomMessageEventContent(body: error, messageType: "m.text") { FormattedBody = $"{error}: {error}", Format = "org.matrix.custom.html" }; } - public static RoomMessageEventData FormatException(string error, Exception e) { - return new RoomMessageEventData(body: $"{error}: {e.Message}", messageType: "m.text") { + public static RoomMessageEventContent FormatException(string error, Exception e) { + return new RoomMessageEventContent(body: $"{error}: {e.Message}", messageType: "m.text") { FormattedBody = $"{error}:
{e.Message}
" + $"
", Format = "org.matrix.custom.html" }; } - public static RoomMessageEventData FormatSuccess(string text) { - return new RoomMessageEventData(body: text, messageType: "m.text") { + public static RoomMessageEventContent FormatSuccess(string text) { + return new RoomMessageEventContent(body: text, messageType: "m.text") { FormattedBody = $"{text}", Format = "org.matrix.custom.html" }; } - public static RoomMessageEventData FormatSuccessJson(string text, object data) { - return new RoomMessageEventData(body: text, messageType: "m.text") { + public static RoomMessageEventContent FormatSuccessJson(string text, object data) { + return new RoomMessageEventContent(body: text, messageType: "m.text") { FormattedBody = $"{text}:
{data.ToJson(ignoreNull: true)}
", Format = "org.matrix.custom.html" }; diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs index 0b3201c..a280c54 100644 --- a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs +++ b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs @@ -2,6 +2,7 @@ using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; +using ArcaneLibs.Extensions; using LibMatrix.Extensions; using LibMatrix.Helpers; using LibMatrix.Responses; @@ -14,21 +15,18 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer { public AuthenticatedHomeserverGeneric(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) : base(canonicalHomeServerDomain) { Storage = storage; AccessToken = accessToken.Trim(); - HomeServerDomain = canonicalHomeServerDomain.Trim(); SyncHelper = new SyncHelper(this, storage); - _httpClient = new MatrixHttpClient(); } - public TieredStorageService Storage { get; set; } - public SyncHelper SyncHelper { get; init; } - public WhoAmIResponse WhoAmI { get; set; } = null!; - public string UserId => WhoAmI.UserId; - public string AccessToken { get; set; } + public virtual TieredStorageService Storage { get; set; } + public virtual SyncHelper SyncHelper { get; init; } + public virtual WhoAmIResponse WhoAmI { get; set; } = null!; + public virtual string UserId => WhoAmI.UserId; + public virtual string AccessToken { get; set; } + public virtual Task GetRoom(string roomId) => Task.FromResult(new(this, roomId)); - public Task GetRoom(string roomId) => Task.FromResult(new(this, roomId)); - - public async Task> GetJoinedRooms() { + public virtual async Task> GetJoinedRooms() { var roomQuery = await _httpClient.GetAsync("/_matrix/client/v3/joined_rooms"); var roomsJson = await roomQuery.Content.ReadFromJsonAsync(); @@ -39,7 +37,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer { return rooms; } - public async Task UploadFile(string fileName, Stream fileStream, string contentType = "application/octet-stream") { + public virtual async Task UploadFile(string fileName, Stream fileStream, string contentType = "application/octet-stream") { var res = await _httpClient.PostAsync($"/_matrix/media/v3/upload?filename={fileName}", new StreamContent(fileStream)); if (!res.IsSuccessStatusCode) { Console.WriteLine($"Failed to upload file: {await res.Content.ReadAsStringAsync()}"); @@ -50,7 +48,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer { return resJson.GetProperty("content_uri").GetString()!; } - public async Task CreateRoom(CreateRoomRequest creationEvent) { + public virtual async Task CreateRoom(CreateRoomRequest creationEvent) { creationEvent.CreationContent["creator"] = UserId; var res = await _httpClient.PostAsJsonAsync("/_matrix/client/v3/createRoom", creationEvent, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull @@ -60,12 +58,36 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer { throw new InvalidDataException($"Failed to create room: {await res.Content.ReadAsStringAsync()}"); } - return await GetRoom((await res.Content.ReadFromJsonAsync())!["room_id"]!.ToString()); + var room = await GetRoom((await res.Content.ReadFromJsonAsync())!["room_id"]!.ToString()); + + foreach (var user in creationEvent.Invite) { + await room.InviteUser(user); + } + + return room; + } + +#region Utility Functions + public virtual async IAsyncEnumerable GetJoinedRoomsByType(string type) { + var rooms = await GetJoinedRooms(); + var tasks = rooms.Select(async room => { + var roomType = await room.GetRoomType(); + if (roomType == type) { + return room; + } + + return null; + }).ToAsyncEnumerable(); + + await foreach (var result in tasks) { + if (result is not null) yield return result; + } } +#endregion #region Account Data - public async Task GetAccountData(string key) { + public virtual async Task GetAccountData(string key) { // var res = await _httpClient.GetAsync($"/_matrix/client/v3/user/{UserId}/account_data/{key}"); // if (!res.IsSuccessStatusCode) { // Console.WriteLine($"Failed to get account data: {await res.Content.ReadAsStringAsync()}"); @@ -76,7 +98,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeServer { return await _httpClient.GetFromJsonAsync($"/_matrix/client/v3/user/{UserId}/account_data/{key}"); } - public async Task SetAccountData(string key, object data) { + public virtual async Task SetAccountData(string key, object data) { var res = await _httpClient.PutAsJsonAsync($"/_matrix/client/v3/user/{UserId}/account_data/{key}", data); if (!res.IsSuccessStatusCode) { Console.WriteLine($"Failed to set account data: {await res.Content.ReadAsStringAsync()}"); diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs index 8ffcfaf..e44d727 100644 --- a/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs +++ b/LibMatrix/Homeservers/AuthenticatedHomeserverMxApiExtended.cs @@ -4,11 +4,5 @@ using LibMatrix.Services; namespace LibMatrix.Homeservers; -public class AuthenticatedHomeserverMxApiExtended : AuthenticatedHomeserverGeneric { - public AuthenticatedHomeserverMxApiExtended(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) : base(storage, canonicalHomeServerDomain, accessToken) { - AccessToken = accessToken.Trim(); - HomeServerDomain = canonicalHomeServerDomain.Trim(); - SyncHelper = new SyncHelper(this, storage); - _httpClient = new MatrixHttpClient(); - } -} +public class AuthenticatedHomeserverMxApiExtended(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) : AuthenticatedHomeserverGeneric(storage, canonicalHomeServerDomain, + accessToken); diff --git a/LibMatrix/Homeservers/RemoteHomeServer.cs b/LibMatrix/Homeservers/RemoteHomeServer.cs index 923986d..caed397 100644 --- a/LibMatrix/Homeservers/RemoteHomeServer.cs +++ b/LibMatrix/Homeservers/RemoteHomeServer.cs @@ -5,28 +5,24 @@ using LibMatrix.StateEventTypes.Spec; namespace LibMatrix.Homeservers; -public class RemoteHomeServer { - public RemoteHomeServer(string canonicalHomeServerDomain) { - HomeServerDomain = canonicalHomeServerDomain; - _httpClient = new MatrixHttpClient(); - _httpClient.Timeout = TimeSpan.FromSeconds(5); - } +public class RemoteHomeServer(string canonicalHomeServerDomain) { + // _httpClient.Timeout = TimeSpan.FromSeconds(5); private Dictionary _profileCache { get; set; } = new(); - public string HomeServerDomain { get; set; } + public string HomeServerDomain { get; } = canonicalHomeServerDomain.Trim(); public string FullHomeServerDomain { get; set; } - public MatrixHttpClient _httpClient { get; set; } + public MatrixHttpClient _httpClient { get; set; } = new(); - public async Task GetProfile(string mxid) { + public async Task GetProfile(string mxid) { if(mxid is null) throw new ArgumentNullException(nameof(mxid)); if (_profileCache.TryGetValue(mxid, out var value)) { if (value is SemaphoreSlim s) await s.WaitAsync(); - if (value is ProfileResponseEventData p) return p; + if (value is ProfileResponseEventContent p) return p; } _profileCache[mxid] = new SemaphoreSlim(1); var resp = await _httpClient.GetAsync($"/_matrix/client/v3/profile/{mxid}"); - var data = await resp.Content.ReadFromJsonAsync(); + var data = await resp.Content.ReadFromJsonAsync(); if (!resp.IsSuccessStatusCode) Console.WriteLine("Profile: " + data); _profileCache[mxid] = data; diff --git a/LibMatrix/Interfaces/IStateEventType.cs b/LibMatrix/Interfaces/IStateEventType.cs index 13a0d05..f2e4a3b 100644 --- a/LibMatrix/Interfaces/IStateEventType.cs +++ b/LibMatrix/Interfaces/IStateEventType.cs @@ -1,3 +1,23 @@ +using System.Text.Json.Serialization; + namespace LibMatrix.Interfaces; -public interface IStateEventType { } +public abstract class EventContent { + [JsonPropertyName("m.relates_to")] + public virtual MessageRelatesTo? RelatesTo { get; set; } + + [JsonPropertyName("m.new_content")] + public virtual EventContent? NewContent { get; set; } + + public abstract class MessageRelatesTo { + [JsonPropertyName("m.in_reply_to")] + public EventInReplyTo? InReplyTo { get; set; } + + + + public abstract class EventInReplyTo { + [JsonPropertyName("event_id")] + public string EventId { get; set; } + } + } +} diff --git a/LibMatrix/LibMatrix.csproj b/LibMatrix/LibMatrix.csproj index 709e079..805695b 100644 --- a/LibMatrix/LibMatrix.csproj +++ b/LibMatrix/LibMatrix.csproj @@ -8,12 +8,22 @@ - - + + - + + + - + + + + + diff --git a/LibMatrix/Responses/CreateRoomRequest.cs b/LibMatrix/Responses/CreateRoomRequest.cs index 24c9ae0..82a4b12 100644 --- a/LibMatrix/Responses/CreateRoomRequest.cs +++ b/LibMatrix/Responses/CreateRoomRequest.cs @@ -4,6 +4,7 @@ using System.Text.Json.Serialization; using System.Text.RegularExpressions; using LibMatrix.Helpers; using LibMatrix.Homeservers; +using LibMatrix.Interfaces; using LibMatrix.StateEventTypes.Spec; namespace LibMatrix.Responses; @@ -33,7 +34,7 @@ public class CreateRoomRequest { public string Visibility { get; set; } = null!; [JsonPropertyName("power_level_content_override")] - public RoomPowerLevelEventData PowerLevelContentOverride { get; set; } = null!; + public RoomPowerLevelEventContent PowerLevelContentOverride { get; set; } = null!; [JsonPropertyName("creation_content")] public JsonObject CreationContent { get; set; } = new(); @@ -52,7 +53,7 @@ public class CreateRoomRequest { InitialState.Add(stateEvent = new StateEvent { Type = event_type, StateKey = event_key, - TypedContent = Activator.CreateInstance( + TypedContent = (EventContent)Activator.CreateInstance( StateEvent.KnownStateEventTypes.FirstOrDefault(x => x.GetCustomAttributes()? .Any(y => y.EventName == event_type) ?? false) ?? typeof(object) diff --git a/LibMatrix/RoomTypes/GenericRoom.cs b/LibMatrix/RoomTypes/GenericRoom.cs index 4c784ce..146b5dd 100644 --- a/LibMatrix/RoomTypes/GenericRoom.cs +++ b/LibMatrix/RoomTypes/GenericRoom.cs @@ -85,7 +85,7 @@ public class GenericRoom { // TODO: should we even error handle here? public async Task GetNameAsync() { try { - var res = await GetStateAsync("m.room.name"); + var res = await GetStateAsync("m.room.name"); return res?.Name ?? RoomId; } catch (MatrixException e) { @@ -108,7 +108,7 @@ public class GenericRoom { // var res = GetFullStateAsync(); // await foreach (var member in res) { // if (member?.Type != "m.room.member") continue; - // if (joinedOnly && (member.TypedContent as RoomMemberEventData)?.Membership is not "join") continue; + // if (joinedOnly && (member.TypedContent as RoomMemberEventContent)?.Membership is not "join") continue; // yield return member; // } var res = await _httpClient.GetAsync($"/_matrix/client/v3/rooms/{RoomId}/members"); @@ -116,7 +116,7 @@ public class GenericRoom { JsonSerializer.DeserializeAsyncEnumerable(await res.Content.ReadAsStreamAsync()); await foreach (var resp in result) { if (resp?.Type != "m.room.member") continue; - if (joinedOnly && (resp.TypedContent as RoomMemberEventData)?.Membership is not "join") continue; + if (joinedOnly && (resp.TypedContent as RoomMemberEventContent)?.Membership is not "join") continue; yield return resp; } } @@ -124,38 +124,38 @@ public class GenericRoom { #region Utility shortcuts public async Task> GetAliasesAsync() { - var res = await GetStateAsync("m.room.aliases"); + var res = await GetStateAsync("m.room.aliases"); return res.Aliases; } - public async Task GetCanonicalAliasAsync() => - await GetStateAsync("m.room.canonical_alias"); + public async Task GetCanonicalAliasAsync() => + await GetStateAsync("m.room.canonical_alias"); - public async Task GetTopicAsync() => - await GetStateAsync("m.room.topic"); + public async Task GetTopicAsync() => + await GetStateAsync("m.room.topic"); - public async Task GetAvatarUrlAsync() => - await GetStateAsync("m.room.avatar"); + public async Task GetAvatarUrlAsync() => + await GetStateAsync("m.room.avatar"); - public async Task GetJoinRuleAsync() => - await GetStateAsync("m.room.join_rules"); + public async Task GetJoinRuleAsync() => + await GetStateAsync("m.room.join_rules"); - public async Task GetHistoryVisibilityAsync() => - await GetStateAsync("m.room.history_visibility"); + public async Task GetHistoryVisibilityAsync() => + await GetStateAsync("m.room.history_visibility"); - public async Task GetGuestAccessAsync() => - await GetStateAsync("m.room.guest_access"); + public async Task GetGuestAccessAsync() => + await GetStateAsync("m.room.guest_access"); - public async Task GetCreateEventAsync() => - await GetStateAsync("m.room.create"); + public async Task GetCreateEventAsync() => + await GetStateAsync("m.room.create"); public async Task GetRoomType() { - var res = await GetStateAsync("m.room.create"); + var res = await GetStateAsync("m.room.create"); return res.Type; } - public async Task GetPowerLevelsAsync() => - await GetStateAsync("m.room.power_levels"); + public async Task GetPowerLevelsAsync() => + await GetStateAsync("m.room.power_levels"); #endregion @@ -187,7 +187,7 @@ public class GenericRoom { await (await _httpClient.PutAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state/{eventType}/{stateKey}", content)) .Content.ReadFromJsonAsync(); - public async Task SendMessageEventAsync(string eventType, RoomMessageEventData content) { + public async Task SendMessageEventAsync(string eventType, RoomMessageEventContent content) { var res = await _httpClient.PutAsJsonAsync( $"/_matrix/client/v3/rooms/{RoomId}/send/{eventType}/" + Guid.NewGuid(), content, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull @@ -239,4 +239,8 @@ public class GenericRoom { return (await (await _httpClient.PutAsJsonAsync( $"/_matrix/client/v3/rooms/{RoomId}/redact/{eventToRedact}/{Guid.NewGuid()}", data)).Content.ReadFromJsonAsync())!; } + + public async Task InviteUser(string userId, string? reason = null) { + await _httpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/invite", new UserIdAndReason(userId, reason)); + } } diff --git a/LibMatrix/RoomTypes/SpaceRoom.cs b/LibMatrix/RoomTypes/SpaceRoom.cs index e1e9879..0a4447a 100644 --- a/LibMatrix/RoomTypes/SpaceRoom.cs +++ b/LibMatrix/RoomTypes/SpaceRoom.cs @@ -12,7 +12,7 @@ public class SpaceRoom : GenericRoom { } private static SemaphoreSlim _semaphore = new(1, 1); - public async IAsyncEnumerable GetRoomsAsync(bool includeRemoved = false) { + public async IAsyncEnumerable GetChildrenAsync(bool includeRemoved = false) { await _semaphore.WaitAsync(); var rooms = new List(); var state = GetFullStateAsync(); diff --git a/LibMatrix/StateEvent.cs b/LibMatrix/StateEvent.cs index 175d706..9ca9141 100644 --- a/LibMatrix/StateEvent.cs +++ b/LibMatrix/StateEvent.cs @@ -6,28 +6,41 @@ using ArcaneLibs; using ArcaneLibs.Extensions; using LibMatrix.Helpers; using LibMatrix.Interfaces; +using LibMatrix.StateEventTypes; namespace LibMatrix; public class StateEvent { - public static List KnownStateEventTypes = - new ClassCollector().ResolveFromAllAccessibleAssemblies(); + public static readonly List KnownStateEventTypes = + new ClassCollector().ResolveFromAllAccessibleAssemblies(); + + public static readonly Dictionary KnownStateEventTypesByName = KnownStateEventTypes.Aggregate( + new Dictionary(), + (dict, type) => { + var attrs = type.GetCustomAttributes(); + foreach (var attr in attrs) { + dict[attr.EventName] = type; + } + + return dict; + }); public static Type GetStateEventType(string type) { if (type == "m.receipt") { return typeof(Dictionary); } - var eventType = KnownStateEventTypes.FirstOrDefault(x => - x.GetCustomAttributes()?.Any(y => y.EventName == type) ?? false); + // var eventType = KnownStateEventTypes.FirstOrDefault(x => + // x.GetCustomAttributes()?.Any(y => y.EventName == type) ?? false); + var eventType = KnownStateEventTypesByName.GetValueOrDefault(type); - return eventType ?? typeof(object); + return eventType ?? typeof(UnknownEventContent); } - public object TypedContent { + public EventContent TypedContent { get { try { - return RawContent.Deserialize(GetType)!; + return (EventContent) RawContent.Deserialize(GetType)!; } catch (JsonException e) { Console.WriteLine(e); @@ -42,19 +55,8 @@ public class StateEvent { [JsonPropertyName("state_key")] public string StateKey { get; set; } = ""; - private string _type; - [JsonPropertyName("type")] - public string Type { - get => _type; - set { - _type = value; - // if (RawContent is not null && this is StateEventResponse stateEventResponse) { - // if (File.Exists($"unknown_state_events/{Type}/{stateEventResponse.EventId}.json")) return; - // var x = GetType.Name; - // } - } - } + public string Type { get; set; } [JsonPropertyName("replaces_state")] public string? ReplacesState { get; set; } @@ -79,7 +81,7 @@ public class StateEvent { var type = GetStateEventType(Type); //special handling for some types - // if (type == typeof(RoomEmotesEventData)) { + // if (type == typeof(RoomEmotesEventContent)) { // RawContent["emote"] = RawContent["emote"]?.AsObject() ?? new JsonObject(); // } // diff --git a/LibMatrix/StateEventTypes/Common/MjolnirShortcodeEventData.cs b/LibMatrix/StateEventTypes/Common/MjolnirShortcodeEventData.cs index 7a4b3f3..ff11be7 100644 --- a/LibMatrix/StateEventTypes/Common/MjolnirShortcodeEventData.cs +++ b/LibMatrix/StateEventTypes/Common/MjolnirShortcodeEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Common; [MatrixEvent(EventName = "org.matrix.mjolnir.shortcode")] -public class MjolnirShortcodeEventData : IStateEventType { +public class MjolnirShortcodeEventContent : EventContent { [JsonPropertyName("shortcode")] public string? Shortcode { get; set; } } diff --git a/LibMatrix/StateEventTypes/Common/RoomEmotesEventData.cs b/LibMatrix/StateEventTypes/Common/RoomEmotesEventData.cs index ad65b0f..a056eda 100644 --- a/LibMatrix/StateEventTypes/Common/RoomEmotesEventData.cs +++ b/LibMatrix/StateEventTypes/Common/RoomEmotesEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Common; [MatrixEvent(EventName = "im.ponies.room_emotes")] -public class RoomEmotesEventData : IStateEventType { +public class RoomEmotesEventContent : EventContent { [JsonPropertyName("emoticons")] public Dictionary? Emoticons { get; set; } diff --git a/LibMatrix/StateEventTypes/Spec/CanonicalAliasEventContent.cs b/LibMatrix/StateEventTypes/Spec/CanonicalAliasEventContent.cs new file mode 100644 index 0000000..7a0e84c --- /dev/null +++ b/LibMatrix/StateEventTypes/Spec/CanonicalAliasEventContent.cs @@ -0,0 +1,13 @@ +using System.Text.Json.Serialization; +using LibMatrix.Helpers; +using LibMatrix.Interfaces; + +namespace LibMatrix.StateEventTypes.Spec; + +[MatrixEvent(EventName = "m.room.canonical_alias")] +public class CanonicalAliasEventContent : EventContent { + [JsonPropertyName("alias")] + public string? Alias { get; set; } + [JsonPropertyName("alt_aliases")] + public string[]? AltAliases { get; set; } +} diff --git a/LibMatrix/StateEventTypes/Spec/CanonicalAliasEventData.cs b/LibMatrix/StateEventTypes/Spec/CanonicalAliasEventData.cs deleted file mode 100644 index 269bd6d..0000000 --- a/LibMatrix/StateEventTypes/Spec/CanonicalAliasEventData.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Text.Json.Serialization; -using LibMatrix.Helpers; -using LibMatrix.Interfaces; - -namespace LibMatrix.StateEventTypes.Spec; - -[MatrixEvent(EventName = "m.room.canonical_alias")] -public class CanonicalAliasEventData : IStateEventType { - [JsonPropertyName("alias")] - public string? Alias { get; set; } - [JsonPropertyName("alt_aliases")] - public string[]? AltAliases { get; set; } -} diff --git a/LibMatrix/StateEventTypes/Spec/GuestAccessEventData.cs b/LibMatrix/StateEventTypes/Spec/GuestAccessEventData.cs index 7ba3428..0709b86 100644 --- a/LibMatrix/StateEventTypes/Spec/GuestAccessEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/GuestAccessEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.guest_access")] -public class GuestAccessEventData : IStateEventType { +public class GuestAccessEventContent : EventContent { [JsonPropertyName("guest_access")] public string GuestAccess { get; set; } diff --git a/LibMatrix/StateEventTypes/Spec/HistoryVisibilityEventData.cs b/LibMatrix/StateEventTypes/Spec/HistoryVisibilityEventData.cs index deca7c8..b19dd32 100644 --- a/LibMatrix/StateEventTypes/Spec/HistoryVisibilityEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/HistoryVisibilityEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.history_visibility")] -public class HistoryVisibilityEventData : IStateEventType { +public class HistoryVisibilityEventContent : EventContent { [JsonPropertyName("history_visibility")] public string HistoryVisibility { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/JoinRulesEventData.cs b/LibMatrix/StateEventTypes/Spec/JoinRulesEventData.cs index b64c1dd..8c0772f 100644 --- a/LibMatrix/StateEventTypes/Spec/JoinRulesEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/JoinRulesEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.join_rules")] -public class JoinRulesEventData : IStateEventType { +public class JoinRulesEventContent : EventContent { private static string Public = "public"; private static string Invite = "invite"; private static string Knock = "knock"; diff --git a/LibMatrix/StateEventTypes/Spec/PolicyRuleStateEventData.cs b/LibMatrix/StateEventTypes/Spec/PolicyRuleStateEventData.cs index 2e66bd9..539e371 100644 --- a/LibMatrix/StateEventTypes/Spec/PolicyRuleStateEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/PolicyRuleStateEventData.cs @@ -7,7 +7,7 @@ namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.policy.rule.user")] [MatrixEvent(EventName = "m.policy.rule.server")] [MatrixEvent(EventName = "org.matrix.mjolnir.rule.server")] -public class PolicyRuleStateEventData : IStateEventType { +public class PolicyRuleEventContent : EventContent { /// /// Entity this ban applies to, can use * and ? as globs. /// diff --git a/LibMatrix/StateEventTypes/Spec/PresenceStateEventData.cs b/LibMatrix/StateEventTypes/Spec/PresenceStateEventData.cs index 5167502..b897ff0 100644 --- a/LibMatrix/StateEventTypes/Spec/PresenceStateEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/PresenceStateEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.presence")] -public class PresenceStateEventData : IStateEventType { +public class PresenceEventContent : EventContent { [JsonPropertyName("presence")] public string Presence { get; set; } [JsonPropertyName("last_active_ago")] diff --git a/LibMatrix/StateEventTypes/Spec/ProfileResponseEventData.cs b/LibMatrix/StateEventTypes/Spec/ProfileResponseEventData.cs index 14449e0..9b4f1d0 100644 --- a/LibMatrix/StateEventTypes/Spec/ProfileResponseEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/ProfileResponseEventData.cs @@ -3,7 +3,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; -public class ProfileResponseEventData : IStateEventType { +public class ProfileResponseEventContent : EventContent { [JsonPropertyName("avatar_url")] public string? AvatarUrl { get; set; } diff --git a/LibMatrix/StateEventTypes/Spec/RoomAliasEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomAliasEventData.cs index 3f2c39e..d3960a1 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomAliasEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomAliasEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.alias")] -public class RoomAliasEventData : IStateEventType { +public class RoomAliasEventContent : EventContent { [JsonPropertyName("aliases")] public List? Aliases { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/RoomAvatarEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomAvatarEventData.cs index f71e1fb..e2263c8 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomAvatarEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomAvatarEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.avatar")] -public class RoomAvatarEventData : IStateEventType { +public class RoomAvatarEventContent : EventContent { [JsonPropertyName("url")] public string? Url { get; set; } diff --git a/LibMatrix/StateEventTypes/Spec/RoomCreateEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomCreateEventData.cs index 31f9411..22df784 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomCreateEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomCreateEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.create")] -public class RoomCreateEventData : IStateEventType { +public class RoomCreateEventContent : EventContent { [JsonPropertyName("room_version")] public string? RoomVersion { get; set; } [JsonPropertyName("creator")] diff --git a/LibMatrix/StateEventTypes/Spec/RoomEncryptionEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomEncryptionEventData.cs index 9673dcc..1d5ec2c 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomEncryptionEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomEncryptionEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.encryption")] -public class RoomEncryptionEventData : IStateEventType { +public class RoomEncryptionEventContent : EventContent { [JsonPropertyName("algorithm")] public string? Algorithm { get; set; } [JsonPropertyName("rotation_period_ms")] diff --git a/LibMatrix/StateEventTypes/Spec/RoomMemberEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomMemberEventData.cs index c99aa8d..a9d4710 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomMemberEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomMemberEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.member")] -public class RoomMemberEventData : IStateEventType { +public class RoomMemberEventContent : EventContent { [JsonPropertyName("reason")] public string? Reason { get; set; } diff --git a/LibMatrix/StateEventTypes/Spec/RoomMessageEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomMessageEventData.cs index d13c273..a15efe8 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomMessageEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomMessageEventData.cs @@ -6,19 +6,12 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.message")] -public class RoomMessageEventData : IStateEventType { - public RoomMessageEventData() { } - - public RoomMessageEventData(string messageType, string body) { +public class RoomMessageEventContent : EventContent { + public RoomMessageEventContent(string? messageType = "m.notice", string? body = null) { MessageType = messageType; Body = body; } - public RoomMessageEventData(string body) : this() { - Body = body; - MessageType = "m.notice"; - } - [JsonPropertyName("body")] public string Body { get; set; } @@ -31,22 +24,9 @@ public class RoomMessageEventData : IStateEventType { [JsonPropertyName("format")] public string Format { get; set; } - [JsonPropertyName("m.relates_to")] - public MessageRelatesTo? RelatesTo { get; set; } - /// /// Media URI for this message, if any /// [JsonPropertyName("url")] public string? Url { get; set; } - - public class MessageRelatesTo { - [JsonPropertyName("m.in_reply_to")] - public MessageInReplyTo? InReplyTo { get; set; } - - public class MessageInReplyTo { - [JsonPropertyName("event_id")] - public string EventId { get; set; } - } - } } diff --git a/LibMatrix/StateEventTypes/Spec/RoomNameEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomNameEventData.cs index e04f0dc..3002102 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomNameEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomNameEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.name")] -public class RoomNameEventData : IStateEventType { +public class RoomNameEventContent : EventContent { [JsonPropertyName("name")] public string? Name { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/RoomPinnedEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomPinnedEventData.cs index bb78aeb..16144bc 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomPinnedEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomPinnedEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.pinned_events")] -public class RoomPinnedEventData : IStateEventType { +public class RoomPinnedEventContent : EventContent { [JsonPropertyName("pinned")] public string[]? PinnedEvents { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/RoomPowerLevelEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomPowerLevelEventData.cs index b4f7d53..960c198 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomPowerLevelEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomPowerLevelEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.power_levels")] -public class RoomPowerLevelEventData : IStateEventType { +public class RoomPowerLevelEventContent : EventContent { [JsonPropertyName("ban")] public long Ban { get; set; } // = 50; diff --git a/LibMatrix/StateEventTypes/Spec/RoomTopicEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomTopicEventData.cs index c3deb98..61d1a01 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomTopicEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomTopicEventData.cs @@ -6,7 +6,7 @@ namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.topic")] [MatrixEvent(EventName = "org.matrix.msc3765.topic", Legacy = true)] -public class RoomTopicEventData : IStateEventType { +public class RoomTopicEventContent : EventContent { [JsonPropertyName("topic")] public string? Topic { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/RoomTypingEventData.cs b/LibMatrix/StateEventTypes/Spec/RoomTypingEventData.cs index 3812c46..e935cb2 100644 --- a/LibMatrix/StateEventTypes/Spec/RoomTypingEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/RoomTypingEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.typing")] -public class RoomTypingEventData : IStateEventType { +public class RoomTypingEventContent : EventContent { [JsonPropertyName("user_ids")] public string[]? UserIds { get; set; } } diff --git a/LibMatrix/StateEventTypes/Spec/ServerACLEventData.cs b/LibMatrix/StateEventTypes/Spec/ServerACLEventData.cs index d00b464..031d113 100644 --- a/LibMatrix/StateEventTypes/Spec/ServerACLEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/ServerACLEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.room.server_acl")] -public class ServerACLEventData : IStateEventType { +public class ServerACLEventContent : EventContent { [JsonPropertyName("allow")] public List Allow { get; set; } // = null!; diff --git a/LibMatrix/StateEventTypes/Spec/SpaceChildEventData.cs b/LibMatrix/StateEventTypes/Spec/SpaceChildEventData.cs index e8c6d18..80fc771 100644 --- a/LibMatrix/StateEventTypes/Spec/SpaceChildEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/SpaceChildEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.space.child")] -public class SpaceChildEventData : IStateEventType { +public class SpaceChildEventContent : EventContent { [JsonPropertyName("auto_join")] public bool? AutoJoin { get; set; } [JsonPropertyName("via")] diff --git a/LibMatrix/StateEventTypes/Spec/SpaceParentEventData.cs b/LibMatrix/StateEventTypes/Spec/SpaceParentEventData.cs index ebd083e..1bc89ab 100644 --- a/LibMatrix/StateEventTypes/Spec/SpaceParentEventData.cs +++ b/LibMatrix/StateEventTypes/Spec/SpaceParentEventData.cs @@ -5,7 +5,7 @@ using LibMatrix.Interfaces; namespace LibMatrix.StateEventTypes.Spec; [MatrixEvent(EventName = "m.space.parent")] -public class SpaceParentEventData : IStateEventType { +public class SpaceParentEventContent : EventContent { [JsonPropertyName("via")] public string[]? Via { get; set; } diff --git a/LibMatrix/StateEventTypes/UnknownStateEventData.cs b/LibMatrix/StateEventTypes/UnknownStateEventData.cs new file mode 100644 index 0000000..59d8fd4 --- /dev/null +++ b/LibMatrix/StateEventTypes/UnknownStateEventData.cs @@ -0,0 +1,7 @@ +using LibMatrix.Interfaces; + +namespace LibMatrix.StateEventTypes; + +public class UnknownEventContent : EventContent { + +} diff --git a/LibMatrix/UserIdAndReason.cs b/LibMatrix/UserIdAndReason.cs index a0c2acd..09dc461 100644 --- a/LibMatrix/UserIdAndReason.cs +++ b/LibMatrix/UserIdAndReason.cs @@ -2,9 +2,10 @@ using System.Text.Json.Serialization; namespace LibMatrix; -internal class UserIdAndReason { +internal class UserIdAndReason(string? userId = null, string? reason = null) { [JsonPropertyName("user_id")] - public string UserId { get; set; } + public string UserId { get; set; } = userId; + [JsonPropertyName("reason")] - public string? Reason { get; set; } + public string? Reason { get; set; } = reason; } -- cgit 1.4.1