From 3558ba25896876b0c546f4c2decbb0671187745b Mon Sep 17 00:00:00 2001 From: Rory& Date: Fri, 14 Nov 2025 10:48:26 +0100 Subject: StateEvent -> MatrixEvent --- LibMatrix/Extensions/EnumerableExtensions.cs | 12 +++--- LibMatrix/Extensions/JsonElementExtensions.cs | 6 +-- LibMatrix/Helpers/RoomBuilder.cs | 8 ++-- LibMatrix/Helpers/RoomUpgradeBuilder.cs | 4 +- LibMatrix/Helpers/SyncHelper.cs | 10 ++--- .../Msc4222EmulationSyncProcessor.cs | 8 ++-- LibMatrix/Helpers/SyncStateResolver.cs | 2 +- .../Models/Responses/EventReportListResult.cs | 6 +-- .../Synapse/Models/Responses/RoomListResult.cs | 12 +++--- .../Responses/SynapseAdminRoomStateResult.cs | 2 +- .../Synapse/SynapseAdminApiClient.cs | 8 ++-- LibMatrix/Responses/CreateRoomRequest.cs | 12 +++--- LibMatrix/Responses/MessagesResponse.cs | 4 +- LibMatrix/Responses/SyncResponse.cs | 6 +-- LibMatrix/RoomTypes/GenericRoom.cs | 46 +++++++++++----------- LibMatrix/RoomTypes/PolicyRoom.cs | 10 ++--- LibMatrix/StateEvent.cs | 42 ++++++++++---------- 17 files changed, 99 insertions(+), 99 deletions(-) (limited to 'LibMatrix') diff --git a/LibMatrix/Extensions/EnumerableExtensions.cs b/LibMatrix/Extensions/EnumerableExtensions.cs index 4dcf26e..88e79f0 100644 --- a/LibMatrix/Extensions/EnumerableExtensions.cs +++ b/LibMatrix/Extensions/EnumerableExtensions.cs @@ -4,7 +4,7 @@ using System.Collections.Immutable; namespace LibMatrix.Extensions; public static class EnumerableExtensions { - public static void MergeStateEventLists(this IList oldState, IList newState) { + public static void MergeStateEventLists(this IList oldState, IList newState) { // foreach (var stateEvent in newState) { // var old = oldState.FirstOrDefault(x => x.Type == stateEvent.Type && x.StateKey == stateEvent.StateKey); // if (old is null) { @@ -27,7 +27,7 @@ public static class EnumerableExtensions { } } - int FindIndex(StateEvent needle) { + int FindIndex(MatrixEvent needle) { for (int i = 0; i < oldState.Count; i++) { var old = oldState[i]; if (old.Type == needle.Type && old.StateKey == needle.StateKey) @@ -38,7 +38,7 @@ public static class EnumerableExtensions { } } - public static void MergeStateEventLists(this IList oldState, IList newState) { + public static void MergeStateEventLists(this IList oldState, IList newState) { foreach (var e in newState) { switch (FindIndex(e)) { case -1: @@ -50,7 +50,7 @@ public static class EnumerableExtensions { } } - int FindIndex(StateEventResponse needle) { + int FindIndex(MatrixEventResponse needle) { for (int i = 0; i < oldState.Count; i++) { var old = oldState[i]; if (old.Type == needle.Type && old.StateKey == needle.StateKey) @@ -61,7 +61,7 @@ public static class EnumerableExtensions { } } - public static void MergeStateEventLists(this List oldState, List newState) { + public static void MergeStateEventLists(this List oldState, List newState) { foreach (var e in newState) { switch (FindIndex(e)) { case -1: @@ -73,7 +73,7 @@ public static class EnumerableExtensions { } } - int FindIndex(StateEventResponse needle) { + int FindIndex(MatrixEventResponse needle) { for (int i = 0; i < oldState.Count; i++) { var old = oldState[i]; if (old.Type == needle.Type && old.StateKey == needle.StateKey) diff --git a/LibMatrix/Extensions/JsonElementExtensions.cs b/LibMatrix/Extensions/JsonElementExtensions.cs index dfec95b..9225f58 100644 --- a/LibMatrix/Extensions/JsonElementExtensions.cs +++ b/LibMatrix/Extensions/JsonElementExtensions.cs @@ -8,7 +8,7 @@ namespace LibMatrix.Extensions; public static class JsonElementExtensions { public static bool FindExtraJsonElementFields(this JsonElement obj, Type objectType, string objectPropertyName) { if (objectPropertyName == "content" && objectType == typeof(JsonObject)) - objectType = typeof(StateEventResponse); + objectType = typeof(MatrixEventResponse); // if (t == typeof(JsonNode)) // return false; @@ -35,9 +35,9 @@ public static class JsonElementExtensions { continue; } - if (field.Name == "content" && (objectType == typeof(StateEventResponse) || objectType == typeof(StateEvent))) { + if (field.Name == "content" && (objectType == typeof(MatrixEventResponse) || objectType == typeof(MatrixEvent))) { unknownPropertyFound |= field.FindExtraJsonPropertyFieldsByValueKind( - StateEvent.GetStateEventType(obj.GetProperty("type").GetString()!), // We expect type to always be present + MatrixEvent.GetEventType(obj.GetProperty("type").GetString()!), // We expect type to always be present mappedProperty.PropertyType); continue; } diff --git a/LibMatrix/Helpers/RoomBuilder.cs b/LibMatrix/Helpers/RoomBuilder.cs index 6e24103..a292f33 100644 --- a/LibMatrix/Helpers/RoomBuilder.cs +++ b/LibMatrix/Helpers/RoomBuilder.cs @@ -44,12 +44,12 @@ public class RoomBuilder { /// /// State events to be sent *before* room access is configured. Keep this small! /// - public List ImportantState { get; set; } = []; + public List ImportantState { get; set; } = []; /// /// State events to be sent *after* room access is configured, but before invites are sent. /// - public List InitialState { get; set; } = []; + public List InitialState { get; set; } = []; /// /// Users to invite, with optional reason @@ -86,7 +86,7 @@ public class RoomBuilder { { RoomPolicyServerEventContent.EventId, 100 }, { RoomPinnedEventContent.EventId, 50 }, // recommended extensions - { "im.vector.modular.widgets", 50}, + { "im.vector.modular.widgets", 50 }, // { "m.reaction", 0 }, // we probably don't want these to end up as room state // - prevent calls { "io.element.voice_broadcast_info", 50 }, @@ -197,7 +197,7 @@ public class RoomBuilder { await Task.WhenAll(inviteTasks); } - private async Task SetStatesAsync(GenericRoom room, List state) { + private async Task SetStatesAsync(GenericRoom room, List state) { if (state.Count == 0) return; await room.BulkSendEventsAsync(state); // We chunk this up to try to avoid hitting reverse proxy timeouts diff --git a/LibMatrix/Helpers/RoomUpgradeBuilder.cs b/LibMatrix/Helpers/RoomUpgradeBuilder.cs index 85a5e36..ced0ef3 100644 --- a/LibMatrix/Helpers/RoomUpgradeBuilder.cs +++ b/LibMatrix/Helpers/RoomUpgradeBuilder.cs @@ -107,7 +107,7 @@ public class RoomUpgradeBuilder : RoomBuilder { Console.WriteLine($"Imported {total} state events from old room {OldRoom.RoomId} in {sw.ElapsedMilliseconds}ms"); } - private StateEventResponse UpgradeUnstableValues(StateEventResponse evt) { + private MatrixEventResponse UpgradeUnstableValues(MatrixEventResponse evt) { if (evt.IsLegacyType) { var oldType = evt.Type; evt.Type = evt.MappedType.GetCustomAttributes().FirstOrDefault(x => !x.Legacy)!.EventName; @@ -124,7 +124,7 @@ public class RoomUpgradeBuilder : RoomBuilder { return evt; } - private void ImportPolicyEventAsync(StateEventResponse evt) { + private void ImportPolicyEventAsync(MatrixEventResponse evt) { var msc4321Options = UpgradeOptions.Msc4321PolicyListUpgradeOptions; if (msc4321Options is { Enable: true, UpgradeType: Msc4321PolicyListUpgradeOptions.Msc4321PolicyListUpgradeType.Transition }) return; // this upgrade type doesnt copy policies diff --git a/LibMatrix/Helpers/SyncHelper.cs b/LibMatrix/Helpers/SyncHelper.cs index c8e2928..ebe653c 100644 --- a/LibMatrix/Helpers/SyncHelper.cs +++ b/LibMatrix/Helpers/SyncHelper.cs @@ -298,9 +298,9 @@ public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, ILogger? logg if (syncResponse.Rooms is { Join.Count: > 0 }) foreach (var updatedRoom in syncResponse.Rooms.Join) { if (updatedRoom.Value.Timeline is null) continue; - foreach (var stateEventResponse in updatedRoom.Value.Timeline.Events ?? []) { - stateEventResponse.RoomId = updatedRoom.Key; - var tasks = TimelineEventHandlers.Select(x => x(stateEventResponse)).ToList(); + foreach (var MatrixEventResponse in updatedRoom.Value.Timeline.Events ?? []) { + MatrixEventResponse.RoomId = updatedRoom.Key; + var tasks = TimelineEventHandlers.Select(x => x(MatrixEventResponse)).ToList(); await Task.WhenAll(tasks); } } @@ -319,12 +319,12 @@ public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, ILogger? logg /// /// Event fired when a timeline event is received /// - public List> TimelineEventHandlers { get; } = new(); + public List> TimelineEventHandlers { get; } = new(); /// /// Event fired when an account data event is received /// - public List> AccountDataReceivedHandlers { get; } = new(); + public List> AccountDataReceivedHandlers { get; } = new(); /// /// Event fired when an exception is thrown diff --git a/LibMatrix/Helpers/SyncProcessors/Msc4222EmulationSyncProcessor.cs b/LibMatrix/Helpers/SyncProcessors/Msc4222EmulationSyncProcessor.cs index be8aa8d..c887f6e 100644 --- a/LibMatrix/Helpers/SyncProcessors/Msc4222EmulationSyncProcessor.cs +++ b/LibMatrix/Helpers/SyncProcessors/Msc4222EmulationSyncProcessor.cs @@ -8,11 +8,11 @@ using Microsoft.Extensions.Logging; namespace LibMatrix.Helpers.SyncProcessors; public class Msc4222EmulationSyncProcessor(AuthenticatedHomeserverGeneric homeserver, ILogger? logger) { - private static bool StateEventsMatch(StateEventResponse a, StateEventResponse b) { + private static bool StateEventsMatch(MatrixEventResponse a, MatrixEventResponse b) { return a.Type == b.Type && a.StateKey == b.StateKey; } - private static bool StateEventIsNewer(StateEventResponse a, StateEventResponse b) { + private static bool StateEventIsNewer(MatrixEventResponse a, MatrixEventResponse b) { return StateEventsMatch(a, b) && a.OriginServerTs < b.OriginServerTs; } @@ -76,7 +76,7 @@ public class Msc4222EmulationSyncProcessor(AuthenticatedHomeserverGeneric homese Events = [] }; - var oldState = new List(); + var oldState = new List(); if (data.State is { Events.Count: > 0 }) { oldState.ReplaceBy(data.State.Events, StateEventIsNewer); } @@ -160,7 +160,7 @@ public class Msc4222EmulationSyncProcessor(AuthenticatedHomeserverGeneric homese logger?.LogWarning("Msc4222Emulation: Failed to get full state for room {roomId}, state may be incomplete!\n{exception}", roomId, e); } - var oldState = new List(); + var oldState = new List(); if (data.State is { Events.Count: > 0 }) { oldState.ReplaceBy(data.State.Events, StateEventIsNewer); } diff --git a/LibMatrix/Helpers/SyncStateResolver.cs b/LibMatrix/Helpers/SyncStateResolver.cs index f111c79..17c1a41 100644 --- a/LibMatrix/Helpers/SyncStateResolver.cs +++ b/LibMatrix/Helpers/SyncStateResolver.cs @@ -625,7 +625,7 @@ public class SyncStateResolver(AuthenticatedHomeserverGeneric homeserver, ILogge return oldState; } - private static EventList? MergeEventListBy(EventList? oldState, EventList? newState, Func comparer) { + private static EventList? MergeEventListBy(EventList? oldState, EventList? newState, Func comparer) { if (newState is null) return oldState; if (oldState is null) { return newState; diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/EventReportListResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/EventReportListResult.cs index 10fc039..0f3ee56 100644 --- a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/EventReportListResult.cs +++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/EventReportListResult.cs @@ -97,10 +97,10 @@ public class SynapseAdminEventReportListResult : SynapseNextTokenTotalCollection [JsonPropertyName("unsigned")] public JsonObject? Unsigned { get; set; } - // Extra... copied from StateEventResponse + // Extra... copied from MatrixEventResponse [JsonIgnore] - public Type MappedType => StateEvent.GetStateEventType(Type); + public Type MappedType => MatrixEvent.GetEventType(Type); [JsonIgnore] public bool IsLegacyType => MappedType.GetCustomAttributes().FirstOrDefault(x => x.EventName == Type)?.Legacy ?? false; @@ -128,7 +128,7 @@ public class SynapseAdminEventReportListResult : SynapseNextTokenTotalCollection // return null; // } try { - var mappedType = StateEvent.GetStateEventType(Type); + var mappedType = MatrixEvent.GetEventType(Type); if (mappedType == typeof(UnknownEventContent)) Console.WriteLine($"Warning: unknown event type '{Type}'"); var deserialisedContent = (EventContent)RawContent.Deserialize(mappedType, TypedContentSerializerOptions)!; diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RoomListResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RoomListResult.cs index 3bc1f47..7006c07 100644 --- a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RoomListResult.cs +++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RoomListResult.cs @@ -63,15 +63,15 @@ public class SynapseAdminRoomListResult { public int StateEvents { get; set; } [JsonPropertyName("gay.rory.synapse_admin_extensions.tombstone")] - public StateEventResponse? TombstoneEvent { get; set; } + public MatrixEventResponse? TombstoneEvent { get; set; } [JsonPropertyName("gay.rory.synapse_admin_extensions.create")] - public StateEventResponse? CreateEvent { get; set; } + public MatrixEventResponse? CreateEvent { get; set; } [JsonPropertyName("gay.rory.synapse_admin_extensions.topic")] - public StateEventResponse? TopicEvent { get; set; } + public MatrixEventResponse? TopicEvent { get; set; } - public async Task GetCreateEventAsync(AuthenticatedHomeserverSynapse hs) { + public async Task GetCreateEventAsync(AuthenticatedHomeserverSynapse hs) { if (CreateEvent != null) return CreateEvent; try { @@ -85,7 +85,7 @@ public class SynapseAdminRoomListResult { return null; } - public async Task GetTombstoneEventAsync(AuthenticatedHomeserverSynapse hs) { + public async Task GetTombstoneEventAsync(AuthenticatedHomeserverSynapse hs) { if (TombstoneEvent != null) return TombstoneEvent; try { @@ -99,7 +99,7 @@ public class SynapseAdminRoomListResult { return null; } - public async Task GetTopicEventAsync(AuthenticatedHomeserverSynapse hs) { + public async Task GetTopicEventAsync(AuthenticatedHomeserverSynapse hs) { if (TopicEvent != null) return TopicEvent; try { diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminRoomStateResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminRoomStateResult.cs index ae36d4e..d9d5f1a 100644 --- a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminRoomStateResult.cs +++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminRoomStateResult.cs @@ -4,5 +4,5 @@ namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses; public class SynapseAdminRoomStateResult { [JsonPropertyName("state")] - public required List Events { get; set; } + public required List Events { get; set; } } \ No newline at end of file diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminApiClient.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminApiClient.cs index 6d09006..f839e20 100644 --- a/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminApiClient.cs +++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminApiClient.cs @@ -174,13 +174,13 @@ public class SynapseAdminApiClient(AuthenticatedHomeserverSynapse authenticatedH } var parallelisationLimit = new SemaphoreSlim(32, 32); - List> tasks = []; + List> tasks = []; - async Task<(SynapseAdminRoomListResult.SynapseAdminRoomListResultRoom room, StateEventResponse?[] tasks)> fillTask( + async Task<(SynapseAdminRoomListResult.SynapseAdminRoomListResultRoom room, MatrixEventResponse?[] tasks)> fillTask( SynapseAdminRoomListResult.SynapseAdminRoomListResultRoom room) { if (serverSupportsQueryEventsV2) return (room, []); - var fillTasks = await Task.WhenAll(((Task?[]) [ + var fillTasks = await Task.WhenAll(((Task?[]) [ fetchTombstones && room.TombstoneEvent is null ? parallelisationLimit.RunWithLockAsync(() => room.GetTombstoneEventAsync(authenticatedHomeserver)) : null!, @@ -201,7 +201,7 @@ public class SynapseAdminApiClient(AuthenticatedHomeserverSynapse authenticatedH tasks.AddRange( serverSupportsQueryEventsV2 - ? keep.Select(x => Task.FromResult((x, (StateEventResponse?[])[]))) + ? keep.Select(x => Task.FromResult((x, (MatrixEventResponse?[])[]))) : keep.Select(fillTask) ); diff --git a/LibMatrix/Responses/CreateRoomRequest.cs b/LibMatrix/Responses/CreateRoomRequest.cs index db7d004..b4dcc78 100644 --- a/LibMatrix/Responses/CreateRoomRequest.cs +++ b/LibMatrix/Responses/CreateRoomRequest.cs @@ -29,7 +29,7 @@ public class CreateRoomRequest { // public string Preset { get; set; } [JsonPropertyName("initial_state")] - public List? InitialState { get; set; } + public List? InitialState { get; set; } /// /// One of: ["public", "private"] @@ -54,15 +54,15 @@ public class CreateRoomRequest { /// For use only when you can't use the CreationContent property /// - public StateEvent? this[string eventType, string eventKey = ""] { + public MatrixEvent? this[string eventType, string eventKey = ""] { get { var stateEvent = InitialState?.FirstOrDefault(x => x.Type == eventType && x.StateKey == eventKey); if (stateEvent == null) - InitialState?.Add(stateEvent = new StateEvent { + InitialState?.Add(stateEvent = new MatrixEvent { Type = eventType, StateKey = eventKey, TypedContent = (EventContent)Activator.CreateInstance( - StateEvent.KnownStateEventTypes.FirstOrDefault(x => + MatrixEvent.KnownEventTypes.FirstOrDefault(x => x.GetCustomAttributes()? .Any(y => y.EventName == eventType) ?? false) ?? typeof(UnknownEventContent) )! @@ -122,7 +122,7 @@ public class CreateRoomRequest { } }, RoomAliasName = roomAliasName, - InitialState = new List() + InitialState = new List() }; return request; @@ -162,7 +162,7 @@ public class CreateRoomRequest { } }, RoomAliasName = roomAliasName, - InitialState = new List() + InitialState = new List() }; return request; diff --git a/LibMatrix/Responses/MessagesResponse.cs b/LibMatrix/Responses/MessagesResponse.cs index 4912add..1b412fe 100644 --- a/LibMatrix/Responses/MessagesResponse.cs +++ b/LibMatrix/Responses/MessagesResponse.cs @@ -10,8 +10,8 @@ public class MessagesResponse { public string? End { get; set; } [JsonPropertyName("chunk")] - public List Chunk { get; set; } = new(); + public List Chunk { get; set; } = new(); [JsonPropertyName("state")] - public List State { get; set; } = new(); + public List State { get; set; } = new(); } \ No newline at end of file diff --git a/LibMatrix/Responses/SyncResponse.cs b/LibMatrix/Responses/SyncResponse.cs index c2598ae..362ccc4 100644 --- a/LibMatrix/Responses/SyncResponse.cs +++ b/LibMatrix/Responses/SyncResponse.cs @@ -44,7 +44,7 @@ public class SyncResponse { // supporting classes public class PresenceDataStructure { [JsonPropertyName("events")] - public List? Events { get; set; } + public List? Events { get; set; } } public class RoomsDataStructure { @@ -116,13 +116,13 @@ public class SyncResponse { public class TimelineDataStructure : EventList { public TimelineDataStructure() { } - public TimelineDataStructure(List? events, bool? limited) { + public TimelineDataStructure(List? events, bool? limited) { Events = events; Limited = limited; } // [JsonPropertyName("events")] - // public List? Events { get; set; } + // public List? Events { get; set; } [JsonPropertyName("prev_batch")] public string? PrevBatch { get; set; } diff --git a/LibMatrix/RoomTypes/GenericRoom.cs b/LibMatrix/RoomTypes/GenericRoom.cs index 37f301e..6d9a499 100644 --- a/LibMatrix/RoomTypes/GenericRoom.cs +++ b/LibMatrix/RoomTypes/GenericRoom.cs @@ -27,13 +27,13 @@ public class GenericRoom { public string RoomId { get; set; } - public async IAsyncEnumerable GetFullStateAsync() { - var result = Homeserver.ClientHttpClient.GetAsyncEnumerableFromJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state"); + public async IAsyncEnumerable GetFullStateAsync() { + var result = Homeserver.ClientHttpClient.GetAsyncEnumerableFromJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state"); await foreach (var resp in result) yield return resp; } - public Task> GetFullStateAsListAsync() => - Homeserver.ClientHttpClient.GetFromJsonAsync>($"/_matrix/client/v3/rooms/{RoomId}/state"); + public Task> GetFullStateAsListAsync() => + Homeserver.ClientHttpClient.GetFromJsonAsync>($"/_matrix/client/v3/rooms/{RoomId}/state"); public async Task GetStateAsync(string type, string stateKey = "") { if (string.IsNullOrEmpty(type)) throw new ArgumentNullException(nameof(type), "Event type must be specified"); @@ -63,7 +63,7 @@ public class GenericRoom { } } - public async Task GetStateEventAsync(string type, string stateKey = "") { + public async Task GetStateEventAsync(string type, string stateKey = "") { if (string.IsNullOrEmpty(type)) throw new ArgumentNullException(nameof(type), "Event type must be specified"); var url = $"/_matrix/client/v3/rooms/{RoomId}/state/{type}"; if (!string.IsNullOrEmpty(stateKey)) url += $"/{stateKey}"; @@ -76,7 +76,7 @@ public class GenericRoom { ErrorCode = LibMatrixException.ErrorCodes.M_UNSUPPORTED }; // throw new InvalidDataException("Returned event type does not match requested type, or server does not support passing `format`."); - return resp.Deserialize(); + return resp.Deserialize(); } catch (MatrixException e) { // if (e is not { ErrorCodode: "M_NOT_FOUND" }) { @@ -128,7 +128,7 @@ public class GenericRoom { } } - public async Task GetStateEventOrNullAsync(string type, string stateKey = "") { + public async Task GetStateEventOrNullAsync(string type, string stateKey = "") { try { return await GetStateEventAsync(type, stateKey); } @@ -241,13 +241,13 @@ public class GenericRoom { return await res.Content.ReadFromJsonAsync() ?? throw new Exception("Failed to join room?"); } - public async IAsyncEnumerable GetMembersEnumerableAsync(string? membership = null) { + public async IAsyncEnumerable GetMembersEnumerableAsync(string? membership = null) { var url = $"/_matrix/client/v3/rooms/{RoomId}/members"; var isMembershipSet = !string.IsNullOrWhiteSpace(membership); if (isMembershipSet) url += $"?membership={membership}"; var res = await Homeserver.ClientHttpClient.GetAsync(url); - var result = await JsonSerializer.DeserializeAsync(await res.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { - TypeInfoResolver = ChunkedStateEventResponseSerializerContext.Default + var result = await JsonSerializer.DeserializeAsync(await res.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { + TypeInfoResolver = ChunkedMatrixEventResponseSerializerContext.Default }); if (result is null) throw new Exception("Failed to deserialise members response"); @@ -259,18 +259,18 @@ public class GenericRoom { } } - public async Task> GetMembersListAsync(string? membership = null) { + public async Task> GetMembersListAsync(string? membership = null) { var url = $"/_matrix/client/v3/rooms/{RoomId}/members"; var isMembershipSet = !string.IsNullOrWhiteSpace(membership); if (isMembershipSet) url += $"?membership={membership}"; var res = await Homeserver.ClientHttpClient.GetAsync(url); - var result = await JsonSerializer.DeserializeAsync(await res.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { - TypeInfoResolver = ChunkedStateEventResponseSerializerContext.Default + var result = await JsonSerializer.DeserializeAsync(await res.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { + TypeInfoResolver = ChunkedMatrixEventResponseSerializerContext.Default }); if (result is null) throw new Exception("Failed to deserialise members response"); - var members = new List(); + var members = new List(); foreach (var resp in result.Chunk ?? []) { if (resp.Type != "m.room.member") continue; if (isMembershipSet && resp.RawContent?["membership"]?.GetValue() != membership) continue; @@ -478,8 +478,8 @@ public class GenericRoom { } } - public Task GetEventAsync(string eventId, bool includeUnredactedContent = false) => - Homeserver.ClientHttpClient.GetFromJsonAsync( + public Task GetEventAsync(string eventId, bool includeUnredactedContent = false) => + Homeserver.ClientHttpClient.GetFromJsonAsync( // .ToLower() on boolean here because this query param specifically on synapse is checked as a string rather than a boolean $"/_matrix/client/v3/rooms/{RoomId}/event/{eventId}?fi.mau.msc2815.include_unredacted_content={includeUnredactedContent.ToString().ToLower()}"); @@ -597,7 +597,7 @@ public class GenericRoom { #endregion - public async IAsyncEnumerable GetRelatedEventsAsync(string eventId, string? relationType = null, string? eventType = null, string? dir = "f", + public async IAsyncEnumerable GetRelatedEventsAsync(string eventId, string? relationType = null, string? eventType = null, string? dir = "f", string? from = null, int? chunkLimit = 100, bool? recurse = null, string? to = null) { var path = $"/_matrix/client/v1/rooms/{RoomId}/relations/{HttpUtility.UrlEncode(eventId)}"; if (!string.IsNullOrEmpty(relationType)) path += $"/{relationType}"; @@ -612,18 +612,18 @@ public class GenericRoom { if (!string.IsNullOrEmpty(to)) uri = uri.AddQuery("to", to); // Console.WriteLine($"Getting related events from {uri}"); - var result = await Homeserver.ClientHttpClient.GetFromJsonAsync(uri.ToString()); + var result = await Homeserver.ClientHttpClient.GetFromJsonAsync(uri.ToString()); while (result!.Chunk.Count > 0) { foreach (var resp in result.Chunk) { yield return resp; } if (result.NextBatch is null) break; - result = await Homeserver.ClientHttpClient.GetFromJsonAsync(uri.AddQuery("from", result.NextBatch).ToString()); + result = await Homeserver.ClientHttpClient.GetFromJsonAsync(uri.AddQuery("from", result.NextBatch).ToString()); } } - public async Task BulkSendEventsAsync(IEnumerable events, int? forceSyncInterval = null) { + public async Task BulkSendEventsAsync(IEnumerable events, int? forceSyncInterval = null) { if ((await Homeserver.GetCapabilitiesAsync()).Capabilities.BulkSendEvents?.Enabled == true) { var uri = $"/_matrix/client/unstable/gay.rory.bulk_send_events/rooms/{RoomId}/bulk_send_events?_libmatrix_txn_id={Guid.NewGuid()}"; if (forceSyncInterval is not null) uri += $"&force_sync_interval={forceSyncInterval}"; @@ -640,7 +640,7 @@ public class GenericRoom { } } - public async Task BulkSendEventsAsync(IAsyncEnumerable events, int? forceSyncInterval = null) { + public async Task BulkSendEventsAsync(IAsyncEnumerable events, int? forceSyncInterval = null) { if ((await Homeserver.GetCapabilitiesAsync()).Capabilities.BulkSendEvents?.Enabled == true) { var uri = $"/_matrix/client/unstable/gay.rory.bulk_send_events/rooms/{RoomId}/bulk_send_events?_libmatrix_txn_id={Guid.NewGuid()}"; if (forceSyncInterval is not null) uri += $"&force_sync_interval={forceSyncInterval}"; @@ -670,7 +670,7 @@ public class GenericRoom { /// /// A list of size 1 for v11 rooms and older, all creators for v12+ public async Task> GetRoomCreatorsAsync() { - StateEventResponse createEvent; + MatrixEventResponse createEvent; if (IsV12PlusRoomId) { createEvent = await GetEventAsync('$' + RoomId[1..]); } @@ -721,4 +721,4 @@ public class GenericRoom { public class RoomIdResponse { [JsonPropertyName("room_id")] public string RoomId { get; set; } -} +} \ No newline at end of file diff --git a/LibMatrix/RoomTypes/PolicyRoom.cs b/LibMatrix/RoomTypes/PolicyRoom.cs index c6eec63..e4fa6ae 100644 --- a/LibMatrix/RoomTypes/PolicyRoom.cs +++ b/LibMatrix/RoomTypes/PolicyRoom.cs @@ -7,13 +7,13 @@ namespace LibMatrix.RoomTypes; public class PolicyRoom(AuthenticatedHomeserverGeneric homeserver, string roomId) : GenericRoom(homeserver, roomId) { public const string TypeName = "support.feline.policy.lists.msc.v1"; - + public static readonly FrozenSet UserPolicyEventTypes = EventContent.GetMatchingEventTypes().ToFrozenSet(); public static readonly FrozenSet ServerPolicyEventTypes = EventContent.GetMatchingEventTypes().ToFrozenSet(); public static readonly FrozenSet RoomPolicyEventTypes = EventContent.GetMatchingEventTypes().ToFrozenSet(); public static readonly FrozenSet SpecPolicyEventTypes = [..UserPolicyEventTypes, ..ServerPolicyEventTypes, ..RoomPolicyEventTypes]; - public async IAsyncEnumerable GetPoliciesAsync() { + public async IAsyncEnumerable GetPoliciesAsync() { var fullRoomState = GetFullStateAsync(); await foreach (var eventResponse in fullRoomState) { if (SpecPolicyEventTypes.Contains(eventResponse!.Type)) { @@ -22,7 +22,7 @@ public class PolicyRoom(AuthenticatedHomeserverGeneric homeserver, string roomId } } - public async IAsyncEnumerable GetUserPoliciesAsync() { + public async IAsyncEnumerable GetUserPoliciesAsync() { var fullRoomState = GetPoliciesAsync(); await foreach (var eventResponse in fullRoomState) { if (UserPolicyEventTypes.Contains(eventResponse!.Type)) { @@ -31,7 +31,7 @@ public class PolicyRoom(AuthenticatedHomeserverGeneric homeserver, string roomId } } - public async IAsyncEnumerable GetServerPoliciesAsync() { + public async IAsyncEnumerable GetServerPoliciesAsync() { var fullRoomState = GetPoliciesAsync(); await foreach (var eventResponse in fullRoomState) { if (ServerPolicyEventTypes.Contains(eventResponse!.Type)) { @@ -40,7 +40,7 @@ public class PolicyRoom(AuthenticatedHomeserverGeneric homeserver, string roomId } } - public async IAsyncEnumerable GetRoomPoliciesAsync() { + public async IAsyncEnumerable GetRoomPoliciesAsync() { var fullRoomState = GetPoliciesAsync(); await foreach (var eventResponse in fullRoomState) { if (RoomPolicyEventTypes.Contains(eventResponse!.Type)) { diff --git a/LibMatrix/StateEvent.cs b/LibMatrix/StateEvent.cs index 8455098..861b584 100644 --- a/LibMatrix/StateEvent.cs +++ b/LibMatrix/StateEvent.cs @@ -13,10 +13,10 @@ using LibMatrix.Extensions; namespace LibMatrix; -public class StateEvent { - public static FrozenSet KnownStateEventTypes { get; } = ClassCollector.ResolveFromAllAccessibleAssemblies().ToFrozenSet(); +public class MatrixEvent { + public static FrozenSet KnownEventTypes { get; } = ClassCollector.ResolveFromAllAccessibleAssemblies().ToFrozenSet(); - public static FrozenDictionary KnownStateEventTypesByName { get; } = KnownStateEventTypes.Aggregate( + public static FrozenDictionary KnownEventTypesByName { get; } = KnownEventTypes.Aggregate( new Dictionary(), (dict, type) => { var attrs = type.GetCustomAttributes(); @@ -29,11 +29,11 @@ public class StateEvent { return dict; }).OrderBy(x => x.Key).ToFrozenDictionary(); - public static Type GetStateEventType(string? type) => - string.IsNullOrWhiteSpace(type) ? typeof(UnknownEventContent) : KnownStateEventTypesByName.GetValueOrDefault(type) ?? typeof(UnknownEventContent); + public static Type GetEventType(string? type) => + string.IsNullOrWhiteSpace(type) ? typeof(UnknownEventContent) : KnownEventTypesByName.GetValueOrDefault(type) ?? typeof(UnknownEventContent); [JsonIgnore] - public Type MappedType => GetStateEventType(Type); + public Type MappedType => GetEventType(Type); [JsonIgnore] public bool IsLegacyType => MappedType.GetCustomAttributes().FirstOrDefault(x => x.EventName == Type)?.Legacy ?? false; @@ -58,7 +58,7 @@ public class StateEvent { public EventContent? TypedContent { get { try { - var mappedType = GetStateEventType(Type); + var mappedType = GetEventType(Type); if (mappedType == typeof(UnknownEventContent)) Console.WriteLine($"Warning: unknown event type '{Type}'"); var deserialisedContent = (EventContent)RawContent.Deserialize(mappedType, TypedContentSerializerOptions)!; @@ -121,8 +121,8 @@ public class StateEvent { [JsonIgnore] public string InternalContentTypeName => TypedContent?.GetType().Name ?? "null"; - public static bool TypeKeyPairMatches(StateEventResponse x, StateEventResponse y) => x.Type == y.Type && x.StateKey == y.StateKey; - public static bool Equals(StateEventResponse x, StateEventResponse y) => x.Type == y.Type && x.StateKey == y.StateKey && x.EventId == y.EventId; + public static bool TypeKeyPairMatches(MatrixEventResponse x, MatrixEventResponse y) => x.Type == y.Type && x.StateKey == y.StateKey; + public static bool Equals(MatrixEventResponse x, MatrixEventResponse y) => x.Type == y.Type && x.StateKey == y.StateKey && x.EventId == y.EventId; /// /// Compares two state events for deep equality, including type, state key, and raw content. @@ -131,10 +131,10 @@ public class StateEvent { /// /// /// - public static bool DeepEquals(StateEventResponse x, StateEventResponse y) => x.Type == y.Type && x.StateKey == y.StateKey && JsonNode.DeepEquals(x.RawContent, y.RawContent); + public static bool DeepEquals(MatrixEventResponse x, MatrixEventResponse y) => x.Type == y.Type && x.StateKey == y.StateKey && JsonNode.DeepEquals(x.RawContent, y.RawContent); } -public class StateEventResponse : StateEvent { +public class MatrixEventResponse : MatrixEvent { [JsonPropertyName("origin_server_ts")] public long? OriginServerTs { get; set; } @@ -178,27 +178,27 @@ public class StateEventResponse : StateEvent { } [JsonSourceGenerationOptions(WriteIndented = true)] -[JsonSerializable(typeof(ChunkedStateEventResponse))] -internal partial class ChunkedStateEventResponseSerializerContext : JsonSerializerContext; +[JsonSerializable(typeof(ChunkedMatrixEventResponse))] +internal partial class ChunkedMatrixEventResponseSerializerContext : JsonSerializerContext; [DebuggerDisplay("{Events.Count} events")] public class EventList { public EventList() { } - public EventList(List? events) { + public EventList(List? events) { Events = events; } [JsonPropertyName("events")] - public List? Events { get; set; } = new(); + public List? Events { get; set; } = new(); } -public class ChunkedStateEventResponse { +public class ChunkedMatrixEventResponse { [JsonPropertyName("chunk")] - public List? Chunk { get; set; } = new(); + public List? Chunk { get; set; } = new(); } -public class PaginatedChunkedStateEventResponse : ChunkedStateEventResponse { +public class PaginatedChunkedMatrixEventResponse : ChunkedMatrixEventResponse { [JsonPropertyName("start")] public string? Start { get; set; } @@ -206,7 +206,7 @@ public class PaginatedChunkedStateEventResponse : ChunkedStateEventResponse { public string? End { get; set; } } -public class BatchedChunkedStateEventResponse : ChunkedStateEventResponse { +public class BatchedChunkedMatrixEventResponse : ChunkedMatrixEventResponse { [JsonPropertyName("next_batch")] public string? NextBatch { get; set; } @@ -214,7 +214,7 @@ public class BatchedChunkedStateEventResponse : ChunkedStateEventResponse { public string? PrevBatch { get; set; } } -public class RecursedBatchedChunkedStateEventResponse : BatchedChunkedStateEventResponse { +public class RecursedBatchedChunkedMatrixEventResponse : BatchedChunkedMatrixEventResponse { [JsonPropertyName("recursion_depth")] public int? RecursionDepth { get; set; } } @@ -235,7 +235,7 @@ public class StateEventContentPolymorphicTypeInfoResolver : DefaultJsonTypeInfoR IgnoreUnrecognizedTypeDiscriminators = true, UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType, - DerivedTypes = StateEvent.KnownStateEventTypesByName.Select(x => new JsonDerivedType(x.Value, x.Key)).ToList() + DerivedTypes = MatrixEvent.KnownEventTypesByName.Select(x => new JsonDerivedType(x.Value, x.Key)).ToList() // DerivedTypes = new ClassCollector() // .ResolveFromAllAccessibleAssemblies() -- cgit 1.5.1