From 30a0868789466012bab869af4300aef5a9cac108 Mon Sep 17 00:00:00 2001 From: Rory& Date: Thu, 30 May 2024 09:46:43 +0000 Subject: Rename legacy event types --- LibMatrix/Helpers/MessageBuilder.cs | 4 +- LibMatrix/Helpers/MessageFormatter.cs | 18 ++++---- .../Homeservers/AuthenticatedHomeserverGeneric.cs | 12 +++--- LibMatrix/LegacyMatrixEvent.cs | 14 +++---- LibMatrix/Responses/CreateRoomRequest.cs | 16 ++++---- LibMatrix/RoomTypes/GenericRoom.cs | 48 +++++++++++----------- LibMatrix/Utilities/CommonSyncFilters.cs | 16 ++++---- 7 files changed, 64 insertions(+), 64 deletions(-) (limited to 'LibMatrix') diff --git a/LibMatrix/Helpers/MessageBuilder.cs b/LibMatrix/Helpers/MessageBuilder.cs index 54de7ad..0ed0339 100644 --- a/LibMatrix/Helpers/MessageBuilder.cs +++ b/LibMatrix/Helpers/MessageBuilder.cs @@ -3,12 +3,12 @@ using LibMatrix.LegacyEvents.EventTypes.Spec; namespace LibMatrix.Helpers; public class MessageBuilder(string msgType = "m.text", string format = "org.matrix.custom.html") { - private RoomMessageEventContent Content { get; set; } = new() { + private RoomMessageLegacyEventContent Content { get; set; } = new() { MessageType = msgType, Format = format }; - public RoomMessageEventContent Build() => Content; + public RoomMessageLegacyEventContent Build() => Content; public MessageBuilder WithBody(string body) { Content.Body += body; diff --git a/LibMatrix/Helpers/MessageFormatter.cs b/LibMatrix/Helpers/MessageFormatter.cs index f234d8f..2c5021e 100644 --- a/LibMatrix/Helpers/MessageFormatter.cs +++ b/LibMatrix/Helpers/MessageFormatter.cs @@ -4,25 +4,25 @@ using LibMatrix.LegacyEvents.EventTypes.Spec; namespace LibMatrix.Helpers; public static class MessageFormatter { - public static RoomMessageEventContent FormatError(string error) => + public static RoomMessageLegacyEventContent FormatError(string error) => new(body: error, messageType: "m.text") { FormattedBody = $"{error}", Format = "org.matrix.custom.html" }; - public static RoomMessageEventContent FormatException(string error, Exception e) => + public static RoomMessageLegacyEventContent FormatException(string error, Exception e) => new(body: $"{error}: {e.Message}", messageType: "m.text") { FormattedBody = $"{error}:
{e.Message}
", Format = "org.matrix.custom.html" }; - public static RoomMessageEventContent FormatSuccess(string text) => + public static RoomMessageLegacyEventContent FormatSuccess(string text) => new(body: text, messageType: "m.text") { FormattedBody = $"{text}", Format = "org.matrix.custom.html" }; - public static RoomMessageEventContent FormatSuccessJson(string text, object data) => + public static RoomMessageLegacyEventContent FormatSuccessJson(string text, object data) => new(body: text, messageType: "m.text") { FormattedBody = $"{text}:
{data.ToJson(ignoreNull: true)}
", Format = "org.matrix.custom.html" @@ -37,29 +37,29 @@ public static class MessageFormatter { #region Extension functions - public static RoomMessageEventContent ToMatrixMessage(this Exception e, string error) => FormatException(error, e); + public static RoomMessageLegacyEventContent ToMatrixMessage(this Exception e, string error) => FormatException(error, e); #endregion - public static RoomMessageEventContent FormatWarning(string warning) => + public static RoomMessageLegacyEventContent FormatWarning(string warning) => new(body: warning, messageType: "m.text") { FormattedBody = $"{warning}", Format = "org.matrix.custom.html" }; - public static RoomMessageEventContent FormatWarningJson(string warning, object data) => + public static RoomMessageLegacyEventContent FormatWarningJson(string warning, object data) => new(body: warning, messageType: "m.text") { FormattedBody = $"{warning}:
{data.ToJson(ignoreNull: true)}
", Format = "org.matrix.custom.html" }; - public static RoomMessageEventContent Concat(this RoomMessageEventContent a, RoomMessageEventContent b) => + public static RoomMessageLegacyEventContent Concat(this RoomMessageLegacyEventContent a, RoomMessageLegacyEventContent b) => new(body: $"{a.Body}{b.Body}", messageType: a.MessageType) { FormattedBody = $"{a.FormattedBody}{b.FormattedBody}", Format = a.Format }; - public static RoomMessageEventContent ConcatLine(this RoomMessageEventContent a, RoomMessageEventContent b) => + public static RoomMessageLegacyEventContent ConcatLine(this RoomMessageLegacyEventContent a, RoomMessageLegacyEventContent b) => new(body: $"{a.Body}\n{b.Body}", messageType: "m.text") { FormattedBody = $"{a.FormattedBody}
{b.FormattedBody}", Format = "org.matrix.custom.html" diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs index 86977ec..db76985 100644 --- a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs +++ b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs @@ -190,7 +190,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver { if (newProfile is null) return; Console.WriteLine($"Updating profile for {WhoAmI.UserId} to {newProfile.ToJson(ignoreNull: true)} (preserving room profiles: {preserveCustomRoomProfile})"); var oldProfile = await GetProfileAsync(WhoAmI.UserId!); - Dictionary expectedRoomProfiles = new(); + Dictionary expectedRoomProfiles = new(); var syncHelper = new SyncHelper(this) { Filter = new SyncFilter { AccountData = new SyncFilter.EventFilter() { @@ -209,7 +209,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver { targetSyncCount = rooms.Count; await foreach (var (roomId, currentRoomProfile) in roomProfiles) try { - // var currentRoomProfile = await room.GetStateAsync("m.room.member", WhoAmI.UserId!); + // var currentRoomProfile = await room.GetStateAsync("m.room.member", WhoAmI.UserId!); //build new profiles if (currentRoomProfile.DisplayName == oldProfile.DisplayName) currentRoomProfile.DisplayName = newProfile.DisplayName; @@ -243,7 +243,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver { foreach (var (roomId, roomData) in sync.Rooms.Join) if (roomData.State is { Events.Count: > 0 }) { var incommingRoomProfile = - roomData.State?.Events?.FirstOrDefault(x => x.Type == "m.room.member" && x.StateKey == WhoAmI.UserId)?.TypedContent as RoomMemberEventContent; + roomData.State?.Events?.FirstOrDefault(x => x.Type == "m.room.member" && x.StateKey == WhoAmI.UserId)?.TypedContent as RoomMemberLegacyEventContent; if (incommingRoomProfile is null) continue; if (!expectedRoomProfiles.ContainsKey(roomId)) continue; var targetRoomProfileOverride = expectedRoomProfiles[roomId]; @@ -276,7 +276,7 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver { } } - public async IAsyncEnumerable> GetRoomProfilesAsync() { + public async IAsyncEnumerable> GetRoomProfilesAsync() { var rooms = await GetJoinedRooms(); var results = rooms.Select(GetOwnRoomProfileWithIdAsync).ToAsyncEnumerable(); await foreach (var res in results) yield return res; @@ -295,8 +295,8 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver { #region Room Profile Utility - private async Task> GetOwnRoomProfileWithIdAsync(GenericRoom room) => - new(room.RoomId, await room.GetStateAsync("m.room.member", WhoAmI.UserId!)); + private async Task> GetOwnRoomProfileWithIdAsync(GenericRoom room) => + new(room.RoomId, await room.GetStateAsync("m.room.member", WhoAmI.UserId!)); #endregion diff --git a/LibMatrix/LegacyMatrixEvent.cs b/LibMatrix/LegacyMatrixEvent.cs index 1c1ebf3..5433da3 100644 --- a/LibMatrix/LegacyMatrixEvent.cs +++ b/LibMatrix/LegacyMatrixEvent.cs @@ -13,12 +13,12 @@ using LibMatrix.Extensions; namespace LibMatrix; public class LegacyMatrixEvent { - public static FrozenSet KnownStateEventTypes { get; } = new ClassCollector().ResolveFromAllAccessibleAssemblies().ToFrozenSet(); + public static FrozenSet KnownStateEventTypes { get; } = new ClassCollector().ResolveFromAllAccessibleAssemblies().ToFrozenSet(); public static FrozenDictionary KnownStateEventTypesByName { get; } = KnownStateEventTypes.Aggregate( new Dictionary(), (dict, type) => { - var attrs = type.GetCustomAttributes(); + var attrs = type.GetCustomAttributes(); foreach (var attr in attrs) { if (dict.TryGetValue(attr.EventName, out var existing)) Console.WriteLine($"Duplicate event type '{attr.EventName}' registered for types '{existing.Name}' and '{type.Name}'"); @@ -29,13 +29,13 @@ public class LegacyMatrixEvent { }).OrderBy(x => x.Key).ToFrozenDictionary(); public static Type GetStateEventType(string? type) => - string.IsNullOrWhiteSpace(type) ? typeof(UnknownEventContent) : KnownStateEventTypesByName.GetValueOrDefault(type) ?? typeof(UnknownEventContent); + string.IsNullOrWhiteSpace(type) ? typeof(UnknownLegacyEventContent) : KnownStateEventTypesByName.GetValueOrDefault(type) ?? typeof(UnknownLegacyEventContent); [JsonIgnore] public Type MappedType => GetStateEventType(Type); [JsonIgnore] - public bool IsLegacyType => MappedType.GetCustomAttributes().FirstOrDefault(x => x.EventName == Type)?.Legacy ?? false; + public bool IsLegacyType => MappedType.GetCustomAttributes().FirstOrDefault(x => x.EventName == Type)?.Legacy ?? false; [JsonIgnore] public string FriendlyTypeName => MappedType.GetFriendlyNameOrNull() ?? Type; @@ -53,16 +53,16 @@ public class LegacyMatrixEvent { [JsonIgnore] [SuppressMessage("ReSharper", "PropertyCanBeMadeInitOnly.Global")] - public EventContent? TypedContent { + public LegacyEventContent? TypedContent { get { // if (Type == "m.receipt") { // return null; // } try { var mappedType = GetStateEventType(Type); - if (mappedType == typeof(UnknownEventContent)) + if (mappedType == typeof(UnknownLegacyEventContent)) Console.WriteLine($"Warning: unknown event type '{Type}'"); - var deserialisedContent = (EventContent)RawContent.Deserialize(mappedType, TypedContentSerializerOptions)!; + var deserialisedContent = (LegacyEventContent)RawContent.Deserialize(mappedType, TypedContentSerializerOptions)!; return deserialisedContent; } catch (JsonException e) { diff --git a/LibMatrix/Responses/CreateRoomRequest.cs b/LibMatrix/Responses/CreateRoomRequest.cs index 6919b84..cae2a04 100644 --- a/LibMatrix/Responses/CreateRoomRequest.cs +++ b/LibMatrix/Responses/CreateRoomRequest.cs @@ -38,7 +38,7 @@ public class CreateRoomRequest { public string? Visibility { get; set; } [JsonPropertyName("power_level_content_override")] - public RoomPowerLevelEventContent? PowerLevelContentOverride { get; set; } = null!; + public RoomPowerLevelLegacyEventContent? PowerLevelContentOverride { get; set; } = null!; [JsonPropertyName("creation_content")] public JsonObject CreationContent { get; set; } = new(); @@ -57,10 +57,10 @@ public class CreateRoomRequest { InitialState.Add(stateEvent = new LegacyMatrixEvent { Type = eventType, StateKey = eventKey, - TypedContent = (EventContent)Activator.CreateInstance( + TypedContent = (LegacyEventContent)Activator.CreateInstance( LegacyMatrixEvent.KnownStateEventTypes.FirstOrDefault(x => - x.GetCustomAttributes()? - .Any(y => y.EventName == eventType) ?? false) ?? typeof(UnknownEventContent) + x.GetCustomAttributes()? + .Any(y => y.EventName == eventType) ?? false) ?? typeof(UnknownLegacyEventContent) )! }); @@ -89,7 +89,7 @@ public class CreateRoomRequest { Name = name ?? "New public Room", Visibility = "public", CreationContent = new JsonObject(), - PowerLevelContentOverride = new RoomPowerLevelEventContent { + PowerLevelContentOverride = new RoomPowerLevelLegacyEventContent { EventsDefault = 0, UsersDefault = 0, Kick = 50, @@ -97,7 +97,7 @@ public class CreateRoomRequest { Invite = 25, StateDefault = 10, Redact = 50, - NotificationsPl = new RoomPowerLevelEventContent.NotificationsPL { + NotificationsPl = new RoomPowerLevelLegacyEventContent.NotificationsPL { Room = 10 }, Events = new Dictionary { @@ -129,7 +129,7 @@ public class CreateRoomRequest { Name = name ?? "New private Room", Visibility = "private", CreationContent = new JsonObject(), - PowerLevelContentOverride = new RoomPowerLevelEventContent { + PowerLevelContentOverride = new RoomPowerLevelLegacyEventContent { EventsDefault = 0, UsersDefault = 0, Kick = 50, @@ -137,7 +137,7 @@ public class CreateRoomRequest { Invite = 25, StateDefault = 10, Redact = 50, - NotificationsPl = new RoomPowerLevelEventContent.NotificationsPL { + NotificationsPl = new RoomPowerLevelLegacyEventContent.NotificationsPL { Room = 10 }, Events = new Dictionary { diff --git a/LibMatrix/RoomTypes/GenericRoom.cs b/LibMatrix/RoomTypes/GenericRoom.cs index 3ef2395..8fa46d3 100644 --- a/LibMatrix/RoomTypes/GenericRoom.cs +++ b/LibMatrix/RoomTypes/GenericRoom.cs @@ -205,7 +205,7 @@ public class GenericRoom { Console.WriteLine("End of GetManyAsync"); } - public async Task GetNameAsync() => (await GetStateOrNullAsync("m.room.name"))?.Name; + public async Task GetNameAsync() => (await GetStateOrNullAsync("m.room.name"))?.Name; public async Task JoinAsync(string[]? homeservers = null, string? reason = null, bool checkIfAlreadyMember = true) { if (checkIfAlreadyMember) @@ -279,42 +279,42 @@ public class GenericRoom { #region Utility shortcuts - public Task SendMessageEventAsync(RoomMessageEventContent content) => + public Task SendMessageEventAsync(RoomMessageLegacyEventContent content) => SendTimelineEventAsync("m.room.message", content); public async Task?> GetAliasesAsync() { - var res = await GetStateAsync("m.room.aliases"); + var res = await GetStateAsync("m.room.aliases"); return res.Aliases; } - public Task GetCanonicalAliasAsync() => - GetStateAsync("m.room.canonical_alias"); + public Task GetCanonicalAliasAsync() => + GetStateAsync("m.room.canonical_alias"); - public Task GetTopicAsync() => - GetStateAsync("m.room.topic"); + public Task GetTopicAsync() => + GetStateAsync("m.room.topic"); - public Task GetAvatarUrlAsync() => - GetStateAsync("m.room.avatar"); + public Task GetAvatarUrlAsync() => + GetStateAsync("m.room.avatar"); - public Task GetJoinRuleAsync() => - GetStateAsync("m.room.join_rules"); + public Task GetJoinRuleAsync() => + GetStateAsync("m.room.join_rules"); - public Task GetHistoryVisibilityAsync() => - GetStateAsync("m.room.history_visibility"); + public Task GetHistoryVisibilityAsync() => + GetStateAsync("m.room.history_visibility"); - public Task GetGuestAccessAsync() => - GetStateAsync("m.room.guest_access"); + public Task GetGuestAccessAsync() => + GetStateAsync("m.room.guest_access"); - public Task GetCreateEventAsync() => - GetStateAsync("m.room.create"); + public Task GetCreateEventAsync() => + 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 Task GetPowerLevelsAsync() => - GetStateAsync("m.room.power_levels"); + public Task GetPowerLevelsAsync() => + GetStateAsync("m.room.power_levels"); public async Task GetNameOrFallbackAsync(int maxMemberNames = 2) { try { @@ -393,7 +393,7 @@ public class GenericRoom { 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) + if (skipExisting && await GetStateAsync("m.room.member", userId) is not null) return; await Homeserver.ClientHttpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/invite", new UserIdAndReason(userId, reason)); } @@ -410,7 +410,7 @@ public class GenericRoom { await (await Homeserver.ClientHttpClient.PutAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state/{eventType}/{stateKey}", content)) .Content.ReadFromJsonAsync(); - public async Task SendTimelineEventAsync(string eventType, TimelineEventContent content) { + public async Task SendTimelineEventAsync(string eventType, TimelineLegacyEventContent content) { var res = await Homeserver.ClientHttpClient.PutAsJsonAsync( $"/_matrix/client/v3/rooms/{RoomId}/send/{eventType}/" + Guid.NewGuid(), content, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull @@ -420,12 +420,12 @@ public class GenericRoom { public async Task SendFileAsync(string fileName, Stream fileStream, string messageType = "m.file", string contentType = "application/octet-stream") { var url = await Homeserver.UploadFile(fileName, fileStream); - var content = new RoomMessageEventContent() { + var content = new RoomMessageLegacyEventContent() { MessageType = messageType, Url = url, Body = fileName, FileName = fileName, - FileInfo = new RoomMessageEventContent.FileInfoStruct { + FileInfo = new RoomMessageLegacyEventContent.FileInfoStruct { Size = fileStream.Length, MimeType = contentType } diff --git a/LibMatrix/Utilities/CommonSyncFilters.cs b/LibMatrix/Utilities/CommonSyncFilters.cs index 401850c..d07c225 100644 --- a/LibMatrix/Utilities/CommonSyncFilters.cs +++ b/LibMatrix/Utilities/CommonSyncFilters.cs @@ -37,11 +37,11 @@ public static class CommonSyncFilters { Ephemeral = new SyncFilter.RoomFilter.StateFilter(rooms: []), State = new SyncFilter.RoomFilter.StateFilter { Types = new List { - RoomCreateEventContent.EventId, - RoomNameEventContent.EventId, - RoomAvatarEventContent.EventId, - MjolnirShortcodeEventContent.EventId, - RoomPowerLevelEventContent.EventId + RoomCreateLegacyEventContent.EventId, + RoomNameLegacyEventContent.EventId, + RoomAvatarLegacyEventContent.EventId, + MjolnirShortcodeLegacyEventContent.EventId, + RoomPowerLevelLegacyEventContent.EventId }, LazyLoadMembers = true, IncludeRedundantMembers = false }, @@ -57,8 +57,8 @@ public static class CommonSyncFilters { Ephemeral = new SyncFilter.RoomFilter.StateFilter(rooms: []), State = new SyncFilter.RoomFilter.StateFilter { Types = new List { - SpaceChildEventContent.EventId, - SpaceParentEventContent.EventId + SpaceChildLegacyEventContent.EventId, + SpaceParentLegacyEventContent.EventId }, LazyLoadMembers = true, IncludeRedundantMembers = false }, @@ -74,7 +74,7 @@ public static class CommonSyncFilters { Ephemeral = new SyncFilter.RoomFilter.StateFilter(rooms: []), State = new SyncFilter.RoomFilter.StateFilter { Types = new List { - RoomMemberEventContent.EventId + RoomMemberLegacyEventContent.EventId }, LazyLoadMembers = true, IncludeRedundantMembers = false, Senders = ["@me"] -- cgit 1.4.1