diff --git a/.gitmodules b/.gitmodules
index 838d197..126aadf 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,12 +1,3 @@
[submodule "ArcaneLibs"]
path = ArcaneLibs
url = https://github.com/TheArcaneBrony/ArcaneLibs.git
-[submodule "ExampleBots/LibMatrix.ExampleBot"]
- path = ExampleBots/LibMatrix.ExampleBot
- url = https://cgit.rory.gay/matrix/bots/LibMatrix.ExampleBot.git
-[submodule "ExampleBots/ModerationBot"]
- path = ExampleBots/ModerationBot
- url = https://cgit.rory.gay/matrix/bots/ModerationBot.git
-[submodule "ExampleBots/PluralContactBotPoC"]
- path = ExampleBots/PluralContactBotPoC
- url = https://cgit.rory.gay/matrix/bots/PluralContactBotPoC.git
diff --git a/.idea/.idea.LibMatrix/.idea/.name b/.idea/.idea.LibMatrix/.idea/.name
deleted file mode 100644
index 2f382b8..0000000
--- a/.idea/.idea.LibMatrix/.idea/.name
+++ /dev/null
@@ -1 +0,0 @@
-LibMatrix
\ No newline at end of file
diff --git a/.idea/.idea.LibMatrix/.idea/vcs.xml b/.idea/.idea.LibMatrix/.idea/vcs.xml
index 35eb1dd..63ea78b 100644
--- a/.idea/.idea.LibMatrix/.idea/vcs.xml
+++ b/.idea/.idea.LibMatrix/.idea/vcs.xml
@@ -2,5 +2,6 @@
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
+ <mapping directory="$PROJECT_DIR$/ArcaneLibs" vcs="Git" />
</component>
</project>
\ No newline at end of file
diff --git a/ArcaneLibs b/ArcaneLibs
-Subproject b7685c786b29e7f8ae2db6ff0f79a52efc57020
+Subproject 7cbf235cceb82dc711622314c49edfc7e2614dc
diff --git a/LibMatrix.EventTypes/Common/MjolnirShortcodeEventContent.cs b/LibMatrix.EventTypes/Common/MjolnirShortcodeEventContent.cs
index a31cbbb..a1ebd79 100644
--- a/LibMatrix.EventTypes/Common/MjolnirShortcodeEventContent.cs
+++ b/LibMatrix.EventTypes/Common/MjolnirShortcodeEventContent.cs
@@ -3,7 +3,7 @@ using System.Text.Json.Serialization;
namespace LibMatrix.EventTypes.Common;
[MatrixEvent(EventName = EventId)]
-public class MjolnirShortcodeEventContent : TimelineEventContent {
+public class MjolnirShortcodeEventContent : EventContent {
public const string EventId = "org.matrix.mjolnir.shortcode";
[JsonPropertyName("shortcode")]
diff --git a/LibMatrix.EventTypes/EventContent.cs b/LibMatrix.EventTypes/EventContent.cs
index c582cf2..07f56e2 100644
--- a/LibMatrix.EventTypes/EventContent.cs
+++ b/LibMatrix.EventTypes/EventContent.cs
@@ -1,10 +1,23 @@
+using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
namespace LibMatrix.EventTypes;
-public abstract class EventContent;
+public abstract class EventContent {
+ [JsonExtensionData]
+ public Dictionary<string, object>? AdditionalData { get; set; } = [];
+
+ public static List<string> GetMatchingEventTypes<T>() where T : EventContent {
+ var type = typeof(T);
+ var eventTypes = new List<string>();
+ foreach (var attr in type.GetCustomAttributes<MatrixEventAttribute>(true)) {
+ eventTypes.Add(attr.EventName);
+ }
+ return eventTypes;
+ }
+}
public class UnknownEventContent : TimelineEventContent;
@@ -37,6 +50,13 @@ public abstract class TimelineEventContent : EventContent {
[JsonPropertyName("rel_type")]
public string? RelationType { get; set; }
+ // used for reactions
+ [JsonPropertyName("key")]
+ public string? Key { get; set; }
+
+ [JsonExtensionData]
+ public Dictionary<string, object>? AdditionalData { get; set; } = [];
+
public class EventInReplyTo {
[JsonPropertyName("event_id")]
public string? EventId { get; set; }
diff --git a/LibMatrix.EventTypes/Interop/Draupnir/DraupnirProtectedRoomsData.cs b/LibMatrix.EventTypes/Interop/Draupnir/DraupnirProtectedRoomsData.cs
new file mode 100644
index 0000000..1917239
--- /dev/null
+++ b/LibMatrix.EventTypes/Interop/Draupnir/DraupnirProtectedRoomsData.cs
@@ -0,0 +1,11 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.EventTypes.Interop.Draupnir;
+
+[MatrixEvent(EventName = EventId)]
+public class DraupnirProtectedRoomsData : EventContent {
+ public const string EventId = "org.matrix.mjolnir.protected_rooms";
+
+ [JsonPropertyName("rooms")]
+ public List<string> Rooms { get; set; } = new();
+}
\ No newline at end of file
diff --git a/LibMatrix.EventTypes/LibMatrix.EventTypes.csproj b/LibMatrix.EventTypes/LibMatrix.EventTypes.csproj
index 4276003..0924aba 100644
--- a/LibMatrix.EventTypes/LibMatrix.EventTypes.csproj
+++ b/LibMatrix.EventTypes/LibMatrix.EventTypes.csproj
@@ -1,22 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>net8.0</TargetFramework>
+ <TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
- <ProjectReference Condition="Exists('..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj')" Include="..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj"/>
- <!-- This is dangerous, but eases development since locking the version will drift out of sync without noticing,
- which causes build errors due to missing functions.
- Using the NuGet version in development is annoying due to delays between pushing and being able to consume.
- If you want to use a time-appropriate version of the library, recursively clone https://cgit.rory.gay/matrix/MatrixUtils.git
- instead, since this will be locked by the MatrixUtils project, which contains both LibMatrix and ArcaneLibs as a submodule. -->
- <PackageReference Condition="!Exists('..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj')" Include="ArcaneLibs" Version="*-preview*"/>
+ <PackageReference Include="ArcaneLibs" Version="1.0.0-preview.20250419-174711" Condition="'$(Configuration)' == 'Release'" />
+ <ProjectReference Include="..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj" Condition="'$(Configuration)' == 'Debug'"/>
</ItemGroup>
- <Target Name="ArcaneLibsNugetWarning" AfterTargets="AfterBuild">
- <Warning Text="ArcaneLibs is being referenced from NuGet, which is dangerous. Please read the warning in LibMatrix.csproj!" Condition="!Exists('..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj')"/>
- </Target>
</Project>
diff --git a/LibMatrix.EventTypes/Spec/Ephemeral/RoomTypingEventContent.cs b/LibMatrix.EventTypes/Spec/Ephemeral/RoomTypingEventContent.cs
index 494936d..a7d431c 100644
--- a/LibMatrix.EventTypes/Spec/Ephemeral/RoomTypingEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/Ephemeral/RoomTypingEventContent.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.Ephemeral;
[MatrixEvent(EventName = EventId)]
public class RoomTypingEventContent : EventContent {
diff --git a/LibMatrix.EventTypes/Spec/IgnoredUserListEventContent.cs b/LibMatrix.EventTypes/Spec/IgnoredUserListEventContent.cs
new file mode 100644
index 0000000..59e17c9
--- /dev/null
+++ b/LibMatrix.EventTypes/Spec/IgnoredUserListEventContent.cs
@@ -0,0 +1,31 @@
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.EventTypes.Spec;
+
+[MatrixEvent(EventName = EventId)]
+public class IgnoredUserListEventContent : EventContent {
+ public const string EventId = "m.ignored_user_list";
+
+ [JsonPropertyName("ignored_users")]
+ public Dictionary<string, IgnoredUserContent> IgnoredUsers { get; set; } = new();
+
+ // Dummy type to provide easy access to the by-spec empty content
+ public class IgnoredUserContent {
+ [JsonExtensionData]
+ public Dictionary<string, object>? AdditionalData { get; set; } = [];
+
+ public T? GetAdditionalData<T>(string key) where T : class {
+ if (AdditionalData == null || !AdditionalData.TryGetValue(key, out var value))
+ return null;
+
+ if (value is T tValue)
+ return tValue;
+ if (value is JsonElement jsonElement)
+ return jsonElement.Deserialize<T>();
+
+ throw new InvalidCastException($"Value for key '{key}' ({value.GetType()}) cannot be cast to type '{typeof(T)}'. Cannot continue.");
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix.EventTypes/Spec/RoomMessageEventContent.cs b/LibMatrix.EventTypes/Spec/RoomMessageEventContent.cs
index ae893f8..d1cf8be 100644
--- a/LibMatrix.EventTypes/Spec/RoomMessageEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/RoomMessageEventContent.cs
@@ -29,13 +29,34 @@ public class RoomMessageEventContent : TimelineEventContent {
[JsonPropertyName("url")]
public string? Url { get; set; }
+ [JsonPropertyName("filename")]
public string? FileName { get; set; }
[JsonPropertyName("info")]
public FileInfoStruct? FileInfo { get; set; }
-
+
[JsonIgnore]
- public string BodyWithoutReplyFallback => Body.Split('\n').SkipWhile(x => x.StartsWith(">")).SkipWhile(x=>x.Trim().Length == 0).Aggregate((x, y) => $"{x}\n{y}");
+ public string BodyWithoutReplyFallback {
+ get {
+ var parts = Body
+ .Split('\n')
+ .SkipWhile(x => x.StartsWith(">"))
+ .SkipWhile(x => x.Trim().Length == 0)
+ .ToList();
+ return parts.Count > 0 ? parts.Aggregate((x, y) => $"{x}\n{y}") : Body;
+ }
+ }
+
+ [JsonPropertyName("m.mentions")]
+ public MentionsStruct? Mentions { get; set; }
+
+ public class MentionsStruct {
+ [JsonPropertyName("user_ids")]
+ public List<string>? Users { get; set; }
+
+ [JsonPropertyName("room")]
+ public bool? Room { get; set; }
+ }
public class FileInfoStruct {
[JsonPropertyName("mimetype")]
@@ -46,10 +67,10 @@ public class RoomMessageEventContent : TimelineEventContent {
[JsonPropertyName("thumbnail_url")]
public string? ThumbnailUrl { get; set; }
-
+
[JsonPropertyName("w")]
public int? Width { get; set; }
-
+
[JsonPropertyName("h")]
public int? Height { get; set; }
}
diff --git a/LibMatrix.EventTypes/Spec/State/Policy/PolicyRuleStateEventContent.cs b/LibMatrix.EventTypes/Spec/State/Policy/PolicyRuleStateEventContent.cs
index 5bfd77b..d75b19f 100644
--- a/LibMatrix.EventTypes/Spec/State/Policy/PolicyRuleStateEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/Policy/PolicyRuleStateEventContent.cs
@@ -1,5 +1,7 @@
+using System.Diagnostics;
using System.Security.Cryptography;
using System.Text.Json.Serialization;
+using System.Text.RegularExpressions;
using ArcaneLibs.Attributes;
using ArcaneLibs.Extensions;
@@ -30,9 +32,9 @@ public class RoomPolicyRuleEventContent : PolicyRuleEventContent {
public const string EventId = "m.policy.rule.room";
}
+[DebuggerDisplay("""{GetType().Name.Replace("PolicyRuleEventContent", ""),nq} policy matching {Entity}, Reason: {Reason}""")]
public abstract class PolicyRuleEventContent : EventContent {
- public PolicyRuleEventContent() => Console.WriteLine($"init policy {GetType().Name}");
- private string? _reason;
+ // public PolicyRuleEventContent() => Console.WriteLine($"init policy {GetType().Name}");
/// <summary>
/// Entity this ban applies to, can use * and ? as globs.
@@ -42,24 +44,14 @@ public abstract class PolicyRuleEventContent : EventContent {
[FriendlyName(Name = "Entity")]
public string? Entity { get; set; }
- private bool init;
+ // private bool init;
/// <summary>
/// Reason this user is banned
/// </summary>
[JsonPropertyName("reason")]
[FriendlyName(Name = "Reason")]
- public virtual string? Reason {
- get =>
- // Console.WriteLine($"Read policy reason: {_reason}");
- _reason;
- set =>
- // Console.WriteLine($"Set policy reason: {value}");
- // if(init)
- // Console.WriteLine(string.Join('\n', Environment.StackTrace.Split('\n')[..5]));
- // init = true;
- _reason = value;
- }
+ public string? Reason { get; set; }
/// <summary>
/// Suggested action to take
@@ -90,7 +82,48 @@ public abstract class PolicyRuleEventContent : EventContent {
}
}
+ [JsonPropertyName("org.matrix.msc4205.hashes")]
+ [TableHide]
+ public PolicyHash? Hashes { get; set; }
+
public string GetDraupnir2StateKey() => Convert.ToBase64String(SHA256.HashData($"{Entity}{Recommendation}".AsBytes().ToArray()));
+
+ public Regex? GetEntityRegex() => Entity is null ? null : new(Entity.Replace(".", "\\.").Replace("*", ".*").Replace("?", "."));
+
+ public bool IsGlobRule() =>
+ !string.IsNullOrWhiteSpace(Entity)
+ && (Entity.Contains('*') || Entity.Contains('?'));
+
+ public bool EntityMatches(string entity) {
+ if (string.IsNullOrWhiteSpace(entity)) return false;
+
+ if (!string.IsNullOrWhiteSpace(Entity)) {
+ // Check if entity is equal regardless of glob check
+ var match = Entity == entity
+ || (IsGlobRule() && GetEntityRegex()!.IsMatch(entity));
+ if (match) return match;
+ }
+
+ if (Hashes is not null) {
+ if (!string.IsNullOrWhiteSpace(Hashes.Sha256)) {
+ var hash = SHA256.HashData(entity.AsBytes().ToArray());
+ var match = Convert.ToBase64String(hash) == Hashes.Sha256;
+ if (match) return match;
+ }
+ }
+
+ return false;
+ }
+
+ public string? GetNormalizedRecommendation() {
+ if (Recommendation is "m.ban" or "org.matrix.mjolnir.ban")
+ return PolicyRecommendationTypes.Ban;
+
+ if (Recommendation is "m.takedown" or "org.matrix.msc4204.takedown")
+ return "m.takedown";
+
+ return Recommendation;
+ }
}
public static class PolicyRecommendationTypes {
@@ -103,6 +136,13 @@ public static class PolicyRecommendationTypes {
/// Mute this user
/// </summary>
public static string Mute = "support.feline.policy.recommendation_mute"; //stable prefix: m.mute, msc pending
+
+ public static string Takedown = "m.takedown"; //unstable prefix: org.matrix.msc4204.takedown
+}
+
+public class PolicyHash {
+ [JsonPropertyName("sha256")]
+ public string? Sha256 { get; set; }
}
// public class PolicySchemaDefinition {
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCanonicalAliasEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCanonicalAliasEventContent.cs
index 93f13ac..ee3234c 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCanonicalAliasEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCanonicalAliasEventContent.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
public class RoomCanonicalAliasEventContent : EventContent {
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCreateEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCreateEventContent.cs
index c619d0e..37b831a 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCreateEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomCreateEventContent.cs
@@ -1,8 +1,11 @@
+using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
+[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global", Justification = "Deserialization, public API")]
+[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global", Justification = "Deserialization, public API")]
public class RoomCreateEventContent : EventContent {
public const string EventId = "m.room.create";
@@ -15,17 +18,17 @@ public class RoomCreateEventContent : EventContent {
[JsonPropertyName("m.federate")]
public bool? Federate { get; set; }
- [JsonPropertyName("predecessor")]
- public RoomCreatePredecessor? Predecessor { get; set; }
+ // [JsonPropertyName("predecessor")]
+ // public RoomCreatePredecessor? Predecessor { get; set; }
[JsonPropertyName("type")]
public string? Type { get; set; }
+}
- public class RoomCreatePredecessor {
- [JsonPropertyName("room_id")]
- public string? RoomId { get; set; }
+public class RoomCreatePredecessor {
+ [JsonPropertyName("room_id")]
+ public string? RoomId { get; set; }
- [JsonPropertyName("event_id")]
- public string? EventId { get; set; }
- }
+ [JsonPropertyName("event_id")]
+ public string? EventId { get; set; }
}
\ No newline at end of file
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomEncryptionEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomEncryptionEventContent.cs
index b49abfa..16209f0 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomEncryptionEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomEncryptionEventContent.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
public class RoomEncryptionEventContent : EventContent {
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomGuestAccessEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomGuestAccessEventContent.cs
index a7811bf..1ba5a3f 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomGuestAccessEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomGuestAccessEventContent.cs
@@ -1,13 +1,13 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
public class RoomGuestAccessEventContent : EventContent {
public const string EventId = "m.room.guest_access";
[JsonPropertyName("guest_access")]
- public string GuestAccess { get; set; }
+ public required string GuestAccess { get; set; }
[JsonIgnore]
public bool IsGuestAccessEnabled {
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomHistoryVisibilityEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomHistoryVisibilityEventContent.cs
index 7676dad..8edf4a7 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomHistoryVisibilityEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomHistoryVisibilityEventContent.cs
@@ -1,11 +1,17 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
public class RoomHistoryVisibilityEventContent : EventContent {
public const string EventId = "m.room.history_visibility";
[JsonPropertyName("history_visibility")]
- public string HistoryVisibility { get; set; }
+ public required string HistoryVisibility { get; set; }
+
+ public static class HistoryVisibilityTypes {
+ public const string WorldReadable = "world_readable";
+ public const string Invited = "invited";
+ public const string Shared = "shared";
+ }
}
\ No newline at end of file
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomJoinRulesEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomJoinRulesEventContent.cs
index 349c8a7..03d994d 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomJoinRulesEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomJoinRulesEventContent.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
public class RoomJoinRulesEventContent : EventContent {
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomMemberEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomMemberEventContent.cs
index b2d5596..b034425 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomMemberEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomMemberEventContent.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
public class RoomMemberEventContent : EventContent {
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomNameEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomNameEventContent.cs
index 3ea5730..415c675 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomNameEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomNameEventContent.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
public class RoomNameEventContent : EventContent {
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomPinnedEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomPinnedEventContent.cs
index b4474e9..7eee605 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomPinnedEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomPinnedEventContent.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
public class RoomPinnedEventContent : EventContent {
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomPolicyServerEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomPolicyServerEventContent.cs
new file mode 100644
index 0000000..80e254f
--- /dev/null
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomPolicyServerEventContent.cs
@@ -0,0 +1,11 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
+
+[MatrixEvent(EventName = EventId)]
+public class RoomPolicyServerEventContent : EventContent {
+ public const string EventId = "org.matrix.msc4284.policy";
+
+ [JsonPropertyName("via")]
+ public string? Via { get; set; }
+}
\ No newline at end of file
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomPowerLevelEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomPowerLevelEventContent.cs
index eb156b3..22fa3b7 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomPowerLevelEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomPowerLevelEventContent.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
@@ -20,7 +20,7 @@ public class RoomPowerLevelEventContent : EventContent {
public long? Kick { get; set; } = 50;
[JsonPropertyName("notifications")]
- public NotificationsPL? NotificationsPl { get; set; } // = null!;
+ public NotificationsPowerLevels? NotificationsPl { get; set; }
[JsonPropertyName("redact")]
public long? Redact { get; set; } = 50;
@@ -29,10 +29,10 @@ public class RoomPowerLevelEventContent : EventContent {
public long? StateDefault { get; set; } = 50;
[JsonPropertyName("events")]
- public Dictionary<string, long>? Events { get; set; } // = null!;
+ public Dictionary<string, long>? Events { get; set; }
[JsonPropertyName("users")]
- public Dictionary<string, long>? Users { get; set; } // = null!;
+ public Dictionary<string, long>? Users { get; set; }
[JsonPropertyName("users_default")]
public long? UsersDefault { get; set; } = 0;
@@ -42,19 +42,19 @@ public class RoomPowerLevelEventContent : EventContent {
[JsonPropertyName("historical")]
public long Historical { get; set; } // = 50;
- public class NotificationsPL {
+ public class NotificationsPowerLevels {
[JsonPropertyName("room")]
public long Room { get; set; } = 50;
}
public bool IsUserAdmin(string userId) {
ArgumentNullException.ThrowIfNull(userId);
- return Users.TryGetValue(userId, out var level) && level >= Events.Max(x => x.Value);
+ return GetUserPowerLevel(userId) >= Events?.Max(x => x.Value);
}
public bool UserHasTimelinePermission(string userId, string eventType) {
ArgumentNullException.ThrowIfNull(userId);
- return Users.TryGetValue(userId, out var level) && level >= Events.GetValueOrDefault(eventType, EventsDefault ?? 0);
+ return GetUserPowerLevel(userId) >= Events?.GetValueOrDefault(eventType, EventsDefault ?? 0);
}
public bool UserHasStatePermission(string userId, string eventType, bool log = false) {
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomRedactionEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomRedactionEventContent.cs
new file mode 100644
index 0000000..055f22d
--- /dev/null
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomRedactionEventContent.cs
@@ -0,0 +1,18 @@
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
+
+[MatrixEvent(EventName = EventId)]
+public class RoomRedactionEventContent : EventContent {
+ public const string EventId = "m.room.redaction";
+
+ [JsonPropertyName("reason")]
+ public string? Reason { get; set; }
+
+ /// <summary>
+ /// Required in room version 11
+ /// </summary>
+ [JsonPropertyName("redacts")]
+ public string? Redacts { get; set; }
+}
\ No newline at end of file
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomServerACLEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomServerACLEventContent.cs
index be83e37..c492250 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomServerACLEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomServerACLEventContent.cs
@@ -1,16 +1,16 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
-public class RoomServerACLEventContent : EventContent {
+public class RoomServerAclEventContent : EventContent {
public const string EventId = "m.room.server_acl";
[JsonPropertyName("allow")]
- public List<string>? Allow { get; set; } // = null!;
+ public List<string>? Allow { get; set; }
[JsonPropertyName("deny")]
- public List<string>? Deny { get; set; } // = null!;
+ public List<string>? Deny { get; set; }
[JsonPropertyName("allow_ip_literals")]
public bool AllowIpLiterals { get; set; } // = false;
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomTombstoneEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomTombstoneEventContent.cs
new file mode 100644
index 0000000..2c45c41
--- /dev/null
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomTombstoneEventContent.cs
@@ -0,0 +1,14 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
+
+[MatrixEvent(EventName = EventId)]
+public class RoomTombstoneEventContent : EventContent {
+ public const string EventId = "m.room.tombstone";
+
+ [JsonPropertyName("body")]
+ public string Body { get; set; }
+
+ [JsonPropertyName("replacement_room")]
+ public string ReplacementRoom { get; set; }
+}
\ No newline at end of file
diff --git a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomTopicEventContent.cs b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomTopicEventContent.cs
index 92fa75d..065c976 100644
--- a/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomTopicEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/RoomInfo/RoomTopicEventContent.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.RoomInfo;
[MatrixEvent(EventName = EventId)]
[MatrixEvent(EventName = "org.matrix.msc3765.topic", Legacy = true)]
diff --git a/LibMatrix.EventTypes/Spec/State/Space/SpaceChildEventContent.cs b/LibMatrix.EventTypes/Spec/State/Space/SpaceChildEventContent.cs
index d233be4..cd0f1f5 100644
--- a/LibMatrix.EventTypes/Spec/State/Space/SpaceChildEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/Space/SpaceChildEventContent.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.Space;
[MatrixEvent(EventName = EventId)]
public class SpaceChildEventContent : EventContent {
diff --git a/LibMatrix.EventTypes/Spec/State/Space/SpaceParentEventContent.cs b/LibMatrix.EventTypes/Spec/State/Space/SpaceParentEventContent.cs
index 2ab79a4..f50797e 100644
--- a/LibMatrix.EventTypes/Spec/State/Space/SpaceParentEventContent.cs
+++ b/LibMatrix.EventTypes/Spec/State/Space/SpaceParentEventContent.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.EventTypes.Spec.State;
+namespace LibMatrix.EventTypes.Spec.State.Space;
[MatrixEvent(EventName = EventId)]
public class SpaceParentEventContent : EventContent {
diff --git a/LibMatrix.Federation/AuthenticatedFederationClient.cs b/LibMatrix.Federation/AuthenticatedFederationClient.cs
new file mode 100644
index 0000000..6f8d44b
--- /dev/null
+++ b/LibMatrix.Federation/AuthenticatedFederationClient.cs
@@ -0,0 +1,20 @@
+using LibMatrix.Homeservers;
+
+namespace LibMatrix.Federation;
+
+public class AuthenticatedFederationClient : FederationClient {
+
+ public class AuthenticatedFederationConfiguration {
+
+ }
+ public AuthenticatedFederationClient(string federationEndpoint, AuthenticatedFederationConfiguration config, string? proxy = null) : base(federationEndpoint, proxy)
+ {
+
+ }
+
+ // public async Task<UserDeviceListResponse> GetUserDevicesAsync(string userId) {
+ // var response = await GetAsync<UserDeviceListResponse>($"/_matrix/federation/v1/user/devices/{userId}", accessToken);
+ // return response;
+ // }
+
+}
\ No newline at end of file
diff --git a/LibMatrix.Federation/Extensions/Ed25519Extensions.cs b/LibMatrix.Federation/Extensions/Ed25519Extensions.cs
new file mode 100644
index 0000000..69baf58
--- /dev/null
+++ b/LibMatrix.Federation/Extensions/Ed25519Extensions.cs
@@ -0,0 +1,8 @@
+using LibMatrix.FederationTest.Utilities;
+using Org.BouncyCastle.Crypto.Parameters;
+
+namespace LibMatrix.Federation.Extensions;
+
+public static class Ed25519Extensions {
+ public static string ToUnpaddedBase64(this Ed25519PublicKeyParameters key) => UnpaddedBase64.Encode(key.GetEncoded());
+}
\ No newline at end of file
diff --git a/LibMatrix.Federation/LibMatrix.Federation.csproj b/LibMatrix.Federation/LibMatrix.Federation.csproj
new file mode 100644
index 0000000..78086bb
--- /dev/null
+++ b/LibMatrix.Federation/LibMatrix.Federation.csproj
@@ -0,0 +1,19 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net9.0</TargetFramework>
+ <LangVersion>preview</LangVersion>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\LibMatrix\LibMatrix.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="BouncyCastle.Cryptography" Version="2.6.1" />
+ <PackageReference Include="Microsoft.Extensions.Primitives" Version="10.0.0-preview.5.25277.114" />
+ </ItemGroup>
+
+</Project>
diff --git a/LibMatrix.Federation/Utilities/JsonSigning.cs b/LibMatrix.Federation/Utilities/JsonSigning.cs
new file mode 100644
index 0000000..c727cde
--- /dev/null
+++ b/LibMatrix.Federation/Utilities/JsonSigning.cs
@@ -0,0 +1,108 @@
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+using ArcaneLibs.Extensions;
+using LibMatrix.Extensions;
+using LibMatrix.FederationTest.Utilities;
+using LibMatrix.Homeservers;
+using Org.BouncyCastle.Crypto.Parameters;
+using Org.BouncyCastle.Math.EC.Rfc8032;
+
+namespace LibMatrix.Federation.Utilities;
+
+public static class JsonSigning { }
+
+[JsonConverter(typeof(SignedObjectConverterFactory))]
+public class SignedObject<T> {
+ [JsonPropertyName("signatures")]
+ public Dictionary<string, Dictionary<string, string>> Signatures { get; set; } = new();
+
+ [JsonIgnore]
+ public Dictionary<string, Dictionary<ServerKeysResponse.VersionedKeyId, string>> VerifyKeysById {
+ get => Signatures.ToDictionary(server => server.Key, server => server.Value.ToDictionary(key => (ServerKeysResponse.VersionedKeyId)key.Key, key => key.Value));
+ set => Signatures = value.ToDictionary(server => server.Key, server => server.Value.ToDictionary(key => (string)key.Key, key => key.Value));
+ }
+
+ [JsonExtensionData]
+ public required JsonObject Content { get; set; }
+
+ [JsonIgnore]
+ public T TypedContent {
+ get => Content.Deserialize<T>() ?? throw new JsonException("Failed to deserialize TypedContent from Content.");
+ set => Content = JsonSerializer.Deserialize<JsonObject>(JsonSerializer.Serialize(value)) ?? new JsonObject();
+ }
+}
+
+// Content needs to be merged at toplevel
+public class SignedObjectConverter<T> : JsonConverter<SignedObject<T>> {
+ public override SignedObject<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
+ var jsonObject = JsonSerializer.Deserialize<JsonObject>(ref reader, options);
+ if (jsonObject == null) {
+ throw new JsonException("Failed to deserialize SignedObject, JSON object is null.");
+ }
+
+ var signatures = jsonObject["signatures"] ?? throw new JsonException("Failed to find 'signatures' property in JSON object.");
+ jsonObject.Remove("signatures");
+
+ var signedObject = new SignedObject<T> {
+ Content = jsonObject,
+ Signatures = signatures.Deserialize<Dictionary<string, Dictionary<string, string>>>()
+ ?? throw new JsonException("Failed to deserialize 'signatures' property into Dictionary<string, Dictionary<string, string>>.")
+ };
+
+ return signedObject;
+ }
+
+ public override void Write(Utf8JsonWriter writer, SignedObject<T> value, JsonSerializerOptions options) {
+ var targetObj = value.Content.DeepClone();
+ targetObj["signatures"] = value.Signatures.ToJsonNode();
+ JsonSerializer.Serialize(writer, targetObj, options);
+ }
+}
+
+internal class SignedObjectConverterFactory : JsonConverterFactory {
+ public override bool CanConvert(Type typeToConvert) {
+ if (!typeToConvert.IsGenericType) return false;
+ return typeToConvert.GetGenericTypeDefinition() == typeof(SignedObject<>);
+ }
+
+ public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) {
+ var wrappedType = typeToConvert.GetGenericArguments()[0];
+ var converter = (JsonConverter)Activator.CreateInstance(typeof(SignedObjectConverter<>).MakeGenericType(wrappedType))!;
+ return converter;
+ }
+}
+
+public static class ObjectExtensions {
+ public static SignedObject<T> Sign<T>(this SignedObject<T> content, string serverName, string keyName, Ed25519PrivateKeyParameters key) {
+ var signResult = Sign(content.Content, serverName, keyName, key);
+ var signedObject = new SignedObject<T> {
+ Signatures = content.Signatures,
+ Content = signResult.Content
+ };
+
+ if (!signedObject.Signatures.ContainsKey(serverName))
+ signedObject.Signatures[serverName] = new Dictionary<string, string>();
+
+ signedObject.Signatures[serverName][keyName] = signResult.Signatures[serverName][keyName];
+ return signedObject;
+ }
+
+ public static SignedObject<T> Sign<T>(this T content, string serverName, string keyName, Ed25519PrivateKeyParameters key) {
+ SignedObject<T> signedObject = new() {
+ Signatures = [],
+ Content = JsonSerializer.Deserialize<JsonObject>(JsonSerializer.Serialize(content)) ?? new JsonObject(),
+ };
+
+ var contentBytes = CanonicalJsonSerializer.SerializeToUtf8Bytes(signedObject.Content);
+ var signature = new byte[Ed25519.SignatureSize];
+ key.Sign(Ed25519.Algorithm.Ed25519, null, contentBytes, 0, contentBytes.Length, signature, 0);
+
+ if (!signedObject.Signatures.ContainsKey(serverName))
+ signedObject.Signatures[serverName] = new Dictionary<string, string>();
+
+ signedObject.Signatures[serverName][keyName] = UnpaddedBase64.Encode(signature);
+ return signedObject;
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix.Federation/Utilities/UnpaddedBase64.cs b/LibMatrix.Federation/Utilities/UnpaddedBase64.cs
new file mode 100644
index 0000000..06f84b2
--- /dev/null
+++ b/LibMatrix.Federation/Utilities/UnpaddedBase64.cs
@@ -0,0 +1,17 @@
+namespace LibMatrix.FederationTest.Utilities;
+
+public static class UnpaddedBase64 {
+ public static string Encode(byte[] data) {
+ return Convert.ToBase64String(data).TrimEnd('=');
+ }
+
+ public static byte[] Decode(string base64) {
+ string paddedBase64 = base64;
+ switch (paddedBase64.Length % 4) {
+ case 2: paddedBase64 += "=="; break;
+ case 3: paddedBase64 += "="; break;
+ }
+
+ return Convert.FromBase64String(paddedBase64);
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix.Federation/XMatrixAuthorizationScheme.cs b/LibMatrix.Federation/XMatrixAuthorizationScheme.cs
new file mode 100644
index 0000000..fc402b7
--- /dev/null
+++ b/LibMatrix.Federation/XMatrixAuthorizationScheme.cs
@@ -0,0 +1,71 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+using ArcaneLibs.Extensions;
+using Microsoft.Extensions.Primitives;
+
+namespace LibMatrix.Federation;
+
+public class XMatrixAuthorizationScheme {
+ public class XMatrixAuthorizationHeader {
+ public const string Scheme = "X-Matrix";
+
+ [JsonPropertyName("origin")]
+ public required string Origin { get; set; }
+
+ [JsonPropertyName("destination")]
+ public required string Destination { get; set; }
+
+ [JsonPropertyName("key")]
+ public required string Key { get; set; }
+
+ [JsonPropertyName("sig")]
+ public required string Signature { get; set; }
+
+ public static XMatrixAuthorizationHeader FromHeaderValue(AuthenticationHeaderValue header) {
+ if (header.Scheme != Scheme)
+ throw new LibMatrixException() {
+ Error = $"Expected authentication scheme of {Scheme}, got {header.Scheme}",
+ ErrorCode = MatrixException.ErrorCodes.M_UNAUTHORIZED
+ };
+
+ if (string.IsNullOrWhiteSpace(header.Parameter))
+ throw new LibMatrixException() {
+ Error = $"Expected authentication header to have a value.",
+ ErrorCode = MatrixException.ErrorCodes.M_UNAUTHORIZED
+ };
+
+ var headerValues = new StringValues(header.Parameter);
+ foreach (var value in headerValues) {
+ Console.WriteLine(headerValues.ToJson());
+ }
+
+ return new() {
+ Destination = "",
+ Key = "",
+ Origin = "",
+ Signature = ""
+ };
+ }
+
+ public string ToHeaderValue() => $"{Scheme} origin=\"{Origin}\", destination=\"{Destination}\", key=\"{Key}\", sig=\"{Signature}\"";
+ }
+
+ public class XMatrixRequestSignature {
+ [JsonPropertyName("method")]
+ public required string Method { get; set; }
+
+ [JsonPropertyName("uri")]
+ public required string Uri { get; set; }
+
+ [JsonPropertyName("origin")]
+ public required string OriginServerName { get; set; }
+
+ [JsonPropertyName("destination")]
+ public required string DestinationServerName { get; set; }
+
+ [JsonPropertyName("content"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
+ public JsonObject? Content { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix.sln b/LibMatrix.sln
index 3294f77..d6c1c0f 100644
--- a/LibMatrix.sln
+++ b/LibMatrix.sln
@@ -1,154 +1,310 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio Version 17
-VisualStudioVersion = 17.0.31903.59
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix", "LibMatrix\LibMatrix.csproj", "{2A07D7DA-7B8F-432D-8AD3-9679B58A7C19}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Utilities", "Utilities", "{A6345ECE-4C5E-400F-9130-886E343BF314}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.MxApiExtensions", "LibMatrix.MxApiExtensions\LibMatrix.MxApiExtensions.csproj", "{32D9616B-91BB-4B43-97C6-2C3840C12EA6}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.DebugDataValidationApi", "Utilities\LibMatrix.DebugDataValidationApi\LibMatrix.DebugDataValidationApi.csproj", "{35DF9A1A-D988-4225-AFA3-06BB8EDEB559}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.Utilities.Bot", "Utilities\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj", "{3ACF2613-E23F-42C2-925E-0BB4FC3AB1F7}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{BFE16D8E-EFC5-49F6-9854-DB001309B3B4}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.Tests", "Tests\LibMatrix.Tests\LibMatrix.Tests.csproj", "{345934FF-CA81-4A4B-B137-9F198102C65F}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestDataGenerator", "Tests\TestDataGenerator\TestDataGenerator.csproj", "{0B9B34D1-9362-45A9-9C21-816FD6959110}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.JsonSerializerContextGenerator", "Utilities\LibMatrix.JsonSerializerContextGenerator\LibMatrix.JsonSerializerContextGenerator.csproj", "{4D9B5227-48DC-4A30-9263-AFB51DC01ABB}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ArcaneLibs", "ArcaneLibs", "{01A126FE-9D50-40F2-817B-E55F4065EA76}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs", "ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj", "{13A797D1-7E13-4789-A167-8628B1641AC0}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.EventTypes", "LibMatrix.EventTypes\LibMatrix.EventTypes.csproj", "{CD13665B-B964-4AB0-991B-12F067B16DA3}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.HomeserverEmulator", "Tests\LibMatrix.HomeserverEmulator\LibMatrix.HomeserverEmulator.csproj", "{D44DB78D-9BAD-4AB6-A054-839ECA9D68D2}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.Blazor.Components", "ArcaneLibs\ArcaneLibs.Blazor.Components\ArcaneLibs.Blazor.Components.csproj", "{ABAB8F42-A4BC-4ABF-AF1D-FDB40D87A91C}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.Legacy", "ArcaneLibs\ArcaneLibs.Legacy\ArcaneLibs.Legacy.csproj", "{F94D35FF-E90E-4B86-B26E-A8E46EB54BDD}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.Logging", "ArcaneLibs\ArcaneLibs.Logging\ArcaneLibs.Logging.csproj", "{711D1579-9228-47BA-9CB3-C237F7E8F403}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.StringNormalisation", "ArcaneLibs\ArcaneLibs.StringNormalisation\ArcaneLibs.StringNormalisation.csproj", "{87270607-F95C-4EED-AE69-57666863EFDF}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.Timings", "ArcaneLibs\ArcaneLibs.Timings\ArcaneLibs.Timings.csproj", "{5EE6E02C-A63F-4864-91F3-7375B4C50189}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.UsageTest", "ArcaneLibs\ArcaneLibs.UsageTest\ArcaneLibs.UsageTest.csproj", "{7E7BBBDD-CE09-4298-B839-5EBDCA5D0DAF}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLib.Tests", "ArcaneLibs\ArcaneLib.Tests\ArcaneLib.Tests.csproj", "{E6BF8A7E-92F6-4761-A793-1EC709F7E2BF}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.DevTestBot", "Utilities\LibMatrix.DevTestBot\LibMatrix.DevTestBot.csproj", "{6F4A4ABC-5E42-4293-80E6-0C38FE8C9EC5}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.E2eeTestKit", "Utilities\LibMatrix.E2eeTestKit\LibMatrix.E2eeTestKit.csproj", "{A1066F8F-CE8A-4F60-9EFB-553C9E794435}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {2A07D7DA-7B8F-432D-8AD3-9679B58A7C19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {2A07D7DA-7B8F-432D-8AD3-9679B58A7C19}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {2A07D7DA-7B8F-432D-8AD3-9679B58A7C19}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {2A07D7DA-7B8F-432D-8AD3-9679B58A7C19}.Release|Any CPU.Build.0 = Release|Any CPU
- {32D9616B-91BB-4B43-97C6-2C3840C12EA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {32D9616B-91BB-4B43-97C6-2C3840C12EA6}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {32D9616B-91BB-4B43-97C6-2C3840C12EA6}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {32D9616B-91BB-4B43-97C6-2C3840C12EA6}.Release|Any CPU.Build.0 = Release|Any CPU
- {35DF9A1A-D988-4225-AFA3-06BB8EDEB559}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {35DF9A1A-D988-4225-AFA3-06BB8EDEB559}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {35DF9A1A-D988-4225-AFA3-06BB8EDEB559}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {35DF9A1A-D988-4225-AFA3-06BB8EDEB559}.Release|Any CPU.Build.0 = Release|Any CPU
- {3ACF2613-E23F-42C2-925E-0BB4FC3AB1F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {3ACF2613-E23F-42C2-925E-0BB4FC3AB1F7}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {3ACF2613-E23F-42C2-925E-0BB4FC3AB1F7}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {3ACF2613-E23F-42C2-925E-0BB4FC3AB1F7}.Release|Any CPU.Build.0 = Release|Any CPU
- {345934FF-CA81-4A4B-B137-9F198102C65F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {345934FF-CA81-4A4B-B137-9F198102C65F}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {345934FF-CA81-4A4B-B137-9F198102C65F}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {345934FF-CA81-4A4B-B137-9F198102C65F}.Release|Any CPU.Build.0 = Release|Any CPU
- {0B9B34D1-9362-45A9-9C21-816FD6959110}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {0B9B34D1-9362-45A9-9C21-816FD6959110}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {0B9B34D1-9362-45A9-9C21-816FD6959110}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {0B9B34D1-9362-45A9-9C21-816FD6959110}.Release|Any CPU.Build.0 = Release|Any CPU
- {4D9B5227-48DC-4A30-9263-AFB51DC01ABB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {4D9B5227-48DC-4A30-9263-AFB51DC01ABB}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {4D9B5227-48DC-4A30-9263-AFB51DC01ABB}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {4D9B5227-48DC-4A30-9263-AFB51DC01ABB}.Release|Any CPU.Build.0 = Release|Any CPU
- {13A797D1-7E13-4789-A167-8628B1641AC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {13A797D1-7E13-4789-A167-8628B1641AC0}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {13A797D1-7E13-4789-A167-8628B1641AC0}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {13A797D1-7E13-4789-A167-8628B1641AC0}.Release|Any CPU.Build.0 = Release|Any CPU
- {CD13665B-B964-4AB0-991B-12F067B16DA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {CD13665B-B964-4AB0-991B-12F067B16DA3}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {CD13665B-B964-4AB0-991B-12F067B16DA3}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {CD13665B-B964-4AB0-991B-12F067B16DA3}.Release|Any CPU.Build.0 = Release|Any CPU
- {D44DB78D-9BAD-4AB6-A054-839ECA9D68D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {D44DB78D-9BAD-4AB6-A054-839ECA9D68D2}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {D44DB78D-9BAD-4AB6-A054-839ECA9D68D2}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {D44DB78D-9BAD-4AB6-A054-839ECA9D68D2}.Release|Any CPU.Build.0 = Release|Any CPU
- {ABAB8F42-A4BC-4ABF-AF1D-FDB40D87A91C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {ABAB8F42-A4BC-4ABF-AF1D-FDB40D87A91C}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {ABAB8F42-A4BC-4ABF-AF1D-FDB40D87A91C}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {ABAB8F42-A4BC-4ABF-AF1D-FDB40D87A91C}.Release|Any CPU.Build.0 = Release|Any CPU
- {F94D35FF-E90E-4B86-B26E-A8E46EB54BDD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {F94D35FF-E90E-4B86-B26E-A8E46EB54BDD}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {F94D35FF-E90E-4B86-B26E-A8E46EB54BDD}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {F94D35FF-E90E-4B86-B26E-A8E46EB54BDD}.Release|Any CPU.Build.0 = Release|Any CPU
- {711D1579-9228-47BA-9CB3-C237F7E8F403}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {711D1579-9228-47BA-9CB3-C237F7E8F403}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {711D1579-9228-47BA-9CB3-C237F7E8F403}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {711D1579-9228-47BA-9CB3-C237F7E8F403}.Release|Any CPU.Build.0 = Release|Any CPU
- {87270607-F95C-4EED-AE69-57666863EFDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {87270607-F95C-4EED-AE69-57666863EFDF}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {87270607-F95C-4EED-AE69-57666863EFDF}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {87270607-F95C-4EED-AE69-57666863EFDF}.Release|Any CPU.Build.0 = Release|Any CPU
- {5EE6E02C-A63F-4864-91F3-7375B4C50189}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {5EE6E02C-A63F-4864-91F3-7375B4C50189}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {5EE6E02C-A63F-4864-91F3-7375B4C50189}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {5EE6E02C-A63F-4864-91F3-7375B4C50189}.Release|Any CPU.Build.0 = Release|Any CPU
- {7E7BBBDD-CE09-4298-B839-5EBDCA5D0DAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {7E7BBBDD-CE09-4298-B839-5EBDCA5D0DAF}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {7E7BBBDD-CE09-4298-B839-5EBDCA5D0DAF}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {7E7BBBDD-CE09-4298-B839-5EBDCA5D0DAF}.Release|Any CPU.Build.0 = Release|Any CPU
- {E6BF8A7E-92F6-4761-A793-1EC709F7E2BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {E6BF8A7E-92F6-4761-A793-1EC709F7E2BF}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {E6BF8A7E-92F6-4761-A793-1EC709F7E2BF}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {E6BF8A7E-92F6-4761-A793-1EC709F7E2BF}.Release|Any CPU.Build.0 = Release|Any CPU
- {6F4A4ABC-5E42-4293-80E6-0C38FE8C9EC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {6F4A4ABC-5E42-4293-80E6-0C38FE8C9EC5}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {6F4A4ABC-5E42-4293-80E6-0C38FE8C9EC5}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {6F4A4ABC-5E42-4293-80E6-0C38FE8C9EC5}.Release|Any CPU.Build.0 = Release|Any CPU
- {A1066F8F-CE8A-4F60-9EFB-553C9E794435}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {A1066F8F-CE8A-4F60-9EFB-553C9E794435}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {A1066F8F-CE8A-4F60-9EFB-553C9E794435}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {A1066F8F-CE8A-4F60-9EFB-553C9E794435}.Release|Any CPU.Build.0 = Release|Any CPU
- EndGlobalSection
- GlobalSection(NestedProjects) = preSolution
- {35DF9A1A-D988-4225-AFA3-06BB8EDEB559} = {A6345ECE-4C5E-400F-9130-886E343BF314}
- {3ACF2613-E23F-42C2-925E-0BB4FC3AB1F7} = {A6345ECE-4C5E-400F-9130-886E343BF314}
- {345934FF-CA81-4A4B-B137-9F198102C65F} = {BFE16D8E-EFC5-49F6-9854-DB001309B3B4}
- {0B9B34D1-9362-45A9-9C21-816FD6959110} = {BFE16D8E-EFC5-49F6-9854-DB001309B3B4}
- {4D9B5227-48DC-4A30-9263-AFB51DC01ABB} = {A6345ECE-4C5E-400F-9130-886E343BF314}
- {13A797D1-7E13-4789-A167-8628B1641AC0} = {01A126FE-9D50-40F2-817B-E55F4065EA76}
- {D44DB78D-9BAD-4AB6-A054-839ECA9D68D2} = {BFE16D8E-EFC5-49F6-9854-DB001309B3B4}
- {ABAB8F42-A4BC-4ABF-AF1D-FDB40D87A91C} = {01A126FE-9D50-40F2-817B-E55F4065EA76}
- {F94D35FF-E90E-4B86-B26E-A8E46EB54BDD} = {01A126FE-9D50-40F2-817B-E55F4065EA76}
- {711D1579-9228-47BA-9CB3-C237F7E8F403} = {01A126FE-9D50-40F2-817B-E55F4065EA76}
- {87270607-F95C-4EED-AE69-57666863EFDF} = {01A126FE-9D50-40F2-817B-E55F4065EA76}
- {5EE6E02C-A63F-4864-91F3-7375B4C50189} = {01A126FE-9D50-40F2-817B-E55F4065EA76}
- {7E7BBBDD-CE09-4298-B839-5EBDCA5D0DAF} = {01A126FE-9D50-40F2-817B-E55F4065EA76}
- {E6BF8A7E-92F6-4761-A793-1EC709F7E2BF} = {01A126FE-9D50-40F2-817B-E55F4065EA76}
- {6F4A4ABC-5E42-4293-80E6-0C38FE8C9EC5} = {A6345ECE-4C5E-400F-9130-886E343BF314}
- {A1066F8F-CE8A-4F60-9EFB-553C9E794435} = {A6345ECE-4C5E-400F-9130-886E343BF314}
- EndGlobalSection
-EndGlobal
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.0.31903.59
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ArcaneLibs", "ArcaneLibs", "{32C0F9AC-AF7D-4476-A269-99ACA000EF9F}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.Blazor.Components", "ArcaneLibs\ArcaneLibs.Blazor.Components\ArcaneLibs.Blazor.Components.csproj", "{93D00F03-02FF-4C2A-8917-6863D6E633D9}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.Legacy", "ArcaneLibs\ArcaneLibs.Legacy\ArcaneLibs.Legacy.csproj", "{14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.Logging", "ArcaneLibs\ArcaneLibs.Logging\ArcaneLibs.Logging.csproj", "{51F770AF-C0C6-4247-A358-82DF323F473D}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.StringNormalisation", "ArcaneLibs\ArcaneLibs.StringNormalisation\ArcaneLibs.StringNormalisation.csproj", "{8A8E8B67-9351-471E-A502-AF7FAE596CB4}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.Tests", "ArcaneLibs\ArcaneLibs.Tests\ArcaneLibs.Tests.csproj", "{5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.Timings", "ArcaneLibs\ArcaneLibs.Timings\ArcaneLibs.Timings.csproj", "{567DABFB-611E-4779-9F39-1D4A5B8F0247}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs.UsageTest", "ArcaneLibs\ArcaneLibs.UsageTest\ArcaneLibs.UsageTest.csproj", "{28AFDFEF-7597-4450-B999-87C22C24DCD8}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArcaneLibs", "ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj", "{F80D5395-28E3-4C34-9662-A890A215DDA2}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.EventTypes", "LibMatrix.EventTypes\LibMatrix.EventTypes.csproj", "{90A38896-993A-49F1-903B-8C989D8C9B3A}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix", "LibMatrix\LibMatrix.csproj", "{6AE504F8-734B-456B-8BEA-DE37639CB3A7}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{AAAA5609-D8C1-401E-BB5C-724EFE3955FB}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.Tests", "Tests\LibMatrix.Tests\LibMatrix.Tests.csproj", "{7E15D295-B938-409C-98F6-A22ABC7F3005}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Utilities", "Utilities", "{FBC6F613-4E0B-4A90-8854-31887A796EEF}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.DebugDataValidationApi", "Utilities\LibMatrix.DebugDataValidationApi\LibMatrix.DebugDataValidationApi.csproj", "{D632374A-70A1-4954-8F2D-C0B511A24426}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.DevTestBot", "Utilities\LibMatrix.DevTestBot\LibMatrix.DevTestBot.csproj", "{91E41EE3-687B-4CFD-94C4-028D09BACFAB}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.E2eeTestKit", "Utilities\LibMatrix.E2eeTestKit\LibMatrix.E2eeTestKit.csproj", "{4D411F2D-A97D-4485-A318-ED98B96B6CF6}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.HomeserverEmulator", "Utilities\LibMatrix.HomeserverEmulator\LibMatrix.HomeserverEmulator.csproj", "{7F36D200-FE91-4761-B681-BEE091FB953F}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.JsonSerializerContextGenerator", "Utilities\LibMatrix.JsonSerializerContextGenerator\LibMatrix.JsonSerializerContextGenerator.csproj", "{69CCB780-50CC-4E75-B794-932E44ACA80F}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.TestDataGenerator", "Utilities\LibMatrix.TestDataGenerator\LibMatrix.TestDataGenerator.csproj", "{C087F8AC-B438-4980-9A79-1E16D0CFB67A}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.Utilities.Bot", "Utilities\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj", "{E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibMatrix.Federation", "LibMatrix.Federation\LibMatrix.Federation.csproj", "{0E6CF267-14FD-43D7-81CB-EE020FD1D106}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Debug|x64 = Debug|x64
+ Debug|x86 = Debug|x86
+ Release|Any CPU = Release|Any CPU
+ Release|x64 = Release|x64
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Debug|x64.Build.0 = Debug|Any CPU
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Debug|x86.Build.0 = Debug|Any CPU
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Release|Any CPU.Build.0 = Release|Any CPU
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Release|x64.ActiveCfg = Release|Any CPU
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Release|x64.Build.0 = Release|Any CPU
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Release|x86.ActiveCfg = Release|Any CPU
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9}.Release|x86.Build.0 = Release|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Debug|x64.Build.0 = Debug|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Debug|x86.Build.0 = Debug|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Release|Any CPU.Build.0 = Release|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Release|x64.ActiveCfg = Release|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Release|x64.Build.0 = Release|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Release|x86.ActiveCfg = Release|Any CPU
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB}.Release|x86.Build.0 = Release|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Debug|x64.Build.0 = Debug|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Debug|x86.Build.0 = Debug|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Release|x64.ActiveCfg = Release|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Release|x64.Build.0 = Release|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Release|x86.ActiveCfg = Release|Any CPU
+ {51F770AF-C0C6-4247-A358-82DF323F473D}.Release|x86.Build.0 = Release|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Debug|x64.Build.0 = Debug|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Debug|x86.Build.0 = Debug|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Release|Any CPU.Build.0 = Release|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Release|x64.ActiveCfg = Release|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Release|x64.Build.0 = Release|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Release|x86.ActiveCfg = Release|Any CPU
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4}.Release|x86.Build.0 = Release|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Debug|x64.Build.0 = Debug|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Debug|x86.Build.0 = Debug|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Release|Any CPU.Build.0 = Release|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Release|x64.ActiveCfg = Release|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Release|x64.Build.0 = Release|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Release|x86.ActiveCfg = Release|Any CPU
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB}.Release|x86.Build.0 = Release|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Debug|x64.Build.0 = Debug|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Debug|x86.Build.0 = Debug|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Release|Any CPU.Build.0 = Release|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Release|x64.ActiveCfg = Release|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Release|x64.Build.0 = Release|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Release|x86.ActiveCfg = Release|Any CPU
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247}.Release|x86.Build.0 = Release|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Debug|x64.Build.0 = Debug|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Debug|x86.Build.0 = Debug|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Release|Any CPU.Build.0 = Release|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Release|x64.ActiveCfg = Release|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Release|x64.Build.0 = Release|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Release|x86.ActiveCfg = Release|Any CPU
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8}.Release|x86.Build.0 = Release|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Debug|x64.Build.0 = Debug|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Debug|x86.Build.0 = Debug|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Release|x64.ActiveCfg = Release|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Release|x64.Build.0 = Release|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Release|x86.ActiveCfg = Release|Any CPU
+ {F80D5395-28E3-4C34-9662-A890A215DDA2}.Release|x86.Build.0 = Release|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Debug|x64.Build.0 = Debug|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Debug|x86.Build.0 = Debug|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Release|Any CPU.Build.0 = Release|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Release|x64.ActiveCfg = Release|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Release|x64.Build.0 = Release|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Release|x86.ActiveCfg = Release|Any CPU
+ {90A38896-993A-49F1-903B-8C989D8C9B3A}.Release|x86.Build.0 = Release|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Debug|x64.Build.0 = Debug|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Debug|x86.Build.0 = Debug|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Release|Any CPU.Build.0 = Release|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Release|x64.ActiveCfg = Release|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Release|x64.Build.0 = Release|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Release|x86.ActiveCfg = Release|Any CPU
+ {6AE504F8-734B-456B-8BEA-DE37639CB3A7}.Release|x86.Build.0 = Release|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Debug|x64.Build.0 = Debug|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Debug|x86.Build.0 = Debug|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Release|Any CPU.Build.0 = Release|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Release|x64.ActiveCfg = Release|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Release|x64.Build.0 = Release|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Release|x86.ActiveCfg = Release|Any CPU
+ {7E15D295-B938-409C-98F6-A22ABC7F3005}.Release|x86.Build.0 = Release|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Debug|x64.Build.0 = Debug|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Debug|x86.Build.0 = Debug|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Release|Any CPU.Build.0 = Release|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Release|x64.ActiveCfg = Release|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Release|x64.Build.0 = Release|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Release|x86.ActiveCfg = Release|Any CPU
+ {D632374A-70A1-4954-8F2D-C0B511A24426}.Release|x86.Build.0 = Release|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Debug|x64.Build.0 = Debug|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Debug|x86.Build.0 = Debug|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Release|Any CPU.Build.0 = Release|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Release|x64.ActiveCfg = Release|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Release|x64.Build.0 = Release|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Release|x86.ActiveCfg = Release|Any CPU
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB}.Release|x86.Build.0 = Release|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Debug|x64.Build.0 = Debug|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Debug|x86.Build.0 = Debug|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Release|Any CPU.Build.0 = Release|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Release|x64.ActiveCfg = Release|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Release|x64.Build.0 = Release|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Release|x86.ActiveCfg = Release|Any CPU
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6}.Release|x86.Build.0 = Release|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Debug|x64.Build.0 = Debug|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Debug|x86.Build.0 = Debug|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Release|Any CPU.Build.0 = Release|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Release|x64.ActiveCfg = Release|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Release|x64.Build.0 = Release|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Release|x86.ActiveCfg = Release|Any CPU
+ {7F36D200-FE91-4761-B681-BEE091FB953F}.Release|x86.Build.0 = Release|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Debug|x64.Build.0 = Debug|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Debug|x86.Build.0 = Debug|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Release|Any CPU.Build.0 = Release|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Release|x64.ActiveCfg = Release|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Release|x64.Build.0 = Release|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Release|x86.ActiveCfg = Release|Any CPU
+ {69CCB780-50CC-4E75-B794-932E44ACA80F}.Release|x86.Build.0 = Release|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Debug|x64.Build.0 = Debug|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Debug|x86.Build.0 = Debug|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Release|Any CPU.Build.0 = Release|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Release|x64.ActiveCfg = Release|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Release|x64.Build.0 = Release|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Release|x86.ActiveCfg = Release|Any CPU
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A}.Release|x86.Build.0 = Release|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Debug|x64.Build.0 = Debug|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Debug|x86.Build.0 = Debug|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Release|Any CPU.Build.0 = Release|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Release|x64.ActiveCfg = Release|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Release|x64.Build.0 = Release|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Release|x86.ActiveCfg = Release|Any CPU
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A}.Release|x86.Build.0 = Release|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Debug|x64.Build.0 = Debug|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Debug|x86.Build.0 = Debug|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Release|Any CPU.Build.0 = Release|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Release|x64.ActiveCfg = Release|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Release|x64.Build.0 = Release|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Release|x86.ActiveCfg = Release|Any CPU
+ {0E6CF267-14FD-43D7-81CB-EE020FD1D106}.Release|x86.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {93D00F03-02FF-4C2A-8917-6863D6E633D9} = {32C0F9AC-AF7D-4476-A269-99ACA000EF9F}
+ {14CAF7A1-A5C3-4ED1-8BF3-20FC3447BFFB} = {32C0F9AC-AF7D-4476-A269-99ACA000EF9F}
+ {51F770AF-C0C6-4247-A358-82DF323F473D} = {32C0F9AC-AF7D-4476-A269-99ACA000EF9F}
+ {8A8E8B67-9351-471E-A502-AF7FAE596CB4} = {32C0F9AC-AF7D-4476-A269-99ACA000EF9F}
+ {5DE8D878-EEBD-44DF-A8FC-0B4866B807FB} = {32C0F9AC-AF7D-4476-A269-99ACA000EF9F}
+ {567DABFB-611E-4779-9F39-1D4A5B8F0247} = {32C0F9AC-AF7D-4476-A269-99ACA000EF9F}
+ {28AFDFEF-7597-4450-B999-87C22C24DCD8} = {32C0F9AC-AF7D-4476-A269-99ACA000EF9F}
+ {F80D5395-28E3-4C34-9662-A890A215DDA2} = {32C0F9AC-AF7D-4476-A269-99ACA000EF9F}
+ {7E15D295-B938-409C-98F6-A22ABC7F3005} = {AAAA5609-D8C1-401E-BB5C-724EFE3955FB}
+ {D632374A-70A1-4954-8F2D-C0B511A24426} = {FBC6F613-4E0B-4A90-8854-31887A796EEF}
+ {91E41EE3-687B-4CFD-94C4-028D09BACFAB} = {FBC6F613-4E0B-4A90-8854-31887A796EEF}
+ {4D411F2D-A97D-4485-A318-ED98B96B6CF6} = {FBC6F613-4E0B-4A90-8854-31887A796EEF}
+ {7F36D200-FE91-4761-B681-BEE091FB953F} = {FBC6F613-4E0B-4A90-8854-31887A796EEF}
+ {69CCB780-50CC-4E75-B794-932E44ACA80F} = {FBC6F613-4E0B-4A90-8854-31887A796EEF}
+ {C087F8AC-B438-4980-9A79-1E16D0CFB67A} = {FBC6F613-4E0B-4A90-8854-31887A796EEF}
+ {E04E5F37-8F13-4000-ABA1-DAC0D795EA6A} = {FBC6F613-4E0B-4A90-8854-31887A796EEF}
+ EndGlobalSection
+EndGlobal
diff --git a/LibMatrix/Extensions/CanonicalJsonSerializer.cs b/LibMatrix/Extensions/CanonicalJsonSerializer.cs
index a6fbcf4..ae535aa 100644
--- a/LibMatrix/Extensions/CanonicalJsonSerializer.cs
+++ b/LibMatrix/Extensions/CanonicalJsonSerializer.cs
@@ -1,19 +1,15 @@
using System.Collections.Frozen;
using System.Reflection;
-using System.Security.Cryptography;
-using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
-using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
-using System.Text.Unicode;
using ArcaneLibs.Extensions;
namespace LibMatrix.Extensions;
public static class CanonicalJsonSerializer {
// TODO: Alphabetise dictionaries
- private static JsonSerializerOptions _options => new() {
+ private static JsonSerializerOptions JsonOptions => new() {
WriteIndented = false,
Encoder = UnicodeJsonEncoder.Singleton,
};
@@ -24,7 +20,7 @@ public static class CanonicalJsonSerializer {
.ToFrozenSet();
private static JsonSerializerOptions MergeOptions(JsonSerializerOptions? inputOptions) {
- var newOptions = _options;
+ var newOptions = JsonOptions;
if (inputOptions == null)
return newOptions;
@@ -48,7 +44,7 @@ public static class CanonicalJsonSerializer {
public static String Serialize<TValue>(TValue value, JsonSerializerOptions? options = null) {
var newOptions = MergeOptions(options);
- return System.Text.Json.JsonSerializer.SerializeToNode(value, options) // We want to allow passing custom converters for eg. double/float -> string here...
+ return JsonSerializer.SerializeToNode(value, options) // We want to allow passing custom converters for eg. double/float -> string here...
.SortProperties()!
.CanonicalizeNumbers()!
.ToJsonString(newOptions);
@@ -58,13 +54,22 @@ public static class CanonicalJsonSerializer {
}
- public static String Serialize(object value, Type inputType, JsonSerializerOptions? options = null) => JsonSerializer.Serialize(value, inputType, _options);
+ public static String Serialize(object value, Type inputType, JsonSerializerOptions? options = null) => JsonSerializer.Serialize(value, inputType, JsonOptions);
// public static String Serialize<TValue>(TValue value, JsonTypeInfo<TValue> jsonTypeInfo) => JsonSerializer.Serialize(value, jsonTypeInfo, _options);
// public static String Serialize(Object value, JsonTypeInfo jsonTypeInfo)
+ public static byte[] SerializeToUtf8Bytes<T>(T value, JsonSerializerOptions? options = null) {
+ var newOptions = MergeOptions(null);
+ return JsonSerializer.SerializeToNode(value, options) // We want to allow passing custom converters for eg. double/float -> string here...
+ .SortProperties()!
+ .CanonicalizeNumbers()!
+ .ToJsonString(newOptions).AsBytes().ToArray();
+ }
+
#endregion
- private static partial class JsonExtensions {
+ // ReSharper disable once UnusedType.Local
+ private static class JsonExtensions {
public static Action<JsonTypeInfo> AlphabetizeProperties(Type type) {
return typeInfo => {
if (typeInfo.Kind != JsonTypeInfoKind.Object || !type.IsAssignableFrom(typeInfo.Type))
diff --git a/LibMatrix/Extensions/EnumerableExtensions.cs b/LibMatrix/Extensions/EnumerableExtensions.cs
index 42d9491..4dcf26e 100644
--- a/LibMatrix/Extensions/EnumerableExtensions.cs
+++ b/LibMatrix/Extensions/EnumerableExtensions.cs
@@ -1,29 +1,86 @@
+using System.Collections.Frozen;
+using System.Collections.Immutable;
+
namespace LibMatrix.Extensions;
public static class EnumerableExtensions {
public static void MergeStateEventLists(this IList<StateEvent> oldState, IList<StateEvent> newState) {
- foreach (var stateEvent in newState) {
- var old = oldState.FirstOrDefault(x => x.Type == stateEvent.Type && x.StateKey == stateEvent.StateKey);
- if (old is null) {
- oldState.Add(stateEvent);
- continue;
+ // foreach (var stateEvent in newState) {
+ // var old = oldState.FirstOrDefault(x => x.Type == stateEvent.Type && x.StateKey == stateEvent.StateKey);
+ // if (old is null) {
+ // oldState.Add(stateEvent);
+ // continue;
+ // }
+ //
+ // oldState.Remove(old);
+ // oldState.Add(stateEvent);
+ // }
+
+ foreach (var e in newState) {
+ switch (FindIndex(e)) {
+ case -1:
+ oldState.Add(e);
+ break;
+ case var index:
+ oldState[index] = e;
+ break;
+ }
+ }
+
+ int FindIndex(StateEvent needle) {
+ for (int i = 0; i < oldState.Count; i++) {
+ var old = oldState[i];
+ if (old.Type == needle.Type && old.StateKey == needle.StateKey)
+ return i;
}
- oldState.Remove(old);
- oldState.Add(stateEvent);
+ return -1;
}
}
public static void MergeStateEventLists(this IList<StateEventResponse> oldState, IList<StateEventResponse> newState) {
- foreach (var stateEvent in newState) {
- var old = oldState.FirstOrDefault(x => x.Type == stateEvent.Type && x.StateKey == stateEvent.StateKey);
- if (old is null) {
- oldState.Add(stateEvent);
- continue;
+ foreach (var e in newState) {
+ switch (FindIndex(e)) {
+ case -1:
+ oldState.Add(e);
+ break;
+ case var index:
+ oldState[index] = e;
+ break;
+ }
+ }
+
+ int FindIndex(StateEventResponse needle) {
+ for (int i = 0; i < oldState.Count; i++) {
+ var old = oldState[i];
+ if (old.Type == needle.Type && old.StateKey == needle.StateKey)
+ return i;
+ }
+
+ return -1;
+ }
+ }
+
+ public static void MergeStateEventLists(this List<StateEventResponse> oldState, List<StateEventResponse> newState) {
+ foreach (var e in newState) {
+ switch (FindIndex(e)) {
+ case -1:
+ oldState.Add(e);
+ break;
+ case var index:
+ oldState[index] = e;
+ break;
+ }
+ }
+
+ int FindIndex(StateEventResponse needle) {
+ for (int i = 0; i < oldState.Count; i++) {
+ var old = oldState[i];
+ if (old.Type == needle.Type && old.StateKey == needle.StateKey)
+ return i;
}
- oldState.Remove(old);
- oldState.Add(stateEvent);
+ return -1;
}
}
}
\ No newline at end of file
diff --git a/LibMatrix/Extensions/JsonElementExtensions.cs b/LibMatrix/Extensions/JsonElementExtensions.cs
index c4ed743..dfec95b 100644
--- a/LibMatrix/Extensions/JsonElementExtensions.cs
+++ b/LibMatrix/Extensions/JsonElementExtensions.cs
@@ -126,6 +126,7 @@ public static class JsonElementExtensions {
$"Encountered dictionary {field.Name} with key type {keyType.Name} and value type {valueType.Name}!");
return field.Value.EnumerateObject()
+ // TODO: use key.Value?
.Where(key => !valueType.IsPrimitive && valueType != typeof(string))
.Aggregate(false, (current, key) =>
current | key.FindExtraJsonPropertyFieldsByValueKind(containerType, valueType)
diff --git a/LibMatrix/Extensions/MatrixHttpClient.Multi.cs b/LibMatrix/Extensions/MatrixHttpClient.Multi.cs
index e7a2044..bf6fe63 100644
--- a/LibMatrix/Extensions/MatrixHttpClient.Multi.cs
+++ b/LibMatrix/Extensions/MatrixHttpClient.Multi.cs
@@ -1,16 +1,5 @@
#define SINGLE_HTTPCLIENT // Use a single HttpClient instance for all MatrixHttpClient instances
// #define SYNC_HTTPCLIENT // Only allow one request as a time, for debugging
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Net.Http.Headers;
-using System.Reflection;
-using System.Security.Cryptography.X509Certificates;
-using System.Text;
-using System.Text.Json;
-using System.Text.Json.Serialization;
-using ArcaneLibs;
-using ArcaneLibs.Extensions;
-
namespace LibMatrix.Extensions;
public static class HttpClientExtensions {
diff --git a/LibMatrix/Extensions/MatrixHttpClient.Single.cs b/LibMatrix/Extensions/MatrixHttpClient.Single.cs
index 39eb7e5..671566f 100644
--- a/LibMatrix/Extensions/MatrixHttpClient.Single.cs
+++ b/LibMatrix/Extensions/MatrixHttpClient.Single.cs
@@ -1,20 +1,21 @@
#define SINGLE_HTTPCLIENT // Use a single HttpClient instance for all MatrixHttpClient instances
-// #define SYNC_HTTPCLIENT // Only allow one request as a time, for debugging
+// #define SYNC_HTTPCLIENT // Only allow one request as a time, for debugging
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
+using System.Net;
using System.Net.Http.Headers;
using System.Reflection;
-using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using ArcaneLibs;
using ArcaneLibs.Extensions;
+using LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Requests;
namespace LibMatrix.Extensions;
#if SINGLE_HTTPCLIENT
-// TODO: Add URI wrapper for
+// TODO: Add URI wrapper for
public class MatrixHttpClient {
private static readonly HttpClient Client;
@@ -50,6 +51,7 @@ public class MatrixHttpClient {
internal SemaphoreSlim _rateLimitSemaphore { get; } = new(1, 1);
#endif
+ public static bool LogRequests = true;
public Dictionary<string, string> AdditionalQueryParameters { get; set; } = new();
public Uri? BaseAddress { get; set; }
@@ -59,7 +61,7 @@ public class MatrixHttpClient {
typeof(HttpRequestHeaders).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, [], null)?.Invoke([]) as HttpRequestHeaders ??
throw new InvalidOperationException("Failed to create HttpRequestHeaders");
- private JsonSerializerOptions GetJsonSerializerOptions(JsonSerializerOptions? options = null) {
+ private static JsonSerializerOptions GetJsonSerializerOptions(JsonSerializerOptions? options = null) {
options ??= new JsonSerializerOptions();
options.Converters.Add(new JsonFloatStringConverter());
options.Converters.Add(new JsonDoubleStringConverter());
@@ -68,27 +70,54 @@ public class MatrixHttpClient {
return options;
}
- public async Task<HttpResponseMessage> SendUnhandledAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
+ public async Task<HttpResponseMessage> SendUnhandledAsync(HttpRequestMessage request, CancellationToken cancellationToken, int attempt = 0) {
+ if (request.RequestUri is null) throw new NullReferenceException("RequestUri is null");
+ // if (!request.RequestUri.IsAbsoluteUri)
+ request.RequestUri = request.RequestUri.EnsureAbsolute(BaseAddress!);
+ var swWait = Stopwatch.StartNew();
#if SYNC_HTTPCLIENT
await _rateLimitSemaphore.WaitAsync(cancellationToken);
#endif
- Console.WriteLine($"Sending {request.Method} {BaseAddress}{request.RequestUri} ({Util.BytesToString(request.Content?.Headers.ContentLength ?? 0)})");
-
if (request.RequestUri is null) throw new NullReferenceException("RequestUri is null");
- if (!request.RequestUri.IsAbsoluteUri) request.RequestUri = new Uri(BaseAddress, request.RequestUri);
+ if (!request.RequestUri.IsAbsoluteUri)
+ request.RequestUri = new Uri(BaseAddress ?? throw new InvalidOperationException("Relative URI passed, but no BaseAddress is specified!"), request.RequestUri);
+ swWait.Stop();
+ var swExec = Stopwatch.StartNew();
+
foreach (var (key, value) in AdditionalQueryParameters) request.RequestUri = request.RequestUri.AddQuery(key, value);
- foreach (var (key, value) in DefaultRequestHeaders) request.Headers.Add(key, value);
+ foreach (var (key, value) in DefaultRequestHeaders) {
+ if (request.Headers.Contains(key)) continue;
+ request.Headers.Add(key, value);
+ }
request.Options.Set(new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse"), true);
+ if (LogRequests)
+ Console.WriteLine("Sending " + request.Summarise(includeHeaders: true, includeQuery: true, includeContentIfText: false, hideHeaders: ["Accept"]));
+
HttpResponseMessage? responseMessage;
try {
responseMessage = await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
}
catch (Exception e) {
- Console.WriteLine(
- $"Failed to send request {request.Method} {BaseAddress}{request.RequestUri} ({Util.BytesToString(request.Content?.Headers.ContentLength ?? 0)}):\n{e}");
+ // if (attempt >= 5) {
+ // Console.WriteLine(
+ // $"Failed to send request {request.Method} {BaseAddress}{request.RequestUri} ({Util.BytesToString(request.Content?.Headers.ContentLength ?? 0)}):\n{e}");
+ // throw;
+ // }
+ //
+ // if (e is TaskCanceledException or TimeoutException or HttpRequestException) {
+ // if (request.Method == HttpMethod.Get && !cancellationToken.IsCancellationRequested) {
+ // await Task.Delay(Random.Shared.Next(100, 1000), cancellationToken);
+ // request.ResetSendStatus();
+ // return await SendUnhandledAsync(request, cancellationToken, attempt + 1);
+ // }
+ // }
+ // else if (!e.ToString().StartsWith("TypeError: NetworkError"))
+ // Console.WriteLine(
+ // $"Failed to send request {request.Method} {BaseAddress}{request.RequestUri} ({Util.BytesToString(request.Content?.Headers.ContentLength ?? 0)}):\n{e}");
+
throw;
}
#if SYNC_HTTPCLIENT
@@ -97,8 +126,26 @@ public class MatrixHttpClient {
}
#endif
- Console.WriteLine(
- $"Sending {request.Method} {request.RequestUri} ({Util.BytesToString(request.Content?.Headers.ContentLength ?? 0)}) -> {(int)responseMessage.StatusCode} {responseMessage.StatusCode} ({Util.BytesToString(responseMessage.Content.Headers.ContentLength ?? 0)})");
+ // Console.WriteLine($"Sending {request.Method} {request.RequestUri} ({Util.BytesToString(request.Content?.Headers.ContentLength ?? 0)}) -> {(int)responseMessage.StatusCode} {responseMessage.StatusCode} ({Util.BytesToString(responseMessage.GetContentLength())}, WAIT={swWait.ElapsedMilliseconds}ms, EXEC={swExec.ElapsedMilliseconds}ms)");
+ if (LogRequests)
+ Console.WriteLine("Received " + responseMessage.Summarise(includeHeaders: true, includeContentIfText: false, hideHeaders: [
+ "Server",
+ "Date",
+ "Transfer-Encoding",
+ "Connection",
+ "Vary",
+ "Content-Length",
+ "Access-Control-Allow-Origin",
+ "Access-Control-Allow-Methods",
+ "Access-Control-Allow-Headers",
+ "Access-Control-Expose-Headers",
+ "Cache-Control",
+ "Cross-Origin-Resource-Policy",
+ "X-Content-Security-Policy",
+ "Referrer-Policy",
+ "X-Robots-Tag",
+ "Content-Security-Policy"
+ ]));
return responseMessage;
}
@@ -107,6 +154,12 @@ public class MatrixHttpClient {
var responseMessage = await SendUnhandledAsync(request, cancellationToken);
if (responseMessage.IsSuccessStatusCode) return responseMessage;
+ //retry on gateway timeout
+ // if (responseMessage.StatusCode == HttpStatusCode.GatewayTimeout) {
+ // request.ResetSendStatus();
+ // return await SendAsync(request, cancellationToken);
+ // }
+
//error handling
var content = await responseMessage.Content.ReadAsStringAsync(cancellationToken);
if (content.Length == 0)
@@ -114,10 +167,15 @@ public class MatrixHttpClient {
ErrorCode = "M_UNKNOWN",
Error = "Unknown error, server returned no content"
};
- if (!content.StartsWith('{')) throw new InvalidDataException("Encountered invalid data:\n" + content);
+
+ // if (!content.StartsWith('{')) throw new InvalidDataException("Encountered invalid data:\n" + content);
+ if (!content.TrimStart().StartsWith('{')) {
+ responseMessage.EnsureSuccessStatusCode();
+ throw new InvalidDataException("Encountered invalid data:\n" + content);
+ }
//we have a matrix error
- MatrixException? ex = null;
+ MatrixException? ex;
try {
ex = JsonSerializer.Deserialize<MatrixException>(content);
}
@@ -131,7 +189,7 @@ public class MatrixHttpClient {
Debug.Assert(ex != null, nameof(ex) + " != null");
ex.RawContent = content;
// Console.WriteLine($"Failed to send request: {ex}");
- if (ex?.RetryAfterMs is null) throw ex!;
+ if (ex.RetryAfterMs is null) throw ex!;
//we have a ratelimit error
await Task.Delay(ex.RetryAfterMs.Value, cancellationToken);
request.ResetSendStatus();
@@ -170,7 +228,7 @@ public class MatrixHttpClient {
}
// GetStreamAsync
- public new async Task<Stream> GetStreamAsync(string requestUri, CancellationToken cancellationToken = default) {
+ public async Task<Stream> GetStreamAsync(string requestUri, CancellationToken cancellationToken = default) {
var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await SendAsync(request, cancellationToken);
@@ -209,7 +267,7 @@ public class MatrixHttpClient {
await foreach (var resp in result) yield return resp;
}
- public async Task<bool> CheckSuccessStatus(string url) {
+ public static async Task<bool> CheckSuccessStatus(string url) {
//cors causes failure, try to catch
try {
var resp = await Client.GetAsync(url);
@@ -227,5 +285,17 @@ public class MatrixHttpClient {
};
return await SendAsync(request, cancellationToken);
}
+
+ public async Task<HttpResponseMessage> DeleteAsync(string url) {
+ var request = new HttpRequestMessage(HttpMethod.Delete, url);
+ return await SendAsync(request);
+ }
+
+ public async Task<HttpResponseMessage> DeleteAsJsonAsync<T>(string url, T payload) {
+ var request = new HttpRequestMessage(HttpMethod.Delete, url) {
+ Content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json")
+ };
+ return await SendAsync(request);
+ }
}
#endif
\ No newline at end of file
diff --git a/LibMatrix/Filters/SyncFilter.cs b/LibMatrix/Filters/SyncFilter.cs
index 787ffa7..7cb6428 100644
--- a/LibMatrix/Filters/SyncFilter.cs
+++ b/LibMatrix/Filters/SyncFilter.cs
@@ -34,6 +34,15 @@ public class SyncFilter {
[JsonPropertyName("include_leave")]
public bool? IncludeLeave { get; set; }
+ private static RoomFilter Empty => new() {
+ Rooms = [],
+ IncludeLeave = false,
+ AccountData = StateFilter.Empty,
+ Ephemeral = StateFilter.Empty,
+ State = StateFilter.Empty,
+ Timeline = StateFilter.Empty,
+ };
+
public class StateFilter(
bool? containsUrl = null,
bool? includeRedundantMembers = null,
@@ -65,6 +74,9 @@ public class SyncFilter {
[JsonPropertyName("unread_thread_notifications")]
public bool? UnreadThreadNotifications { get; set; } = unreadThreadNotifications;
+
+ // ReSharper disable once MemberHidesStaticFromOuterClass
+ public new static StateFilter Empty => new(limit: 0, senders: [], types: [], rooms: []);
}
}
@@ -83,5 +95,7 @@ public class SyncFilter {
[JsonPropertyName("not_senders")]
public List<string>? NotSenders { get; set; } = notSenders;
+
+ public static EventFilter Empty => new(limit: 0, senders: [], types: []);
}
-}
\ No newline at end of file
+}
diff --git a/LibMatrix/Helpers/MessageBuilder.cs b/LibMatrix/Helpers/MessageBuilder.cs
index d897078..6f55739 100644
--- a/LibMatrix/Helpers/MessageBuilder.cs
+++ b/LibMatrix/Helpers/MessageBuilder.cs
@@ -10,9 +10,9 @@ public class MessageBuilder(string msgType = "m.text", string format = "org.matr
public RoomMessageEventContent Build() => Content;
- public MessageBuilder WithBody(string body) {
+ public MessageBuilder WithBody(string body, string? formattedBody = null) {
Content.Body += body;
- Content.FormattedBody += body;
+ Content.FormattedBody += formattedBody ?? body;
return this;
}
@@ -37,6 +37,10 @@ public class MessageBuilder(string msgType = "m.text", string format = "org.matr
return this;
}
+ public static string GetColoredBody(string color, string body) {
+ return $"<font color=\"{color}\">{body}</font>";
+ }
+
public MessageBuilder WithColoredBody(string color, string body) {
Content.Body += body;
Content.FormattedBody += $"<font color=\"{color}\">{body}</font>";
@@ -91,16 +95,38 @@ public class MessageBuilder(string msgType = "m.text", string format = "org.matr
return this;
}
+ public MessageBuilder WithMention(string id, string? displayName = null) {
+ Content.Body += $"@{displayName ?? id}";
+ Content.FormattedBody += $"<a href=\"https://matrix.to/#/{id}\">{displayName ?? id}</a>";
+ if (id == "@room") {
+ Content.Mentions ??= new();
+ Content.Mentions.Room = true;
+ }
+ else if (id.StartsWith('@')) {
+ Content.Mentions ??= new();
+ Content.Mentions.Users ??= new();
+ Content.Mentions.Users.Add(id);
+ }
+
+ return this;
+ }
+
+ public MessageBuilder WithNewline() {
+ Content.Body += "\n";
+ Content.FormattedBody += "<br>";
+ return this;
+ }
+
public MessageBuilder WithTable(Action<TableBuilder> tableBuilder) {
var tb = new TableBuilder(this);
- this.WithHtmlTag("table", msb => tableBuilder(tb));
+ WithHtmlTag("table", msb => tableBuilder(tb));
return this;
}
public class TableBuilder(MessageBuilder msb) {
public TableBuilder WithTitle(string title, int colspan) {
msb.Content.Body += title + "\n";
- msb.Content.FormattedBody += $"<thead><tr><th colspan=\"{colspan}\">{title}</th></tr></thead>";
+ msb.Content.FormattedBody += $"<thead><tr><th colspan=\"{colspan}\">{title}</th></tr></thead><br/>";
return this;
}
diff --git a/LibMatrix/Helpers/RoomBuilder.cs b/LibMatrix/Helpers/RoomBuilder.cs
new file mode 100644
index 0000000..bef7568
--- /dev/null
+++ b/LibMatrix/Helpers/RoomBuilder.cs
@@ -0,0 +1,173 @@
+using System.Runtime.Intrinsics.X86;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
+using LibMatrix.Homeservers;
+using LibMatrix.Responses;
+using LibMatrix.RoomTypes;
+
+namespace LibMatrix.Helpers;
+
+public class RoomBuilder {
+ public string? Type { get; set; }
+ public string Version { get; set; } = "11";
+ public RoomNameEventContent Name { get; set; } = new();
+ public RoomTopicEventContent Topic { get; set; } = new();
+ public RoomAvatarEventContent Avatar { get; set; } = new();
+ public RoomCanonicalAliasEventContent CanonicalAlias { get; set; } = new();
+ public string AliasLocalPart { get; set; } = string.Empty;
+ public bool IsFederatable { get; set; } = true;
+ public long OwnPowerLevel { get; set; } = MatrixConstants.MaxSafeJsonInteger;
+
+ public RoomJoinRulesEventContent JoinRules { get; set; } = new() {
+ JoinRule = RoomJoinRulesEventContent.JoinRules.Public
+ };
+
+ public RoomHistoryVisibilityEventContent HistoryVisibility { get; set; } = new() {
+ HistoryVisibility = RoomHistoryVisibilityEventContent.HistoryVisibilityTypes.Shared
+ };
+
+ /// <summary>
+ /// State events to be sent *before* room access is configured. Keep this small!
+ /// </summary>
+ public List<StateEvent> ImportantState { get; set; } = [];
+
+ /// <summary>
+ /// State events to be sent *after* room access is configured, but before invites are sent.
+ /// </summary>
+ public List<StateEvent> InitialState { get; set; } = [];
+
+ /// <summary>
+ /// Users to invite, with optional reason
+ /// </summary>
+ public Dictionary<string, string?> Invites { get; set; } = new();
+
+ public RoomPowerLevelEventContent PowerLevels { get; init; } = new() {
+ EventsDefault = 0,
+ UsersDefault = 0,
+ Kick = 50,
+ Invite = 50,
+ Ban = 50,
+ Redact = 50,
+ StateDefault = 50,
+ NotificationsPl = new() {
+ Room = 50
+ },
+ Users = [],
+ Events = new Dictionary<string, long> {
+ { RoomAvatarEventContent.EventId, 50 },
+ { RoomCanonicalAliasEventContent.EventId, 50 },
+ { RoomEncryptionEventContent.EventId, 100 },
+ { RoomHistoryVisibilityEventContent.EventId, 100 },
+ { RoomNameEventContent.EventId, 50 },
+ { RoomPowerLevelEventContent.EventId, 100 },
+ { RoomServerAclEventContent.EventId, 100 },
+ { RoomTombstoneEventContent.EventId, 100 },
+ { RoomPolicyServerEventContent.EventId, 100 }
+ }
+ };
+
+ public async Task<GenericRoom> Create(AuthenticatedHomeserverGeneric homeserver) {
+ var crq = new CreateRoomRequest() {
+ PowerLevelContentOverride = new() {
+ EventsDefault = 1000000,
+ UsersDefault = 1000000,
+ Kick = 1000000,
+ Invite = 1000000,
+ Ban = 1000000,
+ Redact = 1000000,
+ StateDefault = 1000000,
+ NotificationsPl = new() {
+ Room = 1000000
+ },
+ Users = new Dictionary<string, long>() {
+ { homeserver.WhoAmI.UserId, MatrixConstants.MaxSafeJsonInteger }
+ },
+ Events = new Dictionary<string, long> {
+ { RoomAvatarEventContent.EventId, 1000000 },
+ { RoomCanonicalAliasEventContent.EventId, 1000000 },
+ { RoomEncryptionEventContent.EventId, 1000000 },
+ { RoomHistoryVisibilityEventContent.EventId, 1000000 },
+ { RoomNameEventContent.EventId, 1000000 },
+ { RoomPowerLevelEventContent.EventId, 1000000 },
+ { RoomServerAclEventContent.EventId, 1000000 },
+ { RoomTombstoneEventContent.EventId, 1000000 },
+ { RoomPolicyServerEventContent.EventId, 1000000 }
+ }
+ },
+ Visibility = "private",
+ RoomVersion = Version
+ };
+
+ if (!string.IsNullOrWhiteSpace(Type))
+ crq.CreationContent.Add("type", Type);
+
+ if (!IsFederatable)
+ crq.CreationContent.Add("m.federate", false);
+
+ var room = await homeserver.CreateRoom(crq);
+
+ await SetBasicRoomInfoAsync(room);
+ await SetStatesAsync(room, ImportantState);
+ await SetAccessAsync(room);
+ await SetStatesAsync(room, InitialState);
+ await SendInvites(room);
+
+ return room;
+ }
+
+ private async Task SendInvites(GenericRoom room) {
+ if (Invites.Count == 0) return;
+
+ var inviteTasks = Invites.Select(async kvp => {
+ try {
+ await room.InviteUserAsync(kvp.Key, kvp.Value);
+ }
+ catch (MatrixException e) {
+ Console.Error.WriteLine("Failed to invite {0} to {1}: {2}", kvp.Key, room.RoomId, e.Message);
+ }
+ });
+
+ await Task.WhenAll(inviteTasks);
+ }
+
+ private async Task SetStatesAsync(GenericRoom room, List<StateEvent> state) {
+ foreach (var ev in state) {
+ await (string.IsNullOrWhiteSpace(ev.StateKey)
+ ? room.SendStateEventAsync(ev.Type, ev.RawContent)
+ : room.SendStateEventAsync(ev.Type, ev.StateKey, ev.RawContent));
+ }
+ }
+
+ private async Task SetBasicRoomInfoAsync(GenericRoom room) {
+ if (!string.IsNullOrWhiteSpace(Name.Name))
+ await room.SendStateEventAsync(RoomNameEventContent.EventId, Name);
+
+ if (!string.IsNullOrWhiteSpace(Topic.Topic))
+ await room.SendStateEventAsync(RoomTopicEventContent.EventId, Topic);
+
+ if (!string.IsNullOrWhiteSpace(Avatar.Url))
+ await room.SendStateEventAsync(RoomAvatarEventContent.EventId, Avatar);
+
+ if (!string.IsNullOrWhiteSpace(AliasLocalPart))
+ CanonicalAlias.Alias = $"#{AliasLocalPart}:{room.Homeserver.ServerName}";
+
+ if (!string.IsNullOrWhiteSpace(CanonicalAlias.Alias)) {
+ await room.Homeserver.SetRoomAliasAsync(CanonicalAlias.Alias!, room.RoomId);
+ await room.SendStateEventAsync(RoomCanonicalAliasEventContent.EventId, CanonicalAlias);
+ }
+ }
+
+ private async Task SetAccessAsync(GenericRoom room) {
+ PowerLevels.Users![room.Homeserver.WhoAmI.UserId] = OwnPowerLevel;
+ await room.SendStateEventAsync(RoomPowerLevelEventContent.EventId, PowerLevels);
+
+ if (!string.IsNullOrWhiteSpace(HistoryVisibility.HistoryVisibility))
+ await room.SendStateEventAsync(RoomHistoryVisibilityEventContent.EventId, HistoryVisibility);
+
+ if (!string.IsNullOrWhiteSpace(JoinRules.JoinRuleValue))
+ await room.SendStateEventAsync(RoomJoinRulesEventContent.EventId, JoinRules);
+ }
+}
+
+public class MatrixConstants {
+ public const long MaxSafeJsonInteger = 9007199254740991L; // 2^53 - 1
+}
\ No newline at end of file
diff --git a/LibMatrix/Helpers/SyncHelper.cs b/LibMatrix/Helpers/SyncHelper.cs
index 1833bd0..c8e2928 100644
--- a/LibMatrix/Helpers/SyncHelper.cs
+++ b/LibMatrix/Helpers/SyncHelper.cs
@@ -1,22 +1,56 @@
using System.Diagnostics;
using System.Net.Http.Json;
+using System.Reflection;
+using System.Text.Json;
+using ArcaneLibs.Collections;
+using System.Text.Json.Nodes;
using ArcaneLibs.Extensions;
using LibMatrix.Filters;
+using LibMatrix.Helpers.SyncProcessors;
using LibMatrix.Homeservers;
+using LibMatrix.Interfaces.Services;
using LibMatrix.Responses;
using Microsoft.Extensions.Logging;
namespace LibMatrix.Helpers;
-public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, ILogger? logger = null) {
+public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, ILogger? logger = null, IStorageProvider? storageProvider = null) {
+ private readonly Func<SyncResponse?, Task<SyncResponse?>> _msc4222EmulationSyncProcessor = new Msc4222EmulationSyncProcessor(homeserver, logger).EmulateMsc4222;
+
private SyncFilter? _filter;
private string? _namedFilterName;
- private bool _filterIsDirty = false;
- private string? _filterId = null;
+ private bool _filterIsDirty;
+ private string? _filterId;
public string? Since { get; set; }
public int Timeout { get; set; } = 30000;
- public string? SetPresence { get; set; } = "online";
+ public string? SetPresence { get; set; }
+
+ /// <summary>
+ /// Disabling this uses a technically slower code path, useful for checking whether delay comes from waiting for server or deserialising responses
+ /// </summary>
+ public bool UseInternalStreamingSync { get; set; } = true;
+
+ public bool UseMsc4222StateAfter {
+ get;
+ set {
+ field = value;
+ if (value) {
+ AsyncSyncPreprocessors.Add(_msc4222EmulationSyncProcessor);
+ logger?.LogInformation($"Added MSC4222 emulation sync processor");
+ }
+ else {
+ AsyncSyncPreprocessors.Remove(_msc4222EmulationSyncProcessor);
+ logger?.LogInformation($"Removed MSC4222 emulation sync processor");
+ }
+ }
+ } = false;
+
+ public List<Func<SyncResponse?, SyncResponse?>> SyncPreprocessors { get; } = [
+ SimpleSyncProcessors.FillRoomIds
+ ];
+
+ public List<Func<SyncResponse?, Task<SyncResponse?>>> AsyncSyncPreprocessors { get; } = [];
public string? FilterId {
get => _filterId;
@@ -42,16 +76,26 @@ public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, ILogger? logg
_filter = value;
_filterIsDirty = true;
_filterId = null;
+ _namedFilterName = null;
}
}
+ /// <summary>
+ /// Always include all rooms, and their full state according to passed filter
+ /// </summary>
public bool FullState { get; set; }
public bool IsInitialSync { get; set; } = true;
public TimeSpan MinimumDelay { get; set; } = new(0);
- private async Task updateFilterAsync() {
+ public async Task<int> GetUnoptimisedStoreCount() {
+ if (storageProvider is null) return -1;
+ var keys = await storageProvider.GetAllKeysAsync();
+ return keys.Count(static x => !x.StartsWith("old/")) - 1;
+ }
+
+ private async Task UpdateFilterAsync() {
if (!string.IsNullOrWhiteSpace(NamedFilterName)) {
_filterId = await homeserver.NamedCaches.FilterCache.GetOrSetValueAsync(NamedFilterName);
if (_filterId is null)
@@ -61,9 +105,11 @@ public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, ILogger? logg
else if (Filter is not null)
_filterId = (await homeserver.UploadFilterAsync(Filter)).FilterId;
else _filterId = null;
+
+ _filterIsDirty = false;
}
- public async Task<SyncResponse?> SyncAsync(CancellationToken? cancellationToken = null) {
+ public async Task<SyncResponse?> SyncAsync(CancellationToken? cancellationToken = null, bool noDelay = false) {
if (homeserver is null) {
Console.WriteLine("Null passed as homeserver for SyncHelper!");
throw new ArgumentNullException(nameof(homeserver), "Null passed as homeserver for SyncHelper!");
@@ -74,26 +120,86 @@ public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, ILogger? logg
throw new ArgumentNullException(nameof(homeserver.ClientHttpClient), "Null passed as homeserver for SyncHelper!");
}
+ if (storageProvider is null) {
+ var res = await SyncAsyncInternal(cancellationToken, noDelay);
+ if (res is null) return null;
+ if (UseMsc4222StateAfter) res.Msc4222Method = SyncResponse.Msc4222SyncType.Server;
+
+ foreach (var preprocessor in SyncPreprocessors) {
+ res = preprocessor(res);
+ }
+
+ foreach (var preprocessor in AsyncSyncPreprocessors) {
+ res = await preprocessor(res);
+ }
+
+ return res;
+ }
+
+ var key = Since ?? "init";
+ if (await storageProvider.ObjectExistsAsync(key)) {
+ var cached = await storageProvider.LoadObjectAsync<SyncResponse>(key);
+ // We explicitly check that NextBatch doesn't match since to prevent infinite loops...
+ if (cached is not null && cached.NextBatch != Since) {
+ logger?.LogInformation("SyncHelper: Using cached sync response for {}", key);
+ return cached;
+ }
+ }
+
+ var sync = await SyncAsyncInternal(cancellationToken, noDelay);
+ if (sync is null) return null;
+ // Ditto here.
+ if (sync.NextBatch != Since) await storageProvider.SaveObjectAsync(key, sync);
+
+ if (UseMsc4222StateAfter) sync.Msc4222Method = SyncResponse.Msc4222SyncType.Server;
+
+ foreach (var preprocessor in SyncPreprocessors) {
+ sync = preprocessor(sync);
+ }
+
+ foreach (var preprocessor in AsyncSyncPreprocessors) {
+ sync = await preprocessor(sync);
+ }
+
+ return sync;
+ }
+
+ private async Task<SyncResponse?> SyncAsyncInternal(CancellationToken? cancellationToken = null, bool noDelay = false) {
var sw = Stopwatch.StartNew();
- if (_filterIsDirty) await updateFilterAsync();
+ if (_filterIsDirty) await UpdateFilterAsync();
- var url = $"/_matrix/client/v3/sync?timeout={Timeout}&set_presence={SetPresence}&full_state={(FullState ? "true" : "false")}";
+ var url = $"/_matrix/client/v3/sync?timeout={Timeout}";
+ if (!string.IsNullOrWhiteSpace(SetPresence)) url += $"&set_presence={SetPresence}";
if (!string.IsNullOrWhiteSpace(Since)) url += $"&since={Since}";
if (_filterId is not null) url += $"&filter={_filterId}";
+ if (FullState) url += "&full_state=true";
+ if (UseMsc4222StateAfter) url += "&org.matrix.msc4222.use_state_after=true&use_state_after=true"; // We use both unstable and stable names for compatibility
- logger?.LogInformation("SyncHelper: Calling: {}", url);
+ // logger?.LogInformation("SyncHelper: Calling: {}", url);
try {
- var httpResp = await homeserver.ClientHttpClient.GetAsync(url, cancellationToken ?? CancellationToken.None);
- if (httpResp is null) throw new NullReferenceException("Failed to send HTTP request");
- logger?.LogInformation("Got sync response: {} bytes, {} elapsed", httpResp.Content.Headers.ContentLength ?? -1, sw.Elapsed);
- var deserializeSw = Stopwatch.StartNew();
- var resp = await httpResp.Content.ReadFromJsonAsync<SyncResponse>(cancellationToken: cancellationToken ?? CancellationToken.None,
- jsonTypeInfo: SyncResponseSerializerContext.Default.SyncResponse);
- logger?.LogInformation("Deserialized sync response: {} bytes, {} elapsed, {} total", httpResp.Content.Headers.ContentLength ?? -1, deserializeSw.Elapsed, sw.Elapsed);
+ SyncResponse? resp;
+ if (UseInternalStreamingSync) {
+ resp = await homeserver.ClientHttpClient.GetFromJsonAsync<SyncResponse>(url, cancellationToken: cancellationToken ?? CancellationToken.None);
+ logger?.LogInformation("Got sync response: ~{} bytes, {} elapsed", resp.ToJson(false, true, true).Length, sw.Elapsed);
+ }
+ else {
+ var httpResp = await homeserver.ClientHttpClient.GetAsync(url, cancellationToken ?? CancellationToken.None);
+ if (httpResp is null) throw new NullReferenceException("Failed to send HTTP request");
+ var receivedTime = sw.Elapsed;
+ var deserializeSw = Stopwatch.StartNew();
+ resp = await httpResp.Content.ReadFromJsonAsync(cancellationToken: cancellationToken ?? CancellationToken.None,
+ jsonTypeInfo: SyncResponseSerializerContext.Default.SyncResponse);
+ logger?.LogInformation("Deserialized sync response: {} bytes, {} response time, {} deserialize time, {} total", httpResp.GetContentLength(), receivedTime,
+ deserializeSw.Elapsed, sw.Elapsed);
+ }
+
var timeToWait = MinimumDelay.Subtract(sw.Elapsed);
- if (timeToWait.TotalMilliseconds > 0)
+ if (!noDelay && timeToWait.TotalMilliseconds > 0) {
+ logger?.LogWarning("SyncAsyncInternal: Waiting {delay}", timeToWait);
await Task.Delay(timeToWait);
+ }
+
return resp;
}
catch (TaskCanceledException) {
@@ -103,6 +209,8 @@ public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, ILogger? logg
catch (Exception e) {
Console.WriteLine(e);
logger?.LogError(e, "Failed to sync!\n{}", e.ToString());
+ await Task.WhenAll(ExceptionHandlers.Select(x => x.Invoke(e)).ToList());
+ if (e is MatrixException { ErrorCode: MatrixException.ErrorCodes.M_UNKNOWN_TOKEN }) throw;
}
return null;
@@ -110,10 +218,17 @@ public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, ILogger? logg
public async IAsyncEnumerable<SyncResponse> EnumerateSyncAsync(CancellationToken? cancellationToken = null) {
while (!cancellationToken?.IsCancellationRequested ?? true) {
- var sync = await SyncAsync(cancellationToken);
+ var sw = Stopwatch.StartNew();
+ var sync = await SyncAsync(cancellationToken, noDelay: true);
if (sync is null) continue;
if (!string.IsNullOrWhiteSpace(sync.NextBatch)) Since = sync.NextBatch;
yield return sync;
+
+ var timeToWait = MinimumDelay.Subtract(sw.Elapsed);
+ if (timeToWait.TotalMilliseconds > 0) {
+ logger?.LogWarning("EnumerateSyncAsync: Waiting {delay}", timeToWait);
+ await Task.Delay(timeToWait);
+ }
}
}
@@ -183,7 +298,7 @@ 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) {
+ foreach (var stateEventResponse in updatedRoom.Value.Timeline.Events ?? []) {
stateEventResponse.RoomId = updatedRoom.Key;
var tasks = TimelineEventHandlers.Select(x => x(stateEventResponse)).ToList();
await Task.WhenAll(tasks);
@@ -210,7 +325,12 @@ public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, ILogger? logg
/// Event fired when an account data event is received
/// </summary>
public List<Func<StateEventResponse, Task>> AccountDataReceivedHandlers { get; } = new();
-
+
+ /// <summary>
+ /// Event fired when an exception is thrown
+ /// </summary>
+ public List<Func<Exception, Task>> ExceptionHandlers { get; } = new();
+
private void Log(string message) {
if (logger is null) Console.WriteLine(message);
else logger.LogInformation(message);
diff --git a/LibMatrix/Helpers/SyncProcessors/Msc4222EmulationSyncProcessor.cs b/LibMatrix/Helpers/SyncProcessors/Msc4222EmulationSyncProcessor.cs
new file mode 100644
index 0000000..e34b5cf
--- /dev/null
+++ b/LibMatrix/Helpers/SyncProcessors/Msc4222EmulationSyncProcessor.cs
@@ -0,0 +1,210 @@
+using System.Diagnostics;
+using System.Timers;
+using ArcaneLibs.Extensions;
+using LibMatrix.Homeservers;
+using LibMatrix.Responses;
+using Microsoft.Extensions.Logging;
+
+namespace LibMatrix.Helpers.SyncProcessors;
+
+public class Msc4222EmulationSyncProcessor(AuthenticatedHomeserverGeneric homeserver, ILogger? logger) {
+ private static bool StateEventsMatch(StateEventResponse a, StateEventResponse b) {
+ return a.Type == b.Type && a.StateKey == b.StateKey;
+ }
+
+ private static bool StateEventIsNewer(StateEventResponse a, StateEventResponse b) {
+ return StateEventsMatch(a, b) && a.OriginServerTs < b.OriginServerTs;
+ }
+
+ public async Task<SyncResponse?> EmulateMsc4222(SyncResponse? resp) {
+ var sw = Stopwatch.StartNew();
+ if (resp is null or { Rooms: null }) return resp;
+
+ if (
+ resp.Rooms.Join?.Any(x => x.Value.StateAfter is { Events.Count: > 0 }) == true
+ || resp.Rooms.Leave?.Any(x => x.Value.StateAfter is { Events.Count: > 0 }) == true
+ ) {
+ logger?.Log(sw.ElapsedMilliseconds > 100 ? LogLevel.Warning : LogLevel.Debug,
+ "Msc4222EmulationSyncProcessor.EmulateMsc4222 determined that no emulation is needed in {elapsed}", sw.Elapsed);
+ return resp;
+ }
+
+ resp = await EmulateMsc4222Internal(resp, sw);
+
+ return SimpleSyncProcessors.FillRoomIds(resp);
+ }
+
+ private async Task<SyncResponse?> EmulateMsc4222Internal(SyncResponse? resp, Stopwatch sw) {
+ var modified = false;
+ List<Task<bool>> tasks = [];
+ if (resp.Rooms is { Join.Count: > 0 }) {
+ tasks.AddRange(resp.Rooms.Join.Select(ProcessJoinedRooms).ToList());
+ }
+
+ if (resp.Rooms is { Leave.Count: > 0 }) {
+ tasks.AddRange(resp.Rooms.Leave.Select(ProcessLeftRooms).ToList());
+ }
+
+ var tasksEnum = tasks.ToAsyncEnumerable();
+ await foreach (var wasModified in tasksEnum) {
+ if (wasModified) {
+ modified = true;
+ }
+ }
+
+ logger?.Log(sw.ElapsedMilliseconds > 100 ? LogLevel.Warning : LogLevel.Debug,
+ "Msc4222EmulationSyncProcessor.EmulateMsc4222 processed {joinCount}/{leaveCount} rooms in {elapsed} (modified: {modified})",
+ resp.Rooms?.Join?.Count ?? 0, resp.Rooms?.Leave?.Count ?? 0, sw.Elapsed, modified);
+
+ if (modified)
+ resp.Msc4222Method = SyncResponse.Msc4222SyncType.Emulated;
+
+ return resp;
+ }
+
+ private async Task<bool> ProcessJoinedRooms(KeyValuePair<string, SyncResponse.RoomsDataStructure.JoinedRoomDataStructure> roomData) {
+ var (roomId, data) = roomData;
+ var room = homeserver.GetRoom(roomId);
+
+ if (data.StateAfter is { Events.Count: > 0 }) {
+ return false;
+ }
+
+ data.StateAfter = new() { Events = [] };
+
+ data.StateAfter = new() {
+ Events = []
+ };
+
+ var oldState = new List<StateEventResponse>();
+ if (data.State is { Events.Count: > 0 }) {
+ oldState.ReplaceBy(data.State.Events, StateEventIsNewer);
+ }
+
+ if (data.Timeline is { Limited: true }) {
+ if (data.Timeline.Events != null)
+ oldState.ReplaceBy(data.Timeline.Events, StateEventIsNewer);
+
+ try {
+ var timeline = await homeserver.GetRoom(roomId).GetMessagesAsync(limit: 250);
+ if (timeline is { State.Count: > 0 }) {
+ oldState.ReplaceBy(timeline.State, StateEventIsNewer);
+ }
+
+ if (timeline is { Chunk.Count: > 0 }) {
+ oldState.ReplaceBy(timeline.Chunk.Where(x => x.StateKey != null), StateEventIsNewer);
+ }
+ }
+ catch (Exception e) {
+ logger?.LogWarning("Msc4222Emulation: Failed to get timeline for room {roomId}, state may be incomplete!\n{exception}", roomId, e);
+ }
+ }
+
+ oldState = oldState.DistinctBy(x => (x.Type, x.StateKey)).ToList();
+
+ // Different order: we need oldState here to reduce the set
+ try {
+ data.StateAfter.Events = (await room.GetFullStateAsListAsync())
+ // .Where(x=> oldState.Any(y => StateEventsMatch(x, y)))
+ // .Join(oldState, x => (x.Type, x.StateKey), y => (y.Type, y.StateKey), (x, y) => x)
+ .IntersectBy(oldState.Select(s => (s.Type, s.StateKey)), s => (s.Type, s.StateKey))
+ .ToList();
+
+ data.State = null;
+ return true;
+ }
+ catch (Exception e) {
+ logger?.LogWarning("Msc4222Emulation: Failed to get full state for room {roomId}, state may be incomplete!\n{exception}", roomId, e);
+ }
+
+ var tasks = oldState
+ .Select(async oldEvt => {
+ try {
+ return await room.GetStateEventAsync(oldEvt.Type, oldEvt.StateKey!);
+ }
+ catch (Exception e) {
+ logger?.LogWarning("Msc4222Emulation: Failed to get state event {type}/{stateKey} for room {roomId}, state may be incomplete!\n{exception}",
+ oldEvt.Type, oldEvt.StateKey, roomId, e);
+ return oldEvt;
+ }
+ });
+
+ var tasksEnum = tasks.ToAsyncEnumerable();
+ await foreach (var evt in tasksEnum) {
+ data.StateAfter.Events.Add(evt);
+ }
+
+ data.State = null;
+
+ return true;
+ }
+
+ private async Task<bool> ProcessLeftRooms(KeyValuePair<string, SyncResponse.RoomsDataStructure.LeftRoomDataStructure> roomData) {
+ var (roomId, data) = roomData;
+ var room = homeserver.GetRoom(roomId);
+
+ if (data.StateAfter is { Events.Count: > 0 }) {
+ return false;
+ }
+
+ data.StateAfter = new() {
+ Events = []
+ };
+
+ try {
+ data.StateAfter.Events = await room.GetFullStateAsListAsync();
+ data.State = null;
+ return true;
+ }
+ catch (Exception e) {
+ logger?.LogWarning("Msc4222Emulation: Failed to get full state for room {roomId}, state may be incomplete!\n{exception}", roomId, e);
+ }
+
+ var oldState = new List<StateEventResponse>();
+ if (data.State is { Events.Count: > 0 }) {
+ oldState.ReplaceBy(data.State.Events, StateEventIsNewer);
+ }
+
+ if (data.Timeline is { Limited: true }) {
+ if (data.Timeline.Events != null)
+ oldState.ReplaceBy(data.Timeline.Events, StateEventIsNewer);
+
+ try {
+ var timeline = await homeserver.GetRoom(roomId).GetMessagesAsync(limit: 250);
+ if (timeline is { State.Count: > 0 }) {
+ oldState.ReplaceBy(timeline.State, StateEventIsNewer);
+ }
+
+ if (timeline is { Chunk.Count: > 0 }) {
+ oldState.ReplaceBy(timeline.Chunk.Where(x => x.StateKey != null), StateEventIsNewer);
+ }
+ }
+ catch (Exception e) {
+ logger?.LogWarning("Msc4222Emulation: Failed to get timeline for room {roomId}, state may be incomplete!\n{exception}", roomId, e);
+ }
+ }
+
+ oldState = oldState.DistinctBy(x => (x.Type, x.StateKey)).ToList();
+
+ var tasks = oldState
+ .Select(async oldEvt => {
+ try {
+ return await room.GetStateEventAsync(oldEvt.Type, oldEvt.StateKey!);
+ }
+ catch (Exception e) {
+ logger?.LogWarning("Msc4222Emulation: Failed to get state event {type}/{stateKey} for room {roomId}, state may be incomplete!\n{exception}",
+ oldEvt.Type, oldEvt.StateKey, roomId, e);
+ return oldEvt;
+ }
+ });
+
+ var tasksEnum = tasks.ToAsyncEnumerable();
+ await foreach (var evt in tasksEnum) {
+ data.StateAfter.Events.Add(evt);
+ }
+
+ data.State = null;
+
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Helpers/SyncProcessors/SimpleSyncProcessors.cs b/LibMatrix/Helpers/SyncProcessors/SimpleSyncProcessors.cs
new file mode 100644
index 0000000..5981cb5
--- /dev/null
+++ b/LibMatrix/Helpers/SyncProcessors/SimpleSyncProcessors.cs
@@ -0,0 +1,47 @@
+using System.Diagnostics;
+using LibMatrix.Responses;
+
+namespace LibMatrix.Helpers.SyncProcessors;
+
+public class SimpleSyncProcessors {
+ public static SyncResponse? FillRoomIds(SyncResponse? resp) {
+ var sw = Stopwatch.StartNew();
+ if (resp is not { Rooms: not null }) return resp;
+ if (resp.Rooms.Join is { Count: > 0 })
+ Parallel.ForEach(resp.Rooms.Join, (roomEntry) => {
+ var (id, data) = roomEntry;
+ if (data.AccountData is { Events.Count: > 0 })
+ Parallel.ForEach(data.AccountData.Events, evt => evt.RoomId = id);
+ if (data.Ephemeral is { Events.Count: > 0 })
+ Parallel.ForEach(data.Ephemeral.Events, evt => evt.RoomId = id);
+ if (data.Timeline is { Events.Count: > 0 })
+ Parallel.ForEach(data.Timeline.Events, evt => evt.RoomId = id);
+ if (data.State is { Events.Count: > 0 })
+ Parallel.ForEach(data.State.Events, evt => evt.RoomId = id);
+ if (data.StateAfter is { Events.Count: > 0 })
+ Parallel.ForEach(data.StateAfter.Events, evt => evt.RoomId = id);
+ });
+ if (resp.Rooms.Leave is { Count: > 0 })
+ Parallel.ForEach(resp.Rooms.Leave, (roomEntry) => {
+ var (id, data) = roomEntry;
+ if (data.AccountData is { Events.Count: > 0 })
+ Parallel.ForEach(data.AccountData.Events, evt => evt.RoomId = id);
+ if (data.Timeline is { Events.Count: > 0 })
+ Parallel.ForEach(data.Timeline.Events, evt => evt.RoomId = id);
+ if (data.State is { Events.Count: > 0 })
+ Parallel.ForEach(data.State.Events, evt => evt.RoomId = id);
+ if (data.StateAfter is { Events.Count: > 0 })
+ Parallel.ForEach(data.StateAfter.Events, evt => evt.RoomId = id);
+ });
+ if (resp.Rooms.Invite is { Count: > 0 })
+ Parallel.ForEach(resp.Rooms.Invite, (roomEntry) => {
+ var (id, data) = roomEntry;
+ if (data.InviteState is { Events.Count: > 0 })
+ Parallel.ForEach(data.InviteState.Events, evt => evt.RoomId = id);
+ });
+
+ Console.WriteLine($"SimpleSyncProcessors.FillRoomIds took {sw.Elapsed}");
+
+ return resp;
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Helpers/SyncStateResolver.cs b/LibMatrix/Helpers/SyncStateResolver.cs
index 72d600d..f111c79 100644
--- a/LibMatrix/Helpers/SyncStateResolver.cs
+++ b/LibMatrix/Helpers/SyncStateResolver.cs
@@ -1,12 +1,20 @@
+using System.Collections.Concurrent;
+using System.Collections.Frozen;
+using System.Collections.Immutable;
+using System.Diagnostics;
+using System.Text.Json;
+using System.Threading.Tasks.Dataflow;
+using ArcaneLibs.Extensions;
using LibMatrix.Extensions;
using LibMatrix.Filters;
using LibMatrix.Homeservers;
+using LibMatrix.Interfaces.Services;
using LibMatrix.Responses;
using Microsoft.Extensions.Logging;
namespace LibMatrix.Helpers;
-public class SyncStateResolver(AuthenticatedHomeserverGeneric homeserver, ILogger? logger = null) {
+public class SyncStateResolver(AuthenticatedHomeserverGeneric homeserver, ILogger? logger = null, IStorageProvider? storageProvider = null) {
public string? Since { get; set; }
public int Timeout { get; set; } = 30000;
public string? SetPresence { get; set; } = "online";
@@ -15,7 +23,20 @@ public class SyncStateResolver(AuthenticatedHomeserverGeneric homeserver, ILogge
public SyncResponse? MergedState { get; set; }
- private SyncHelper _syncHelper = new(homeserver, logger);
+ private SyncHelper _syncHelper = new(homeserver, logger, storageProvider);
+
+ private async Task<SyncResponse?> LoadSyncResponse(string key) {
+ if (storageProvider is null) ArgumentNullException.ThrowIfNull(storageProvider);
+ var stream = await storageProvider.LoadStreamAsync(key);
+ return JsonSerializer.Deserialize<SyncResponse>(stream!, SyncResponseSerializerContext.Default.SyncResponse);
+ }
+
+ private async Task SaveSyncResponse(string key, SyncResponse value) {
+ ArgumentNullException.ThrowIfNull(storageProvider);
+ var ms = new MemoryStream();
+ await JsonSerializer.SerializeAsync(ms, value, SyncResponseSerializerContext.Default.SyncResponse);
+ await storageProvider.SaveStreamAsync(key, ms);
+ }
public async Task<(SyncResponse next, SyncResponse merged)> ContinueAsync(CancellationToken? cancellationToken = null) {
// copy properties
@@ -24,149 +45,615 @@ public class SyncStateResolver(AuthenticatedHomeserverGeneric homeserver, ILogge
_syncHelper.SetPresence = SetPresence;
_syncHelper.Filter = Filter;
_syncHelper.FullState = FullState;
- // run sync
- var sync = await _syncHelper.SyncAsync(cancellationToken);
+
+ var sync = await _syncHelper.SyncAsync(cancellationToken, noDelay: false);
if (sync is null) return await ContinueAsync(cancellationToken);
+
if (MergedState is null) MergedState = sync;
- else MergedState = MergeSyncs(MergedState, sync);
+ else MergedState = await MergeSyncs(MergedState, sync);
Since = sync.NextBatch;
+
return (sync, MergedState);
}
- private SyncResponse MergeSyncs(SyncResponse oldState, SyncResponse newState) {
- oldState.NextBatch = newState.NextBatch ?? oldState.NextBatch;
+ // private async IAsyncEnumerable<List<SyncResponse>> MergeP() {
+
+ // }
+
+ private async Task<SyncResponse?> OptimiseFrom(string start, Action<int, int>? progressCallback = null) {
+ var a = GetSerializedUnoptimisedResponses(start);
+ SyncResponse merged = null!;
+ int iters = 0;
+ var sw = Stopwatch.StartNew();
+ await foreach (var (key, resp) in a) {
+ if (resp is null) continue;
+ iters++;
+ // if (key == "init") _merged = resp;
+ // else _merged = await MergeSyncs(_merged, resp);
+ // Console.WriteLine($"{key} @ {resp.GetDerivedSyncTime()} -> {resp.NextBatch}");
+ }
- oldState.AccountData ??= new EventList();
- oldState.AccountData.Events ??= new List<StateEventResponse>();
- if (newState.AccountData?.Events is not null)
- oldState.AccountData.Events.MergeStateEventLists(newState.AccountData?.Events ?? new List<StateEventResponse>());
+ Console.WriteLine($"OptimiseFrom {start} finished in {sw.Elapsed.TotalMilliseconds}ms with {iters} iterations");
- oldState.Presence ??= new SyncResponse.PresenceDataStructure();
- if (newState.Presence?.Events is not null)
- oldState.Presence.Events.MergeStateEventLists(newState.Presence?.Events ?? new List<StateEventResponse>());
+ return merged;
+ }
- oldState.DeviceOneTimeKeysCount ??= new Dictionary<string, int>();
- if (newState.DeviceOneTimeKeysCount is not null)
- foreach (var (key, value) in newState.DeviceOneTimeKeysCount)
- oldState.DeviceOneTimeKeysCount[key] = value;
+ private async Task<List<string>> GetSerializedUnoptimisedKeysParallel(string start = "init") {
+ Dictionary<string, string> pairs = [];
+ var unoptimisedKeys = (await storageProvider.GetAllKeysAsync()).Where(static x => !x.Contains('/')).ToFrozenSet();
+ await Parallel.ForEachAsync(unoptimisedKeys, async (key, _) => {
+ var data = await storageProvider.LoadObjectAsync<SyncResponse>(key, SyncResponseSerializerContext.Default.SyncResponse);
+ if (data is null) return;
+ lock (pairs)
+ pairs.Add(key, data.NextBatch);
+ });
+
+ var serializedKeys = new List<string>();
+ var currentKey = start;
+ while (pairs.TryGetValue(currentKey, out var nextKey)) {
+ serializedKeys.Add(currentKey);
+ currentKey = nextKey;
+ }
- oldState.Rooms ??= new SyncResponse.RoomsDataStructure();
- if (newState.Rooms is not null)
- oldState.Rooms = MergeRoomsDataStructure(oldState.Rooms, newState.Rooms);
+ return serializedKeys;
+ }
- oldState.ToDevice ??= new EventList();
- oldState.ToDevice.Events ??= new List<StateEventResponse>();
- if (newState.ToDevice?.Events is not null)
- oldState.ToDevice.Events.MergeStateEventLists(newState.ToDevice?.Events ?? new List<StateEventResponse>());
+ private async Task<SyncResponse> MergeRecursive(string[] keys, int depth = 0) {
+ if (keys.Length > 10) {
+ var newKeys = keys.Chunk((keys.Length / 2) + 1).ToArray();
+ var (left, right) = (MergeRecursive(newKeys[0], depth + 1), MergeRecursive(newKeys[1], depth + 1));
+ await Task.WhenAll(left, right);
+ return await MergeSyncs(await left, await right);
+ }
- oldState.DeviceLists ??= new SyncResponse.DeviceListsDataStructure();
- if (newState.DeviceLists?.Changed is not null)
- foreach (var s in oldState.DeviceLists.Changed!)
- oldState.DeviceLists.Changed.Add(s);
- if (newState.DeviceLists?.Left is not null)
- foreach (var s in oldState.DeviceLists.Left!)
- oldState.DeviceLists.Left.Add(s);
+ // Console.WriteLine("Hit max depth: " + depth);
+ SyncResponse merged = await LoadSyncResponse(keys[0]);
+ foreach (var key in keys[1..]) {
+ merged = await MergeSyncs(merged, await LoadSyncResponse(key));
+ }
- return oldState;
+ return merged;
}
-#region Merge rooms
+ public async Task OptimiseStore(Action<int, int>? progressCallback = null) {
+ if (storageProvider is null) return;
+ if (!await storageProvider.ObjectExistsAsync("init")) return;
+ //
+ // {
+ // var a = GetSerializedUnoptimisedResponses();
+ // SyncResponse _merged = null!;
+ // await foreach (var (key, resp) in a) {
+ // if (resp is null) continue;
+ // // if (key == "init") _merged = resp;
+ // // else _merged = await MergeSyncs(_merged, resp);
+ // // Console.WriteLine($"{key} @ {resp.GetDerivedSyncTime()} -> {resp.NextBatch}");
+ // }
+ // Environment.Exit(0);
+ // }
+
+ {
+ // List<string> serialisedKeys = new(4000000);
+ // await foreach (var res in GetSerializedUnoptimisedResponses()) {
+ // if (res.resp is null) continue;
+ // serialisedKeys.Add(res.key);
+ // if (serialisedKeys.Count % 1000 == 0) _ = Console.Out.WriteAsync($"{serialisedKeys.Count}\r");
+ // }
+
+ List<string> serialisedKeys = await GetSerializedUnoptimisedKeysParallel();
+
+ await MergeRecursive(serialisedKeys.ToArray());
+
+ // var chunkSize = serialisedKeys.Count / Environment.ProcessorCount;
+ // var chunks = serialisedKeys.Chunk(chunkSize+1).Select(x => (x.First(), x.Length)).ToList();
+ // Console.WriteLine($"Got {chunks.Count} chunks:");
+ // foreach (var chunk in chunks) {
+ // Console.WriteLine($"Chunk {chunk.Item1} with length {chunk.Length}");
+ // }
+ //
+ // var mergeTasks = chunks.Select(async chunk => {
+ // var (startKey, length) = chunk;
+ // string currentKey = startKey;
+ // SyncResponse merged = await storageProvider.LoadObjectAsync<SyncResponse>(currentKey, SyncResponseSerializerContext.Default.SyncResponse);
+ // for (int i = 0; i < length; i++) {
+ // if (i % 1000 == 0) Console.Write($"{i}... \r");
+ // var newData = await storageProvider.LoadObjectAsync<SyncResponse>(currentKey, SyncResponseSerializerContext.Default.SyncResponse);
+ // merged = await MergeSyncs(merged, newData);
+ // currentKey = merged.NextBatch;
+ // }
+ //
+ // return merged;
+ // }).ToList();
+ //
+ // var mergedResults = await Task.WhenAll(mergeTasks);
+ // SyncResponse _merged = mergedResults[0];
+ // foreach (var key in mergedResults[1..]) {
+ // _merged = await MergeSyncs(_merged, key);
+ // }
+ }
+
+ Environment.Exit(0);
+
+ return;
+
+ var totalSw = Stopwatch.StartNew();
+ Console.Write("Optimising sync store...");
+ var initLoadTask = LoadSyncResponse("init");
+ var keys = (await storageProvider.GetAllKeysAsync()).Where(static x => !x.StartsWith("old/")).ToFrozenSet();
+ var count = keys.Count - 1;
+ int total = count;
+ Console.WriteLine($"Found {count} entries to optimise in {totalSw.Elapsed}.");
+
+ var merged = await initLoadTask;
+ if (merged is null) return;
+ if (!keys.Contains(merged.NextBatch)) {
+ Console.WriteLine("Next response after initial sync is not present, not checkpointing!");
+ return;
+ }
+
+ // if (keys.Count > 100_000) {
+ // // batch data by core count
+ //
+ // return;
+ // }
+
+ // We back up old entries
+ var oldPath = $"old/{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
+ await storageProvider.MoveObjectAsync("init", $"{oldPath}/init");
+
+ var moveTasks = new List<Task>();
+
+ Dictionary<string, Dictionary<string, TimeSpan>> traces = [];
+ string[] loopTrace = new string[4];
+ while (keys.Contains(merged.NextBatch)) {
+ loopTrace[0] = $"Merging {merged.NextBatch}, {--count} remaining";
+ var sw = Stopwatch.StartNew();
+ var swt = Stopwatch.StartNew();
+ var next = await LoadSyncResponse(merged.NextBatch);
+ loopTrace[1] = $"Load {sw.GetElapsedAndRestart().TotalMilliseconds}ms";
+ if (next is null || merged.NextBatch == next.NextBatch) break;
+
+ // back up old entry
+ moveTasks.Add(storageProvider.MoveObjectAsync(merged.NextBatch, $"{oldPath}/{merged.NextBatch}"));
+
+ if (moveTasks.Count >= 250)
+ moveTasks.RemoveAll(t => t.IsCompleted);
+
+ if (moveTasks.Count >= 500) {
+ Console.Write("Reached 500 moveTasks... ");
+ moveTasks.RemoveAll(t => t.IsCompleted);
+ Console.WriteLine($"{moveTasks.Count} remaining");
+ }
+
+ var trace = new Dictionary<string, TimeSpan>();
+ traces[merged.NextBatch] = trace;
+ merged = await MergeSyncs(merged, next, trace);
+ loopTrace[2] = $"Merge {sw.GetElapsedAndRestart().TotalMilliseconds}ms";
+ loopTrace[3] = $"Total {swt.Elapsed.TotalMilliseconds}ms";
+
+ if (swt.ElapsedMilliseconds >= 25)
+ Console.WriteLine(string.Join("... ", loopTrace));
+
+ if (count % 50 == 0)
+ progressCallback?.Invoke(count, total);
+#if WRITE_TRACE
+ var traceString = string.Join("\n", traces.Select(x => $"{x.Key}\t{x.Value.ToJson(indent: false, ignoreNull: true)}"));
+ var ms = new MemoryStream(Encoding.UTF8.GetBytes(traceString));
+ var traceSaveTask = storageProvider.SaveStreamAsync($"traces/{oldPath}", ms);
+ var slowtraceString = string.Join("\n",
+ traces
+ .Where(x=>x.Value.Max(y=>y.Value.TotalMilliseconds) >= 100)
+ .OrderBy(x=>x.Value.Max(y=>y.Value))
+ .Select(x => $"{x.Key}\t{x.Value.Where(y => y.Value.TotalMilliseconds >= 100).ToDictionary().ToJson(indent: false, ignoreNull: true)}"));
+ var slowms = new MemoryStream(Encoding.UTF8.GetBytes(slowtraceString));
+ var slowTraceSaveTask = storageProvider.SaveStreamAsync($"traces/{oldPath}-slow", slowms);
+ var slow1straceString = string.Join("\n",
+ traces
+ .Where(x=>x.Value.Max(y=>y.Value.TotalMilliseconds) >= 1000)
+ .OrderBy(x=>x.Value.Max(y=>y.Value))
+ .Select(x => $"{x.Key}\t{x.Value.Where(y => y.Value.TotalMilliseconds >= 1000).ToDictionary().ToJson(indent: false, ignoreNull: true)}"));
+ var slow1sms = new MemoryStream(Encoding.UTF8.GetBytes(slow1straceString));
+ var slow1sTraceSaveTask = storageProvider.SaveStreamAsync($"traces/{oldPath}-slow-1s", slow1sms);
+
+ await Task.WhenAll(traceSaveTask, slowTraceSaveTask, slow1sTraceSaveTask);
+#endif
+ }
- private SyncResponse.RoomsDataStructure MergeRoomsDataStructure(SyncResponse.RoomsDataStructure oldState, SyncResponse.RoomsDataStructure newState) {
- oldState.Join ??= new Dictionary<string, SyncResponse.RoomsDataStructure.JoinedRoomDataStructure>();
- foreach (var (key, value) in newState.Join ?? new Dictionary<string, SyncResponse.RoomsDataStructure.JoinedRoomDataStructure>())
- if (!oldState.Join.ContainsKey(key)) oldState.Join[key] = value;
- else oldState.Join[key] = MergeJoinedRoomDataStructure(oldState.Join[key], value);
+ await SaveSyncResponse("init", merged);
+ await Task.WhenAll(moveTasks);
- oldState.Invite ??= new Dictionary<string, SyncResponse.RoomsDataStructure.InvitedRoomDataStructure>();
- foreach (var (key, value) in newState.Invite ?? new Dictionary<string, SyncResponse.RoomsDataStructure.InvitedRoomDataStructure>())
- if (!oldState.Invite.ContainsKey(key)) oldState.Invite[key] = value;
- else oldState.Invite[key] = MergeInvitedRoomDataStructure(oldState.Invite[key], value);
+ Console.WriteLine($"Optimised store in {totalSw.Elapsed.TotalMilliseconds}ms");
+ }
+
+ /// <summary>
+ /// Remove all but initial sync and last checkpoint
+ /// </summary>
+ public async Task RemoveOldSnapshots() {
+ if (storageProvider is null) return;
+ var sw = Stopwatch.StartNew();
+
+ var map = await GetCheckpointMap();
+ if (map is null) return;
+ if (map.Count < 3) return;
+
+ var toRemove = map.Keys.Skip(1).Take(map.Count - 2).ToList();
+ Console.Write("Cleaning up old snapshots: ");
+ foreach (var key in toRemove) {
+ var path = $"old/{key}/init";
+ if (await storageProvider.ObjectExistsAsync(path)) {
+ Console.Write($"{key}... ");
+ await storageProvider.DeleteObjectAsync(path);
+ }
+ }
+
+ Console.WriteLine("Done!");
+ Console.WriteLine($"Removed {toRemove.Count} old snapshots in {sw.Elapsed.TotalMilliseconds}ms");
+ }
+
+ public async Task UnrollOptimisedStore() {
+ if (storageProvider is null) return;
+ Console.WriteLine("WARNING: Unrolling sync store!");
+ }
+
+ public async Task SquashOptimisedStore(int targetCountPerCheckpoint) {
+ Console.Write($"Balancing optimised store to {targetCountPerCheckpoint} per checkpoint...");
+ var checkpoints = await GetCheckpointMap();
+ if (checkpoints is null) return;
+
+ Console.WriteLine(
+ $" Stats: {checkpoints.Count} checkpoints with [{checkpoints.Min(x => x.Value.Count)} < ~{checkpoints.Average(x => x.Value.Count)} < {checkpoints.Max(x => x.Value.Count)}] entries");
+ Console.WriteLine($"Found {checkpoints?.Count ?? 0} checkpoints.");
+ }
+
+ public async Task dev() {
+ int i = 0;
+ var sw = Stopwatch.StartNew();
+ var hist = GetSerialisedHistory();
+ await foreach (var (key, resp) in hist) {
+ if (resp is null) continue;
+ // Console.WriteLine($"[{++i}] {key} -> {resp.NextBatch} ({resp.GetDerivedSyncTime()})");
+ i++;
+ }
+
+ Console.WriteLine($"Iterated {i} syncResponses in {sw.Elapsed}");
+ Environment.Exit(0);
+ }
+
+ private async IAsyncEnumerable<(string key, SyncResponse? resp)> GetSerialisedHistory() {
+ if (storageProvider is null) yield break;
+ var map = await GetCheckpointMap();
+ var currentRange = map.First();
+ var nextKey = $"old/{map.First().Key}/init";
+ var next = storageProvider.LoadObjectAsync<SyncResponse>(nextKey);
+ while (true) {
+ var data = await next;
+ if (data is null) break;
+ yield return (nextKey, data);
+ if (currentRange.Value.Contains(data.NextBatch)) {
+ nextKey = $"old/{currentRange.Key}/{data.NextBatch}";
+ }
+ else if (map.Any(x => x.Value.Contains(data.NextBatch))) {
+ currentRange = map.First(x => x.Value.Contains(data.NextBatch));
+ nextKey = $"old/{currentRange.Key}/{data.NextBatch}";
+ }
+ else if (await storageProvider.ObjectExistsAsync(data.NextBatch)) {
+ nextKey = data.NextBatch;
+ }
+ else break;
+
+ next = storageProvider.LoadObjectAsync<SyncResponse>(nextKey);
+ }
+ }
+
+ private async IAsyncEnumerable<(string key, SyncResponse? resp)> GetSerializedUnoptimisedResponses(string since = "init") {
+ if (storageProvider is null) yield break;
+ var nextKey = since;
+ var next = storageProvider.LoadObjectAsync<SyncResponse>(nextKey);
+ while (true) {
+ var data = await next;
+
+ if (data is null) break;
+ yield return (nextKey, data);
+ if (await storageProvider.ObjectExistsAsync(data.NextBatch)) {
+ nextKey = data.NextBatch;
+ }
+ else break;
+
+ next = storageProvider.LoadObjectAsync<SyncResponse>(nextKey);
+ }
+ }
+
+ public async Task<SyncResponse?> GetMergedUpTo(DateTime time) {
+ if (storageProvider is null) return null;
+ var unixTime = new DateTimeOffset(time.ToUniversalTime()).ToUnixTimeMilliseconds();
+ var map = await GetCheckpointMap();
+ if (map is null) return new();
+ var stream = GetSerialisedHistory().GetAsyncEnumerator();
+ SyncResponse? merged = await stream.MoveNextAsync() ? stream.Current.resp : null;
+
+ if (merged.GetDerivedSyncTime() > unixTime) {
+ Console.WriteLine("Initial sync is already past the target time!");
+ Console.WriteLine($"CURRENT: {merged.GetDerivedSyncTime()} (UTC: {DateTimeOffset.FromUnixTimeMilliseconds(merged.GetDerivedSyncTime())})");
+ Console.WriteLine($" TARGET: {unixTime} ({time.Kind}: {time}, UTC: {time.ToUniversalTime()})");
+ return null;
+ }
- oldState.Leave ??= new Dictionary<string, SyncResponse.RoomsDataStructure.LeftRoomDataStructure>();
- foreach (var (key, value) in newState.Leave ?? new Dictionary<string, SyncResponse.RoomsDataStructure.LeftRoomDataStructure>()) {
- if (!oldState.Leave.ContainsKey(key)) oldState.Leave[key] = value;
- else oldState.Leave[key] = MergeLeftRoomDataStructure(oldState.Leave[key], value);
- if (oldState.Invite.ContainsKey(key)) oldState.Invite.Remove(key);
- if (oldState.Join.ContainsKey(key)) oldState.Join.Remove(key);
+ while (await stream.MoveNextAsync()) {
+ var (key, resp) = stream.Current;
+ if (resp is null) continue;
+ if (resp.GetDerivedSyncTime() > unixTime) break;
+ merged = await MergeSyncs(merged, resp);
}
+ return merged;
+ }
+
+ private async Task<ImmutableSortedDictionary<ulong, FrozenSet<string>>> GetCheckpointMap() {
+ if (storageProvider is null) return null;
+ var keys = (await storageProvider.GetAllKeysAsync()).ToFrozenSet();
+ var map = new Dictionary<ulong, List<string>>();
+ foreach (var key in keys) {
+ if (!key.StartsWith("old/")) continue;
+ var parts = key.Split('/');
+ if (parts.Length < 3) continue;
+ if (!ulong.TryParse(parts[1], out var checkpoint)) continue;
+ if (!map.ContainsKey(checkpoint)) map[checkpoint] = new();
+ map[checkpoint].Add(parts[2]);
+ }
+
+ return map.OrderBy(static x => x.Key).ToImmutableSortedDictionary(static x => x.Key, x => x.Value.ToFrozenSet());
+ }
+
+ private async Task<SyncResponse> MergeSyncs(SyncResponse oldSync, SyncResponse newSync, Dictionary<string, TimeSpan>? trace = null) {
+ // var sw = Stopwatch.StartNew();
+ oldSync.NextBatch = newSync.NextBatch;
+
+ void Trace(string key, TimeSpan span) {
+ if (trace is not null) {
+ lock (trace)
+ trace.Add(key, span);
+ }
+ }
+
+ var accountDataTask = Task.Run(() => {
+ var sw = Stopwatch.StartNew();
+ oldSync.AccountData = MergeEventList(oldSync.AccountData, newSync.AccountData);
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: AccountData took {sw.ElapsedMilliseconds}ms");
+ Trace("AccountData", sw.GetElapsedAndRestart());
+ });
+
+ var presenceTask = Task.Run(() => {
+ var sw = Stopwatch.StartNew();
+ oldSync.Presence = MergeEventListBy(oldSync.Presence, newSync.Presence,
+ static (oldState, newState) => oldState.Sender == newState.Sender && oldState.Type == newState.Type);
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: Presence took {sw.ElapsedMilliseconds}ms");
+ Trace("Presence", sw.GetElapsedAndRestart());
+ });
+
+ {
+ var sw = Stopwatch.StartNew();
+ // TODO: can this be cleaned up?
+ oldSync.DeviceOneTimeKeysCount ??= new();
+ if (newSync.DeviceOneTimeKeysCount is not null)
+ foreach (var (key, value) in newSync.DeviceOneTimeKeysCount)
+ oldSync.DeviceOneTimeKeysCount[key] = value;
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: DeviceOneTimeKeysCount took {sw.ElapsedMilliseconds}ms");
+ Trace("DeviceOneTimeKeysCount", sw.GetElapsedAndRestart());
+ }
+
+ var roomsTask = Task.Run(() => {
+ var sw = Stopwatch.StartNew();
+ if (newSync.Rooms is not null)
+ oldSync.Rooms = MergeRoomsDataStructure(oldSync.Rooms, newSync.Rooms, Trace);
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: Rooms took {sw.ElapsedMilliseconds}ms");
+ Trace("Rooms", sw.GetElapsedAndRestart());
+ });
+
+ var toDeviceTask = Task.Run(() => {
+ var sw = Stopwatch.StartNew();
+ // oldSync.ToDevice = MergeEventList(oldSync.ToDevice, newSync.ToDevice);
+ oldSync.ToDevice = AppendEventList(oldSync.ToDevice, newSync.ToDevice);
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: ToDevice took {sw.ElapsedMilliseconds}ms");
+ Trace("ToDevice", sw.GetElapsedAndRestart());
+ });
+
+ var deviceListsTask = Task.Run(() => {
+ var sw = Stopwatch.StartNew();
+ oldSync.DeviceLists ??= new SyncResponse.DeviceListsDataStructure();
+ oldSync.DeviceLists.Changed ??= [];
+ oldSync.DeviceLists.Left ??= [];
+ if (newSync.DeviceLists?.Changed is not null)
+ foreach (var s in newSync.DeviceLists.Changed!) {
+ oldSync.DeviceLists.Left.Remove(s);
+ oldSync.DeviceLists.Changed.Add(s);
+ }
+
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: DeviceLists.Changed took {sw.ElapsedMilliseconds}ms");
+ Trace("DeviceLists.Changed", sw.GetElapsedAndRestart());
+
+ if (newSync.DeviceLists?.Left is not null)
+ foreach (var s in newSync.DeviceLists.Left!) {
+ oldSync.DeviceLists.Changed.Remove(s);
+ oldSync.DeviceLists.Left.Add(s);
+ }
+
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: DeviceLists.Left took {sw.ElapsedMilliseconds}ms");
+ Trace("DeviceLists.Left", sw.GetElapsedAndRestart());
+ });
+
+ await Task.WhenAll(accountDataTask, presenceTask, roomsTask, toDeviceTask, deviceListsTask);
+
+ return oldSync;
+ }
+
+#region Merge rooms
+
+ private SyncResponse.RoomsDataStructure MergeRoomsDataStructure(SyncResponse.RoomsDataStructure? oldState, SyncResponse.RoomsDataStructure newState,
+ Action<string, TimeSpan> trace) {
+ var sw = Stopwatch.StartNew();
+ if (oldState is null) return newState;
+
+ if (newState.Join is { Count: > 0 })
+ if (oldState.Join is null)
+ oldState.Join = newState.Join;
+ else
+ foreach (var (key, value) in newState.Join)
+ if (!oldState.Join.TryAdd(key, value))
+ oldState.Join[key] = MergeJoinedRoomDataStructure(oldState.Join[key], value, key, trace);
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: MergeRoomsDataStructure.Join took {sw.ElapsedMilliseconds}ms");
+ trace("MergeRoomsDataStructure.Join", sw.GetElapsedAndRestart());
+
+ if (newState.Invite is { Count: > 0 })
+ if (oldState.Invite is null)
+ oldState.Invite = newState.Invite;
+ else
+ foreach (var (key, value) in newState.Invite)
+ if (!oldState.Invite.TryAdd(key, value))
+ oldState.Invite[key] = MergeInvitedRoomDataStructure(oldState.Invite[key], value, key, trace);
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: MergeRoomsDataStructure.Invite took {sw.ElapsedMilliseconds}ms");
+ trace("MergeRoomsDataStructure.Invite", sw.GetElapsedAndRestart());
+
+ if (newState.Leave is { Count: > 0 })
+ if (oldState.Leave is null)
+ oldState.Leave = newState.Leave;
+ else
+ foreach (var (key, value) in newState.Leave) {
+ if (!oldState.Leave.TryAdd(key, value))
+ oldState.Leave[key] = MergeLeftRoomDataStructure(oldState.Leave[key], value, key, trace);
+ if (oldState.Invite?.ContainsKey(key) ?? false) oldState.Invite.Remove(key);
+ if (oldState.Join?.ContainsKey(key) ?? false) oldState.Join.Remove(key);
+ }
+
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: MergeRoomsDataStructure.Leave took {sw.ElapsedMilliseconds}ms");
+ trace("MergeRoomsDataStructure.Leave", sw.GetElapsedAndRestart());
+
return oldState;
}
- private SyncResponse.RoomsDataStructure.LeftRoomDataStructure MergeLeftRoomDataStructure(SyncResponse.RoomsDataStructure.LeftRoomDataStructure oldData,
- SyncResponse.RoomsDataStructure.LeftRoomDataStructure newData) {
- oldData.AccountData ??= new EventList();
- oldData.AccountData.Events ??= new List<StateEventResponse>();
- oldData.Timeline ??= new SyncResponse.RoomsDataStructure.JoinedRoomDataStructure.TimelineDataStructure();
- oldData.Timeline.Events ??= new List<StateEventResponse>();
- oldData.State ??= new EventList();
- oldData.State.Events ??= new List<StateEventResponse>();
+ private static SyncResponse.RoomsDataStructure.LeftRoomDataStructure MergeLeftRoomDataStructure(SyncResponse.RoomsDataStructure.LeftRoomDataStructure oldData,
+ SyncResponse.RoomsDataStructure.LeftRoomDataStructure newData, string roomId, Action<string, TimeSpan> trace) {
+ var sw = Stopwatch.StartNew();
- if (newData.AccountData?.Events is not null)
- oldData.AccountData.Events.MergeStateEventLists(newData.AccountData?.Events ?? new List<StateEventResponse>());
+ oldData.AccountData = MergeEventList(oldData.AccountData, newData.AccountData);
+ trace($"LeftRoomDataStructure.AccountData/{roomId}", sw.GetElapsedAndRestart());
- if (newData.Timeline?.Events is not null)
- oldData.Timeline.Events.MergeStateEventLists(newData.Timeline?.Events ?? new List<StateEventResponse>());
+ oldData.Timeline = AppendEventList(oldData.Timeline, newData.Timeline) as SyncResponse.RoomsDataStructure.JoinedRoomDataStructure.TimelineDataStructure
+ ?? throw new InvalidOperationException("Merged room timeline was not TimelineDataStructure");
oldData.Timeline.Limited = newData.Timeline?.Limited ?? oldData.Timeline.Limited;
oldData.Timeline.PrevBatch = newData.Timeline?.PrevBatch ?? oldData.Timeline.PrevBatch;
+ trace($"LeftRoomDataStructure.Timeline/{roomId}", sw.GetElapsedAndRestart());
- if (newData.State?.Events is not null)
- oldData.State.Events.MergeStateEventLists(newData.State?.Events ?? new List<StateEventResponse>());
+ oldData.State = MergeEventList(oldData.State, newData.State);
+ trace($"LeftRoomDataStructure.State/{roomId}", sw.GetElapsedAndRestart());
return oldData;
}
- private SyncResponse.RoomsDataStructure.InvitedRoomDataStructure MergeInvitedRoomDataStructure(SyncResponse.RoomsDataStructure.InvitedRoomDataStructure oldData,
- SyncResponse.RoomsDataStructure.InvitedRoomDataStructure newData) {
- oldData.InviteState ??= new EventList();
- oldData.InviteState.Events ??= new List<StateEventResponse>();
- if (newData.InviteState?.Events is not null)
- oldData.InviteState.Events.MergeStateEventLists(newData.InviteState?.Events ?? new List<StateEventResponse>());
+ private static SyncResponse.RoomsDataStructure.InvitedRoomDataStructure MergeInvitedRoomDataStructure(SyncResponse.RoomsDataStructure.InvitedRoomDataStructure oldData,
+ SyncResponse.RoomsDataStructure.InvitedRoomDataStructure newData, string roomId, Action<string, TimeSpan> trace) {
+ var sw = Stopwatch.StartNew();
+ oldData.InviteState = MergeEventList(oldData.InviteState, newData.InviteState);
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: MergeInvitedRoomDataStructure.InviteState took {sw.ElapsedMilliseconds}ms for {roomId}");
+ trace($"InvitedRoomDataStructure.InviteState/{roomId}", sw.GetElapsedAndRestart());
return oldData;
}
- private SyncResponse.RoomsDataStructure.JoinedRoomDataStructure MergeJoinedRoomDataStructure(SyncResponse.RoomsDataStructure.JoinedRoomDataStructure oldData,
- SyncResponse.RoomsDataStructure.JoinedRoomDataStructure newData) {
- oldData.AccountData ??= new EventList();
- oldData.AccountData.Events ??= new List<StateEventResponse>();
- oldData.Timeline ??= new SyncResponse.RoomsDataStructure.JoinedRoomDataStructure.TimelineDataStructure();
- oldData.Timeline.Events ??= new List<StateEventResponse>();
- oldData.State ??= new EventList();
- oldData.State.Events ??= new List<StateEventResponse>();
- oldData.Ephemeral ??= new EventList();
- oldData.Ephemeral.Events ??= new List<StateEventResponse>();
+ private static SyncResponse.RoomsDataStructure.JoinedRoomDataStructure MergeJoinedRoomDataStructure(SyncResponse.RoomsDataStructure.JoinedRoomDataStructure oldData,
+ SyncResponse.RoomsDataStructure.JoinedRoomDataStructure newData, string roomId, Action<string, TimeSpan> trace) {
+ var sw = Stopwatch.StartNew();
+
+ oldData.AccountData = MergeEventList(oldData.AccountData, newData.AccountData);
- if (newData.AccountData?.Events is not null)
- oldData.AccountData.Events.MergeStateEventLists(newData.AccountData?.Events ?? new List<StateEventResponse>());
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: MergeJoinedRoomDataStructure.AccountData took {sw.ElapsedMilliseconds}ms for {roomId}");
+ trace($"JoinedRoomDataStructure.AccountData/{roomId}", sw.GetElapsedAndRestart());
- if (newData.Timeline?.Events is not null)
- oldData.Timeline.Events.MergeStateEventLists(newData.Timeline?.Events ?? new List<StateEventResponse>());
+ oldData.Timeline = AppendEventList(oldData.Timeline, newData.Timeline) as SyncResponse.RoomsDataStructure.JoinedRoomDataStructure.TimelineDataStructure
+ ?? throw new InvalidOperationException("Merged room timeline was not TimelineDataStructure");
oldData.Timeline.Limited = newData.Timeline?.Limited ?? oldData.Timeline.Limited;
oldData.Timeline.PrevBatch = newData.Timeline?.PrevBatch ?? oldData.Timeline.PrevBatch;
- if (newData.State?.Events is not null)
- oldData.State.Events.MergeStateEventLists(newData.State?.Events ?? new List<StateEventResponse>());
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: MergeJoinedRoomDataStructure.Timeline took {sw.ElapsedMilliseconds}ms for {roomId}");
+ trace($"JoinedRoomDataStructure.Timeline/{roomId}", sw.GetElapsedAndRestart());
- if (newData.Ephemeral?.Events is not null)
- oldData.Ephemeral.Events.MergeStateEventLists(newData.Ephemeral?.Events ?? new List<StateEventResponse>());
+ oldData.State = MergeEventList(oldData.State, newData.State);
+
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: MergeJoinedRoomDataStructure.State took {sw.ElapsedMilliseconds}ms for {roomId}");
+ trace($"JoinedRoomDataStructure.State/{roomId}", sw.GetElapsedAndRestart());
+
+ oldData.Ephemeral = MergeEventList(oldData.Ephemeral, newData.Ephemeral);
+
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: MergeJoinedRoomDataStructure.Ephemeral took {sw.ElapsedMilliseconds}ms for {roomId}");
+ trace($"JoinedRoomDataStructure.Ephemeral/{roomId}", sw.GetElapsedAndRestart());
oldData.UnreadNotifications ??= new SyncResponse.RoomsDataStructure.JoinedRoomDataStructure.UnreadNotificationsDataStructure();
oldData.UnreadNotifications.HighlightCount = newData.UnreadNotifications?.HighlightCount ?? oldData.UnreadNotifications.HighlightCount;
oldData.UnreadNotifications.NotificationCount = newData.UnreadNotifications?.NotificationCount ?? oldData.UnreadNotifications.NotificationCount;
- oldData.Summary ??= new SyncResponse.RoomsDataStructure.JoinedRoomDataStructure.SummaryDataStructure {
- Heroes = newData.Summary?.Heroes ?? oldData.Summary.Heroes,
- JoinedMemberCount = newData.Summary?.JoinedMemberCount ?? oldData.Summary.JoinedMemberCount,
- InvitedMemberCount = newData.Summary?.InvitedMemberCount ?? oldData.Summary.InvitedMemberCount
- };
- oldData.Summary.Heroes = newData.Summary?.Heroes ?? oldData.Summary.Heroes;
- oldData.Summary.JoinedMemberCount = newData.Summary?.JoinedMemberCount ?? oldData.Summary.JoinedMemberCount;
- oldData.Summary.InvitedMemberCount = newData.Summary?.InvitedMemberCount ?? oldData.Summary.InvitedMemberCount;
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: MergeJoinedRoomDataStructure.UnreadNotifications took {sw.ElapsedMilliseconds}ms for {roomId}");
+ trace($"JoinedRoom$DataStructure.UnreadNotifications/{roomId}", sw.GetElapsedAndRestart());
+
+ if (oldData.Summary is null)
+ oldData.Summary = newData.Summary;
+ else {
+ oldData.Summary.Heroes = newData.Summary?.Heroes ?? oldData.Summary.Heroes;
+ oldData.Summary.JoinedMemberCount = newData.Summary?.JoinedMemberCount ?? oldData.Summary.JoinedMemberCount;
+ oldData.Summary.InvitedMemberCount = newData.Summary?.InvitedMemberCount ?? oldData.Summary.InvitedMemberCount;
+ }
+
+ if (sw.ElapsedMilliseconds > 100) Console.WriteLine($"WARN: MergeJoinedRoomDataStructure.Summary took {sw.ElapsedMilliseconds}ms for {roomId}");
+ trace($"JoinedRoomDataStructure.Summary/{roomId}", sw.GetElapsedAndRestart());
return oldData;
}
#endregion
+
+ private static EventList? MergeEventList(EventList? oldState, EventList? newState) {
+ if (newState is null) return oldState;
+ if (oldState is null) {
+ return newState;
+ }
+
+ if (newState.Events is null) return oldState;
+ if (oldState.Events is null) {
+ oldState.Events = newState.Events;
+ return oldState;
+ }
+
+ // oldState.Events.MergeStateEventLists(newState.Events);
+ oldState = MergeEventListBy(oldState, newState, static (oldEvt, newEvt) => oldEvt.Type == newEvt.Type && oldEvt.StateKey == newEvt.StateKey);
+ return oldState;
+ }
+
+ private static EventList? MergeEventListBy(EventList? oldState, EventList? newState, Func<StateEventResponse, StateEventResponse, bool> comparer) {
+ if (newState is null) return oldState;
+ if (oldState is null) {
+ return newState;
+ }
+
+ if (newState.Events is null) return oldState;
+ if (oldState.Events is null) {
+ oldState.Events = newState.Events;
+ return oldState;
+ }
+
+ oldState.Events.ReplaceBy(newState.Events, comparer);
+ return oldState;
+ }
+
+ private static EventList? AppendEventList(EventList? oldState, EventList? newState) {
+ if (newState is null) return oldState;
+ if (oldState is null) {
+ return newState;
+ }
+
+ if (newState.Events is null) return oldState;
+ if (oldState.Events is null) {
+ oldState.Events = newState.Events;
+ return oldState;
+ }
+
+ oldState.Events.AddRange(newState.Events);
+ return oldState;
+ }
}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs
index 6be49b9..5fd3311 100644
--- a/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs
+++ b/LibMatrix/Homeservers/AuthenticatedHomeserverGeneric.cs
@@ -5,8 +5,8 @@ using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Web;
using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
-using LibMatrix.Extensions;
+using LibMatrix.EventTypes.Spec;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Filters;
using LibMatrix.Helpers;
using LibMatrix.Homeservers.Extensions.NamedCaches;
@@ -14,7 +14,6 @@ using LibMatrix.Responses;
using LibMatrix.RoomTypes;
using LibMatrix.Services;
using LibMatrix.Utilities;
-using Microsoft.Extensions.Logging.Abstractions;
namespace LibMatrix.Homeservers;
@@ -41,14 +40,14 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver {
public string UserId => WhoAmI.UserId;
public string UserLocalpart => UserId.Split(":")[0][1..];
public string ServerName => UserId.Split(":", 2)[1];
+ public string BaseUrl => ClientHttpClient.BaseAddress!.ToString().TrimEnd('/');
[JsonIgnore]
public string AccessToken { get; set; }
- public HsNamedCaches NamedCaches { get; set; } = null!;
+ public HsNamedCaches NamedCaches { get; set; }
public GenericRoom GetRoom(string roomId) {
- if (roomId is null || !roomId.StartsWith("!")) throw new ArgumentException("Room ID must start with !", nameof(roomId));
return new GenericRoom(this, roomId);
}
@@ -171,8 +170,9 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver {
try {
return await GetAccountDataAsync<T>(key);
}
- catch (Exception e) {
- return default;
+ catch (MatrixException e) {
+ if (e is { ErrorCode: MatrixException.ErrorCodes.M_NOT_FOUND }) return default;
+ throw;
}
}
@@ -186,6 +186,16 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver {
#endregion
+#region MSC 4133
+
+ public async Task UpdateProfilePropertyAsync(string name, object? value) {
+ var caps = await GetCapabilitiesAsync();
+ if (caps is null) throw new Exception("Failed to get capabilities");
+ }
+
+#endregion
+
+ [Obsolete("This method assumes no support for MSC 4069 and MSC 4133")]
public async Task UpdateProfileAsync(UserProfileResponse? newProfile, bool preserveCustomRoomProfile = true) {
if (newProfile is null) return;
Console.WriteLine($"Updating profile for {WhoAmI.UserId} to {newProfile.ToJson(ignoreNull: true)} (preserving room profiles: {preserveCustomRoomProfile})");
@@ -377,11 +387,11 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver {
/// <returns>All account data.</returns>
/// <exception cref="Exception"></exception>
public async Task<EventList?> EnumerateAccountData() {
- var syncHelper = new SyncHelper(this);
- syncHelper.FilterId = await NamedCaches.FilterCache.GetOrSetValueAsync(CommonSyncFilters.GetAccountData);
+ var syncHelper = new SyncHelper(this) {
+ FilterId = await NamedCaches.FilterCache.GetOrSetValueAsync(CommonSyncFilters.GetAccountData)
+ };
var resp = await syncHelper.SyncAsync();
- if (resp is null) throw new Exception("Sync failed");
- return resp.AccountData;
+ return resp?.AccountData ?? throw new Exception("Sync failed");
}
private Dictionary<string, string>? _namedFilterCache;
@@ -410,22 +420,22 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver {
#region Authenticated Media
// TODO: implement /_matrix/client/v1/media/config when it's actually useful - https://spec.matrix.org/v1.11/client-server-api/#get_matrixclientv1mediaconfig
+ private bool? _serverSupportsAuthMedia;
- private (string ServerName, string MediaId) ParseMxcUri(string mxcUri) {
- if (!mxcUri.StartsWith("mxc://")) throw new ArgumentException("Matrix Content URIs must start with 'mxc://'", nameof(mxcUri));
- var parts = mxcUri[6..].Split('/');
- if (parts.Length != 2) throw new ArgumentException($"Invalid Matrix Content URI '{mxcUri}' passed! Matrix Content URIs must exist of only 2 parts!", nameof(mxcUri));
- return (parts[0], parts[1]);
- }
+ public async Task<string> GetMediaUrlAsync(MxcUri mxcUri, string? filename = null, int? timeout = null) {
+ if (_serverSupportsAuthMedia == true) return mxcUri.ToDownloadUri(BaseUrl, filename, timeout);
+ if (_serverSupportsAuthMedia == false) return mxcUri.ToLegacyDownloadUri(BaseUrl, filename, timeout);
- public async Task<Stream> GetMediaStreamAsync(string mxcUri, string? filename = null, int? timeout = null) {
- var (serverName, mediaId) = ParseMxcUri(mxcUri);
try {
- var uri = $"/_matrix/client/v1/media/download/{serverName}/{mediaId}";
- if (!string.IsNullOrWhiteSpace(filename)) uri += $"/{HttpUtility.UrlEncode(filename)}";
- if (timeout is not null) uri += $"?timeout_ms={timeout}";
- var res = await ClientHttpClient.GetAsync(uri);
- return await res.Content.ReadAsStreamAsync();
+ // Console.WriteLine($"Trying authenticated media URL: {uri}");
+ var res = await ClientHttpClient.SendAsync(new() {
+ Method = HttpMethod.Head,
+ RequestUri = (new Uri(mxcUri.ToDownloadUri(BaseUrl, filename, timeout), string.IsNullOrWhiteSpace(BaseUrl) ? UriKind.Relative : UriKind.Absolute))
+ });
+ if (res.IsSuccessStatusCode) {
+ _serverSupportsAuthMedia = true;
+ return mxcUri.ToDownloadUri(BaseUrl, filename, timeout);
+ }
}
catch (MatrixException e) {
if (e is not { ErrorCode: "M_UNKNOWN" }) throw;
@@ -433,11 +443,15 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver {
//fallback to legacy media
try {
- var uri = $"/_matrix/media/v1/download/{serverName}/{mediaId}";
- if (!string.IsNullOrWhiteSpace(filename)) uri += $"/{HttpUtility.UrlEncode(filename)}";
- if (timeout is not null) uri += $"?timeout_ms={timeout}";
- var res = await ClientHttpClient.GetAsync(uri);
- return await res.Content.ReadAsStreamAsync();
+ // Console.WriteLine($"Trying legacy media URL: {uri}");
+ var res = await ClientHttpClient.SendAsync(new() {
+ Method = HttpMethod.Head,
+ RequestUri = new(mxcUri.ToLegacyDownloadUri(BaseUrl, filename, timeout), string.IsNullOrWhiteSpace(BaseUrl) ? UriKind.Relative : UriKind.Absolute)
+ });
+ if (res.IsSuccessStatusCode) {
+ _serverSupportsAuthMedia = false;
+ return mxcUri.ToLegacyDownloadUri(BaseUrl, filename, timeout);
+ }
}
catch (MatrixException e) {
if (e is not { ErrorCode: "M_UNKNOWN" }) throw;
@@ -445,19 +459,25 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver {
throw new LibMatrixException() {
ErrorCode = LibMatrixException.ErrorCodes.M_UNSUPPORTED,
- Error = "Failed to download media"
+ Error = "Failed to get media URL"
};
- // return default;
}
- public async Task<Stream> GetThumbnailStreamAsync(string mxcUri, int width, int height, string? method = null, int? timeout = null) {
- var (serverName, mediaId) = ParseMxcUri(mxcUri);
+ public async Task<Stream> GetMediaStreamAsync(string mxcUri, string? filename = null, int? timeout = null) {
+ var uri = await GetMediaUrlAsync(mxcUri, filename, timeout);
+ var res = await ClientHttpClient.GetAsync(uri);
+ return await res.Content.ReadAsStreamAsync();
+ }
+
+ public async Task<Stream> GetThumbnailStreamAsync(MxcUri mxcUri, int width, int height, string? method = null, int? timeout = null) {
+ var (serverName, mediaId) = mxcUri;
+
try {
var uri = new Uri($"/_matrix/client/v1/thumbnail/{serverName}/{mediaId}");
uri = uri.AddQuery("width", width.ToString());
uri = uri.AddQuery("height", height.ToString());
if (!string.IsNullOrWhiteSpace(method)) uri = uri.AddQuery("method", method);
- if (timeout is not null) uri = uri.AddQuery("timeout_ms", timeout.ToString());
+ if (timeout is not null) uri = uri.AddQuery("timeout_ms", timeout.ToString()!);
var res = await ClientHttpClient.GetAsync(uri.ToString());
return await res.Content.ReadAsStreamAsync();
@@ -468,11 +488,11 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver {
//fallback to legacy media
try {
- var uri = new Uri($"/_matrix/media/v1/thumbnail/{serverName}/{mediaId}");
+ var uri = new Uri($"/_matrix/media/v3/thumbnail/{serverName}/{mediaId}");
uri = uri.AddQuery("width", width.ToString());
uri = uri.AddQuery("height", height.ToString());
if (!string.IsNullOrWhiteSpace(method)) uri = uri.AddQuery("method", method);
- if (timeout is not null) uri = uri.AddQuery("timeout_ms", timeout.ToString());
+ if (timeout is not null) uri = uri.AddQuery("timeout_ms", timeout.ToString()!);
var res = await ClientHttpClient.GetAsync(uri.ToString());
return await res.Content.ReadAsStreamAsync();
@@ -496,16 +516,16 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver {
catch (MatrixException e) {
if (e is not { ErrorCode: "M_UNRECOGNIZED" }) throw;
}
-
+
//fallback to legacy media
try {
- var res = await ClientHttpClient.GetAsync($"/_matrix/media/v1/preview_url?url={HttpUtility.UrlEncode(url)}");
+ var res = await ClientHttpClient.GetAsync($"/_matrix/media/v3/preview_url?url={HttpUtility.UrlEncode(url)}");
return await res.Content.ReadFromJsonAsync<Dictionary<string, JsonValue>>();
}
catch (MatrixException e) {
if (e is not { ErrorCode: "M_UNRECOGNIZED" }) throw;
}
-
+
throw new LibMatrixException() {
ErrorCode = LibMatrixException.ErrorCodes.M_UNSUPPORTED,
Error = "Failed to download URL preview"
@@ -513,4 +533,86 @@ public class AuthenticatedHomeserverGeneric : RemoteHomeserver {
}
#endregion
+
+ public Task ReportRoomAsync(string roomId, string reason) =>
+ ClientHttpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{roomId}/report", new {
+ reason
+ });
+
+ public async Task ReportRoomEventAsync(string roomId, string eventId, string reason, int score = 0, bool ignoreSender = false) {
+ await ClientHttpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{roomId}/report/{eventId}", new {
+ reason,
+ score
+ });
+
+ if (ignoreSender) {
+ var eventContent = await GetRoom(roomId).GetEventAsync(eventId);
+ var sender = eventContent.Sender;
+ await IgnoreUserAsync(sender);
+ }
+ }
+
+ public async Task ReportUserAsync(string userId, string reason, bool ignore = false) {
+ await ClientHttpClient.PostAsJsonAsync($"/_matrix/client/v3/users/{userId}/report", new {
+ reason
+ });
+
+ if (ignore) {
+ await IgnoreUserAsync(userId);
+ }
+ }
+
+ public async Task<IgnoredUserListEventContent> GetIgnoredUserListAsync() {
+ return await GetAccountDataOrNullAsync<IgnoredUserListEventContent>(IgnoredUserListEventContent.EventId) ?? new();
+ }
+
+ public async Task IgnoreUserAsync(string userId, IgnoredUserListEventContent.IgnoredUserContent? content = null) {
+ content ??= new();
+
+ var ignoredUserList = await GetIgnoredUserListAsync();
+ ignoredUserList.IgnoredUsers.TryAdd(userId, content);
+ await SetAccountDataAsync(IgnoredUserListEventContent.EventId, ignoredUserList);
+ }
+
+ private class CapabilitiesResponse {
+ [JsonPropertyName("capabilities")]
+ public Dictionary<string, object>? Capabilities { get; set; }
+ }
+
+#region Room Directory/aliases
+
+ public async Task SetRoomAliasAsync(string roomAlias, string roomId) {
+ var resp = await ClientHttpClient.PutAsJsonAsync($"/_matrix/client/v3/directory/room/{HttpUtility.UrlEncode(roomAlias)}", new RoomIdResponse() {
+ RoomId = roomId
+ });
+ if (!resp.IsSuccessStatusCode) {
+ Console.WriteLine($"Failed to set room alias: {await resp.Content.ReadAsStringAsync()}");
+ throw new InvalidDataException($"Failed to set room alias: {await resp.Content.ReadAsStringAsync()}");
+ }
+ }
+
+ public async Task DeleteRoomAliasAsync(string roomAlias) {
+ var resp = await ClientHttpClient.DeleteAsync("/_matrix/client/v3/directory/room/" + HttpUtility.UrlEncode(roomAlias));
+ if (!resp.IsSuccessStatusCode) {
+ Console.WriteLine($"Failed to set room alias: {await resp.Content.ReadAsStringAsync()}");
+ throw new InvalidDataException($"Failed to set room alias: {await resp.Content.ReadAsStringAsync()}");
+ }
+ }
+
+ public async Task<RoomAliasesResponse> GetLocalRoomAliasesAsync(string roomId) {
+ var resp = await ClientHttpClient.GetAsync($"/_matrix/client/v3/rooms/{HttpUtility.UrlEncode(roomId)}/aliases");
+ if (!resp.IsSuccessStatusCode) {
+ Console.WriteLine($"Failed to get room aliases: {await resp.Content.ReadAsStringAsync()}");
+ throw new InvalidDataException($"Failed to get room aliases: {await resp.Content.ReadAsStringAsync()}");
+ }
+
+ return await resp.Content.ReadFromJsonAsync<RoomAliasesResponse>() ?? throw new Exception("Failed to get room aliases?");
+ }
+
+ public class RoomAliasesResponse {
+ [JsonPropertyName("aliases")]
+ public required List<string> Aliases { get; set; }
+ }
+
+#endregion
}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverHSE.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverHSE.cs
new file mode 100644
index 0000000..1cc8ca2
--- /dev/null
+++ b/LibMatrix/Homeservers/AuthenticatedHomeserverHSE.cs
@@ -0,0 +1,16 @@
+using LibMatrix.Homeservers.ImplementationDetails.Synapse;
+using LibMatrix.Responses;
+using LibMatrix.Services;
+
+namespace LibMatrix.Homeservers;
+
+public class AuthenticatedHomeserverHSE : AuthenticatedHomeserverGeneric {
+ public AuthenticatedHomeserverHSE(string serverName, HomeserverResolverService.WellKnownUris wellKnownUris, string? proxy, string accessToken) : base(serverName,
+ wellKnownUris, proxy, accessToken) { }
+
+ public Task<Dictionary<string, LoginResponse>> GetExternalProfilesAsync() =>
+ ClientHttpClient.GetFromJsonAsync<Dictionary<string, LoginResponse>>("/_hse/client/v1/external_profiles");
+
+ public Task SetExternalProfile(string sessionName, LoginResponse session) =>
+ ClientHttpClient.PutAsJsonAsync($"/_hse/client/v1/external_profiles/{sessionName}", session);
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/AuthenticatedHomeserverSynapse.cs b/LibMatrix/Homeservers/AuthenticatedHomeserverSynapse.cs
index 83ebf20..1c0a656 100644
--- a/LibMatrix/Homeservers/AuthenticatedHomeserverSynapse.cs
+++ b/LibMatrix/Homeservers/AuthenticatedHomeserverSynapse.cs
@@ -1,7 +1,4 @@
-using ArcaneLibs.Extensions;
-using LibMatrix.Filters;
using LibMatrix.Homeservers.ImplementationDetails.Synapse;
-using LibMatrix.Responses.Admin;
using LibMatrix.Services;
namespace LibMatrix.Homeservers;
diff --git a/LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs b/LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs
index 622eef6..1f62637 100644
--- a/LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs
+++ b/LibMatrix/Homeservers/Extensions/NamedCaches/NamedCache.cs
@@ -3,35 +3,72 @@ namespace LibMatrix.Homeservers.Extensions.NamedCaches;
public class NamedCache<T>(AuthenticatedHomeserverGeneric hs, string name) where T : class {
private Dictionary<string, T>? _cache = new();
private DateTime _expiry = DateTime.MinValue;
-
+ private SemaphoreSlim _lock = new(1, 1);
+
+ public TimeSpan ExpiryTime { get; set; } = TimeSpan.FromMinutes(5);
+ public DateTime GetCurrentExpiryTime() => _expiry;
+
+ /// <summary>
+ /// Update the cached map with the latest data from the homeserver.
+ /// </summary>
+ /// <returns>The updated data</returns>
public async Task<Dictionary<string, T>> ReadCacheMapAsync() {
- _cache = await hs.GetAccountDataOrNullAsync<Dictionary<string, T>>(name);
+ try {
+ _cache = await hs.GetAccountDataAsync<Dictionary<string, T>>(name);
+ }
+ catch (MatrixException e) {
+ if (e is { ErrorCode: MatrixException.ErrorCodes.M_NOT_FOUND })
+ _cache = [];
+ else throw;
+ }
return _cache ?? new();
}
-
- public async Task<Dictionary<string,T>> ReadCacheMapCachedAsync() {
+
+ public async Task<Dictionary<string, T>> ReadCacheMapCachedAsync() {
+ await _lock.WaitAsync();
if (_expiry < DateTime.Now || _cache == null) {
_cache = await ReadCacheMapAsync();
- _expiry = DateTime.Now.AddMinutes(5);
+ _expiry = DateTime.Now.Add(ExpiryTime);
}
+ _lock.Release();
+
return _cache;
}
-
- public virtual async Task<T?> GetValueAsync(string key) {
- return (await ReadCacheMapCachedAsync()).GetValueOrDefault(key);
+
+ public virtual async Task<T?> GetValueAsync(string key, bool useCache = true) {
+ return (await (useCache ? ReadCacheMapCachedAsync() : ReadCacheMapAsync())).GetValueOrDefault(key);
}
-
- public virtual async Task<T> SetValueAsync(string key, T value) {
- var cache = await ReadCacheMapCachedAsync();
+
+ public virtual async Task<T> SetValueAsync(string key, T value, bool unsafeUseCache = false) {
+ if (!unsafeUseCache)
+ await _lock.WaitAsync();
+ var cache = await (unsafeUseCache ? ReadCacheMapCachedAsync() : ReadCacheMapAsync());
cache[key] = value;
await hs.SetAccountDataAsync(name, cache);
+ if (!unsafeUseCache)
+ _lock.Release();
+
return value;
}
-
- public virtual async Task<T> GetOrSetValueAsync(string key, Func<Task<T>> value) {
- return (await ReadCacheMapCachedAsync()).GetValueOrDefault(key) ?? await SetValueAsync(key, await value());
+
+ public virtual async Task<T> RemoveValueAsync(string key, bool unsafeUseCache = false) {
+ if (!unsafeUseCache)
+ await _lock.WaitAsync();
+ var cache = await (unsafeUseCache ? ReadCacheMapCachedAsync() : ReadCacheMapAsync());
+ var removedValue = cache[key];
+ cache.Remove(key);
+ await hs.SetAccountDataAsync(name, cache);
+
+ if (!unsafeUseCache)
+ _lock.Release();
+
+ return removedValue;
+ }
+
+ public virtual async Task<T> GetOrSetValueAsync(string key, Func<Task<T>> value, bool unsafeUseCache = false) {
+ return (await (unsafeUseCache ? ReadCacheMapCachedAsync() : ReadCacheMapAsync())).GetValueOrDefault(key) ?? await SetValueAsync(key, await value());
}
}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/Extensions/NamedCaches/NamedFilterCache.cs b/LibMatrix/Homeservers/Extensions/NamedCaches/NamedFilterCache.cs
index 76533a4..e3c5943 100644
--- a/LibMatrix/Homeservers/Extensions/NamedCaches/NamedFilterCache.cs
+++ b/LibMatrix/Homeservers/Extensions/NamedCaches/NamedFilterCache.cs
@@ -1,3 +1,5 @@
+using System.Text.Json.Nodes;
+using ArcaneLibs.Extensions;
using LibMatrix.Filters;
using LibMatrix.Utilities;
@@ -16,7 +18,13 @@ public class NamedFilterCache(AuthenticatedHomeserverGeneric hs) : NamedCache<st
public async Task<string> GetOrSetValueAsync(string key, SyncFilter? filter = null) {
var existingValue = await GetValueAsync(key);
if (existingValue != null) {
- return existingValue;
+ try {
+ var existingFilter = await hs.GetFilterAsync(existingValue);
+ return existingValue;
+ }
+ catch {
+ // ignored
+ }
}
if (filter is null) {
diff --git a/LibMatrix/Homeservers/FederationClient.cs b/LibMatrix/Homeservers/FederationClient.cs
index 22653e4..a2cb12d 100644
--- a/LibMatrix/Homeservers/FederationClient.cs
+++ b/LibMatrix/Homeservers/FederationClient.cs
@@ -1,7 +1,7 @@
using System.Text.Json.Serialization;
using LibMatrix.Extensions;
using LibMatrix.Services;
-using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.VisualBasic.CompilerServices;
namespace LibMatrix.Homeservers;
@@ -14,10 +14,74 @@ public class FederationClient {
if (proxy is not null) HttpClient.DefaultRequestHeaders.Add("MXAE_UPSTREAM", federationEndpoint);
}
- public MatrixHttpClient HttpClient { get; set; } = null!;
- public HomeserverResolverService.WellKnownUris WellKnownUris { get; set; } = null!;
+ public MatrixHttpClient HttpClient { get; set; }
+ public HomeserverResolverService.WellKnownUris WellKnownUris { get; set; }
public async Task<ServerVersionResponse> GetServerVersionAsync() => await HttpClient.GetFromJsonAsync<ServerVersionResponse>("/_matrix/federation/v1/version");
+ public async Task<ServerKeysResponse> GetServerKeysAsync() => await HttpClient.GetFromJsonAsync<ServerKeysResponse>("/_matrix/key/v2/server");
+}
+
+public class ServerKeysResponse {
+ [JsonPropertyName("server_name")]
+ public string ServerName { get; set; }
+
+ [JsonPropertyName("valid_until_ts")]
+ public ulong ValidUntilTs { get; set; }
+
+ [JsonIgnore]
+ public DateTime ValidUntil {
+ get => DateTimeOffset.FromUnixTimeMilliseconds((long)ValidUntilTs).DateTime;
+ set => ValidUntilTs = (ulong)new DateTimeOffset(value).ToUnixTimeMilliseconds();
+ }
+
+ [JsonPropertyName("verify_keys")]
+ public Dictionary<string, CurrentVerifyKey> VerifyKeys { get; set; } = new();
+
+ [JsonIgnore]
+ public Dictionary<VersionedKeyId, CurrentVerifyKey> VerifyKeysById {
+ get => VerifyKeys.ToDictionary(key => (VersionedKeyId)key.Key, key => key.Value);
+ set => VerifyKeys = value.ToDictionary(key => (string)key.Key, key => key.Value);
+ }
+
+ [JsonPropertyName("old_verify_keys")]
+ public Dictionary<string, ExpiredVerifyKey> OldVerifyKeys { get; set; } = new();
+
+ [JsonIgnore]
+ public Dictionary<VersionedKeyId, ExpiredVerifyKey> OldVerifyKeysById {
+ get => OldVerifyKeys.ToDictionary(key => (VersionedKeyId)key.Key, key => key.Value);
+ set => OldVerifyKeys = value.ToDictionary(key => (string)key.Key, key => key.Value);
+ }
+
+ public class VersionedKeyId {
+ public required string Algorithm { get; set; }
+ public required string KeyId { get; set; }
+
+ public static implicit operator VersionedKeyId(string key) {
+ var parts = key.Split(':', 2);
+ if (parts.Length != 2) throw new ArgumentException("Invalid key format. Expected 'algorithm:keyId'.", nameof(key));
+ return new VersionedKeyId { Algorithm = parts[0], KeyId = parts[1] };
+ }
+
+ public static implicit operator string(VersionedKeyId key) => $"{key.Algorithm}:{key.KeyId}";
+ public static implicit operator (string, string)(VersionedKeyId key) => (key.Algorithm, key.KeyId);
+ public static implicit operator VersionedKeyId((string algorithm, string keyId) key) => (key.algorithm, key.keyId);
+ }
+
+ public class CurrentVerifyKey {
+ [JsonPropertyName("key")]
+ public string Key { get; set; }
+ }
+
+ public class ExpiredVerifyKey : CurrentVerifyKey {
+ [JsonPropertyName("expired_ts")]
+ public ulong ExpiredTs { get; set; }
+
+ [JsonIgnore]
+ public DateTime Expired {
+ get => DateTimeOffset.FromUnixTimeMilliseconds((long)ExpiredTs).DateTime;
+ set => ExpiredTs = (ulong)new DateTimeOffset(value).ToUnixTimeMilliseconds();
+ }
+ }
}
public class ServerVersionResponse {
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Filters/SynapseAdminLocalEventReportQueryFilter.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Filters/SynapseAdminLocalEventReportQueryFilter.cs
new file mode 100644
index 0000000..c34ad7c
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Filters/SynapseAdminLocalEventReportQueryFilter.cs
@@ -0,0 +1,27 @@
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Filters;
+
+public class SynapseAdminLocalEventReportQueryFilter {
+ public string UserIdContains { get; set; } = "";
+ public string NameContains { get; set; } = "";
+ public string CanonicalAliasContains { get; set; } = "";
+ public string VersionContains { get; set; } = "";
+ public string CreatorContains { get; set; } = "";
+ public string EncryptionContains { get; set; } = "";
+ public string JoinRulesContains { get; set; } = "";
+ public string GuestAccessContains { get; set; } = "";
+ public string HistoryVisibilityContains { get; set; } = "";
+
+ public bool Federatable { get; set; } = true;
+ public bool Public { get; set; } = true;
+
+ public int JoinedMembersGreaterThan { get; set; }
+ public int JoinedMembersLessThan { get; set; } = int.MaxValue;
+
+ public int JoinedLocalMembersGreaterThan { get; set; }
+ public int JoinedLocalMembersLessThan { get; set; } = int.MaxValue;
+ public int StateEventsGreaterThan { get; set; }
+ public int StateEventsLessThan { get; set; } = int.MaxValue;
+
+ public bool CheckFederation { get; set; }
+ public bool CheckPublic { get; set; }
+}
\ No newline at end of file
diff --git a/LibMatrix/Filters/LocalRoomQueryFilter.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Filters/SynapseAdminLocalRoomQueryFilter.cs
index b3bd4c0..b8929a0 100644
--- a/LibMatrix/Filters/LocalRoomQueryFilter.cs
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Filters/SynapseAdminLocalRoomQueryFilter.cs
@@ -1,6 +1,6 @@
-namespace LibMatrix.Filters;
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Filters;
-public class LocalRoomQueryFilter {
+public class SynapseAdminLocalRoomQueryFilter {
public string RoomIdContains { get; set; } = "";
public string NameContains { get; set; } = "";
public string CanonicalAliasContains { get; set; } = "";
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Filters/SynapseAdminLocalUserQueryFilter.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Filters/SynapseAdminLocalUserQueryFilter.cs
new file mode 100644
index 0000000..5a4acf7
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Filters/SynapseAdminLocalUserQueryFilter.cs
@@ -0,0 +1,5 @@
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Filters;
+
+public class SynapseAdminLocalUserQueryFilter {
+
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Requests/AdminRoomDeleteRequest.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Requests/AdminRoomDeleteRequest.cs
deleted file mode 100644
index f4c927a..0000000
--- a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Requests/AdminRoomDeleteRequest.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using System.Text.Json.Serialization;
-
-namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Requests;
-
-public class AdminRoomDeleteRequest {
- [JsonPropertyName("new_room_user_id")]
- public string? NewRoomUserId { get; set; }
-
- [JsonPropertyName("room_name")]
- public string? RoomName { get; set; }
-
- [JsonPropertyName("block")]
- public bool Block { get; set; }
-
- [JsonPropertyName("purge")]
- public bool Purge { get; set; }
-
- [JsonPropertyName("message")]
- public string? Message { get; set; }
-
- [JsonPropertyName("force_purge")]
- public bool ForcePurge { get; set; }
-}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Requests/SynapseAdminRegistrationTokenCreateRequest.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Requests/SynapseAdminRegistrationTokenCreateRequest.cs
new file mode 100644
index 0000000..197fd5d
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Requests/SynapseAdminRegistrationTokenCreateRequest.cs
@@ -0,0 +1,31 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseAdminRegistrationTokenUpdateRequest {
+ [JsonPropertyName("uses_allowed")]
+ public int? UsesAllowed { get; set; }
+
+ [JsonPropertyName("expiry_time")]
+ public long? ExpiryTime { get; set; }
+
+ [JsonIgnore]
+ public DateTime? ExpiresAt {
+ get => ExpiryTime.HasValue ? DateTimeOffset.FromUnixTimeMilliseconds(ExpiryTime.Value).DateTime : null;
+ set => ExpiryTime = value.HasValue ? new DateTimeOffset(value.Value).ToUnixTimeMilliseconds() : null;
+ }
+
+ [JsonIgnore]
+ public TimeSpan? ExpiresAfter {
+ get => ExpiryTime.HasValue ? DateTimeOffset.FromUnixTimeMilliseconds(ExpiryTime.Value).DateTime - DateTimeOffset.Now : null;
+ set => ExpiryTime = value.HasValue ? (DateTimeOffset.Now + value.Value).ToUnixTimeMilliseconds() : null;
+ }
+}
+
+public class SynapseAdminRegistrationTokenCreateRequest : SynapseAdminRegistrationTokenUpdateRequest {
+ [JsonPropertyName("token")]
+ public string? Token { get; set; }
+
+ [JsonPropertyName("length")]
+ public int? Length { get; set; }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Requests/SynapseAdminRoomDeleteRequest.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Requests/SynapseAdminRoomDeleteRequest.cs
new file mode 100644
index 0000000..c2b2fac
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Requests/SynapseAdminRoomDeleteRequest.cs
@@ -0,0 +1,60 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Requests;
+
+public class SynapseAdminRoomDeleteRequest {
+ [JsonPropertyName("new_room_user_id")]
+ public string? NewRoomUserId { get; set; }
+
+ [JsonPropertyName("room_name")]
+ public string? RoomName { get; set; }
+
+ [JsonPropertyName("block")]
+ public bool Block { get; set; }
+
+ [JsonPropertyName("purge")]
+ public bool Purge { get; set; }
+
+ [JsonPropertyName("message")]
+ public string? Message { get; set; }
+
+ [JsonPropertyName("force_purge")]
+ public bool ForcePurge { get; set; }
+}
+
+public class SynapseAdminRoomDeleteResponse {
+ [JsonPropertyName("delete_id")]
+ public string DeleteId { get; set; } = null!;
+}
+
+public class SynapseAdminRoomDeleteStatusList {
+ [JsonPropertyName("results")]
+ public List<SynapseAdminRoomDeleteStatus> Results { get; set; }
+}
+
+public class SynapseAdminRoomDeleteStatus {
+ public const string Scheduled = "scheduled";
+ public const string Active = "active";
+ public const string Complete = "complete";
+ public const string Failed = "failed";
+
+ [JsonPropertyName("status")]
+ public string Status { get; set; } = null!;
+
+ [JsonPropertyName("shutdown_room")]
+ public RoomShutdownInfo ShutdownRoom { get; set; }
+
+ public class RoomShutdownInfo {
+ [JsonPropertyName("kicked_users")]
+ public List<string>? KickedUsers { get; set; }
+
+ [JsonPropertyName("failed_to_kick_users")]
+ public List<string>? FailedToKickUsers { get; set; }
+
+ [JsonPropertyName("local_aliases")]
+ public List<string>? LocalAliasses { get; set; }
+
+ [JsonPropertyName("new_room_id")]
+ public string? NewRoomId { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/BackgroundUpdates.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/BackgroundUpdates.cs
new file mode 100644
index 0000000..2394b98
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/BackgroundUpdates.cs
@@ -0,0 +1,28 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseAdminBackgroundUpdateStatusResponse {
+ [JsonPropertyName("enabled")]
+ public bool Enabled { get; set; }
+
+ [JsonPropertyName("current_updates")]
+ public Dictionary<string, BackgroundUpdateInfo> CurrentUpdates { get; set; }
+
+ public class BackgroundUpdateInfo {
+ [JsonPropertyName("name")]
+ public string Name { get; set; }
+
+ [JsonPropertyName("total_item_count")]
+ public int TotalItemCount { get; set; }
+
+ [JsonPropertyName("total_duration_ms")]
+ public double TotalDurationMs { get; set; }
+
+ [JsonPropertyName("average_items_per_ms")]
+ public double AverageItemsPerMs { get; set; }
+
+ [JsonIgnore]
+ public TimeSpan TotalDuration => TimeSpan.FromMilliseconds(TotalDurationMs);
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/Destinations.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/Destinations.cs
new file mode 100644
index 0000000..646a4b5
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/Destinations.cs
@@ -0,0 +1,56 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseAdminDestinationListResult : SynapseNextTokenTotalCollectionResult {
+ [JsonPropertyName("destinations")]
+ public List<SynapseAdminDestinationListResultDestination> Destinations { get; set; } = new();
+
+ public class SynapseAdminDestinationListResultDestination {
+ [JsonPropertyName("destination")]
+ public string Destination { get; set; }
+
+ [JsonPropertyName("retry_last_ts")]
+ public long RetryLastTs { get; set; }
+
+ [JsonPropertyName("retry_interval")]
+ public long RetryInterval { get; set; }
+
+ [JsonPropertyName("failure_ts")]
+ public long? FailureTs { get; set; }
+
+ [JsonPropertyName("last_successful_stream_ordering")]
+ public long? LastSuccessfulStreamOrdering { get; set; }
+
+ [JsonIgnore]
+ public DateTime? FailureTsDateTime {
+ get => FailureTs.HasValue ? DateTimeOffset.FromUnixTimeMilliseconds(FailureTs.Value).DateTime : null;
+ set => FailureTs = value.HasValue ? new DateTimeOffset(value.Value).ToUnixTimeMilliseconds() : null;
+ }
+
+ [JsonIgnore]
+ public DateTime? RetryLastTsDateTime {
+ get => DateTimeOffset.FromUnixTimeMilliseconds(RetryLastTs).DateTime;
+ set => RetryLastTs = new DateTimeOffset(value.Value).ToUnixTimeMilliseconds();
+ }
+
+ [JsonIgnore]
+ public TimeSpan RetryIntervalTimeSpan {
+ get => TimeSpan.FromMilliseconds(RetryInterval);
+ set => RetryInterval = (long)value.TotalMilliseconds;
+ }
+ }
+}
+
+public class SynapseAdminDestinationRoomListResult : SynapseNextTokenTotalCollectionResult {
+ [JsonPropertyName("rooms")]
+ public List<SynapseAdminDestinationRoomListResultRoom> Rooms { get; set; } = new();
+
+ public class SynapseAdminDestinationRoomListResultRoom {
+ [JsonPropertyName("room_id")]
+ public string RoomId { get; set; }
+
+ [JsonPropertyName("stream_ordering")]
+ public int StreamOrdering { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/EventReportListResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/EventReportListResult.cs
new file mode 100644
index 0000000..10fc039
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/EventReportListResult.cs
@@ -0,0 +1,169 @@
+using System.Diagnostics.CodeAnalysis;
+using System.Reflection;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+using ArcaneLibs;
+using ArcaneLibs.Attributes;
+using ArcaneLibs.Extensions;
+using LibMatrix.EventTypes;
+using LibMatrix.Extensions;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseAdminEventReportListResult : SynapseNextTokenTotalCollectionResult {
+ [JsonPropertyName("event_reports")]
+ public List<SynapseAdminEventReportListResultReport> Reports { get; set; } = new();
+
+ public class SynapseAdminEventReportListResultReport {
+ [JsonPropertyName("event_id")]
+ public string EventId { get; set; }
+
+ [JsonPropertyName("id")]
+ public string Id { get; set; }
+
+ [JsonPropertyName("reason")]
+ public string? Reason { get; set; }
+
+ [JsonPropertyName("score")]
+ public int? Score { get; set; }
+
+ [JsonPropertyName("received_ts")]
+ public long ReceivedTs { get; set; }
+
+ [JsonPropertyName("canonical_alias")]
+ public string? CanonicalAlias { get; set; }
+
+ [JsonPropertyName("room_id")]
+ public string RoomId { get; set; }
+
+ [JsonPropertyName("name")]
+ public string? Name { get; set; }
+
+ [JsonPropertyName("sender")]
+ public string Sender { get; set; }
+
+ [JsonPropertyName("user_id")]
+ public string UserId { get; set; }
+
+ [JsonIgnore]
+ public DateTime ReceivedTsDateTime {
+ get => DateTimeOffset.FromUnixTimeMilliseconds(ReceivedTs).DateTime;
+ set => ReceivedTs = new DateTimeOffset(value).ToUnixTimeMilliseconds();
+ }
+ }
+
+ public class SynapseAdminEventReportListResultReportWithDetails : SynapseAdminEventReportListResultReport {
+ [JsonPropertyName("event_json")]
+ public SynapseEventJson EventJson { get; set; }
+
+ public class SynapseEventJson {
+ [JsonPropertyName("auth_events")]
+ public List<string> AuthEvents { get; set; }
+
+ [JsonPropertyName("content")]
+ public JsonObject? RawContent { get; set; }
+
+ [JsonPropertyName("depth")]
+ public int Depth { get; set; }
+
+ [JsonPropertyName("hashes")]
+ public Dictionary<string, string> Hashes { get; set; }
+
+ [JsonPropertyName("origin")]
+ public string Origin { get; set; }
+
+ [JsonPropertyName("origin_server_ts")]
+ public long OriginServerTs { get; set; }
+
+ [JsonPropertyName("prev_events")]
+ public List<string> PrevEvents { get; set; }
+
+ [JsonPropertyName("prev_state")]
+ public List<object> PrevState { get; set; }
+
+ [JsonPropertyName("room_id")]
+ public string RoomId { get; set; }
+
+ [JsonPropertyName("sender")]
+ public string Sender { get; set; }
+
+ [JsonPropertyName("signatures")]
+ public Dictionary<string, Dictionary<string, string>> Signatures { get; set; }
+
+ [JsonPropertyName("type")]
+ public string Type { get; set; }
+
+ [JsonPropertyName("unsigned")]
+ public JsonObject? Unsigned { get; set; }
+
+ // Extra... copied from StateEventResponse
+
+ [JsonIgnore]
+ public Type MappedType => StateEvent.GetStateEventType(Type);
+
+ [JsonIgnore]
+ public bool IsLegacyType => MappedType.GetCustomAttributes<MatrixEventAttribute>().FirstOrDefault(x => x.EventName == Type)?.Legacy ?? false;
+
+ [JsonIgnore]
+ public string FriendlyTypeName => MappedType.GetFriendlyNameOrNull() ?? Type;
+
+ [JsonIgnore]
+ public string FriendlyTypeNamePlural => MappedType.GetFriendlyNamePluralOrNull() ?? Type;
+
+ private static readonly JsonSerializerOptions TypedContentSerializerOptions = new() {
+ Converters = {
+ new JsonFloatStringConverter(),
+ new JsonDoubleStringConverter(),
+ new JsonDecimalStringConverter()
+ }
+ };
+
+ [JsonIgnore]
+ [SuppressMessage("ReSharper", "PropertyCanBeMadeInitOnly.Global")]
+ public EventContent? TypedContent {
+ get {
+ ClassCollector<EventContent>.ResolveFromAllAccessibleAssemblies();
+ // if (Type == "m.receipt") {
+ // return null;
+ // }
+ try {
+ var mappedType = StateEvent.GetStateEventType(Type);
+ if (mappedType == typeof(UnknownEventContent))
+ Console.WriteLine($"Warning: unknown event type '{Type}'");
+ var deserialisedContent = (EventContent)RawContent.Deserialize(mappedType, TypedContentSerializerOptions)!;
+ return deserialisedContent;
+ }
+ catch (JsonException e) {
+ Console.WriteLine(e);
+ Console.WriteLine("Content:\n" + (RawContent?.ToJson() ?? "null"));
+ }
+
+ return null;
+ }
+ set {
+ if (value is null)
+ RawContent?.Clear();
+ else
+ RawContent = JsonSerializer.Deserialize<JsonObject>(JsonSerializer.Serialize(value, value.GetType(),
+ new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }));
+ }
+ }
+
+ //debug
+ [JsonIgnore]
+ public string InternalSelfTypeName {
+ get {
+ var res = GetType().Name switch {
+ "StateEvent`1" => "StateEvent",
+ _ => GetType().Name
+ };
+ return res;
+ }
+ }
+
+ [JsonIgnore]
+ public string InternalContentTypeName => TypedContent?.GetType().Name ?? "null";
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RegistrationTokenListResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RegistrationTokenListResult.cs
new file mode 100644
index 0000000..fa92ef9
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RegistrationTokenListResult.cs
@@ -0,0 +1,31 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseAdminRegistrationTokenListResult {
+ [JsonPropertyName("registration_tokens")]
+ public List<SynapseAdminRegistrationTokenListResultToken> RegistrationTokens { get; set; } = new();
+
+ public class SynapseAdminRegistrationTokenListResultToken {
+ [JsonPropertyName("token")]
+ public string Token { get; set; }
+
+ [JsonPropertyName("uses_allowed")]
+ public int? UsesAllowed { get; set; }
+
+ [JsonPropertyName("pending")]
+ public int Pending { get; set; }
+
+ [JsonPropertyName("completed")]
+ public int Completed { get; set; }
+
+ [JsonPropertyName("expiry_time")]
+ public long? ExpiryTime { get; set; }
+
+ [JsonIgnore]
+ public DateTime? ExpiryTimeDateTime {
+ get => ExpiryTime.HasValue ? DateTimeOffset.FromUnixTimeMilliseconds(ExpiryTime.Value).DateTime : null;
+ set => ExpiryTime = value.HasValue ? new DateTimeOffset(value.Value).ToUnixTimeMilliseconds() : null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/AdminRoomListingResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RoomListResult.cs
index 7ab96ac..d84c89b 100644
--- a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/AdminRoomListingResult.cs
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RoomListResult.cs
@@ -1,8 +1,8 @@
using System.Text.Json.Serialization;
-namespace LibMatrix.Responses.Admin;
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
-public class AdminRoomListingResult {
+public class SynapseAdminRoomListResult {
[JsonPropertyName("offset")]
public int Offset { get; set; }
@@ -16,9 +16,9 @@ public class AdminRoomListingResult {
public int? PrevBatch { get; set; }
[JsonPropertyName("rooms")]
- public List<AdminRoomListingResultRoom> Rooms { get; set; } = new();
+ public List<SynapseAdminRoomListResultRoom> Rooms { get; set; } = new();
- public class AdminRoomListingResultRoom {
+ public class SynapseAdminRoomListResultRoom {
[JsonPropertyName("room_id")]
public required string RoomId { get; set; }
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RoomMediaListResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RoomMediaListResult.cs
new file mode 100644
index 0000000..97e85ad
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/RoomMediaListResult.cs
@@ -0,0 +1,11 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseAdminRoomMediaListResult {
+ [JsonPropertyName("local")]
+ public List<string> Local { get; set; } = new();
+
+ [JsonPropertyName("remote")]
+ public List<string> Remote { get; set; } = new();
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminRoomMemberListResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminRoomMemberListResult.cs
new file mode 100644
index 0000000..cb2ec08
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminRoomMemberListResult.cs
@@ -0,0 +1,11 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseAdminRoomMemberListResult {
+ [JsonPropertyName("members")]
+ public List<string> Members { get; set; }
+
+ [JsonPropertyName("total")]
+ public int Total { get; set; }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminRoomStateResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminRoomStateResult.cs
new file mode 100644
index 0000000..ae36d4e
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminRoomStateResult.cs
@@ -0,0 +1,8 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseAdminRoomStateResult {
+ [JsonPropertyName("state")]
+ public required List<StateEventResponse> Events { get; set; }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminUserRedactIdResponse.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminUserRedactIdResponse.cs
new file mode 100644
index 0000000..3f5f865
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseAdminUserRedactIdResponse.cs
@@ -0,0 +1,22 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseAdminUserRedactIdResponse {
+ [JsonPropertyName("redact_id")]
+ public string RedactionId { get; set; }
+}
+
+public class SynapseAdminRedactStatusResponse {
+ /// <summary>
+ /// One of "scheduled", "active", "completed", "failed"
+ /// </summary>
+ [JsonPropertyName("status")]
+ public string Status { get; set; }
+
+ /// <summary>
+ /// Key: Event ID, Value: Error message
+ /// </summary>
+ [JsonPropertyName("failed_redactions")]
+ public Dictionary<string, string> FailedRedactions { get; set; }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseCollectionResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseCollectionResult.cs
new file mode 100644
index 0000000..36a5596
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseCollectionResult.cs
@@ -0,0 +1,250 @@
+using System.Buffers;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using ArcaneLibs.Extensions;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseNextTokenTotalCollectionResult {
+ [JsonPropertyName("total")]
+ public int Total { get; set; }
+
+ [JsonPropertyName("next_token")]
+ public string? NextToken { get; set; }
+}
+
+// [JsonConverter(typeof(SynapseCollectionJsonConverter<>))]
+public class SynapseCollectionResult<T>(string chunkKey = "chunk", string prevTokenKey = "prev_token", string nextTokenKey = "next_token", string totalKey = "total") {
+ public int? Total { get; set; }
+ public string? PrevToken { get; set; }
+ public string? NextToken { get; set; }
+ public List<T> Chunk { get; set; } = [];
+
+ // TODO: figure out how to provide an IAsyncEnumerable<T> for this
+ // https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/use-utf8jsonreader#read-from-a-stream-using-utf8jsonreader
+
+ // public async IAsyncEnumerable<T> FromJsonAsync(Stream stream) {
+ //
+ // }
+
+ public SynapseCollectionResult<T> FromJson(Stream stream, Action<T> action) {
+ byte[] buffer = new byte[4096];
+ _ = stream.Read(buffer);
+ var reader = new Utf8JsonReader(buffer, isFinalBlock: false, state: default);
+
+ try {
+ FromJsonInternal(stream, ref buffer, ref reader, action);
+ }
+ catch (JsonException e) {
+ Console.WriteLine($"Caught a JsonException: {e}");
+ int hexdumpWidth = 64;
+ Console.WriteLine($"Check hexdump line {reader.BytesConsumed / hexdumpWidth} index {reader.BytesConsumed % hexdumpWidth}");
+ buffer.HexDump(64);
+ }
+ finally { }
+
+ return this;
+ }
+
+ private void FromJsonInternal(Stream stream, ref byte[] buffer, ref Utf8JsonReader reader, Action<T> action) {
+ while (!reader.IsFinalBlock) {
+ while (!reader.Read()) {
+ GetMoreBytesFromStream(stream, ref buffer, ref reader);
+ }
+
+ if (reader.TokenType == JsonTokenType.PropertyName) {
+ var propName = reader.GetString();
+ Console.WriteLine($"SynapseCollectionResult: encountered property name: {propName}");
+
+ while (!reader.Read()) {
+ GetMoreBytesFromStream(stream, ref buffer, ref reader);
+ }
+
+ Console.WriteLine($"{reader.BytesConsumed}/{stream.Position} {reader.TokenType}");
+
+ if (propName == totalKey && reader.TokenType == JsonTokenType.Number) {
+ Total = reader.GetInt32();
+ }
+ else if (propName == prevTokenKey && reader.TokenType == JsonTokenType.String) {
+ PrevToken = reader.GetString();
+ }
+ else if (propName == nextTokenKey && reader.TokenType == JsonTokenType.String) {
+ NextToken = reader.GetString();
+ }
+ else if (propName == chunkKey) {
+ if (reader.TokenType == JsonTokenType.StartArray) {
+ while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) {
+ // if (reader.TokenType == JsonTokenType.EndArray) {
+ // break;
+ // }
+ // Console.WriteLine($"Encountered token in chunk: {reader.TokenType}");
+ // var _buf = reader.ValueSequence.ToArray();
+ // try {
+ // var item = JsonSerializer.Deserialize<T>(_buf);
+ // action(item);
+ // Chunk.Add(item);
+ // }
+ // catch(JsonException e) {
+ // Console.WriteLine($"Caught a JsonException: {e}");
+ // int hexdumpWidth = 64;
+ //
+ // // Console.WriteLine($"Check hexdump line {reader.BytesConsumed / hexdumpWidth} index {reader.BytesConsumed % hexdumpWidth}");
+ // Console.WriteLine($"Buffer length: {_buf.Length}");
+ // _buf.HexDump(64);
+ // throw;
+ // }
+ var item = ReadItem(stream, ref buffer, ref reader);
+ action(item);
+ Chunk.Add(item);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private T ReadItem(Stream stream, ref byte[] buffer, ref Utf8JsonReader reader) {
+ while (!reader.Read()) {
+ GetMoreBytesFromStream(stream, ref buffer, ref reader);
+ }
+
+ // handle nullable types
+ if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>)) {
+ if (reader.TokenType == JsonTokenType.Null) {
+ return default(T);
+ }
+ }
+
+ // if(typeof(T) == typeof(string)) {
+ // return (T)(object)reader.GetString();
+ // }
+ // else if(typeof(T) == typeof(int)) {
+ // return (T)(object)reader.GetInt32();
+ // }
+ // else {
+ // var _buf = reader.ValueSequence.ToArray();
+ // return JsonSerializer.Deserialize<T>(_buf);
+ // }
+
+ // default branch uses "object?" cast to avoid compiler error
+ // add more branches here as nessesary
+ // reader.Read();
+ var call = typeof(T) switch {
+ Type t when t == typeof(string) => reader.GetString(),
+ _ => ReadObject<T>(stream, ref buffer, ref reader)
+ };
+
+ object ReadObject<T>(Stream stream, ref byte[] buffer, ref Utf8JsonReader reader) {
+ if (reader.TokenType != JsonTokenType.PropertyName) {
+ throw new JsonException();
+ }
+
+ List<byte> objBuffer = [(byte)'{', ..reader.ValueSequence.ToArray()];
+ var currentDepth = reader.CurrentDepth;
+ while (reader.CurrentDepth >= currentDepth) {
+ while (!reader.Read()) {
+ GetMoreBytesFromStream(stream, ref buffer, ref reader);
+ }
+
+ if (reader.TokenType == JsonTokenType.EndObject && reader.CurrentDepth == currentDepth) {
+ break;
+ }
+
+ objBuffer.AddRange(reader.ValueSpan);
+ }
+
+ return JsonSerializer.Deserialize<T>(objBuffer.ToArray());
+ }
+
+ return (T)call;
+
+ // return JsonSerializer.Deserialize<T>(ref reader);
+ }
+
+ private static void GetMoreBytesFromStream(Stream stream, ref byte[] buffer, ref Utf8JsonReader reader) {
+ int bytesRead;
+ if (reader.BytesConsumed < buffer.Length) {
+ ReadOnlySpan<byte> leftover = buffer.AsSpan((int)reader.BytesConsumed);
+
+ if (leftover.Length == buffer.Length) {
+ Array.Resize(ref buffer, buffer.Length * 2);
+ Console.WriteLine($"Increased buffer size to {buffer.Length}");
+ }
+
+ leftover.CopyTo(buffer);
+ bytesRead = stream.Read(buffer.AsSpan(leftover.Length));
+ }
+ else {
+ bytesRead = stream.Read(buffer);
+ }
+
+ // Console.WriteLine($"String in buffer is: {Encoding.UTF8.GetString(buffer)}");
+ reader = new Utf8JsonReader(buffer, isFinalBlock: bytesRead == 0, reader.CurrentState);
+ }
+}
+
+public partial class SynapseCollectionJsonConverter<T> : JsonConverter<SynapseCollectionResult<T>> {
+ public override SynapseCollectionResult<T>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
+ if (reader.TokenType != JsonTokenType.StartObject) {
+ throw new JsonException();
+ }
+
+ var result = new SynapseCollectionResult<T>();
+ while (reader.Read()) {
+ if (reader.TokenType == JsonTokenType.EndObject) {
+ break;
+ }
+
+ if (reader.TokenType != JsonTokenType.PropertyName) {
+ throw new JsonException();
+ }
+
+ var propName = reader.GetString();
+ reader.Read();
+ if (propName == "total") {
+ result.Total = reader.GetInt32();
+ }
+ else if (propName == "prev_token") {
+ result.PrevToken = reader.GetString();
+ }
+ else if (propName == "next_token") {
+ result.NextToken = reader.GetString();
+ }
+ else if (propName == "chunk") {
+ if (reader.TokenType != JsonTokenType.StartArray) {
+ throw new JsonException();
+ }
+
+ while (reader.Read()) {
+ if (reader.TokenType == JsonTokenType.EndArray) {
+ break;
+ }
+
+ var item = JsonSerializer.Deserialize<T>(ref reader, options);
+ result.Chunk.Add(item);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public override void Write(Utf8JsonWriter writer, SynapseCollectionResult<T> value, JsonSerializerOptions options) {
+ writer.WriteStartObject();
+ if (value.Total is not null)
+ writer.WriteNumber("total", value.Total ?? 0);
+ if (value.PrevToken is not null)
+ writer.WriteString("prev_token", value.PrevToken);
+ if (value.NextToken is not null)
+ writer.WriteString("next_token", value.NextToken);
+
+ writer.WriteStartArray("chunk");
+ foreach (var item in value.Chunk) {
+ JsonSerializer.Serialize(writer, item, options);
+ }
+
+ writer.WriteEndArray();
+ writer.WriteEndObject();
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseUserMediaResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseUserMediaResult.cs
new file mode 100644
index 0000000..5530cc3
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/SynapseUserMediaResult.cs
@@ -0,0 +1,40 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseAdminUserMediaResult {
+ [JsonPropertyName("total")]
+ public int Total { get; set; }
+
+ [JsonPropertyName("next_token")]
+ public string? NextToken { get; set; }
+
+ [JsonPropertyName("media")]
+ public List<MediaInfo> Media { get; set; } = new();
+
+ public class MediaInfo {
+ [JsonPropertyName("created_ts")]
+ public long CreatedTimestamp { get; set; }
+
+ [JsonPropertyName("last_access_ts")]
+ public long? LastAccessTimestamp { get; set; }
+
+ [JsonPropertyName("media_id")]
+ public string MediaId { get; set; }
+
+ [JsonPropertyName("media_length")]
+ public int MediaLength { get; set; }
+
+ [JsonPropertyName("media_type")]
+ public string MediaType { get; set; }
+
+ [JsonPropertyName("quarantined_by")]
+ public string? QuarantinedBy { get; set; }
+
+ [JsonPropertyName("safe_from_quarantine")]
+ public bool SafeFromQuarantine { get; set; }
+
+ [JsonPropertyName("upload_name")]
+ public string UploadName { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/UserListResult.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/UserListResult.cs
new file mode 100644
index 0000000..3132906
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/Models/Responses/UserListResult.cs
@@ -0,0 +1,71 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+
+public class SynapseAdminUserListResult {
+ [JsonPropertyName("offset")]
+ public int Offset { get; set; }
+
+ [JsonPropertyName("total")]
+ public int Total { get; set; }
+
+ [JsonPropertyName("next_token")]
+ public string? NextToken { get; set; }
+
+ [JsonPropertyName("users")]
+ public List<SynapseAdminUserListResultUser> Users { get; set; } = new();
+
+ public class SynapseAdminUserListResultUser {
+ [JsonPropertyName("name")]
+ public string Name { get; set; }
+
+ [JsonPropertyName("is_guest")]
+ public bool? IsGuest { get; set; }
+
+ [JsonPropertyName("admin")]
+ public bool? Admin { get; set; }
+
+ [JsonPropertyName("user_type")]
+ public string? UserType { get; set; }
+
+ [JsonPropertyName("deactivated")]
+ public bool Deactivated { get; set; }
+
+ [JsonPropertyName("erased")]
+ public bool Erased { get; set; }
+
+ [JsonPropertyName("shadow_banned")]
+ public bool ShadowBanned { get; set; }
+
+ [JsonPropertyName("displayname")]
+ public string? DisplayName { get; set; }
+
+ [JsonPropertyName("avatar_url")]
+ public string? AvatarUrl { get; set; }
+
+ [JsonPropertyName("creation_ts")]
+ public long CreationTs { get; set; }
+
+ [JsonPropertyName("last_seen_ts")]
+ public long? LastSeenTs { get; set; }
+
+ [JsonPropertyName("locked")]
+ public bool Locked { get; set; }
+
+ // Requires enabling MSC3866
+ [JsonPropertyName("approved")]
+ public bool? Approved { get; set; }
+
+ [JsonIgnore]
+ public DateTime CreationTsDateTime {
+ get => DateTimeOffset.FromUnixTimeMilliseconds(CreationTs).DateTime;
+ set => CreationTs = new DateTimeOffset(value).ToUnixTimeMilliseconds();
+ }
+
+ [JsonIgnore]
+ public DateTime? LastSeenTsDateTime {
+ get => LastSeenTs.HasValue ? DateTimeOffset.FromUnixTimeMilliseconds(LastSeenTs.Value).DateTime : null;
+ set => LastSeenTs = value.HasValue ? new DateTimeOffset(value.Value).ToUnixTimeMilliseconds() : null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminApiClient.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminApiClient.cs
index ac94a7a..cee3d8d 100644
--- a/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminApiClient.cs
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminApiClient.cs
@@ -1,90 +1,163 @@
+// #define LOG_SKIP
+
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
using ArcaneLibs.Extensions;
+using LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Filters;
+using LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Requests;
+using LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+using LibMatrix.Responses;
using LibMatrix.Filters;
-using LibMatrix.Responses.Admin;
+using LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Filters;
+using LibMatrix.Homeservers.ImplementationDetails.Synapse.Models.Responses;
+using LibMatrix.Responses;
namespace LibMatrix.Homeservers.ImplementationDetails.Synapse;
public class SynapseAdminApiClient(AuthenticatedHomeserverSynapse authenticatedHomeserver) {
- public async IAsyncEnumerable<AdminRoomListingResult.AdminRoomListingResultRoom> SearchRoomsAsync(int limit = int.MaxValue, string orderBy = "name", string dir = "f",
- string? searchTerm = null, LocalRoomQueryFilter? localFilter = null) {
- AdminRoomListingResult? res = null;
+ private SynapseAdminUserCleanupExecutor UserCleanupExecutor { get; } = new(authenticatedHomeserver);
+ // https://github.com/element-hq/synapse/tree/develop/docs/admin_api
+ // https://github.com/element-hq/synapse/tree/develop/docs/usage/administration/admin_api
+
+#region Rooms
+
+ public async IAsyncEnumerable<SynapseAdminRoomListResult.SynapseAdminRoomListResultRoom> SearchRoomsAsync(int limit = int.MaxValue, int chunkLimit = 250,
+ string orderBy = "name", string dir = "f", string? searchTerm = null, SynapseAdminLocalRoomQueryFilter? localFilter = null) {
+ SynapseAdminRoomListResult? res = null;
var i = 0;
int? totalRooms = null;
do {
- var url = $"/_synapse/admin/v1/rooms?limit={Math.Min(limit, 250)}&dir={dir}&order_by={orderBy}";
+ var url = $"/_synapse/admin/v1/rooms?limit={Math.Min(limit, chunkLimit)}&dir={dir}&order_by={orderBy}";
if (!string.IsNullOrEmpty(searchTerm)) url += $"&search_term={searchTerm}";
if (res?.NextBatch is not null) url += $"&from={res.NextBatch}";
Console.WriteLine($"--- ADMIN Querying Room List with URL: {url} - Already have {i} items... ---");
- res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<AdminRoomListingResult>(url);
+ res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRoomListResult>(url);
totalRooms ??= res.TotalRooms;
- Console.WriteLine(res.ToJson(false));
+ // Console.WriteLine(res.ToJson(false));
foreach (var room in res.Rooms) {
if (localFilter is not null) {
- if (!room.RoomId.Contains(localFilter.RoomIdContains)) {
+ if (!string.IsNullOrWhiteSpace(localFilter.RoomIdContains) && !room.RoomId.Contains(localFilter.RoomIdContains, StringComparison.OrdinalIgnoreCase)) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule roomid.");
+#endif
continue;
}
- if (!room.Name?.Contains(localFilter.NameContains) == true) {
+ if (!string.IsNullOrWhiteSpace(localFilter.NameContains) && room.Name?.Contains(localFilter.NameContains, StringComparison.OrdinalIgnoreCase) != true) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule roomname.");
+#endif
continue;
}
- if (!room.CanonicalAlias?.Contains(localFilter.CanonicalAliasContains) == true) {
+ if (!string.IsNullOrWhiteSpace(localFilter.CanonicalAliasContains) &&
+ room.CanonicalAlias?.Contains(localFilter.CanonicalAliasContains, StringComparison.OrdinalIgnoreCase) != true) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule alias.");
+#endif
continue;
}
- if (!room.Version.Contains(localFilter.VersionContains)) {
+ if (!string.IsNullOrWhiteSpace(localFilter.VersionContains) && !room.Version.Contains(localFilter.VersionContains, StringComparison.OrdinalIgnoreCase)) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule version.");
+#endif
continue;
}
- if (!room.Creator.Contains(localFilter.CreatorContains)) {
+ if (!string.IsNullOrWhiteSpace(localFilter.CreatorContains) && !room.Creator.Contains(localFilter.CreatorContains, StringComparison.OrdinalIgnoreCase)) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule creator.");
+#endif
continue;
}
- if (!room.Encryption?.Contains(localFilter.EncryptionContains) == true) {
+ if (!string.IsNullOrWhiteSpace(localFilter.EncryptionContains) &&
+ room.Encryption?.Contains(localFilter.EncryptionContains, StringComparison.OrdinalIgnoreCase) != true) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule encryption.");
+#endif
continue;
}
- if (!room.JoinRules?.Contains(localFilter.JoinRulesContains) == true) {
+ if (!string.IsNullOrWhiteSpace(localFilter.JoinRulesContains) &&
+ room.JoinRules?.Contains(localFilter.JoinRulesContains, StringComparison.OrdinalIgnoreCase) != true) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule joinrules.");
+#endif
continue;
}
- if (!room.GuestAccess?.Contains(localFilter.GuestAccessContains) == true) {
+ if (!string.IsNullOrWhiteSpace(localFilter.GuestAccessContains) &&
+ room.GuestAccess?.Contains(localFilter.GuestAccessContains, StringComparison.OrdinalIgnoreCase) != true) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule guestaccess.");
+#endif
continue;
}
- if (!room.HistoryVisibility?.Contains(localFilter.HistoryVisibilityContains) == true) {
+ if (!string.IsNullOrWhiteSpace(localFilter.HistoryVisibilityContains) &&
+ room.HistoryVisibility?.Contains(localFilter.HistoryVisibilityContains, StringComparison.OrdinalIgnoreCase) != true) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule history visibility.");
+#endif
continue;
}
if (localFilter.CheckFederation && room.Federatable != localFilter.Federatable) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule federation.");
+#endif
continue;
}
if (localFilter.CheckPublic && room.Public != localFilter.Public) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule public.");
+#endif
+ continue;
+ }
+
+ if (room.StateEvents < localFilter.StateEventsGreaterThan || room.StateEvents > localFilter.StateEventsLessThan) {
+ totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule joined local members.");
+#endif
continue;
}
if (room.JoinedMembers < localFilter.JoinedMembersGreaterThan || room.JoinedMembers > localFilter.JoinedMembersLessThan) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule joined members: {localFilter.JoinedMembersGreaterThan} < {room.JoinedLocalMembers} < {localFilter.JoinedMembersLessThan}.");
+#endif
continue;
}
if (room.JoinedLocalMembers < localFilter.JoinedLocalMembersGreaterThan || room.JoinedLocalMembers > localFilter.JoinedLocalMembersLessThan) {
totalRooms--;
+#if LOG_SKIP
+ Console.WriteLine($"Skipped room {room.ToJson(indent: false)} on rule joined local members: {localFilter.JoinedLocalMembersGreaterThan} < {room.JoinedLocalMembers} < {localFilter.JoinedLocalMembersLessThan}.");
+#endif
continue;
}
}
@@ -104,4 +177,386 @@ public class SynapseAdminApiClient(AuthenticatedHomeserverSynapse authenticatedH
}
} while (i < Math.Min(limit, totalRooms ?? limit));
}
+
+#endregion
+
+#region Users
+
+ public async IAsyncEnumerable<SynapseAdminUserListResult.SynapseAdminUserListResultUser> SearchUsersAsync(int limit = int.MaxValue, int chunkLimit = 250,
+ string orderBy = "name", string dir = "f",
+ SynapseAdminLocalUserQueryFilter? localFilter = null) {
+ // TODO: implement filters
+ string? from = null;
+ while (limit > 0) {
+ var url = new Uri("/_synapse/admin/v3/users", UriKind.Relative);
+ url = url.AddQuery("limit", Math.Min(limit, chunkLimit).ToString());
+ if (!string.IsNullOrWhiteSpace(from)) url = url.AddQuery("from", from);
+ if (!string.IsNullOrWhiteSpace(orderBy)) url = url.AddQuery("order_by", orderBy);
+ if (!string.IsNullOrWhiteSpace(dir)) url = url.AddQuery("dir", dir);
+
+ Console.WriteLine($"--- ADMIN Querying User List with URL: {url} ---");
+ // TODO: implement URI methods in http client
+ var res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminUserListResult>(url.ToString());
+ foreach (var user in res.Users) {
+ limit--;
+ yield return user;
+ }
+
+ if (string.IsNullOrWhiteSpace(res.NextToken)) break;
+ from = res.NextToken;
+ }
+ }
+
+ public async Task<LoginResponse> LoginUserAsync(string userId, TimeSpan expireAfter) {
+ var url = new Uri($"/_synapse/admin/v1/users/{userId.UrlEncode()}/login", UriKind.Relative);
+ url.AddQuery("valid_until_ms", DateTimeOffset.UtcNow.Add(expireAfter).ToUnixTimeMilliseconds().ToString());
+ var resp = await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync<JsonObject>(url.ToString(), new());
+ var loginResp = await resp.Content.ReadFromJsonAsync<LoginResponse>();
+ loginResp.UserId = userId; // Synapse only returns the access token
+ return loginResp;
+ }
+
+ public async Task<AuthenticatedHomeserverSynapse> GetHomeserverForUserAsync(string userId, TimeSpan expireAfter) {
+ var loginResp = await LoginUserAsync(userId, expireAfter);
+ var homeserver = new AuthenticatedHomeserverSynapse(
+ authenticatedHomeserver.ServerName, authenticatedHomeserver.WellKnownUris, authenticatedHomeserver.Proxy, loginResp.AccessToken
+ );
+ await homeserver.Initialise();
+ return homeserver;
+ }
+
+#endregion
+
+#region Reports
+
+ public async IAsyncEnumerable<SynapseAdminEventReportListResult.SynapseAdminEventReportListResultReport> GetEventReportsAsync(int limit = int.MaxValue, int chunkLimit = 250,
+ string dir = "f", SynapseAdminLocalEventReportQueryFilter? filter = null) {
+ // TODO: implement filters
+ string? from = null;
+ while (limit > 0) {
+ var url = new Uri("/_synapse/admin/v1/event_reports", UriKind.Relative);
+ url = url.AddQuery("limit", Math.Min(limit, chunkLimit).ToString());
+ if (!string.IsNullOrWhiteSpace(from)) url = url.AddQuery("from", from);
+ Console.WriteLine($"--- ADMIN Querying Reports with URL: {url} ---");
+ var res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminEventReportListResult>(url.ToString());
+ foreach (var report in res.Reports) {
+ limit--;
+ yield return report;
+ }
+
+ if (string.IsNullOrWhiteSpace(res.NextToken)) break;
+ from = res.NextToken;
+ }
+ }
+
+ public async Task<SynapseAdminEventReportListResult.SynapseAdminEventReportListResultReportWithDetails> GetEventReportDetailsAsync(string reportId) {
+ var url = new Uri($"/_synapse/admin/v1/event_reports/{reportId.UrlEncode()}", UriKind.Relative);
+ return await authenticatedHomeserver.ClientHttpClient
+ .GetFromJsonAsync<SynapseAdminEventReportListResult.SynapseAdminEventReportListResultReportWithDetails>(url.ToString());
+ }
+
+ // Utility function to get details straight away
+ public async IAsyncEnumerable<SynapseAdminEventReportListResult.SynapseAdminEventReportListResultReportWithDetails> GetEventReportsWithDetailsAsync(int limit = int.MaxValue,
+ int chunkLimit = 250, string dir = "f", SynapseAdminLocalEventReportQueryFilter? filter = null) {
+ Queue<Task<SynapseAdminEventReportListResult.SynapseAdminEventReportListResultReportWithDetails>> tasks = [];
+ await foreach (var report in GetEventReportsAsync(limit, chunkLimit, dir, filter)) {
+ tasks.Enqueue(GetEventReportDetailsAsync(report.Id));
+ while (tasks.Peek().IsCompleted) yield return await tasks.Dequeue(); // early return if possible
+ }
+
+ while (tasks.Count > 0) yield return await tasks.Dequeue();
+ }
+
+ public async Task DeleteEventReportAsync(string reportId) {
+ var url = new Uri($"/_synapse/admin/v1/event_reports/{reportId.UrlEncode()}", UriKind.Relative);
+ await authenticatedHomeserver.ClientHttpClient.DeleteAsync(url.ToString());
+ }
+
+#endregion
+
+#region Background Updates
+
+ public async Task<bool> GetBackgroundUpdatesEnabledAsync() {
+ var url = new Uri("/_synapse/admin/v1/background_updates/enabled", UriKind.Relative);
+ // The return type is technically wrong, but includes the field we want.
+ var resp = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminBackgroundUpdateStatusResponse>(url.ToString());
+ return resp.Enabled;
+ }
+
+ public async Task<bool> SetBackgroundUpdatesEnabledAsync(bool enabled) {
+ var url = new Uri("/_synapse/admin/v1/background_updates/enabled", UriKind.Relative);
+ // The used types are technically wrong, but include the field we want.
+ var resp = await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync<JsonObject>(url.ToString(), new JsonObject {
+ ["enabled"] = enabled
+ });
+ var json = await resp.Content.ReadFromJsonAsync<SynapseAdminBackgroundUpdateStatusResponse>();
+ return json!.Enabled;
+ }
+
+ public async Task<SynapseAdminBackgroundUpdateStatusResponse> GetBackgroundUpdatesStatusAsync() {
+ var url = new Uri("/_synapse/admin/v1/background_updates/status", UriKind.Relative);
+ return await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminBackgroundUpdateStatusResponse>(url.ToString());
+ }
+
+ /// <summary>
+ /// Run a background job
+ /// </summary>
+ /// <param name="jobName">One of "populate_stats_process_rooms" or "regenerate_directory"</param>
+ public async Task RunBackgroundJobsAsync(string jobName) {
+ var url = new Uri("/_synapse/admin/v1/background_updates/run", UriKind.Relative);
+ await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync(url.ToString(), new JsonObject() {
+ ["job_name"] = jobName
+ });
+ }
+
+#endregion
+
+#region Federation
+
+ public async IAsyncEnumerable<SynapseAdminDestinationListResult.SynapseAdminDestinationListResultDestination> GetFederationDestinationsAsync(int limit = int.MaxValue,
+ int chunkLimit = 250) {
+ string? from = null;
+ while (limit > 0) {
+ var url = new Uri("/_synapse/admin/v1/federation/destinations", UriKind.Relative);
+ url = url.AddQuery("limit", Math.Min(limit, chunkLimit).ToString());
+ if (!string.IsNullOrWhiteSpace(from)) url = url.AddQuery("from", from);
+ Console.WriteLine($"--- ADMIN Querying Federation Destinations with URL: {url} ---");
+ var res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminDestinationListResult>(url.ToString());
+ foreach (var dest in res.Destinations) {
+ limit--;
+ yield return dest;
+ }
+ }
+ }
+
+ public async Task<SynapseAdminDestinationListResult.SynapseAdminDestinationListResultDestination> GetFederationDestinationDetailsAsync(string destination) {
+ var url = new Uri($"/_synapse/admin/v1/federation/destinations/{destination}", UriKind.Relative);
+ return await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminDestinationListResult.SynapseAdminDestinationListResultDestination>(url.ToString());
+ }
+
+ public async IAsyncEnumerable<SynapseAdminDestinationRoomListResult.SynapseAdminDestinationRoomListResultRoom> GetFederationDestinationRoomsAsync(string destination,
+ int limit = int.MaxValue, int chunkLimit = 250) {
+ string? from = null;
+ while (limit > 0) {
+ var url = new Uri($"/_synapse/admin/v1/federation/destinations/{destination}/rooms", UriKind.Relative);
+ url = url.AddQuery("limit", Math.Min(limit, chunkLimit).ToString());
+ if (!string.IsNullOrWhiteSpace(from)) url = url.AddQuery("from", from);
+ Console.WriteLine($"--- ADMIN Querying Federation Destination Rooms with URL: {url} ---");
+ var res = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminDestinationRoomListResult>(url.ToString());
+ foreach (var room in res.Rooms) {
+ limit--;
+ yield return room;
+ }
+ }
+ }
+
+ public async Task ResetFederationConnectionTimeoutAsync(string destination) {
+ await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync($"/_synapse/admin/v1/federation/destinations/{destination}/reset_connection", new JsonObject());
+ }
+
+#endregion
+
+#region Registration Tokens
+
+ // does not support pagination
+ public async Task<List<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken>> GetRegistrationTokensAsync() {
+ var url = new Uri("/_synapse/admin/v1/registration_tokens", UriKind.Relative);
+ var resp = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRegistrationTokenListResult>(url.ToString());
+ return resp.RegistrationTokens;
+ }
+
+ public async Task<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken> GetRegistrationTokenAsync(string token) {
+ var url = new Uri($"/_synapse/admin/v1/registration_tokens/{token.UrlEncode()}", UriKind.Relative);
+ var resp =
+ await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken>(url.ToString());
+ return resp;
+ }
+
+ public async Task<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken> CreateRegistrationTokenAsync(
+ SynapseAdminRegistrationTokenCreateRequest request) {
+ var url = new Uri("/_synapse/admin/v1/", UriKind.Relative);
+ var resp = await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync(url.ToString(), request);
+ var token = await resp.Content.ReadFromJsonAsync<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken>();
+ return token!;
+ }
+
+ public async Task<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken> UpdateRegistrationTokenAsync(string token,
+ SynapseAdminRegistrationTokenUpdateRequest request) {
+ var url = new Uri($"/_synapse/admin/v1/registration_tokens/{token.UrlEncode()}", UriKind.Relative);
+ var resp = await authenticatedHomeserver.ClientHttpClient.PutAsJsonAsync(url.ToString(), request);
+ return await resp.Content.ReadFromJsonAsync<SynapseAdminRegistrationTokenListResult.SynapseAdminRegistrationTokenListResultToken>();
+ }
+
+ public async Task DeleteRegistrationTokenAsync(string token) {
+ var url = new Uri($"/_synapse/admin/v1/registration_tokens/{token.UrlEncode()}", UriKind.Relative);
+ await authenticatedHomeserver.ClientHttpClient.DeleteAsync(url.ToString());
+ }
+
+#endregion
+
+#region Account Validity
+
+ // Does anyone even use this?
+ // README: https://github.com/matrix-org/synapse/issues/15271
+ // -> Don't implement unless requested, if not for this feature almost never being used.
+
+#endregion
+
+#region Experimental Features
+
+ public async Task<Dictionary<string, bool>> GetExperimentalFeaturesAsync(string userId) {
+ var url = new Uri($"/_synapse/admin/v1/experimental_features/{userId.UrlEncode()}", UriKind.Relative);
+ var resp = await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<JsonObject>(url.ToString());
+ return resp["features"]!.GetValue<Dictionary<string, bool>>();
+ }
+
+ public async Task SetExperimentalFeaturesAsync(string userId, Dictionary<string, bool> features) {
+ var url = new Uri($"/_synapse/admin/v1/experimental_features/{userId.UrlEncode()}", UriKind.Relative);
+ await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync<JsonObject>(url.ToString(), new JsonObject {
+ ["features"] = JsonSerializer.Deserialize<JsonObject>(features.ToJson())
+ });
+ }
+
+#endregion
+
+#region Media
+
+ public async Task<SynapseAdminRoomMediaListResult> GetRoomMediaAsync(string roomId) {
+ var url = new Uri($"/_synapse/admin/v1/room/{roomId.UrlEncode()}/media", UriKind.Relative);
+ return await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRoomMediaListResult>(url.ToString());
+ }
+
+ // This is in the user admin API section
+ // public async IAsyncEnumerable<SynapseAdminRoomMediaListResult>
+
+#endregion
+
+ public async Task<SynapseAdminUserRedactIdResponse?> DeleteAllMessages(string mxid, List<string>? rooms = null, string? reason = null, int? limit = 100000,
+ bool waitForCompletion = true) {
+ rooms ??= [];
+
+ Dictionary<string, object> payload = new();
+ if (rooms.Count > 0) payload["rooms"] = rooms;
+ if (!string.IsNullOrEmpty(reason)) payload["reason"] = reason;
+ if (limit.HasValue) payload["limit"] = limit.Value;
+
+ var redactIdResp = await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync($"/_synapse/admin/v1/user/{mxid}/redact", payload);
+ var redactId = await redactIdResp.Content.ReadFromJsonAsync<SynapseAdminUserRedactIdResponse>();
+
+ if (waitForCompletion) {
+ while (true) {
+ var status = await GetRedactStatus(redactId!.RedactionId);
+ if (status?.Status != "pending") break;
+ await Task.Delay(1000);
+ }
+ }
+
+ return redactId;
+ }
+
+ public async Task<SynapseAdminRedactStatusResponse?> GetRedactStatus(string redactId) {
+ return await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRedactStatusResponse>(
+ $"/_synapse/admin/v1/user/redact_status/{redactId}");
+ }
+
+ public async Task DeactivateUserAsync(string mxid, bool erase = false, bool eraseMessages = false, bool extraCleanup = false) {
+ if (eraseMessages) {
+ await DeleteAllMessages(mxid);
+ }
+
+ if (extraCleanup) {
+ await UserCleanupExecutor.CleanupUser(mxid);
+ }
+
+ await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync($"/_synapse/admin/v1/deactivate", new { erase });
+ }
+
+ public async Task ResetPasswordAsync(string mxid, string newPassword, bool logoutDevices = false) {
+ await authenticatedHomeserver.ClientHttpClient.PostAsJsonAsync($"/_synapse/admin/v1/reset_password/{mxid}",
+ new { new_password = newPassword, logout_devices = logoutDevices });
+ }
+
+ public async Task<SynapseAdminUserMediaResult> GetUserMediaAsync(string mxid, int? limit = 100, string? from = null, string? orderBy = null, string? dir = null) {
+ var url = $"/_synapse/admin/v1/users/{mxid}/media";
+ if (limit.HasValue) url += $"?limit={limit}";
+ if (!string.IsNullOrEmpty(from)) url += $"&from={from}";
+ if (!string.IsNullOrEmpty(orderBy)) url += $"&order_by={orderBy}";
+ if (!string.IsNullOrEmpty(dir)) url += $"&dir={dir}";
+ return await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminUserMediaResult>(url);
+ }
+
+ public async IAsyncEnumerable<SynapseAdminUserMediaResult.MediaInfo> GetUserMediaEnumerableAsync(string mxid, int chunkSize = 100, string? orderBy = null, string? dir = null) {
+ SynapseAdminUserMediaResult? res = null;
+ do {
+ res = await GetUserMediaAsync(mxid, chunkSize, res?.NextToken, orderBy, dir);
+ foreach (var media in res.Media) {
+ yield return media;
+ }
+ } while (!string.IsNullOrEmpty(res.NextToken));
+ }
+
+ public async Task BlockRoom(string roomId, bool block = true) {
+ await authenticatedHomeserver.ClientHttpClient.PutAsJsonAsync($"/_synapse/admin/v1/rooms/{roomId.UrlEncode()}/block", new {
+ block
+ });
+ }
+
+ public async Task<SynapseAdminRoomDeleteResponse> DeleteRoom(string roomId, SynapseAdminRoomDeleteRequest request, bool waitForCompletion = true) {
+ var resp = await authenticatedHomeserver.ClientHttpClient.DeleteAsJsonAsync($"/_synapse/admin/v2/rooms/{roomId.UrlEncode()}", request);
+ var deleteResp = await resp.Content.ReadFromJsonAsync<SynapseAdminRoomDeleteResponse>();
+
+ if (waitForCompletion) {
+ while (true) {
+ var status = await GetRoomDeleteStatus(deleteResp!.DeleteId);
+ if (status?.Status != "pending") break;
+ await Task.Delay(1000);
+ }
+ }
+
+ return deleteResp!;
+ }
+
+ public async Task<SynapseAdminRoomDeleteStatus> GetRoomDeleteStatusByRoomId(string roomId) {
+ return await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRoomDeleteStatus>(
+ $"/_synapse/admin/v2/rooms/{roomId.UrlEncode()}/delete_status");
+ }
+
+ public async Task<SynapseAdminRoomDeleteStatus> GetRoomDeleteStatus(string deleteId) {
+ return await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRoomDeleteStatus>(
+ $"/_synapse/admin/v2/rooms/delete_status/{deleteId}");
+ }
+
+ public async Task<SynapseAdminRoomMemberListResult> GetRoomMembersAsync(string roomId) {
+ return await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRoomMemberListResult>($"/_synapse/admin/v1/rooms/{roomId.UrlEncode()}/members");
+ }
+
+ public async Task<SynapseAdminRoomStateResult> GetRoomStateAsync(string roomId, string? type = null) {
+ return string.IsNullOrWhiteSpace(type)
+ ? await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRoomStateResult>($"/_synapse/admin/v1/rooms/{roomId.UrlEncode()}/state")
+ : await authenticatedHomeserver.ClientHttpClient.GetFromJsonAsync<SynapseAdminRoomStateResult>($"/_synapse/admin/v1/rooms/{roomId.UrlEncode()}/state?type={type}");
+ }
+
+ public async Task QuarantineMediaByRoomId(string roomId) {
+ await authenticatedHomeserver.ClientHttpClient.PutAsJsonAsync($"/_synapse/admin/v1/room/{roomId.UrlEncode()}/media/quarantine", new { });
+ }
+
+ public async Task QuarantineMediaByUserId(string mxid) {
+ await authenticatedHomeserver.ClientHttpClient.PutAsJsonAsync($"/_synapse/admin/v1/user/{mxid}/media/quarantine", new { });
+ }
+
+ public async Task QuarantineMediaById(string serverName, string mediaId) {
+ await authenticatedHomeserver.ClientHttpClient.PutAsJsonAsync($"/_synapse/admin/v1/media/quarantine/{serverName}/{mediaId}", new { });
+ }
+
+ public async Task QuarantineMediaById(MxcUri mxcUri) {
+ await authenticatedHomeserver.ClientHttpClient.PutAsJsonAsync($"/_synapse/admin/v1/media/quarantine/{mxcUri.ServerName}/{mxcUri.MediaId}", new { });
+ }
+
+ public async Task DeleteMediaById(string serverName, string mediaId) {
+ await authenticatedHomeserver.ClientHttpClient.DeleteAsync($"/_synapse/admin/v1/media/{serverName}/{mediaId}");
+ }
+
+ public async Task DeleteMediaById(MxcUri mxcUri) {
+ await authenticatedHomeserver.ClientHttpClient.DeleteAsync($"/_synapse/admin/v1/media/{mxcUri.ServerName}/{mxcUri.MediaId}");
+ }
}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminUserCleanupExecutor.cs b/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminUserCleanupExecutor.cs
new file mode 100644
index 0000000..6edf40c
--- /dev/null
+++ b/LibMatrix/Homeservers/ImplementationDetails/Synapse/SynapseAdminUserCleanupExecutor.cs
@@ -0,0 +1,27 @@
+namespace LibMatrix.Homeservers.ImplementationDetails.Synapse;
+
+public class SynapseAdminUserCleanupExecutor(AuthenticatedHomeserverSynapse homeserver) {
+ /*
+ Remove mappings of SSO IDs
+ Delete media uploaded by user (included avatar images)
+ Delete sent and received messages
+ Remove the user's creation (registration) timestamp
+ Remove rate limit overrides
+ Remove from monthly active users
+ Remove user's consent information (consent version and timestamp)
+ */
+ public async Task CleanupUser(string mxid) {
+ // change the user's password to a random one
+ var newPassword = Guid.NewGuid().ToString();
+ await homeserver.Admin.ResetPasswordAsync(mxid, newPassword, true);
+ await homeserver.Admin.DeleteAllMessages(mxid);
+
+ }
+ private async Task RunUserTasks(string mxid) {
+ var auth = await homeserver.Admin.LoginUserAsync(mxid, TimeSpan.FromDays(1));
+ var userHs = new AuthenticatedHomeserverSynapse(homeserver.ServerName, homeserver.WellKnownUris, null, auth.AccessToken);
+ await userHs.Initialise();
+
+
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/RemoteHomeServer.cs b/LibMatrix/Homeservers/RemoteHomeServer.cs
index f9e3d04..f0b35f9 100644
--- a/LibMatrix/Homeservers/RemoteHomeServer.cs
+++ b/LibMatrix/Homeservers/RemoteHomeServer.cs
@@ -1,35 +1,36 @@
using System.Net.Http.Json;
+using System.Text;
using System.Text.Json;
-using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Web;
using ArcaneLibs.Extensions;
using LibMatrix.Extensions;
using LibMatrix.Responses;
using LibMatrix.Services;
-using Microsoft.Extensions.Logging.Abstractions;
namespace LibMatrix.Homeservers;
public class RemoteHomeserver {
- public RemoteHomeserver(string baseUrl, HomeserverResolverService.WellKnownUris wellKnownUris, string? proxy) {
+ public RemoteHomeserver(string serverName, HomeserverResolverService.WellKnownUris wellKnownUris, string? proxy) {
if (string.IsNullOrWhiteSpace(proxy))
proxy = null;
- BaseUrl = baseUrl;
+ ServerNameOrUrl = serverName;
WellKnownUris = wellKnownUris;
+ Proxy = proxy;
ClientHttpClient = new MatrixHttpClient {
- BaseAddress = new Uri(proxy?.TrimEnd('/') ?? wellKnownUris.Client?.TrimEnd('/') ?? throw new InvalidOperationException($"No client URI for {baseUrl}!")),
+ BaseAddress = new Uri(proxy?.TrimEnd('/') ?? wellKnownUris.Client?.TrimEnd('/') ?? throw new InvalidOperationException($"No client URI for {serverName}!")),
// Timeout = TimeSpan.FromSeconds(300) // TODO: Re-implement this
};
- if (proxy is not null) ClientHttpClient.DefaultRequestHeaders.Add("MXAE_UPSTREAM", baseUrl);
+ if (proxy is not null) ClientHttpClient.DefaultRequestHeaders.Add("MXAE_UPSTREAM", serverName);
if (!string.IsNullOrWhiteSpace(wellKnownUris.Server))
FederationClient = new FederationClient(WellKnownUris.Server!, proxy);
Auth = new(this);
}
private Dictionary<string, object> _profileCache { get; set; } = new();
- public string BaseUrl { get; }
+ public string ServerNameOrUrl { get; }
+ public string? Proxy { get; }
[JsonIgnore]
public MatrixHttpClient ClientHttpClient { get; set; }
@@ -51,16 +52,18 @@ public class RemoteHomeserver {
var resp = await ClientHttpClient.GetAsync($"/_matrix/client/v3/profile/{HttpUtility.UrlEncode(mxid)}");
var data = await resp.Content.ReadFromJsonAsync<UserProfileResponse>();
if (!resp.IsSuccessStatusCode) Console.WriteLine("Profile: " + data);
- _profileCache[mxid] = data;
+ _profileCache[mxid] = data ?? throw new InvalidOperationException($"Could not get profile for {mxid}");
return data;
}
+
+ // TODO: Do we need to support retrieving individual profile properties? Is there any use for that besides just getting the full profile?
public async Task<ClientVersionsResponse> GetClientVersionsAsync() {
var resp = await ClientHttpClient.GetAsync($"/_matrix/client/versions");
var data = await resp.Content.ReadFromJsonAsync<ClientVersionsResponse>();
if (!resp.IsSuccessStatusCode) Console.WriteLine("ClientVersions: " + data);
- return data;
+ return data ?? throw new InvalidOperationException("ClientVersionsResponse is null");
}
public async Task<AliasResult> ResolveRoomAliasAsync(string alias) {
@@ -68,7 +71,16 @@ public class RemoteHomeserver {
var data = await resp.Content.ReadFromJsonAsync<AliasResult>();
//var text = await resp.Content.ReadAsStringAsync();
if (!resp.IsSuccessStatusCode) Console.WriteLine("ResolveAlias: " + data.ToJson());
- return data;
+ return data ?? throw new InvalidOperationException($"Could not resolve alias {alias}");
+ }
+
+ public Task<PublicRoomDirectoryResult> GetPublicRoomsAsync(int limit = 100, string? server = null, string? since = null) =>
+ ClientHttpClient.GetFromJsonAsync<PublicRoomDirectoryResult>(buildUriWithParams("/_matrix/client/v3/publicRooms", (nameof(limit), true, limit),
+ (nameof(server), !string.IsNullOrWhiteSpace(server), server), (nameof(since), !string.IsNullOrWhiteSpace(since), since)));
+
+ // TODO: move this somewhere else
+ private string buildUriWithParams(string url, params (string name, bool include, object? value)[] values) {
+ return url + "?" + string.Join("&", values.Where(x => x.include));
}
#region Authentication
@@ -80,12 +92,11 @@ public class RemoteHomeserver {
type = "m.id.user",
user = username
},
- password = password,
+ password,
initial_device_display_name = deviceName
});
var data = await resp.Content.ReadFromJsonAsync<LoginResponse>();
- if (!resp.IsSuccessStatusCode) Console.WriteLine("Login: " + data.ToJson());
- return data;
+ return data ?? throw new InvalidOperationException("LoginResponse is null");
}
public async Task<LoginResponse> RegisterAsync(string username, string password, string? deviceName = null) {
@@ -101,26 +112,64 @@ public class RemoteHomeserver {
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
});
var data = await resp.Content.ReadFromJsonAsync<LoginResponse>();
- if (!resp.IsSuccessStatusCode) Console.WriteLine("Register: " + data.ToJson());
- return data;
+ return data ?? throw new InvalidOperationException("LoginResponse is null");
}
#endregion
[Obsolete("This call uses the deprecated unauthenticated media endpoints, please switch to the relevant AuthenticatedHomeserver methods instead.", true)]
- public string? ResolveMediaUri(string? mxcUri) {
- if (mxcUri is null) return null;
- if (mxcUri.StartsWith("https://")) return mxcUri;
- return $"{ClientHttpClient.BaseAddress}/_matrix/media/v3/download/{mxcUri.Replace("mxc://", "")}".Replace("//_matrix", "/_matrix");
- }
+ public virtual string? ResolveMediaUri(string? mxcUri) => null;
public UserInteractiveAuthClient Auth;
}
+public class PublicRoomDirectoryResult {
+ [JsonPropertyName("chunk")]
+ public List<PublicRoomListItem> Chunk { get; set; }
+
+ [JsonPropertyName("next_batch")]
+ public string? NextBatch { get; set; }
+
+ [JsonPropertyName("prev_batch")]
+ public string? PrevBatch { get; set; }
+
+ [JsonPropertyName("total_room_count_estimate")]
+ public int TotalRoomCountEstimate { get; set; }
+
+ public class PublicRoomListItem {
+ [JsonPropertyName("avatar_url")]
+ public string? AvatarUrl { get; set; }
+
+ [JsonPropertyName("canonical_alias")]
+ public string? CanonicalAlias { get; set; }
+
+ [JsonPropertyName("guest_can_join")]
+ public bool GuestCanJoin { get; set; }
+
+ [JsonPropertyName("join_rule")]
+ public string JoinRule { get; set; }
+
+ [JsonPropertyName("name")]
+ public string? Name { get; set; }
+
+ [JsonPropertyName("num_joined_members")]
+ public int NumJoinedMembers { get; set; }
+
+ [JsonPropertyName("room_id")]
+ public string RoomId { get; set; }
+
+ [JsonPropertyName("topic")]
+ public string? Topic { get; set; }
+
+ [JsonPropertyName("world_readable")]
+ public bool WorldReadable { get; set; }
+ }
+}
+
public class AliasResult {
[JsonPropertyName("room_id")]
- public string RoomId { get; set; } = null!;
+ public string RoomId { get; set; }
[JsonPropertyName("servers")]
- public List<string> Servers { get; set; } = null!;
+ public List<string> Servers { get; set; }
}
\ No newline at end of file
diff --git a/LibMatrix/Homeservers/UserInteractiveAuthClient.cs b/LibMatrix/Homeservers/UserInteractiveAuthClient.cs
index 8be2cb9..8de01d2 100644
--- a/LibMatrix/Homeservers/UserInteractiveAuthClient.cs
+++ b/LibMatrix/Homeservers/UserInteractiveAuthClient.cs
@@ -1,7 +1,5 @@
-using System.Net.Http.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
-using ArcaneLibs.Extensions;
using LibMatrix.Responses;
namespace LibMatrix.Homeservers;
@@ -51,27 +49,27 @@ public class UserInteractiveAuthClient {
internal class RegisterFlowsResponse {
[JsonPropertyName("session")]
- public string Session { get; set; } = null!;
+ public string Session { get; set; }
[JsonPropertyName("flows")]
- public List<RegisterFlow> Flows { get; set; } = null!;
+ public List<RegisterFlow> Flows { get; set; }
[JsonPropertyName("params")]
- public JsonObject Params { get; set; } = null!;
+ public JsonObject Params { get; set; }
public class RegisterFlow {
[JsonPropertyName("stages")]
- public List<string> Stages { get; set; } = null!;
+ public List<string> Stages { get; set; }
}
}
internal class LoginFlowsResponse {
[JsonPropertyName("flows")]
- public List<LoginFlow> Flows { get; set; } = null!;
+ public List<LoginFlow> Flows { get; set; }
public class LoginFlow {
[JsonPropertyName("type")]
- public string Type { get; set; } = null!;
+ public string Type { get; set; }
}
}
diff --git a/LibMatrix/Interfaces/Services/IStorageProvider.cs b/LibMatrix/Interfaces/Services/IStorageProvider.cs
index 165e7df..f7e5488 100644
--- a/LibMatrix/Interfaces/Services/IStorageProvider.cs
+++ b/LibMatrix/Interfaces/Services/IStorageProvider.cs
@@ -1,3 +1,7 @@
+using System.Text.Json;
+using System.Text.Json.Serialization.Metadata;
+using LibMatrix.Responses;
+
namespace LibMatrix.Interfaces.Services;
public interface IStorageProvider {
@@ -17,6 +21,13 @@ public interface IStorageProvider {
Console.WriteLine($"StorageProvider<{GetType().Name}> does not implement SaveObject<T>(key, value)!");
throw new NotImplementedException();
}
+
+ public Task SaveObjectAsync<T>(string key, T value, JsonTypeInfo<T> jsonTypeInfo) {
+ Console.WriteLine($"StorageProvider<{GetType().Name}> does not implement SaveObjectAsync<T>(key, value, typeInfo), using default implementation w/ MemoryStream!");
+ var ms = new MemoryStream();
+ JsonSerializer.Serialize(ms, value, jsonTypeInfo);
+ return SaveStreamAsync(key, ms);
+ }
// load
public Task<T?> LoadObjectAsync<T>(string key) {
@@ -24,6 +35,12 @@ public interface IStorageProvider {
throw new NotImplementedException();
}
+ public async Task<T?> LoadObjectAsync<T>(string key, JsonTypeInfo<T> jsonTypeInfo) {
+ Console.WriteLine($"StorageProvider<{GetType().Name}> does not implement SaveObject<T>(key, typeInfo), using default implementation!");
+ await using var stream = await LoadStreamAsync(key);
+ return JsonSerializer.Deserialize(stream!, jsonTypeInfo);
+ }
+
// check if exists
public Task<bool> ObjectExistsAsync(string key) {
Console.WriteLine($"StorageProvider<{GetType().Name}> does not implement ObjectExists(key)!");
@@ -31,7 +48,7 @@ public interface IStorageProvider {
}
// get all keys
- public Task<List<string>> GetAllKeysAsync() {
+ public Task<IEnumerable<string>> GetAllKeysAsync() {
Console.WriteLine($"StorageProvider<{GetType().Name}> does not implement GetAllKeys()!");
throw new NotImplementedException();
}
@@ -53,4 +70,18 @@ public interface IStorageProvider {
Console.WriteLine($"StorageProvider<{GetType().Name}> does not implement LoadStream(key)!");
throw new NotImplementedException();
}
+
+ // copy
+ public async Task CopyObjectAsync(string sourceKey, string destKey) {
+ Console.WriteLine($"StorageProvider<{GetType().Name}> does not implement CopyObject(sourceKey, destKey), using load + save!");
+ var data = await LoadObjectAsync<object>(sourceKey);
+ await SaveObjectAsync(destKey, data);
+ }
+
+ // move
+ public async Task MoveObjectAsync(string sourceKey, string destKey) {
+ Console.WriteLine($"StorageProvider<{GetType().Name}> does not implement MoveObject(sourceKey, destKey), using copy + delete!");
+ await CopyObjectAsync(sourceKey, destKey);
+ await DeleteObjectAsync(sourceKey);
+ }
}
\ No newline at end of file
diff --git a/LibMatrix/LibMatrix.csproj b/LibMatrix/LibMatrix.csproj
index e037672..62bb48f 100644
--- a/LibMatrix/LibMatrix.csproj
+++ b/LibMatrix/LibMatrix.csproj
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>net8.0</TargetFramework>
+ <TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
@@ -12,23 +12,15 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
- <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
+ <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.1"/>
+ <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.1"/>
+ <ProjectReference Include="..\LibMatrix.EventTypes\LibMatrix.EventTypes.csproj"/>
</ItemGroup>
<ItemGroup>
- <ProjectReference Condition="Exists('..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj')" Include="..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj"/>
- <!-- This is dangerous, but eases development since locking the version will drift out of sync without noticing,
- which causes build errors due to missing functions.
- Using the NuGet version in development is annoying due to delays between pushing and being able to consume.
- If you want to use a time-appropriate version of the library, recursively clone https://cgit.rory.gay/matrix/MatrixUtils.git
- instead, since this will be locked by the MatrixUtils project, which contains both LibMatrix and ArcaneLibs as a submodule. -->
- <PackageReference Condition="!Exists('..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj')" Include="ArcaneLibs" Version="*-preview*"/>
- <ProjectReference Include="..\LibMatrix.EventTypes\LibMatrix.EventTypes.csproj"/>
+ <!-- <PackageReference Include="ArcaneLibs" Version="1.0.0-preview.20250313-104848" Condition="'$(Configuration)' == 'Release'" />-->
+ <!-- <ProjectReference Include="..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj" Condition="'$(Configuration)' == 'Debug'"/>-->
+ <ProjectReference Include="..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj"/>
</ItemGroup>
- <Target Name="ArcaneLibsNugetWarning" AfterTargets="AfterBuild">
- <Warning Text="ArcaneLibs is being referenced from NuGet, which is dangerous. Please read the warning in LibMatrix.csproj!" Condition="!Exists('..\ArcaneLibs\ArcaneLibs\ArcaneLibs.csproj')"/>
- </Target>
-
</Project>
diff --git a/LibMatrix/LibMatrixException.cs b/LibMatrix/LibMatrixException.cs
index 5854826..27cfc2a 100644
--- a/LibMatrix/LibMatrixException.cs
+++ b/LibMatrix/LibMatrixException.cs
@@ -1,5 +1,7 @@
+using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;
using ArcaneLibs.Extensions;
+// ReSharper disable MemberCanBePrivate.Global
namespace LibMatrix;
@@ -20,6 +22,7 @@ public class LibMatrixException : Exception {
_ => $"Unknown error: {GetAsObject().ToJson(ignoreNull: true)}"
}}\nError: {Error}";
+ [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Follows spec naming")]
public static class ErrorCodes {
public const string M_NOT_FOUND = "M_NOT_FOUND";
public const string M_UNSUPPORTED = "M_UNSUPPORTED";
diff --git a/LibMatrix/MatrixException.cs b/LibMatrix/MatrixException.cs
index eb207da..519f99e 100644
--- a/LibMatrix/MatrixException.cs
+++ b/LibMatrix/MatrixException.cs
@@ -1,5 +1,7 @@
+using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;
using ArcaneLibs.Extensions;
+// ReSharper disable MemberCanBePrivate.Global
namespace LibMatrix;
@@ -17,51 +19,56 @@ public class MatrixException : Exception {
[JsonPropertyName("retry_after_ms")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public int? RetryAfterMs { get; set; }
-
+
public string RawContent { get; set; }
public object GetAsObject() => new { errcode = ErrorCode, error = Error, soft_logout = SoftLogout, retry_after_ms = RetryAfterMs };
public string GetAsJson() => GetAsObject().ToJson(ignoreNull: true);
public override string Message =>
- $"{ErrorCode}: {ErrorCode switch {
- // common
- "M_FORBIDDEN" => $"You do not have permission to perform this action: {Error}",
- "M_UNKNOWN_TOKEN" => $"The access token specified was not recognised: {Error}{(SoftLogout == true ? " (soft logout)" : "")}",
- "M_MISSING_TOKEN" => $"No access token was specified: {Error}",
- "M_BAD_JSON" => $"Request contained valid JSON, but it was malformed in some way: {Error}",
- "M_NOT_JSON" => $"Request did not contain valid JSON: {Error}",
- "M_NOT_FOUND" => $"The requested resource was not found: {Error}",
- "M_LIMIT_EXCEEDED" => $"Too many requests have been sent in a short period of time. Wait a while then try again: {Error}",
- "M_UNRECOGNISED" => $"The server did not recognise the request: {Error}",
- "M_UNKOWN" => $"The server encountered an unexpected error: {Error}",
- // endpoint specific
- "M_UNAUTHORIZED" => $"The request did not contain valid authentication information for the target of the request: {Error}",
- "M_USER_DEACTIVATED" => $"The user ID associated with the request has been deactivated: {Error}",
- "M_USER_IN_USE" => $"The user ID associated with the request is already in use: {Error}",
- "M_INVALID_USERNAME" => $"The requested user ID is not valid: {Error}",
- "M_ROOM_IN_USE" => $"The room alias requested is already taken: {Error}",
- "M_INVALID_ROOM_STATE" => $"The room associated with the request is not in a valid state to perform the request: {Error}",
- "M_THREEPID_IN_USE" => $"The threepid requested is already associated with a user ID on this server: {Error}",
- "M_THREEPID_NOT_FOUND" => $"The threepid requested is not associated with any user ID: {Error}",
- "M_THREEPID_AUTH_FAILED" => $"The provided threepid and/or token was invalid: {Error}",
- "M_THREEPID_DENIED" => $"The homeserver does not permit the third party identifier in question: {Error}",
- "M_SERVER_NOT_TRUSTED" => $"The homeserver does not trust the identity server: {Error}",
- "M_UNSUPPORTED_ROOM_VERSION" => $"The room version is not supported: {Error}",
- "M_INCOMPATIBLE_ROOM_VERSION" => $"The room version is incompatible: {Error}",
- "M_BAD_STATE" => $"The request was invalid because the state was invalid: {Error}",
- "M_GUEST_ACCESS_FORBIDDEN" => $"Guest access is forbidden: {Error}",
- "M_CAPTCHA_NEEDED" => $"Captcha needed: {Error}",
- "M_CAPTCHA_INVALID" => $"Captcha invalid: {Error}",
- "M_MISSING_PARAM" => $"Missing parameter: {Error}",
- "M_INVALID_PARAM" => $"Invalid parameter: {Error}",
- "M_TOO_LARGE" => $"The request or entity was too large: {Error}",
- "M_EXCLUSIVE" => $"The resource being requested is reserved by an application service, or the application service making the request has not created the resource: {Error}",
- "M_RESOURCE_LIMIT_EXCEEDED" => $"Exceeded resource limit: {Error}",
- "M_CANNOT_LEAVE_SERVER_NOTICE_ROOM" => $"Cannot leave server notice room: {Error}",
- _ => $"Unknown error: {new { ErrorCode, Error, SoftLogout, RetryAfterMs }.ToJson(ignoreNull: true)}"
- }}";
+ $"{ErrorCode}: " +
+ (!string.IsNullOrWhiteSpace(Error)
+ ? Error
+ : ErrorCode switch {
+ // common
+ "M_FORBIDDEN" => $"You do not have permission to perform this action: {Error}",
+ "M_UNKNOWN_TOKEN" => $"The access token specified was not recognised: {Error}{(SoftLogout == true ? " (soft logout)" : "")}",
+ "M_MISSING_TOKEN" => $"No access token was specified: {Error}",
+ "M_BAD_JSON" => $"Request contained valid JSON, but it was malformed in some way: {Error}",
+ "M_NOT_JSON" => $"Request did not contain valid JSON: {Error}",
+ "M_NOT_FOUND" => $"The requested resource was not found: {Error}",
+ "M_LIMIT_EXCEEDED" => $"Too many requests have been sent in a short period of time. Wait a while then try again: {Error}",
+ "M_UNRECOGNISED" => $"The server did not recognise the request: {Error}",
+ "M_UNKOWN" => $"The server encountered an unexpected error: {Error}",
+ // endpoint specific
+ "M_UNAUTHORIZED" => $"The request did not contain valid authentication information for the target of the request: {Error}",
+ "M_USER_DEACTIVATED" => $"The user ID associated with the request has been deactivated: {Error}",
+ "M_USER_IN_USE" => $"The user ID associated with the request is already in use: {Error}",
+ "M_INVALID_USERNAME" => $"The requested user ID is not valid: {Error}",
+ "M_ROOM_IN_USE" => $"The room alias requested is already taken: {Error}",
+ "M_INVALID_ROOM_STATE" => $"The room associated with the request is not in a valid state to perform the request: {Error}",
+ "M_THREEPID_IN_USE" => $"The threepid requested is already associated with a user ID on this server: {Error}",
+ "M_THREEPID_NOT_FOUND" => $"The threepid requested is not associated with any user ID: {Error}",
+ "M_THREEPID_AUTH_FAILED" => $"The provided threepid and/or token was invalid: {Error}",
+ "M_THREEPID_DENIED" => $"The homeserver does not permit the third party identifier in question: {Error}",
+ "M_SERVER_NOT_TRUSTED" => $"The homeserver does not trust the identity server: {Error}",
+ "M_UNSUPPORTED_ROOM_VERSION" => $"The room version is not supported: {Error}",
+ "M_INCOMPATIBLE_ROOM_VERSION" => $"The room version is incompatible: {Error}",
+ "M_BAD_STATE" => $"The request was invalid because the state was invalid: {Error}",
+ "M_GUEST_ACCESS_FORBIDDEN" => $"Guest access is forbidden: {Error}",
+ "M_CAPTCHA_NEEDED" => $"Captcha needed: {Error}",
+ "M_CAPTCHA_INVALID" => $"Captcha invalid: {Error}",
+ "M_MISSING_PARAM" => $"Missing parameter: {Error}",
+ "M_INVALID_PARAM" => $"Invalid parameter: {Error}",
+ "M_TOO_LARGE" => $"The request or entity was too large: {Error}",
+ "M_EXCLUSIVE" =>
+ $"The resource being requested is reserved by an application service, or the application service making the request has not created the resource: {Error}",
+ "M_RESOURCE_LIMIT_EXCEEDED" => $"Exceeded resource limit: {Error}",
+ "M_CANNOT_LEAVE_SERVER_NOTICE_ROOM" => $"Cannot leave server notice room: {Error}",
+ _ => $"Unknown error: {new { ErrorCode, Error, SoftLogout, RetryAfterMs }.ToJson(ignoreNull: true)}"
+ });
+ [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Follows spec naming")]
public static class ErrorCodes {
public const string M_FORBIDDEN = "M_FORBIDDEN";
public const string M_UNKNOWN_TOKEN = "M_UNKNOWN_TOKEN";
diff --git a/LibMatrix/MxcUri.cs b/LibMatrix/MxcUri.cs
new file mode 100644
index 0000000..875ae53
--- /dev/null
+++ b/LibMatrix/MxcUri.cs
@@ -0,0 +1,43 @@
+using System.Diagnostics.CodeAnalysis;
+
+namespace LibMatrix;
+
+public class MxcUri {
+ public required string ServerName { get; set; }
+ public required string MediaId { get; set; }
+
+ public static MxcUri Parse([StringSyntax("Uri")] string mxcUri) {
+ if (!mxcUri.StartsWith("mxc://")) throw new ArgumentException("Matrix Content URIs must start with 'mxc://'", nameof(mxcUri));
+ var parts = mxcUri[6..].Split('/');
+ if (parts.Length != 2) throw new ArgumentException($"Invalid Matrix Content URI '{mxcUri}' passed! Matrix Content URIs must exist of only 2 parts!", nameof(mxcUri));
+ return new MxcUri {
+ ServerName = parts[0],
+ MediaId = parts[1]
+ };
+ }
+
+ public static implicit operator MxcUri(string mxcUri) => Parse(mxcUri);
+ public static implicit operator string(MxcUri mxcUri) => $"mxc://{mxcUri.ServerName}/{mxcUri.MediaId}";
+ public static implicit operator (string, string)(MxcUri mxcUri) => (mxcUri.ServerName, mxcUri.MediaId);
+ public static implicit operator MxcUri((string serverName, string mediaId) mxcUri) => (mxcUri.serverName, mxcUri.mediaId);
+ // public override string ToString() => $"mxc://{ServerName}/{MediaId}";
+
+ public string ToDownloadUri(string? baseUrl = null, string? filename = null, int? timeout = null) {
+ var uri = $"{baseUrl}/_matrix/client/v1/media/download/{ServerName}/{MediaId}";
+ if (filename is not null) uri += $"/{filename}";
+ if (timeout is not null) uri += $"?timeout={timeout}";
+ return uri;
+ }
+
+ public string ToLegacyDownloadUri(string? baseUrl = null, string? filename = null, int? timeout = null) {
+ var uri = $"{baseUrl}/_matrix/media/v3/download/{ServerName}/{MediaId}";
+ if (filename is not null) uri += $"/{filename}";
+ if (timeout is not null) uri += $"?timeout_ms={timeout}";
+ return uri;
+ }
+
+ public void Deconstruct(out string serverName, out string mediaId) {
+ serverName = ServerName;
+ mediaId = MediaId;
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Responses/CreateRoomRequest.cs b/LibMatrix/Responses/CreateRoomRequest.cs
index 6f47183..6933622 100644
--- a/LibMatrix/Responses/CreateRoomRequest.cs
+++ b/LibMatrix/Responses/CreateRoomRequest.cs
@@ -3,7 +3,7 @@ using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using LibMatrix.EventTypes;
-using LibMatrix.EventTypes.Spec.State;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Homeservers;
namespace LibMatrix.Responses;
@@ -26,7 +26,7 @@ public class CreateRoomRequest {
//we dont want to use this, we want more control
// [JsonPropertyName("preset")]
- // public string Preset { get; set; } = null!;
+ // public string Preset { get; set; }
[JsonPropertyName("initial_state")]
public List<StateEvent>? InitialState { get; set; }
@@ -35,10 +35,11 @@ public class CreateRoomRequest {
/// One of: ["public", "private"]
/// </summary>
[JsonPropertyName("visibility")]
+ // ReSharper disable once UnusedAutoPropertyAccessor.Global
public string? Visibility { get; set; }
[JsonPropertyName("power_level_content_override")]
- public RoomPowerLevelEventContent? PowerLevelContentOverride { get; set; } = null!;
+ public RoomPowerLevelEventContent? PowerLevelContentOverride { get; set; }
[JsonPropertyName("creation_content")]
public JsonObject CreationContent { get; set; } = new();
@@ -46,15 +47,17 @@ public class CreateRoomRequest {
[JsonPropertyName("invite")]
public List<string>? Invite { get; set; }
+ public string? RoomVersion { get; set; }
+
/// <summary>
/// For use only when you can't use the CreationContent property
/// </summary>
- public StateEvent this[string eventType, string eventKey = ""] {
+ public StateEvent? this[string eventType, string eventKey = ""] {
get {
- var stateEvent = InitialState.FirstOrDefault(x => x.Type == eventType && x.StateKey == eventKey);
+ var stateEvent = InitialState?.FirstOrDefault(x => x.Type == eventType && x.StateKey == eventKey);
if (stateEvent == null)
- InitialState.Add(stateEvent = new StateEvent {
+ InitialState?.Add(stateEvent = new StateEvent {
Type = eventType,
StateKey = eventKey,
TypedContent = (EventContent)Activator.CreateInstance(
@@ -77,7 +80,7 @@ public class CreateRoomRequest {
public Dictionary<string, string> Validate() {
Dictionary<string, string> errors = new();
- if (!Regex.IsMatch(RoomAliasName, @"[a-zA-Z0-9_\-]+$"))
+ if (!string.IsNullOrWhiteSpace(RoomAliasName) && !Regex.IsMatch(RoomAliasName, @"[a-zA-Z0-9_\-]+$"))
errors.Add("room_alias_name",
"Room alias name must only contain letters, numbers, underscores, and hyphens.");
@@ -97,7 +100,7 @@ public class CreateRoomRequest {
Invite = 25,
StateDefault = 10,
Redact = 50,
- NotificationsPl = new RoomPowerLevelEventContent.NotificationsPL {
+ NotificationsPl = new RoomPowerLevelEventContent.NotificationsPowerLevels {
Room = 10
},
Events = new Dictionary<string, long> {
@@ -137,7 +140,7 @@ public class CreateRoomRequest {
Invite = 25,
StateDefault = 10,
Redact = 50,
- NotificationsPl = new RoomPowerLevelEventContent.NotificationsPL {
+ NotificationsPl = new RoomPowerLevelEventContent.NotificationsPowerLevels {
Room = 10
},
Events = new Dictionary<string, long> {
diff --git a/LibMatrix/Responses/DeviceKeysUploadRequest.cs b/LibMatrix/Responses/DeviceKeysUploadRequest.cs
new file mode 100644
index 0000000..c93c4c6
--- /dev/null
+++ b/LibMatrix/Responses/DeviceKeysUploadRequest.cs
@@ -0,0 +1,24 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Responses;
+
+public class DeviceKeysUploadRequest {
+ [JsonPropertyName("device_keys")]
+ public DeviceKeysSchema DeviceKeys { get; set; }
+
+
+ [JsonPropertyName("one_time_keys")]
+ public Dictionary<string, OneTimeKey> OneTimeKeys { get; set; }
+
+ public class DeviceKeysSchema {
+ [JsonPropertyName("algorithms")]
+ public List<string> Algorithms { get; set; }
+ }
+ public class OneTimeKey {
+ [JsonPropertyName("key")]
+ public string Key { get; set; }
+
+ [JsonPropertyName("signatures")]
+ public Dictionary<string, Dictionary<string, string>> Signatures { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/EventIdResponse.cs b/LibMatrix/Responses/EventIdResponse.cs
index 4d715a4..9e23210 100644
--- a/LibMatrix/EventIdResponse.cs
+++ b/LibMatrix/Responses/EventIdResponse.cs
@@ -1,8 +1,8 @@
using System.Text.Json.Serialization;
-namespace LibMatrix;
+namespace LibMatrix.Responses;
public class EventIdResponse {
[JsonPropertyName("event_id")]
- public string EventId { get; set; }
+ public required string EventId { get; set; }
}
\ No newline at end of file
diff --git a/LibMatrix/Responses/LoginResponse.cs b/LibMatrix/Responses/LoginResponse.cs
index 28fb245..1944276 100644
--- a/LibMatrix/Responses/LoginResponse.cs
+++ b/LibMatrix/Responses/LoginResponse.cs
@@ -1,30 +1,24 @@
+using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;
-using LibMatrix.Homeservers;
namespace LibMatrix.Responses;
public class LoginResponse {
[JsonPropertyName("access_token")]
- public string AccessToken { get; set; } = null!;
+ public string AccessToken { get; set; }
[JsonPropertyName("device_id")]
- public string DeviceId { get; set; } = null!;
-
- private string? _homeserver;
+ public string DeviceId { get; set; }
[JsonPropertyName("home_server")]
+ [field: AllowNull, MaybeNull]
public string Homeserver {
- get => _homeserver ?? UserId.Split(':', 2).Last();
- protected init => _homeserver = value;
+ get => field ?? UserId.Split(':', 2).Last();
+ set;
}
[JsonPropertyName("user_id")]
- public string UserId { get; set; } = null!;
-
- // public async Task<AuthenticatedHomeserverGeneric> GetAuthenticatedHomeserver(string? proxy = null) {
- // var urls = await new HomeserverResolverService().ResolveHomeserverFromWellKnown(Homeserver);
- // await AuthenticatedHomeserverGeneric.Create<AuthenticatedHomeserverGeneric>(Homeserver, AccessToken, proxy);
- // }
+ public string UserId { get; set; }
}
public class LoginRequest {
diff --git a/LibMatrix/MessagesResponse.cs b/LibMatrix/Responses/MessagesResponse.cs
index 526da74..4912add 100644
--- a/LibMatrix/MessagesResponse.cs
+++ b/LibMatrix/Responses/MessagesResponse.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix;
+namespace LibMatrix.Responses;
public class MessagesResponse {
[JsonPropertyName("start")]
diff --git a/LibMatrix/Responses/SyncResponse.cs b/LibMatrix/Responses/SyncResponse.cs
index e4addb6..d79e820 100644
--- a/LibMatrix/Responses/SyncResponse.cs
+++ b/LibMatrix/Responses/SyncResponse.cs
@@ -1,4 +1,5 @@
using System.Text.Json.Serialization;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
namespace LibMatrix.Responses;
@@ -8,16 +9,16 @@ internal partial class SyncResponseSerializerContext : JsonSerializerContext { }
public class SyncResponse {
[JsonPropertyName("next_batch")]
- public string NextBatch { get; set; } = null!;
+ public string NextBatch { get; set; }
[JsonPropertyName("account_data")]
public EventList? AccountData { get; set; }
[JsonPropertyName("presence")]
- public PresenceDataStructure? Presence { get; set; }
+ public EventList? Presence { get; set; }
[JsonPropertyName("device_one_time_keys_count")]
- public Dictionary<string, int>? DeviceOneTimeKeysCount { get; set; } = null!;
+ public Dictionary<string, int>? DeviceOneTimeKeysCount { get; set; }
[JsonPropertyName("rooms")]
public RoomsDataStructure? Rooms { get; set; }
@@ -28,6 +29,9 @@ public class SyncResponse {
[JsonPropertyName("device_lists")]
public DeviceListsDataStructure? DeviceLists { get; set; }
+ [JsonPropertyName("gay.rory.libmatrix.msc4222_sync_type")]
+ public Msc4222SyncType Msc4222Method { get; set; } = Msc4222SyncType.None;
+
public class DeviceListsDataStructure {
[JsonPropertyName("changed")]
public List<string>? Changed { get; set; }
@@ -39,7 +43,7 @@ public class SyncResponse {
// supporting classes
public class PresenceDataStructure {
[JsonPropertyName("events")]
- public List<StateEventResponse> Events { get; set; } = new();
+ public List<StateEventResponse>? Events { get; set; }
}
public class RoomsDataStructure {
@@ -61,6 +65,22 @@ public class SyncResponse {
[JsonPropertyName("state")]
public EventList? State { get; set; }
+
+ [JsonPropertyName("state_after")]
+ public EventList? StateAfter { get; set; }
+
+ [Obsolete("This property is only used for de/serialisation")]
+ [JsonPropertyName("org.matrix.msc4222.state_after")]
+ public EventList? StateAfterUnstable {
+ get => StateAfter;
+ set => StateAfter = value;
+ }
+
+ public override string ToString() {
+ var lastEvent = Timeline?.Events?.LastOrDefault(x => x.Type == "m.room.member");
+ var membership = (lastEvent?.TypedContent as RoomMemberEventContent);
+ return $"LeftRoomDataStructure: {lastEvent?.Sender} {membership?.Membership} ({membership?.Reason})";
+ }
}
public class JoinedRoomDataStructure {
@@ -70,6 +90,16 @@ public class SyncResponse {
[JsonPropertyName("state")]
public EventList? State { get; set; }
+ [JsonPropertyName("state_after")]
+ public EventList? StateAfter { get; set; }
+
+ [Obsolete("This property is only used for de/serialisation")]
+ [JsonPropertyName("org.matrix.msc4222.state_after")]
+ public EventList? StateAfterUnstable {
+ get => StateAfter;
+ set => StateAfter = value;
+ }
+
[JsonPropertyName("account_data")]
public EventList? AccountData { get; set; }
@@ -82,7 +112,7 @@ public class SyncResponse {
[JsonPropertyName("summary")]
public SummaryDataStructure? Summary { get; set; }
- public class TimelineDataStructure {
+ public class TimelineDataStructure : EventList {
public TimelineDataStructure() { }
public TimelineDataStructure(List<StateEventResponse>? events, bool? limited) {
@@ -90,8 +120,8 @@ public class SyncResponse {
Limited = limited;
}
- [JsonPropertyName("events")]
- public List<StateEventResponse>? Events { get; set; }
+ // [JsonPropertyName("events")]
+ // public List<StateEventResponse>? Events { get; set; }
[JsonPropertyName("prev_batch")]
public string? PrevBatch { get; set; }
@@ -125,4 +155,22 @@ public class SyncResponse {
public EventList? InviteState { get; set; }
}
}
+
+ public long GetDerivedSyncTime() {
+ return ((long[]) [
+ AccountData?.Events?.Max(x => x.OriginServerTs) ?? 0,
+ Presence?.Events?.Max(x => x.OriginServerTs) ?? 0,
+ ToDevice?.Events?.Max(x => x.OriginServerTs) ?? 0,
+ Rooms?.Join?.Values?.Max(x => x.Timeline?.Events?.Max(y => y.OriginServerTs)) ?? 0,
+ Rooms?.Invite?.Values?.Max(x => x.InviteState?.Events?.Max(y => y.OriginServerTs)) ?? 0,
+ Rooms?.Leave?.Values?.Max(x => x.Timeline?.Events?.Max(y => y.OriginServerTs)) ?? 0
+ ]).Max();
+ }
+
+ [JsonConverter(typeof(JsonStringEnumConverter<Msc4222SyncType>))]
+ public enum Msc4222SyncType {
+ None,
+ Server,
+ Emulated
+ }
}
\ No newline at end of file
diff --git a/LibMatrix/Responses/UserDirectoryResponse.cs b/LibMatrix/Responses/UserDirectoryResponse.cs
new file mode 100644
index 0000000..13235d9
--- /dev/null
+++ b/LibMatrix/Responses/UserDirectoryResponse.cs
@@ -0,0 +1,30 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Responses;
+
+public class UserDirectoryResponse {
+ [JsonPropertyName("limited")]
+ public bool Limited { get; set; }
+
+ [JsonPropertyName("results")]
+ public List<UserDirectoryResult> Results { get; set; }
+
+ public class UserDirectoryResult {
+ [JsonPropertyName("avatar_url")]
+ public string? AvatarUrl { get; set; }
+
+ [JsonPropertyName("display_name")]
+ public string? DisplayName { get; set; }
+
+ [JsonPropertyName("user_id")]
+ public string UserId { get; set; }
+ }
+}
+
+public class UserDirectoryRequest {
+ [JsonPropertyName("search_term")]
+ public string SearchTerm { get; set; }
+
+ [JsonPropertyName("limit")]
+ public int? Limit { get; set; }
+}
\ No newline at end of file
diff --git a/LibMatrix/UserIdAndReason.cs b/LibMatrix/Responses/UserIdAndReason.cs
index 99c9eaf..176cf7c 100644
--- a/LibMatrix/UserIdAndReason.cs
+++ b/LibMatrix/Responses/UserIdAndReason.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix;
+namespace LibMatrix.Responses;
internal class UserIdAndReason(string userId = null!, string reason = null!) {
[JsonPropertyName("user_id")]
diff --git a/LibMatrix/Responses/UserProfileResponse.cs b/LibMatrix/Responses/UserProfileResponse.cs
index 6c9380f..30e4c32 100644
--- a/LibMatrix/Responses/UserProfileResponse.cs
+++ b/LibMatrix/Responses/UserProfileResponse.cs
@@ -1,3 +1,4 @@
+using System.Text.Json;
using System.Text.Json.Serialization;
namespace LibMatrix.Responses;
@@ -8,4 +9,18 @@ public class UserProfileResponse {
[JsonPropertyName("displayname")]
public string? DisplayName { get; set; }
+
+ // MSC 4133 - Extending User Profile API with Key:Value pairs
+ [JsonExtensionData]
+ public Dictionary<string, JsonElement>? CustomKeys { get; set; }
+
+ public JsonElement? this[string key] {
+ get => CustomKeys?[key];
+ set {
+ if (value is null)
+ CustomKeys?.Remove(key);
+ else
+ (CustomKeys ??= [])[key] = value.Value;
+ }
+ }
}
\ No newline at end of file
diff --git a/LibMatrix/WhoAmIResponse.cs b/LibMatrix/Responses/WhoAmIResponse.cs
index 10fff35..db47152 100644
--- a/LibMatrix/WhoAmIResponse.cs
+++ b/LibMatrix/Responses/WhoAmIResponse.cs
@@ -1,6 +1,6 @@
using System.Text.Json.Serialization;
-namespace LibMatrix;
+namespace LibMatrix.Responses;
public class WhoAmIResponse {
[JsonPropertyName("user_id")]
diff --git a/LibMatrix/RoomTypes/GenericRoom.cs b/LibMatrix/RoomTypes/GenericRoom.cs
index b9d98bd..fd4db4d 100644
--- a/LibMatrix/RoomTypes/GenericRoom.cs
+++ b/LibMatrix/RoomTypes/GenericRoom.cs
@@ -1,5 +1,4 @@
using System.Collections.Frozen;
-using System.Diagnostics;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Nodes;
@@ -8,13 +7,11 @@ using System.Web;
using ArcaneLibs.Extensions;
using LibMatrix.EventTypes;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.EventTypes.Spec.State;
using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Filters;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
-using LibMatrix.Services;
-using Microsoft.Extensions.Logging.Abstractions;
+using LibMatrix.Responses;
namespace LibMatrix.RoomTypes;
@@ -26,8 +23,6 @@ public class GenericRoom {
throw new ArgumentException("Room ID cannot be null or whitespace", nameof(roomId));
Homeserver = homeserver;
RoomId = roomId;
- // if (GetType() != typeof(SpaceRoom))
- if (GetType() == typeof(GenericRoom)) AsSpace = new SpaceRoom(homeserver, RoomId);
}
public string RoomId { get; set; }
@@ -106,7 +101,7 @@ public class GenericRoom {
Console.WriteLine("WARNING: Homeserver does not support getting event ID from state events, falling back to sync");
var sh = new SyncHelper(Homeserver);
var emptyFilter = new SyncFilter.EventFilter(types: [], limit: 1, senders: [], notTypes: ["*"]);
- var emptyStateFilter = new SyncFilter.RoomFilter.StateFilter(types: [], limit: 1, senders: [], notTypes: ["*"], rooms:[]);
+ var emptyStateFilter = new SyncFilter.RoomFilter.StateFilter(types: [], limit: 1, senders: [], notTypes: ["*"], rooms: []);
sh.Filter = new() {
Presence = emptyFilter,
AccountData = emptyFilter,
@@ -121,10 +116,11 @@ public class GenericRoom {
var sync = await sh.SyncAsync();
var state = sync.Rooms.Join[RoomId].State.Events;
var stateEvent = state.FirstOrDefault(x => x.Type == type && x.StateKey == stateKey);
- if (stateEvent is null) throw new LibMatrixException() {
- ErrorCode = LibMatrixException.ErrorCodes.M_NOT_FOUND,
- Error = "State event not found in sync response"
- };
+ if (stateEvent is null)
+ throw new LibMatrixException() {
+ ErrorCode = LibMatrixException.ErrorCodes.M_NOT_FOUND,
+ Error = "State event not found in sync response"
+ };
return stateEvent.EventId;
}
@@ -137,16 +133,17 @@ public class GenericRoom {
return await GetStateEventAsync(type, stateKey);
}
catch (MatrixException e) {
- if (e.ErrorCode == "M_NOT_FOUND") return default;
+ if (e.ErrorCode == "M_NOT_FOUND") return null;
throw;
}
}
- public async Task<MessagesResponse> GetMessagesAsync(string from = "", int? limit = null, string dir = "b", string filter = "") {
+ public async Task<MessagesResponse> GetMessagesAsync(string from = "", int? limit = null, string dir = "b", string? filter = "") {
var url = $"/_matrix/client/v3/rooms/{RoomId}/messages?dir={dir}";
if (!string.IsNullOrWhiteSpace(from)) url += $"&from={from}";
if (limit is not null) url += $"&limit={limit}";
if (!string.IsNullOrWhiteSpace(filter)) url += $"&filter={filter}";
+
var res = await Homeserver.ClientHttpClient.GetFromJsonAsync<MessagesResponse>(url);
return res;
}
@@ -154,8 +151,8 @@ public class GenericRoom {
/// <summary>
/// Same as <see cref="GetMessagesAsync"/>, except keeps fetching more responses until the beginning of the room is found, or the target message limit is reached
/// </summary>
- public async IAsyncEnumerable<MessagesResponse> GetManyMessagesAsync(string from = "", int limit = 100, string dir = "b", string filter = "", bool includeState = true,
- bool fixForward = false, int chunkSize = 100) {
+ public async IAsyncEnumerable<MessagesResponse> GetManyMessagesAsync(string from = "", int limit = int.MaxValue, string dir = "b", string filter = "", bool includeState = true,
+ bool fixForward = false, int chunkSize = 250) {
if (dir == "f" && fixForward) {
var concat = new List<MessagesResponse>();
while (true) {
@@ -207,7 +204,7 @@ public class GenericRoom {
public async Task<string?> GetNameAsync() => (await GetStateOrNullAsync<RoomNameEventContent>("m.room.name"))?.Name;
- public async Task<RoomIdResponse> JoinAsync(string[]? homeservers = null, string? reason = null, bool checkIfAlreadyMember = true) {
+ public async Task<RoomIdResponse> JoinAsync(IEnumerable<string>? homeservers = null, string? reason = null, bool checkIfAlreadyMember = true) {
if (checkIfAlreadyMember)
try {
var ser = await GetStateEventOrNullAsync(RoomMemberEventContent.EventId, Homeserver.UserId);
@@ -216,68 +213,74 @@ public class GenericRoom {
RoomId = RoomId
};
}
- catch { } //ignore
+ catch {
+ // ignored
+ }
var joinUrl = $"/_matrix/client/v3/join/{HttpUtility.UrlEncode(RoomId)}";
- Console.WriteLine($"Calling {joinUrl} with {homeservers?.Length ?? 0} via's...");
- if (homeservers == null || homeservers.Length == 0) homeservers = new[] { RoomId.Split(':', 2)[1] };
- var fullJoinUrl = $"{joinUrl}?server_name=" + string.Join("&server_name=", homeservers);
+
+ var materialisedHomeservers = homeservers as string[] ?? homeservers?.ToArray() ?? [];
+ if (!materialisedHomeservers.Any()) materialisedHomeservers = [RoomId.Split(':', 2)[1]];
+
+ Console.WriteLine($"Calling {joinUrl} with {materialisedHomeservers.Length} via(s)...");
+
+ var fullJoinUrl = $"{joinUrl}?server_name=" + string.Join("&server_name=", materialisedHomeservers);
+
var res = await Homeserver.ClientHttpClient.PostAsJsonAsync(fullJoinUrl, new {
reason
});
return await res.Content.ReadFromJsonAsync<RoomIdResponse>() ?? throw new Exception("Failed to join room?");
}
- public async IAsyncEnumerable<StateEventResponse> GetMembersEnumerableAsync(bool joinedOnly = true) {
- // var sw = Stopwatch.StartNew();
- var res = await Homeserver.ClientHttpClient.GetAsync($"/_matrix/client/v3/rooms/{RoomId}/members");
- // if (sw.ElapsedMilliseconds > 1000)
- // Console.WriteLine($"Members call responded in {sw.GetElapsedAndRestart()}");
- // else sw.Restart();
- // var resText = await res.Content.ReadAsStringAsync();
- // Console.WriteLine($"Members call response read in {sw.GetElapsedAndRestart()}");
+ public async IAsyncEnumerable<StateEventResponse> 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<ChunkedStateEventResponse>(await res.Content.ReadAsStreamAsync(), new JsonSerializerOptions() {
TypeInfoResolver = ChunkedStateEventResponseSerializerContext.Default
});
- // if (sw.ElapsedMilliseconds > 100)
- // Console.WriteLine($"Members call deserialised in {sw.GetElapsedAndRestart()}");
- // else sw.Restart();
- foreach (var resp in result.Chunk) {
- if (resp?.Type != "m.room.member") continue;
- if (joinedOnly && resp.RawContent?["membership"]?.GetValue<string>() != "join") continue;
+
+ if (result is null) throw new Exception("Failed to deserialise members response");
+
+ foreach (var resp in result.Chunk ?? []) {
+ if (resp.Type != "m.room.member") continue;
+ if (isMembershipSet && resp.RawContent?["membership"]?.GetValue<string>() != membership) continue;
yield return resp;
}
-
- // if (sw.ElapsedMilliseconds > 100)
- // Console.WriteLine($"Members call iterated in {sw.GetElapsedAndRestart()}");
}
- public async Task<FrozenSet<StateEventResponse>> GetMembersListAsync(bool joinedOnly = true) {
- // var sw = Stopwatch.StartNew();
- var res = await Homeserver.ClientHttpClient.GetAsync($"/_matrix/client/v3/rooms/{RoomId}/members");
- // if (sw.ElapsedMilliseconds > 1000)
- // Console.WriteLine($"Members call responded in {sw.GetElapsedAndRestart()}");
- // else sw.Restart();
- // var resText = await res.Content.ReadAsStringAsync();
- // Console.WriteLine($"Members call response read in {sw.GetElapsedAndRestart()}");
+ public async Task<FrozenSet<StateEventResponse>> 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<ChunkedStateEventResponse>(await res.Content.ReadAsStreamAsync(), new JsonSerializerOptions() {
TypeInfoResolver = ChunkedStateEventResponseSerializerContext.Default
});
- // if (sw.ElapsedMilliseconds > 100)
- // Console.WriteLine($"Members call deserialised in {sw.GetElapsedAndRestart()}");
- // else sw.Restart();
+
+ if (result is null) throw new Exception("Failed to deserialise members response");
+
var members = new List<StateEventResponse>();
- foreach (var resp in result.Chunk) {
- if (resp?.Type != "m.room.member") continue;
- if (joinedOnly && resp.RawContent?["membership"]?.GetValue<string>() != "join") continue;
+ foreach (var resp in result.Chunk ?? []) {
+ if (resp.Type != "m.room.member") continue;
+ if (isMembershipSet && resp.RawContent?["membership"]?.GetValue<string>() != membership) continue;
members.Add(resp);
}
- // if (sw.ElapsedMilliseconds > 100)
- // Console.WriteLine($"Members call iterated in {sw.GetElapsedAndRestart()}");
return members.ToFrozenSet();
}
+ public async IAsyncEnumerable<string> GetMemberIdsEnumerableAsync(string? membership = null) {
+ await foreach (var evt in GetMembersEnumerableAsync(membership))
+ yield return evt.StateKey!;
+ }
+
+ public async Task<FrozenSet<string>> GetMemberIdsListAsync(string? membership = null) {
+ var members = await GetMembersListAsync(membership);
+ return members.Select(x => x.StateKey!).ToFrozenSet();
+ }
+
#region Utility shortcuts
public Task<EventIdResponse> SendMessageEventAsync(RoomMessageEventContent content) =>
@@ -285,7 +288,7 @@ public class GenericRoom {
public async Task<List<string>?> GetAliasesAsync() {
var res = await GetStateAsync<RoomAliasEventContent>("m.room.aliases");
- return res.Aliases;
+ return res?.Aliases;
}
public Task<RoomCanonicalAliasEventContent?> GetCanonicalAliasAsync() =>
@@ -317,16 +320,17 @@ public class GenericRoom {
public Task<RoomPowerLevelEventContent?> GetPowerLevelsAsync() =>
GetStateAsync<RoomPowerLevelEventContent>("m.room.power_levels");
- [Obsolete("This method will be merged into GetNameAsync() in the future.")]
public async Task<string> GetNameOrFallbackAsync(int maxMemberNames = 2) {
try {
- return await GetNameAsync();
+ var name = await GetNameAsync();
+ if (!string.IsNullOrEmpty(name)) return name;
+ throw new();
}
catch {
try {
var alias = await GetCanonicalAliasAsync();
- if (alias?.Alias is not null) return alias.Alias;
- throw new Exception("No name or alias");
+ if (!string.IsNullOrWhiteSpace(alias?.Alias)) return alias.Alias;
+ throw new Exception("No alias");
}
catch {
try {
@@ -334,7 +338,8 @@ public class GenericRoom {
var memberList = new List<string>();
var memberCount = 0;
await foreach (var member in members)
- memberList.Add(member.RawContent?["displayname"]?.GetValue<string>() ?? "");
+ if (member.StateKey != Homeserver.UserId)
+ memberList.Add(member.RawContent?["displayname"]?.GetValue<string>() ?? "");
memberCount = memberList.Count;
memberList.RemoveAll(string.IsNullOrWhiteSpace);
memberList = memberList.OrderBy(x => x).ToList();
@@ -376,7 +381,7 @@ public class GenericRoom {
public async Task UnbanAsync(string userId, string? reason = null) =>
await Homeserver.ClientHttpClient.PostAsJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/unban",
- new UserIdAndReason { UserId = userId, Reason = reason});
+ new UserIdAndReason { UserId = userId, Reason = reason });
public async Task InviteUserAsync(string userId, string? reason = null, bool skipExisting = true) {
if (skipExisting && await GetStateOrNullAsync<RoomMemberEventContent>("m.room.member", userId) is not null)
@@ -404,6 +409,15 @@ public class GenericRoom {
return await res.Content.ReadFromJsonAsync<EventIdResponse>() ?? throw new Exception("Failed to send event");
}
+ public async Task<EventIdResponse> SendReactionAsync(string eventId, string key) =>
+ await SendTimelineEventAsync("m.reaction", new RoomMessageReactionEventContent() {
+ RelatesTo = new() {
+ RelationType = "m.annotation",
+ EventId = eventId,
+ Key = key
+ }
+ });
+
public async Task<EventIdResponse?> 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() {
@@ -429,6 +443,16 @@ public class GenericRoom {
return await res.Content.ReadFromJsonAsync<T>();
}
+ public async Task<T?> GetRoomAccountDataOrNullAsync<T>(string key) {
+ try {
+ return await GetRoomAccountDataAsync<T>(key);
+ }
+ catch (MatrixException e) {
+ if (e.ErrorCode == "M_NOT_FOUND") return default;
+ throw;
+ }
+ }
+
public async Task SetRoomAccountDataAsync(string key, object data) {
var res = await Homeserver.ClientHttpClient.PutAsJsonAsync($"/_matrix/client/v3/user/{Homeserver.UserId}/rooms/{RoomId}/account_data/{key}", data);
if (!res.IsSuccessStatusCode) {
@@ -437,13 +461,65 @@ public class GenericRoom {
}
}
- public Task<StateEventResponse> GetEventAsync(string eventId) =>
- Homeserver.ClientHttpClient.GetFromJsonAsync<StateEventResponse>($"/_matrix/client/v3/rooms/{RoomId}/event/{eventId}");
+ public Task<StateEventResponse> GetEventAsync(string eventId, bool includeUnredactedContent = false) =>
+ Homeserver.ClientHttpClient.GetFromJsonAsync<StateEventResponse>($"/_matrix/client/v3/rooms/{RoomId}/event/{eventId}?fi.mau.msc2815.include_unredacted_content={includeUnredactedContent}");
- public async Task<EventIdResponse> RedactEventAsync(string eventToRedact, string reason) {
+ public async Task<EventIdResponse> RedactEventAsync(string eventToRedact, string? reason = null) {
var data = new { reason };
- return (await (await Homeserver.ClientHttpClient.PutAsJsonAsync(
- $"/_matrix/client/v3/rooms/{RoomId}/redact/{eventToRedact}/{Guid.NewGuid()}", data)).Content.ReadFromJsonAsync<EventIdResponse>())!;
+ var url = $"/_matrix/client/v3/rooms/{RoomId}/redact/{eventToRedact}/{Guid.NewGuid().ToString()}";
+ while (true) {
+ try {
+ return (await (await Homeserver.ClientHttpClient.PutAsJsonAsync(url, data)).Content.ReadFromJsonAsync<EventIdResponse>())!;
+ }
+ catch (MatrixException e) {
+ if (e is { ErrorCode: MatrixException.ErrorCodes.M_FORBIDDEN }) throw;
+ throw;
+ }
+ }
+ }
+
+#endregion
+
+#region Ephemeral Events
+
+ /// <summary>
+ /// This tells the server that the user is typing for the next N milliseconds where
+ /// N is the value specified in the timeout key. Alternatively, if typing is false,
+ /// it tells the server that the user has stopped typing.
+ /// </summary>
+ /// <param name="typing">Whether the user is typing or not.</param>
+ /// <param name="timeout">The length of time in milliseconds to mark this user as typing.</param>
+ public async Task SendTypingNotificationAsync(bool typing, int timeout = 30000) {
+ await Homeserver.ClientHttpClient.PutAsJsonAsync(
+ $"/_matrix/client/v3/rooms/{RoomId}/typing/{Homeserver.UserId}", new JsonObject {
+ ["timeout"] = typing ? timeout : null,
+ ["typing"] = typing
+ }, new JsonSerializerOptions {
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
+ });
+ }
+
+ /// <summary>
+ /// Updates the marker for the given receipt type to the event ID specified.
+ /// </summary>
+ /// <param name="eventId">The event ID to acknowledge up to.</param>
+ /// <param name="threadId">
+ /// The root thread event’s ID (or main) for which thread this receipt is intended to be under.
+ /// If not specified, the read receipt is unthreaded (default).
+ /// </param>
+ /// <param name="isPrivate">
+ /// If set to true, a receipt type of m.read.private is sent instead of m.read, which marks the
+ /// room as "read" only for the current user
+ /// </param>
+ public async Task SendReadReceiptAsync(string eventId, string? threadId = null, bool isPrivate = false) {
+ var request = new JsonObject();
+ if (threadId != null)
+ request.Add("thread_id", threadId);
+ await Homeserver.ClientHttpClient.PostAsJsonAsync(
+ $"/_matrix/client/v3/rooms/{RoomId}/receipt/m.read{(isPrivate ? ".private" : "")}/{eventId}", request,
+ new JsonSerializerOptions {
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
+ });
}
#endregion
@@ -510,7 +586,7 @@ public class GenericRoom {
var uri = new Uri(path, UriKind.Relative);
if (dir == "b" || dir == "f") uri = uri.AddQuery("dir", dir);
- else if(!string.IsNullOrWhiteSpace(dir)) throw new ArgumentException("Invalid direction", nameof(dir));
+ else if (!string.IsNullOrWhiteSpace(dir)) throw new ArgumentException("Invalid direction", nameof(dir));
if (!string.IsNullOrEmpty(from)) uri = uri.AddQuery("from", from);
if (chunkLimit is not null) uri = uri.AddQuery("limit", chunkLimit.Value.ToString());
if (recurse is not null) uri = uri.AddQuery("recurse", recurse.Value.ToString());
@@ -528,10 +604,11 @@ public class GenericRoom {
}
}
- public readonly SpaceRoom AsSpace;
+ public SpaceRoom AsSpace() => new SpaceRoom(Homeserver, RoomId);
+ public PolicyRoom AsPolicyRoom() => new PolicyRoom(Homeserver, RoomId);
}
public class RoomIdResponse {
[JsonPropertyName("room_id")]
- public string RoomId { get; set; } = null!;
+ public string RoomId { get; set; }
}
\ No newline at end of file
diff --git a/LibMatrix/RoomTypes/PolicyRoom.cs b/LibMatrix/RoomTypes/PolicyRoom.cs
new file mode 100644
index 0000000..c6eec63
--- /dev/null
+++ b/LibMatrix/RoomTypes/PolicyRoom.cs
@@ -0,0 +1,51 @@
+using System.Collections.Frozen;
+using LibMatrix.EventTypes;
+using LibMatrix.EventTypes.Spec.State.Policy;
+using LibMatrix.Homeservers;
+
+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<string> UserPolicyEventTypes = EventContent.GetMatchingEventTypes<UserPolicyRuleEventContent>().ToFrozenSet();
+ public static readonly FrozenSet<string> ServerPolicyEventTypes = EventContent.GetMatchingEventTypes<ServerPolicyRuleEventContent>().ToFrozenSet();
+ public static readonly FrozenSet<string> RoomPolicyEventTypes = EventContent.GetMatchingEventTypes<RoomPolicyRuleEventContent>().ToFrozenSet();
+ public static readonly FrozenSet<string> SpecPolicyEventTypes = [..UserPolicyEventTypes, ..ServerPolicyEventTypes, ..RoomPolicyEventTypes];
+
+ public async IAsyncEnumerable<StateEventResponse> GetPoliciesAsync() {
+ var fullRoomState = GetFullStateAsync();
+ await foreach (var eventResponse in fullRoomState) {
+ if (SpecPolicyEventTypes.Contains(eventResponse!.Type)) {
+ yield return eventResponse;
+ }
+ }
+ }
+
+ public async IAsyncEnumerable<StateEventResponse> GetUserPoliciesAsync() {
+ var fullRoomState = GetPoliciesAsync();
+ await foreach (var eventResponse in fullRoomState) {
+ if (UserPolicyEventTypes.Contains(eventResponse!.Type)) {
+ yield return eventResponse;
+ }
+ }
+ }
+
+ public async IAsyncEnumerable<StateEventResponse> GetServerPoliciesAsync() {
+ var fullRoomState = GetPoliciesAsync();
+ await foreach (var eventResponse in fullRoomState) {
+ if (ServerPolicyEventTypes.Contains(eventResponse!.Type)) {
+ yield return eventResponse;
+ }
+ }
+ }
+
+ public async IAsyncEnumerable<StateEventResponse> GetRoomPoliciesAsync() {
+ var fullRoomState = GetPoliciesAsync();
+ await foreach (var eventResponse in fullRoomState) {
+ if (RoomPolicyEventTypes.Contains(eventResponse!.Type)) {
+ yield return eventResponse;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/RoomTypes/SpaceRoom.cs b/LibMatrix/RoomTypes/SpaceRoom.cs
index 4563ed3..96abd77 100644
--- a/LibMatrix/RoomTypes/SpaceRoom.cs
+++ b/LibMatrix/RoomTypes/SpaceRoom.cs
@@ -1,5 +1,6 @@
using ArcaneLibs.Extensions;
using LibMatrix.Homeservers;
+using LibMatrix.Responses;
namespace LibMatrix.RoomTypes;
@@ -17,7 +18,7 @@ public class SpaceRoom(AuthenticatedHomeserverGeneric homeserver, string roomId)
}
public async Task<EventIdResponse> AddChildAsync(GenericRoom room) {
- var members = room.GetMembersEnumerableAsync(true);
+ var members = room.GetMembersEnumerableAsync("join");
Dictionary<string, int> memberCountByHs = new();
await foreach (var member in members) {
var server = member.StateKey.Split(':')[1];
diff --git a/LibMatrix/Services/HomeserverProviderService.cs b/LibMatrix/Services/HomeserverProviderService.cs
index 3e42c21..36bc828 100644
--- a/LibMatrix/Services/HomeserverProviderService.cs
+++ b/LibMatrix/Services/HomeserverProviderService.cs
@@ -1,6 +1,5 @@
using System.Net.Http.Json;
using ArcaneLibs.Collections;
-using ArcaneLibs.Extensions;
using LibMatrix.Homeservers;
using LibMatrix.Responses;
using Microsoft.Extensions.Logging;
@@ -8,9 +7,9 @@ using Microsoft.Extensions.Logging;
namespace LibMatrix.Services;
public class HomeserverProviderService(ILogger<HomeserverProviderService> logger, HomeserverResolverService hsResolver) {
- private static SemaphoreCache<AuthenticatedHomeserverGeneric> AuthenticatedHomeserverCache = new();
- private static SemaphoreCache<RemoteHomeserver> RemoteHomeserverCache = new();
- private static SemaphoreCache<FederationClient> FederationClientCache = new();
+ private static readonly SemaphoreCache<AuthenticatedHomeserverGeneric> AuthenticatedHomeserverCache = new();
+ private static readonly SemaphoreCache<RemoteHomeserver> RemoteHomeserverCache = new();
+ private static readonly SemaphoreCache<FederationClient> FederationClientCache = new();
public async Task<AuthenticatedHomeserverGeneric> GetAuthenticatedWithToken(string homeserver, string accessToken, string? proxy = null, string? impersonatedMxid = null,
bool useGeneric = false, bool enableClient = true, bool enableServer = true) {
@@ -23,9 +22,11 @@ public class HomeserverProviderService(ILogger<HomeserverProviderService> logger
AuthenticatedHomeserverGeneric? hs = null;
if (!useGeneric) {
- ClientVersionsResponse? clientVersions = new();
+ var clientVersionsTask = rhs.GetClientVersionsAsync();
+ var serverVersionTask = rhs.FederationClient?.GetServerVersionAsync() ?? Task.FromResult<ServerVersionResponse?>(null)!;
+ ClientVersionsResponse clientVersions = new();
try {
- clientVersions = await rhs.GetClientVersionsAsync();
+ clientVersions = await clientVersionsTask;
}
catch (Exception e) {
logger.LogError(e, "Failed to get client versions for {homeserver}", homeserver);
@@ -33,7 +34,7 @@ public class HomeserverProviderService(ILogger<HomeserverProviderService> logger
ServerVersionResponse? serverVersion;
try {
- serverVersion = await (rhs.FederationClient?.GetServerVersionAsync() ?? Task.FromResult<ServerVersionResponse?>(null)!);
+ serverVersion = await serverVersionTask;
}
catch (Exception e) {
logger.LogWarning(e, "Failed to get server version for {homeserver}", homeserver);
@@ -46,6 +47,8 @@ public class HomeserverProviderService(ILogger<HomeserverProviderService> logger
else {
if (serverVersion is { Server.Name: "Synapse" })
hs = new AuthenticatedHomeserverSynapse(homeserver, wellKnownUris, proxy, accessToken);
+ else if (serverVersion is { Server.Name: "LibMatrix.HomeserverEmulator"})
+ hs = new AuthenticatedHomeserverHSE(homeserver, wellKnownUris, proxy, accessToken);
}
}
catch (Exception e) {
@@ -65,7 +68,7 @@ public class HomeserverProviderService(ILogger<HomeserverProviderService> logger
});
}
- public async Task<RemoteHomeserver> GetRemoteHomeserver(string homeserver, string? proxy = null, bool useCache = true, bool enableServer = true) =>
+ public async Task<RemoteHomeserver> GetRemoteHomeserver(string homeserver, string? proxy = null, bool useCache = true, bool enableServer = false) =>
useCache
? await RemoteHomeserverCache.GetOrAdd($"{homeserver}{proxy}",
async () => { return new RemoteHomeserver(homeserver, await hsResolver.ResolveHomeserverFromWellKnown(homeserver, enableServer: enableServer), proxy); })
diff --git a/LibMatrix/Services/HomeserverResolverService.cs b/LibMatrix/Services/HomeserverResolverService.cs
index f899230..94a3826 100644
--- a/LibMatrix/Services/HomeserverResolverService.cs
+++ b/LibMatrix/Services/HomeserverResolverService.cs
@@ -1,8 +1,4 @@
-using System.Collections.Concurrent;
using System.Diagnostics;
-using System.Net.Http.Json;
-using System.Text.Json;
-using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using ArcaneLibs.Collections;
using ArcaneLibs.Extensions;
@@ -13,9 +9,7 @@ using Microsoft.Extensions.Logging.Abstractions;
namespace LibMatrix.Services;
public class HomeserverResolverService {
- private readonly MatrixHttpClient _httpClient = new() {
- // Timeout = TimeSpan.FromSeconds(60) // TODO: Re-implement this
- };
+ private readonly MatrixHttpClient _httpClient = new();
private static readonly SemaphoreCache<WellKnownUris> WellKnownCache = new();
@@ -26,68 +20,67 @@ public class HomeserverResolverService {
if (logger is NullLogger<HomeserverResolverService>) {
var stackFrame = new StackTrace(true).GetFrame(1);
Console.WriteLine(
- $"WARN | Null logger provided to HomeserverResolverService!\n{stackFrame.GetMethod().DeclaringType} at {stackFrame.GetFileName()}:{stackFrame.GetFileLineNumber()}");
+ $"WARN | Null logger provided to HomeserverResolverService!\n{stackFrame?.GetMethod()?.DeclaringType?.ToString() ?? "null"} at {stackFrame?.GetFileName() ?? "null"}:{stackFrame?.GetFileLineNumber().ToString() ?? "null"}");
}
}
- // private static SemaphoreSlim _wellKnownSemaphore = new(1, 1);
-
public async Task<WellKnownUris> ResolveHomeserverFromWellKnown(string homeserver, bool enableClient = true, bool enableServer = true) {
ArgumentNullException.ThrowIfNull(homeserver);
return await WellKnownCache.GetOrAdd(homeserver, async () => {
- // await _wellKnownSemaphore.WaitAsync();
_logger.LogTrace($"Resolving homeserver well-knowns: {homeserver}");
var client = enableClient ? _tryResolveClientEndpoint(homeserver) : null;
var server = enableServer ? _tryResolveServerEndpoint(homeserver) : null;
var res = new WellKnownUris();
- // try {
if (client != null)
- res.Client = await client ?? throw new Exception($"Could not resolve client URL for {homeserver}.");
- // }
- // catch (Exception e) {
- // _logger.LogError(e, "Error resolving client well-known for {hs}", homeserver);
- // }
+ res.Client = (await client)?.TrimEnd('/') ?? throw new Exception($"Could not resolve client URL for {homeserver}.");
- // try {
if (server != null)
- res.Server = await server ?? throw new Exception($"Could not resolve server URL for {homeserver}.");
- // }
- // catch (Exception e) {
- // _logger.LogError(e, "Error resolving server well-known for {hs}", homeserver);
- // }
+ res.Server = (await server)?.TrimEnd('/') ?? throw new Exception($"Could not resolve server URL for {homeserver}.");
_logger.LogInformation("Resolved well-knowns for {hs}: {json}", homeserver, res.ToJson(indent: false));
- // _wellKnownSemaphore.Release();
return res;
});
}
-
- // private async Task<WellKnownUris> InternalResolveHomeserverFromWellKnown(string homeserver) {
-
- // }
-
+
+ private async Task<T?> GetFromJsonAsync<T>(string url) {
+ try {
+ return await _httpClient.GetFromJsonAsync<T>(url);
+ }
+ catch (Exception e) {
+ _logger.LogWarning(e, "Failed to get JSON from {url}", url);
+ return default;
+ }
+ }
+
private async Task<string?> _tryResolveClientEndpoint(string homeserver) {
ArgumentNullException.ThrowIfNull(homeserver);
_logger.LogTrace("Resolving client well-known: {homeserver}", homeserver);
ClientWellKnown? clientWellKnown = null;
+ homeserver = homeserver.TrimEnd('/');
// check if homeserver has a client well-known
if (homeserver.StartsWith("https://")) {
- clientWellKnown = await _httpClient.TryGetFromJsonAsync<ClientWellKnown>($"{homeserver}/.well-known/matrix/client");
+ clientWellKnown = await GetFromJsonAsync<ClientWellKnown>($"{homeserver}/.well-known/matrix/client");
+
+ if (clientWellKnown is null && await MatrixHttpClient.CheckSuccessStatus($"{homeserver}/_matrix/client/versions"))
+ return homeserver;
}
else if (homeserver.StartsWith("http://")) {
- clientWellKnown = await _httpClient.TryGetFromJsonAsync<ClientWellKnown>($"{homeserver}/.well-known/matrix/client");
+ clientWellKnown = await GetFromJsonAsync<ClientWellKnown>($"{homeserver}/.well-known/matrix/client");
+
+ if (clientWellKnown is null && await MatrixHttpClient.CheckSuccessStatus($"{homeserver}/_matrix/client/versions"))
+ return homeserver;
}
else {
- clientWellKnown ??= await _httpClient.TryGetFromJsonAsync<ClientWellKnown>($"https://{homeserver}/.well-known/matrix/client");
- clientWellKnown ??= await _httpClient.TryGetFromJsonAsync<ClientWellKnown>($"http://{homeserver}/.well-known/matrix/client");
+ clientWellKnown ??= await GetFromJsonAsync<ClientWellKnown>($"https://{homeserver}/.well-known/matrix/client");
+ clientWellKnown ??= await GetFromJsonAsync<ClientWellKnown>($"http://{homeserver}/.well-known/matrix/client");
if (clientWellKnown is null) {
- if (await _httpClient.CheckSuccessStatus($"https://{homeserver}/_matrix/client/versions"))
+ if (await MatrixHttpClient.CheckSuccessStatus($"https://{homeserver}/_matrix/client/versions"))
return $"https://{homeserver}";
- if (await _httpClient.CheckSuccessStatus($"http://{homeserver}/_matrix/client/versions"))
+ if (await MatrixHttpClient.CheckSuccessStatus($"http://{homeserver}/_matrix/client/versions"))
return $"http://{homeserver}";
}
}
@@ -104,40 +97,42 @@ public class HomeserverResolverService {
ArgumentNullException.ThrowIfNull(homeserver);
_logger.LogTrace($"Resolving server well-known: {homeserver}");
ServerWellKnown? serverWellKnown = null;
+ homeserver = homeserver.TrimEnd('/');
// check if homeserver has a server well-known
if (homeserver.StartsWith("https://")) {
- serverWellKnown = await _httpClient.TryGetFromJsonAsync<ServerWellKnown>($"{homeserver}/.well-known/matrix/server");
+ serverWellKnown = await GetFromJsonAsync<ServerWellKnown>($"{homeserver}/.well-known/matrix/server");
}
else if (homeserver.StartsWith("http://")) {
- serverWellKnown = await _httpClient.TryGetFromJsonAsync<ServerWellKnown>($"{homeserver}/.well-known/matrix/server");
+ serverWellKnown = await GetFromJsonAsync<ServerWellKnown>($"{homeserver}/.well-known/matrix/server");
}
else {
- serverWellKnown ??= await _httpClient.TryGetFromJsonAsync<ServerWellKnown>($"https://{homeserver}/.well-known/matrix/server");
- serverWellKnown ??= await _httpClient.TryGetFromJsonAsync<ServerWellKnown>($"http://{homeserver}/.well-known/matrix/server");
+ serverWellKnown ??= await GetFromJsonAsync<ServerWellKnown>($"https://{homeserver}/.well-known/matrix/server");
+ serverWellKnown ??= await GetFromJsonAsync<ServerWellKnown>($"http://{homeserver}/.well-known/matrix/server");
}
_logger.LogInformation("Server well-known for {hs}: {json}", homeserver, serverWellKnown?.ToJson() ?? "null");
if (!string.IsNullOrWhiteSpace(serverWellKnown?.Homeserver)) {
- var resolved = serverWellKnown.Homeserver;
+ var resolved = serverWellKnown.Homeserver.TrimEnd('/');
if (resolved.StartsWith("https://") || resolved.StartsWith("http://"))
return resolved;
- if (await _httpClient.CheckSuccessStatus($"https://{resolved}/_matrix/federation/v1/version"))
+ if (await MatrixHttpClient.CheckSuccessStatus($"https://{resolved}/_matrix/federation/v1/version"))
return $"https://{resolved}";
- if (await _httpClient.CheckSuccessStatus($"http://{resolved}/_matrix/federation/v1/version"))
+ if (await MatrixHttpClient.CheckSuccessStatus($"http://{resolved}/_matrix/federation/v1/version"))
return $"http://{resolved}";
_logger.LogWarning("Server well-known points to invalid server: {resolved}", resolved);
}
// fallback: most servers host C2S and S2S on the same domain
- var clientUrl = await _tryResolveClientEndpoint(homeserver);
- if (clientUrl is not null && await _httpClient.CheckSuccessStatus($"{clientUrl}/_matrix/federation/v1/version"))
+ var clientUrl = (await _tryResolveClientEndpoint(homeserver)).TrimEnd('/');
+ if (clientUrl is not null && await MatrixHttpClient.CheckSuccessStatus($"{clientUrl}/_matrix/federation/v1/version"))
return clientUrl;
_logger.LogInformation("No server well-known for {server}...", homeserver);
return null;
}
-
+
+ [Obsolete("Use authenticated media, available on AuthenticatedHomeserverGeneric", true)]
public async Task<string?> ResolveMediaUri(string homeserver, string mxc) {
if (homeserver is null) throw new ArgumentNullException(nameof(homeserver));
if (mxc is null) throw new ArgumentNullException(nameof(mxc));
diff --git a/LibMatrix/Services/ServiceInstaller.cs b/LibMatrix/Services/ServiceInstaller.cs
index 06ea9de..5ffd43a 100644
--- a/LibMatrix/Services/ServiceInstaller.cs
+++ b/LibMatrix/Services/ServiceInstaller.cs
@@ -1,27 +1,25 @@
+using LibMatrix.Services.WellKnownResolver;
+using LibMatrix.Services.WellKnownResolver.WellKnownResolvers;
using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Logging;
namespace LibMatrix.Services;
public static class ServiceInstaller {
public static IServiceCollection AddRoryLibMatrixServices(this IServiceCollection services, RoryLibMatrixConfiguration? config = null) {
- //Check required services
- // if (!services.Any(x => x.ServiceType == typeof(TieredStorageService)))
- // throw new Exception("[RMUCore/DI] No TieredStorageService has been registered!");
//Add config
services.AddSingleton(config ?? new RoryLibMatrixConfiguration());
//Add services
- services.AddSingleton<HomeserverResolverService>(sp => new HomeserverResolverService(sp.GetRequiredService<ILogger<HomeserverResolverService>>()));
-
- // if (services.First(x => x.ServiceType == typeof(TieredStorageService)).Lifetime == ServiceLifetime.Singleton) {
+ services.AddSingleton<ClientWellKnownResolver>();
+ services.AddSingleton<ServerWellKnownResolver>();
+ services.AddSingleton<SupportWellKnownResolver>();
+ if (!services.Any(x => x.ServiceType == typeof(WellKnownResolverConfiguration)))
+ services.AddSingleton<WellKnownResolverConfiguration>();
+ services.AddSingleton<WellKnownResolverService>();
+ // Legacy
+ services.AddSingleton<HomeserverResolverService>();
services.AddSingleton<HomeserverProviderService>();
- // }
- // else {
- // services.AddScoped<HomeserverProviderService>();
- // }
- // services.AddScoped<MatrixHttpClient>();
return services;
}
}
diff --git a/LibMatrix/Services/WellKnownResolver/WellKnownResolverConfiguration.cs b/LibMatrix/Services/WellKnownResolver/WellKnownResolverConfiguration.cs
new file mode 100644
index 0000000..26a4c43
--- /dev/null
+++ b/LibMatrix/Services/WellKnownResolver/WellKnownResolverConfiguration.cs
@@ -0,0 +1,49 @@
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Services.WellKnownResolver;
+
+public class WellKnownResolverConfiguration {
+ /// <summary>
+ /// Allow transparent downgrades to plaintext HTTP if HTTPS fails
+ /// Enabling this is unsafe!
+ /// </summary>
+ [JsonPropertyName("allow_http")]
+ public bool AllowHttp { get; set; } = false;
+
+ /// <summary>
+ /// Use DNS resolution if available, for resolving SRV records
+ /// </summary>
+ [JsonPropertyName("allow_dns")]
+ public bool AllowDns { get; set; } = true;
+
+ /// <summary>
+ /// Use system resolver(s) if empty
+ /// </summary>
+ [JsonPropertyName("dns_servers")]
+ public List<string> DnsServers { get; set; } = new();
+
+ /// <summary>
+ /// Same as AllowDns, but for DNS over HTTPS - useful in browser contexts
+ /// </summary>
+ [JsonPropertyName("allow_doh")]
+ public bool AllowDoh { get; set; } = true;
+
+ /// <summary>
+ /// Use DNS over HTTPS - useful in browser contexts
+ /// Disabled if empty
+ /// </summary>
+ [JsonPropertyName("doh_servers")]
+ public List<string> DohServers { get; set; } = new();
+
+ /// <summary>
+ /// Whether to allow fallback subdomain lookups
+ /// </summary>
+ [JsonPropertyName("allow_fallback_subdomains")]
+ public bool AllowFallbackSubdomains { get; set; } = true;
+
+ /// <summary>
+ /// Fallback subdomains to try if the homeserver is not found
+ /// </summary>
+ [JsonPropertyName("fallback_subdomains")]
+ public List<string> FallbackSubdomains { get; set; } = ["matrix", "chat", "im"];
+}
\ No newline at end of file
diff --git a/LibMatrix/Services/WellKnownResolver/WellKnownResolverService.cs b/LibMatrix/Services/WellKnownResolver/WellKnownResolverService.cs
new file mode 100644
index 0000000..4c78347
--- /dev/null
+++ b/LibMatrix/Services/WellKnownResolver/WellKnownResolverService.cs
@@ -0,0 +1,91 @@
+using System.Diagnostics;
+using System.Text.Json.Serialization;
+using LibMatrix.Extensions;
+using LibMatrix.Services.WellKnownResolver.WellKnownResolvers;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+
+namespace LibMatrix.Services.WellKnownResolver;
+
+public class WellKnownResolverService {
+ private readonly MatrixHttpClient _httpClient = new();
+
+ private readonly ILogger<WellKnownResolverService> _logger;
+ private readonly ClientWellKnownResolver _clientWellKnownResolver;
+ private readonly SupportWellKnownResolver _supportWellKnownResolver;
+ private readonly ServerWellKnownResolver _serverWellKnownResolver;
+ private readonly WellKnownResolverConfiguration _configuration;
+
+ public WellKnownResolverService(ILogger<WellKnownResolverService> logger, ClientWellKnownResolver clientWellKnownResolver, SupportWellKnownResolver supportWellKnownResolver,
+ WellKnownResolverConfiguration configuration, ServerWellKnownResolver serverWellKnownResolver) {
+ _logger = logger;
+ _clientWellKnownResolver = clientWellKnownResolver;
+ _supportWellKnownResolver = supportWellKnownResolver;
+ _configuration = configuration;
+ _serverWellKnownResolver = serverWellKnownResolver;
+ if (logger is NullLogger<WellKnownResolverService>) {
+ var stackFrame = new StackTrace(true).GetFrame(1);
+ Console.WriteLine(
+ $"WARN | Null logger provided to WellKnownResolverService!\n{stackFrame?.GetMethod()?.DeclaringType?.ToString() ?? "null"} at {stackFrame?.GetFileName() ?? "null"}:{stackFrame?.GetFileLineNumber().ToString() ?? "null"}");
+ }
+ }
+
+ public async Task<WellKnownRecords> TryResolveWellKnownRecords(string homeserver, bool includeClient = true, bool includeServer = true, bool includeSupport = true,
+ WellKnownResolverConfiguration? config = null) {
+ WellKnownRecords records = new();
+ _logger.LogDebug($"Resolving well-knowns for {homeserver}");
+ if (includeClient && await _clientWellKnownResolver.TryResolveWellKnown(homeserver, config ?? _configuration) is { } clientResult) {
+ records.ClientWellKnown = clientResult;
+ }
+
+ if (includeServer && await _serverWellKnownResolver.TryResolveWellKnown(homeserver, config ?? _configuration) is { } serverResult) {
+ records.ServerWellKnown = serverResult;
+ }
+
+ if (includeSupport && await _supportWellKnownResolver.TryResolveWellKnown(homeserver, config ?? _configuration) is { } supportResult) {
+ records.SupportWellKnown = supportResult;
+ }
+
+ return records;
+ }
+
+ public class WellKnownRecords {
+ public WellKnownResolutionResult<ClientWellKnown?>? ClientWellKnown { get; set; }
+ public WellKnownResolutionResult<ServerWellKnown?>? ServerWellKnown { get; set; }
+ public WellKnownResolutionResult<SupportWellKnown?>? SupportWellKnown { get; set; }
+ }
+
+ public class WellKnownResolutionResult<T> {
+ public WellKnownSource Source { get; set; }
+ public string? SourceUri { get; set; }
+ public T? Content { get; set; }
+ public List<WellKnownResolutionWarning> Warnings { get; set; } = [];
+ }
+
+ [JsonConverter(typeof(JsonStringEnumConverter))]
+ public enum WellKnownSource {
+ None,
+ Https,
+ Dns,
+ Http,
+ ManualCheck,
+ Search
+ }
+
+ public struct WellKnownResolutionWarning {
+ public WellKnownResolutionWarningType Type { get; set; }
+ public string Message { get; set; }
+ [JsonIgnore]
+ public Exception? Exception { get; set; }
+ public string? ExceptionMessage => Exception?.Message;
+
+ [JsonConverter(typeof(JsonStringEnumConverter))]
+ public enum WellKnownResolutionWarningType {
+ None,
+ Exception,
+ InvalidResponse,
+ Timeout,
+ SlowResponse
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/BaseWellKnownResolver.cs b/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/BaseWellKnownResolver.cs
new file mode 100644
index 0000000..cbe5b0a
--- /dev/null
+++ b/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/BaseWellKnownResolver.cs
@@ -0,0 +1,52 @@
+using System.Diagnostics;
+using System.Net.Http.Json;
+using ArcaneLibs.Collections;
+using LibMatrix.Extensions;
+
+namespace LibMatrix.Services.WellKnownResolver.WellKnownResolvers;
+
+public class BaseWellKnownResolver<T> where T : class, new() {
+ internal static readonly SemaphoreCache<WellKnownResolverService.WellKnownResolutionResult<T>> WellKnownCache = new() {
+ StoreNulls = false
+ };
+
+ internal static readonly MatrixHttpClient HttpClient = new();
+
+ internal async Task<WellKnownResolverService.WellKnownResolutionResult<T>> TryGetWellKnownFromUrl(string url,
+ WellKnownResolverService.WellKnownSource source) {
+ var sw = Stopwatch.StartNew();
+ try {
+ var request = await HttpClient.GetAsync(url);
+ sw.Stop();
+ var result = new WellKnownResolverService.WellKnownResolutionResult<T> {
+ Content = await request.Content.ReadFromJsonAsync<T>(),
+ Source = source,
+ SourceUri = url,
+ Warnings = []
+ };
+
+ if (sw.ElapsedMilliseconds > 1000) {
+ // logger.LogWarning($"Support well-known resolution took {sw.ElapsedMilliseconds}ms: {url}");
+ result.Warnings.Add(new() {
+ Type = WellKnownResolverService.WellKnownResolutionWarning.WellKnownResolutionWarningType.SlowResponse,
+ Message = $"Well-known resolution took {sw.ElapsedMilliseconds}ms"
+ });
+ }
+
+ return result;
+ }
+ catch (Exception e) {
+ return new WellKnownResolverService.WellKnownResolutionResult<T> {
+ Source = source,
+ SourceUri = url,
+ Warnings = [
+ new() {
+ Exception = e,
+ Type = WellKnownResolverService.WellKnownResolutionWarning.WellKnownResolutionWarningType.Exception,
+ Message = e.Message
+ }
+ ]
+ };
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/ClientWellKnownResolver.cs b/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/ClientWellKnownResolver.cs
new file mode 100644
index 0000000..f8de38d
--- /dev/null
+++ b/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/ClientWellKnownResolver.cs
@@ -0,0 +1,42 @@
+using System.Text.Json.Serialization;
+using ArcaneLibs.Collections;
+using LibMatrix.Extensions;
+using Microsoft.Extensions.Logging;
+using WellKnownType = LibMatrix.Services.WellKnownResolver.WellKnownResolvers.ClientWellKnown;
+using ResultType =
+ LibMatrix.Services.WellKnownResolver.WellKnownResolverService.WellKnownResolutionResult<LibMatrix.Services.WellKnownResolver.WellKnownResolvers.ClientWellKnown?>;
+
+namespace LibMatrix.Services.WellKnownResolver.WellKnownResolvers;
+
+public class ClientWellKnownResolver(ILogger<ClientWellKnownResolver> logger, WellKnownResolverConfiguration configuration)
+ : BaseWellKnownResolver<ClientWellKnown> {
+ private static readonly SemaphoreCache<WellKnownResolverService.WellKnownResolutionResult<ClientWellKnown>> ClientWellKnownCache = new() {
+ StoreNulls = false
+ };
+
+ private static readonly MatrixHttpClient HttpClient = new();
+
+ public Task<WellKnownResolverService.WellKnownResolutionResult<ClientWellKnown>> TryResolveWellKnown(string homeserver, WellKnownResolverConfiguration? config = null) {
+ config ??= configuration;
+ return ClientWellKnownCache.TryGetOrAdd(homeserver, async () => {
+ logger.LogTrace($"Resolving client well-known: {homeserver}");
+
+ WellKnownResolverService.WellKnownResolutionResult<ClientWellKnown> result =
+ await TryGetWellKnownFromUrl($"https://{homeserver}/.well-known/matrix/client", WellKnownResolverService.WellKnownSource.Https);
+ if (result.Content != null) return result;
+
+
+ return result;
+ });
+ }
+}
+
+public class ClientWellKnown {
+ [JsonPropertyName("m.homeserver")]
+ public WellKnownHomeserver Homeserver { get; set; }
+
+ public class WellKnownHomeserver {
+ [JsonPropertyName("base_url")]
+ public required string BaseUrl { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/ServerWellKnownResolver.cs b/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/ServerWellKnownResolver.cs
new file mode 100644
index 0000000..a99185c
--- /dev/null
+++ b/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/ServerWellKnownResolver.cs
@@ -0,0 +1,38 @@
+using System.Text.Json.Serialization;
+using ArcaneLibs.Collections;
+using LibMatrix.Extensions;
+using Microsoft.Extensions.Logging;
+using WellKnownType = LibMatrix.Services.WellKnownResolver.WellKnownResolvers.ServerWellKnown;
+using ResultType =
+ LibMatrix.Services.WellKnownResolver.WellKnownResolverService.WellKnownResolutionResult<LibMatrix.Services.WellKnownResolver.WellKnownResolvers.ServerWellKnown?>;
+
+namespace LibMatrix.Services.WellKnownResolver.WellKnownResolvers;
+
+public class ServerWellKnownResolver(ILogger<ServerWellKnownResolver> logger, WellKnownResolverConfiguration configuration)
+ : BaseWellKnownResolver<ServerWellKnown> {
+ private static readonly SemaphoreCache<WellKnownResolverService.WellKnownResolutionResult<ServerWellKnown>> ClientWellKnownCache = new() {
+ StoreNulls = false
+ };
+
+ private static readonly MatrixHttpClient HttpClient = new();
+
+ public Task<WellKnownResolverService.WellKnownResolutionResult<ServerWellKnown>> TryResolveWellKnown(string homeserver, WellKnownResolverConfiguration? config = null) {
+ config ??= configuration;
+ return ClientWellKnownCache.TryGetOrAdd(homeserver, async () => {
+ logger.LogTrace($"Resolving client well-known: {homeserver}");
+
+ WellKnownResolverService.WellKnownResolutionResult<ServerWellKnown> result =
+ await TryGetWellKnownFromUrl($"https://{homeserver}/.well-known/matrix/server", WellKnownResolverService.WellKnownSource.Https);
+ if (result.Content != null) return result;
+
+
+ return result;
+ });
+ }
+}
+
+
+public class ServerWellKnown {
+ [JsonPropertyName("m.server")]
+ public string Homeserver { get; set; }
+}
\ No newline at end of file
diff --git a/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/SupportWellKnownResolver.cs b/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/SupportWellKnownResolver.cs
new file mode 100644
index 0000000..99313db
--- /dev/null
+++ b/LibMatrix/Services/WellKnownResolver/WellKnownResolvers/SupportWellKnownResolver.cs
@@ -0,0 +1,44 @@
+using System.Diagnostics;
+using System.Net.Http.Json;
+using System.Text.Json.Serialization;
+using Microsoft.Extensions.Logging;
+using WellKnownType = LibMatrix.Services.WellKnownResolver.WellKnownResolvers.SupportWellKnown;
+using ResultType = LibMatrix.Services.WellKnownResolver.WellKnownResolverService.WellKnownResolutionResult<
+ LibMatrix.Services.WellKnownResolver.WellKnownResolvers.SupportWellKnown?
+>;
+
+namespace LibMatrix.Services.WellKnownResolver.WellKnownResolvers;
+
+public class SupportWellKnownResolver(ILogger<SupportWellKnownResolver> logger, WellKnownResolverConfiguration configuration) : BaseWellKnownResolver<WellKnownType> {
+ public Task<ResultType> TryResolveWellKnown(string homeserver, WellKnownResolverConfiguration? config = null) {
+ config ??= configuration;
+ return WellKnownCache.TryGetOrAdd(homeserver, async () => {
+ logger.LogTrace($"Resolving support well-known: {homeserver}");
+
+ ResultType result = await TryGetWellKnownFromUrl($"https://{homeserver}/.well-known/matrix/support", WellKnownResolverService.WellKnownSource.Https);
+ if (result.Content != null)
+ return result;
+
+ return null;
+ });
+ }
+}
+
+public class SupportWellKnown {
+ [JsonPropertyName("contacts")]
+ public List<WellKnownContact>? Contacts { get; set; }
+
+ [JsonPropertyName("support_page")]
+ public Uri? SupportPage { get; set; }
+
+ public class WellKnownContact {
+ [JsonPropertyName("email_address")]
+ public string? EmailAddress { get; set; }
+
+ [JsonPropertyName("matrix_id")]
+ public string? MatrixId { get; set; }
+
+ [JsonPropertyName("role")]
+ public required string Role { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/LibMatrix/StateEvent.cs b/LibMatrix/StateEvent.cs
index 073d26d..af25805 100644
--- a/LibMatrix/StateEvent.cs
+++ b/LibMatrix/StateEvent.cs
@@ -44,6 +44,7 @@ public class StateEvent {
public string FriendlyTypeNamePlural => MappedType.GetFriendlyNamePluralOrNull() ?? Type;
private static readonly JsonSerializerOptions TypedContentSerializerOptions = new() {
+ // We need these, NumberHandling covers other number types that we don't want to convert
Converters = {
new JsonFloatStringConverter(),
new JsonDoubleStringConverter(),
@@ -55,9 +56,6 @@ public class StateEvent {
[SuppressMessage("ReSharper", "PropertyCanBeMadeInitOnly.Global")]
public EventContent? TypedContent {
get {
- // if (Type == "m.receipt") {
- // return null;
- // }
try {
var mappedType = GetStateEventType(Type);
if (mappedType == typeof(UnknownEventContent))
@@ -81,6 +79,18 @@ public class StateEvent {
}
}
+ public T? ContentAs<T>() {
+ try {
+ return RawContent.Deserialize<T>(TypedContentSerializerOptions)!;
+ }
+ catch (JsonException e) {
+ Console.WriteLine(e);
+ Console.WriteLine("Content:\n" + (RawContent?.ToJson() ?? "null"));
+ }
+
+ return default;
+ }
+
[JsonPropertyName("state_key")]
public string? StateKey { get; set; }
@@ -90,44 +100,10 @@ public class StateEvent {
[JsonPropertyName("replaces_state")]
public string? ReplacesState { get; set; }
- private JsonObject? _rawContent;
-
[JsonPropertyName("content")]
- public JsonObject? RawContent {
- get => _rawContent;
- set => _rawContent = value;
- }
- //
- // [JsonIgnore]
- // public new Type GetType {
- // get {
- // var type = GetStateEventType(Type);
- //
- // //special handling for some types
- // // if (type == typeof(RoomEmotesEventContent)) {
- // // RawContent["emote"] = RawContent["emote"]?.AsObject() ?? new JsonObject();
- // // }
- // //
- // // if (this is StateEventResponse stateEventResponse) {
- // // if (type == null || type == typeof(object)) {
- // // Console.WriteLine($"Warning: unknown event type '{Type}'!");
- // // Console.WriteLine(RawContent.ToJson());
- // // Directory.CreateDirectory($"unknown_state_events/{Type}");
- // // File.WriteAllText($"unknown_state_events/{Type}/{stateEventResponse.EventId}.json",
- // // RawContent.ToJson());
- // // Console.WriteLine($"Saved to unknown_state_events/{Type}/{stateEventResponse.EventId}.json");
- // // }
- // // else if (RawContent is not null && RawContent.FindExtraJsonObjectFields(type)) {
- // // Directory.CreateDirectory($"unknown_state_events/{Type}");
- // // File.WriteAllText($"unknown_state_events/{Type}/{stateEventResponse.EventId}.json",
- // // RawContent.ToJson());
- // // Console.WriteLine($"Saved to unknown_state_events/{Type}/{stateEventResponse.EventId}.json");
- // // }
- // // }
- //
- // return type;
- // }
- // }
+ // [field: AllowNull, MaybeNull]
+ [NotNull]
+ public JsonObject? RawContent { get; set; }
//debug
[JsonIgnore]
@@ -143,6 +119,18 @@ 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;
+
+ /// <summary>
+ /// Compares two state events for deep equality, including type, state key, and raw content.
+ /// If you trust the server, use Equals instead, as that compares by event ID instead of raw content.
+ /// </summary>
+ /// <param name="x"></param>
+ /// <param name="y"></param>
+ /// <returns></returns>
+ public static bool DeepEquals(StateEventResponse x, StateEventResponse y) => x.Type == y.Type && x.StateKey == y.StateKey && JsonNode.DeepEquals(x.RawContent, y.RawContent);
}
public class StateEventResponse : StateEvent {
@@ -156,13 +144,13 @@ public class StateEventResponse : StateEvent {
public string? Sender { get; set; }
[JsonPropertyName("unsigned")]
- public UnsignedData? Unsigned { get; set; }
+ public JsonObject? Unsigned { get; set; }
[JsonPropertyName("event_id")]
public string? EventId { get; set; }
public class UnsignedData {
- [JsonPropertyName("age")]
+ [JsonPropertyName("age"), JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
public ulong? Age { get; set; }
[JsonPropertyName("redacted_because")]
@@ -254,4 +242,23 @@ public class StateEventContentPolymorphicTypeInfoResolver : DefaultJsonTypeInfoR
}
*/
+/*
+public class ForgivingObjectConverter<T> : JsonConverter<T> where T : new() {
+ public override T? Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) {
+ try {
+ var text = JsonDocument.ParseValue(ref reader).RootElement.GetRawText();
+ return JsonSerializer.Deserialize<T>(text, options);
+ }
+ catch (JsonException ex) {
+ Console.WriteLine(ex);
+ return null;
+ }
+ }
+
+ public override bool CanConvert(Type typeToConvert) => true;
+
+ public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
+ => JsonSerializer.Serialize<T>(writer, value, options);
+}*/
+
#endregion
\ No newline at end of file
diff --git a/LibMatrix/Utilities/CommonSyncFilters.cs b/LibMatrix/Utilities/CommonSyncFilters.cs
index bf8b987..503cc1f 100644
--- a/LibMatrix/Utilities/CommonSyncFilters.cs
+++ b/LibMatrix/Utilities/CommonSyncFilters.cs
@@ -1,7 +1,7 @@
using System.Collections.Frozen;
using LibMatrix.EventTypes.Common;
-using LibMatrix.EventTypes.Spec.State;
using LibMatrix.EventTypes.Spec.State.RoomInfo;
+using LibMatrix.EventTypes.Spec.State.Space;
using LibMatrix.Filters;
namespace LibMatrix.Utilities;
diff --git a/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs b/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs
index 2819f80..6878b44 100644
--- a/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs
+++ b/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs
@@ -3,9 +3,7 @@ using LibMatrix.Homeservers;
using LibMatrix.Responses;
using LibMatrix.Services;
using Microsoft.Extensions.Logging;
-using Microsoft.Extensions.Logging.Abstractions;
using Xunit.Abstractions;
-using Xunit.Sdk;
namespace LibMatrix.Tests.Abstractions;
diff --git a/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs b/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs
index 88b6758..b1176ca 100644
--- a/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs
+++ b/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs
@@ -1,7 +1,6 @@
-using System.Diagnostics;
using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
using LibMatrix.EventTypes.Spec.State.RoomInfo;
+using LibMatrix.EventTypes.Spec.State.Space;
using LibMatrix.Homeservers;
using LibMatrix.Responses;
using LibMatrix.RoomTypes;
@@ -53,7 +52,7 @@ public static class RoomAbstraction {
return testRoom;
}
- private static SemaphoreSlim _spaceSemaphore = null!;
+ private static SemaphoreSlim _spaceSemaphore = new(1, 1);
public static async Task<SpaceRoom> GetTestSpace(AuthenticatedHomeserverGeneric hs, int roomCount = 100, bool addSpaces = false, int spaceSizeReduction = 10) {
_spaceSemaphore ??= new SemaphoreSlim(roomCount / spaceSizeReduction, roomCount / spaceSizeReduction);
@@ -97,7 +96,7 @@ public static class RoomAbstraction {
});
}
- var testSpace = (await hs.CreateRoom(crq)).AsSpace;
+ var testSpace = (await hs.CreateRoom(crq)).AsSpace();
await testSpace.SendStateEventAsync("gay.rory.libmatrix.unit_test_room", new object());
diff --git a/Tests/LibMatrix.Tests/Config.cs b/Tests/LibMatrix.Tests/Config.cs
index 045ea40..b59b238 100644
--- a/Tests/LibMatrix.Tests/Config.cs
+++ b/Tests/LibMatrix.Tests/Config.cs
@@ -18,7 +18,7 @@ public class Config {
{ "matrix.org", "https://matrix-client.matrix.org" },
{ "rory.gay", "https://matrix.rory.gay" },
{ "feline.support", "https://matrix.feline.support" },
- { "transfem.dev", "https://matrix.transfem.dev" },
+ { "transfem.dev", "https://matrix.transfem.dev/" },
{ "the-apothecary.club", "https://the-apothecary.club" },
{ "nixos.org", "https://matrix.nixos.org" },
{ "fedora.im", "https://fedora.ems.host" }
diff --git a/Tests/LibMatrix.Tests/DataTests/WhoAmITests.cs b/Tests/LibMatrix.Tests/DataTests/WhoAmITests.cs
index e1da3d5..2a25056 100644
--- a/Tests/LibMatrix.Tests/DataTests/WhoAmITests.cs
+++ b/Tests/LibMatrix.Tests/DataTests/WhoAmITests.cs
@@ -1,3 +1,5 @@
+using LibMatrix.Responses;
+
namespace LibMatrix.Tests.DataTests;
public static class WhoAmITests {
diff --git a/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs b/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs
index 01a0d2f..e3c4388 100644
--- a/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs
+++ b/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs
@@ -1,4 +1,3 @@
-using ArcaneLibs.Extensions;
using LibMatrix.Services;
using LibMatrix.Tests.Abstractions;
using Microsoft.Extensions.Configuration;
diff --git a/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj b/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj
index 52bec9f..98c8101 100644
--- a/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj
+++ b/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>net8.0</TargetFramework>
+ <TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
@@ -10,20 +10,20 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0"/>
+ <PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.1" />
- <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
- <PackageReference Include="xunit" Version="2.8.0" />
- <PackageReference Include="Xunit.Microsoft.DependencyInjection" Version="8.1.0" />
- <PackageReference Include="xunit.runner.visualstudio" Version="2.5.3">
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
+ <PackageReference Include="xunit" Version="2.9.3" />
+ <PackageReference Include="Xunit.Microsoft.DependencyInjection" Version="9.0.0" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="3.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
- <PackageReference Include="coverlet.collector" Version="6.0.2">
+ <PackageReference Include="coverlet.collector" Version="6.0.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
- <PackageReference Include="Xunit.SkippableFact" Version="1.4.13"/>
+ <PackageReference Include="Xunit.SkippableFact" Version="1.5.23" />
</ItemGroup>
<ItemGroup>
diff --git a/Tests/LibMatrix.Tests/Tests/AuthMediaTests.cs b/Tests/LibMatrix.Tests/Tests/AuthMediaTests.cs
index 712e45a..29d37e0 100644
--- a/Tests/LibMatrix.Tests/Tests/AuthMediaTests.cs
+++ b/Tests/LibMatrix.Tests/Tests/AuthMediaTests.cs
@@ -1,6 +1,5 @@
using ArcaneLibs.Extensions;
using ArcaneLibs.Extensions.Streams;
-using LibMatrix.Homeservers;
using LibMatrix.Services;
using LibMatrix.Tests.Abstractions;
using LibMatrix.Tests.Fixtures;
diff --git a/Tests/LibMatrix.Tests/Tests/CanonicalJsonTests.cs b/Tests/LibMatrix.Tests/Tests/CanonicalJsonTests.cs
index c7fde54..b6bde71 100644
--- a/Tests/LibMatrix.Tests/Tests/CanonicalJsonTests.cs
+++ b/Tests/LibMatrix.Tests/Tests/CanonicalJsonTests.cs
@@ -2,13 +2,9 @@ using System.Collections.Frozen;
using System.Diagnostics;
using System.Text.Json;
using LibMatrix.Extensions;
-using LibMatrix.Services;
-using LibMatrix.Tests.Abstractions;
-using LibMatrix.Tests.DataTests;
using LibMatrix.Tests.Fixtures;
using Xunit.Abstractions;
using Xunit.Microsoft.DependencyInjection.Abstracts;
-using Xunit.Sdk;
namespace LibMatrix.Tests.Tests;
diff --git a/Tests/LibMatrix.Tests/Tests/HomeserverResolverTests/ClientWellKnownResolverTests.cs b/Tests/LibMatrix.Tests/Tests/HomeserverResolverTests/ClientWellKnownResolverTests.cs
new file mode 100644
index 0000000..ea494fa
--- /dev/null
+++ b/Tests/LibMatrix.Tests/Tests/HomeserverResolverTests/ClientWellKnownResolverTests.cs
@@ -0,0 +1,41 @@
+using LibMatrix.Services;
+using LibMatrix.Services.WellKnownResolver.WellKnownResolvers;
+using LibMatrix.Tests.Fixtures;
+using Xunit.Abstractions;
+using Xunit.Microsoft.DependencyInjection.Abstracts;
+
+namespace LibMatrix.Tests.Tests.HomeserverResolverTests;
+
+public class ClientWellKnownResolverTests : TestBed<TestFixture> {
+ private readonly Config _config;
+ private readonly ClientWellKnownResolver _resolver;
+
+ public ClientWellKnownResolverTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) {
+ _config = _fixture.GetService<Config>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(Config)}");
+ _resolver = _fixture.GetService<ClientWellKnownResolver>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}");
+ }
+
+ [Fact]
+ public async Task ResolveServerClient() {
+ var tasks = _config.ExpectedHomeserverClientMappings.Select(async mapping => {
+ var server = await _resolver.TryResolveWellKnown(mapping.Key);
+ Assert.Equal(mapping.Value, server.Content.Homeserver.BaseUrl);
+ return server;
+ }).ToList();
+ await Task.WhenAll(tasks);
+ }
+
+ private async Task AssertClientWellKnown(string homeserver, string expected) {
+ var server = await _resolver.TryResolveWellKnown(homeserver);
+ Assert.Equal(expected, server.Content.Homeserver.BaseUrl);
+ }
+
+ [Fact]
+ public Task ResolveMatrixOrg() => AssertClientWellKnown("matrix.org", "https://matrix-client.matrix.org");
+
+ [Fact]
+ public Task ResolveRoryGay() => AssertClientWellKnown("rory.gay", "https://matrix.rory.gay");
+
+ [Fact]
+ public Task ResolveTransfemDev() => AssertClientWellKnown("transfem.dev", "https://matrix.transfem.dev/");
+}
\ No newline at end of file
diff --git a/Tests/LibMatrix.Tests/Tests/HomeserverResolverTests.cs b/Tests/LibMatrix.Tests/Tests/LegacyHomeserverResolverTests.cs
index ef2426d..20dc4fb 100644
--- a/Tests/LibMatrix.Tests/Tests/HomeserverResolverTests.cs
+++ b/Tests/LibMatrix.Tests/Tests/LegacyHomeserverResolverTests.cs
@@ -5,11 +5,11 @@ using Xunit.Microsoft.DependencyInjection.Abstracts;
namespace LibMatrix.Tests.Tests;
-public class HomeserverResolverTests : TestBed<TestFixture> {
+public class LegacyHomeserverResolverTests : TestBed<TestFixture> {
private readonly Config _config;
private readonly HomeserverResolverService _resolver;
- public HomeserverResolverTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) {
+ public LegacyHomeserverResolverTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) {
_config = _fixture.GetService<Config>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(Config)}");
_resolver = _fixture.GetService<HomeserverResolverService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}");
}
@@ -33,11 +33,4 @@ public class HomeserverResolverTests : TestBed<TestFixture> {
}).ToList();
await Task.WhenAll(tasks);
}
-
- [Fact]
- public async Task ResolveMedia() {
- var media = await _resolver.ResolveMediaUri("matrix.org", "mxc://matrix.org/eqwrRZRoPpNbcMeUwyXAuVRo");
-
- Assert.Equal("https://matrix-client.matrix.org/_matrix/media/v3/download/matrix.org/eqwrRZRoPpNbcMeUwyXAuVRo", media);
- }
}
\ No newline at end of file
diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomNameTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomNameTests.cs
index 1ea3e18..7f53b08 100644
--- a/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomNameTests.cs
+++ b/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomNameTests.cs
@@ -1,4 +1,4 @@
-using LibMatrix.EventTypes.Spec.State;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Tests.Abstractions;
using LibMatrix.Tests.Fixtures;
using Xunit.Abstractions;
diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests/RoomEventTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/RoomEventTests.cs
index 9081a5a..97f4525 100644
--- a/Tests/LibMatrix.Tests/Tests/RoomTests/RoomEventTests.cs
+++ b/Tests/LibMatrix.Tests/Tests/RoomTests/RoomEventTests.cs
@@ -1,5 +1,3 @@
-using LibMatrix.Homeservers;
-using LibMatrix.Services;
using LibMatrix.Tests.Abstractions;
using LibMatrix.Tests.Fixtures;
using Xunit.Abstractions;
diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests/RoomMembershipTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/RoomMembershipTests.cs
index 2e552e2..8419518 100644
--- a/Tests/LibMatrix.Tests/Tests/RoomTests/RoomMembershipTests.cs
+++ b/Tests/LibMatrix.Tests/Tests/RoomTests/RoomMembershipTests.cs
@@ -1,10 +1,6 @@
-using System.Diagnostics;
-using System.Text;
using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Homeservers;
-using LibMatrix.Responses;
-using LibMatrix.Services;
using LibMatrix.Tests.Abstractions;
using LibMatrix.Tests.Fixtures;
using Xunit.Abstractions;
@@ -166,7 +162,7 @@ public class RoomMembershipTests : TestBed<TestFixture> {
await otherUser.GetRoom(room.RoomId).JoinAsync(reason: "Unit test!");
}
- var states = await room.GetMembersListAsync(false);
+ var states = await room.GetMembersListAsync();
Assert.Equal(count + 1, states.Count);
await room.LeaveAsync();
diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests/RoomTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/RoomTests.cs
index 401b24f..7801ed0 100644
--- a/Tests/LibMatrix.Tests/Tests/RoomTests/RoomTests.cs
+++ b/Tests/LibMatrix.Tests/Tests/RoomTests/RoomTests.cs
@@ -1,12 +1,8 @@
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
using System.Text;
using ArcaneLibs.Extensions;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.EventTypes.Spec.State;
-using LibMatrix.Homeservers;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Responses;
-using LibMatrix.Services;
using LibMatrix.Tests.Abstractions;
using LibMatrix.Tests.Fixtures;
using Xunit.Abstractions;
@@ -304,7 +300,7 @@ public class RoomTests : TestBed<TestFixture> {
});
await room.InviteUsersAsync(users.Select(u => u.UserId));
- var members = await room.GetMembersListAsync(false);
+ var members = await room.GetMembersListAsync();
Assert.NotNull(members);
Assert.NotEmpty(members);
Assert.All(members, Assert.NotNull);
diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests/SpaceTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/SpaceTests.cs
index 148b5fe..be8076a 100644
--- a/Tests/LibMatrix.Tests/Tests/RoomTests/SpaceTests.cs
+++ b/Tests/LibMatrix.Tests/Tests/RoomTests/SpaceTests.cs
@@ -1,11 +1,7 @@
-using System.Diagnostics;
-using System.Text;
using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
-using LibMatrix.Homeservers;
+using LibMatrix.EventTypes.Spec.State.Space;
using LibMatrix.Responses;
using LibMatrix.RoomTypes;
-using LibMatrix.Services;
using LibMatrix.Tests.Abstractions;
using LibMatrix.Tests.Fixtures;
using Xunit.Abstractions;
@@ -27,7 +23,7 @@ public class SpaceTests : TestBed<TestFixture> {
Name = "Test space"
};
crq.CreationContent["type"] = SpaceRoom.TypeName;
- var space = (await hs.CreateRoom(crq)).AsSpace;
+ var space = (await hs.CreateRoom(crq)).AsSpace();
var child = await hs.CreateRoom(new CreateRoomRequest() {
Name = "Test child"
@@ -49,7 +45,7 @@ public class SpaceTests : TestBed<TestFixture> {
Name = "Test space"
};
crq.CreationContent["type"] = SpaceRoom.TypeName;
- var space = (await hs.CreateRoom(crq)).AsSpace;
+ var space = (await hs.CreateRoom(crq)).AsSpace();
var child = await hs.CreateRoom(new CreateRoomRequest() {
Name = "Test child"
@@ -87,7 +83,7 @@ public class SpaceTests : TestBed<TestFixture> {
}).ToList()
};
crq.CreationContent["type"] = SpaceRoom.TypeName;
- var space = (await hs.CreateRoom(crq)).AsSpace;
+ var space = (await hs.CreateRoom(crq)).AsSpace();
var children = space.GetChildrenAsync().ToBlockingEnumerable().ToList();
Assert.NotNull(children);
diff --git a/Utilities/LibMatrix.DebugDataValidationApi/LibMatrix.DebugDataValidationApi.csproj b/Utilities/LibMatrix.DebugDataValidationApi/LibMatrix.DebugDataValidationApi.csproj
index 7d97b70..ee4fd58 100644
--- a/Utilities/LibMatrix.DebugDataValidationApi/LibMatrix.DebugDataValidationApi.csproj
+++ b/Utilities/LibMatrix.DebugDataValidationApi/LibMatrix.DebugDataValidationApi.csproj
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
- <TargetFramework>net8.0</TargetFramework>
+ <TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
@@ -9,8 +9,8 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.6" />
- <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
+ <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.1" />
+ <PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
</ItemGroup>
<ItemGroup>
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs
index 89a9033..874d195 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/CmdCommand.cs
@@ -1,11 +1,13 @@
using ArcaneLibs.StringNormalisation;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.ExampleBot.Bot.Interfaces;
+using LibMatrix.Utilities.Bot.Interfaces;
namespace LibMatrix.ExampleBot.Bot.Commands;
public class CmdCommand : ICommand {
public string Name => "cmd";
+ public string[]? Aliases => [];
+ public bool Unlisted => false;
public string Description => "Runs a command on the host system";
public Task<bool> CanInvoke(CommandContext ctx) => Task.FromResult(ctx.MessageEvent.Sender.EndsWith(":rory.gay") || ctx.MessageEvent.Sender.EndsWith(":conduit.rory.gay"));
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs
index f75c863..0dde297 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/DbgAniRainbowTest.cs
@@ -1,16 +1,20 @@
using System.Diagnostics;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.ExampleBot.Bot.Interfaces;
using LibMatrix.Helpers;
-using LibMatrix.RoomTypes;
using LibMatrix.Services;
+using LibMatrix.Utilities.Bot.Interfaces;
namespace ModerationBot.Commands;
public class DbgAniRainbowTest(IServiceProvider services, HomeserverProviderService hsProvider, HomeserverResolverService hsResolver) : ICommand {
public string Name { get; } = "ani-rainbow";
+
+ public string[]? Aliases => [];
+ public bool Unlisted => false;
+
public string Description { get; } = "[Debug] animated rainbow :)";
+
public async Task<bool> CanInvoke(CommandContext ctx) => ctx.Room.RoomId == "!hLEefBaYvNfJwcTjmt:rory.gay";
public async Task Invoke(CommandContext ctx) {
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs
index 7ecbeb3..33bbc5a 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/HelpCommand.cs
@@ -1,12 +1,14 @@
using System.Text;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.ExampleBot.Bot.Interfaces;
+using LibMatrix.Utilities.Bot.Interfaces;
using Microsoft.Extensions.DependencyInjection;
namespace LibMatrix.ExampleBot.Bot.Commands;
public class HelpCommand(IServiceProvider services) : ICommand {
public string Name { get; } = "help";
+ public string[]? Aliases => [];
+ public bool Unlisted => false;
public string Description { get; } = "Displays this help message";
public async Task Invoke(CommandContext ctx) {
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs
index 85c86a3..350d89e 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/Commands/PingCommand.cs
@@ -1,11 +1,24 @@
using LibMatrix.EventTypes.Spec;
-using LibMatrix.ExampleBot.Bot.Interfaces;
+using LibMatrix.Utilities.Bot.Interfaces;
namespace LibMatrix.ExampleBot.Bot.Commands;
public class PingCommand : ICommand {
- public string Name { get; } = "ping";
+ public string Name { get; } = "do-ping";
+ public string[]? Aliases => [];
+ public bool Unlisted => false;
public string Description { get; } = "Pong!";
- public async Task Invoke(CommandContext ctx) => await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "pong!"));
+ // public async Task Invoke(CommandContext ctx) => await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "pong!"));
+ public async Task Invoke(CommandContext ctx) {
+ // await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "pong!"));
+ var count = ctx.Args.Length > 0 ? int.Parse(ctx.Args[0]) : 1;
+ var tasks = Enumerable.Range(0, count).Select(async i => {
+ await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: $"!ping {i}", messageType: "m.text"));
+ await Task.Delay(1000);
+ }).ToList();
+ await Task.WhenAll(tasks);
+
+ await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "Pong!"));
+ }
}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs b/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs
index fa80bfd..3bb0c25 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/DevTestBot.cs
@@ -1,8 +1,7 @@
using System.Diagnostics.CodeAnalysis;
using ArcaneLibs.Extensions;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.EventTypes.Spec.State;
-using LibMatrix.ExampleBot.Bot.Interfaces;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
using LibMatrix.Services;
@@ -16,17 +15,13 @@ public class DevTestBot : IHostedService {
private readonly HomeserverProviderService _homeserverProviderService;
private readonly ILogger<DevTestBot> _logger;
private readonly DevTestBotConfiguration _configuration;
- private readonly IEnumerable<ICommand> _commands;
public DevTestBot(HomeserverProviderService homeserverProviderService, ILogger<DevTestBot> logger,
- DevTestBotConfiguration configuration, IServiceProvider services) {
+ DevTestBotConfiguration configuration) {
logger.LogInformation("{} instantiated!", GetType().Name);
_homeserverProviderService = homeserverProviderService;
_logger = logger;
_configuration = configuration;
- _logger.LogInformation("Getting commands...");
- _commands = services.GetServices<ICommand>();
- _logger.LogInformation("Got {} commands!", _commands.Count());
}
/// <summary>Triggered when the application host is ready to start the service.</summary>
@@ -59,48 +54,6 @@ public class DevTestBot : IHostedService {
// _logger.LogInformation($"Got room state for {room.RoomId}!");
// }
- syncHelper.InviteReceivedHandlers.Add(async Task (args) => {
- var inviteEvent =
- args.Value.InviteState.Events.FirstOrDefault(x =>
- x.Type == "m.room.member" && x.StateKey == hs.UserId);
- _logger.LogInformation(
- $"Got invite to {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventContent).Reason}");
- if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent.Sender == "@mxidupwitch:the-apothecary.club")
- try {
- var senderProfile = await hs.GetProfileAsync(inviteEvent.Sender);
- await hs.GetRoom(args.Key).JoinAsync(reason: $"I was invited by {senderProfile.DisplayName ?? inviteEvent.Sender}!");
- }
- catch (Exception e) {
- _logger.LogError("{}", e.ToString());
- await hs.GetRoom(args.Key).LeaveAsync("I was unable to join the room: " + e);
- }
- });
- syncHelper.TimelineEventHandlers.Add(async @event => {
- _logger.LogInformation(
- "Got timeline event in {}: {}", @event.RoomId, @event.ToJson(false, true));
-
- var room = hs.GetRoom(@event.RoomId);
- // _logger.LogInformation(eventResponse.ToJson(indent: false));
- if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message })
- if (message is { MessageType: "m.text" } && message.Body.StartsWith(_configuration.Prefix)) {
- var command = _commands.FirstOrDefault(x => x.Name == message.Body.Split(' ')[0][_configuration.Prefix.Length..]);
- if (command == null) {
- await room.SendMessageEventAsync(
- new RoomMessageEventContent("m.text", "Command not found!"));
- return;
- }
-
- var ctx = new CommandContext {
- Room = room,
- MessageEvent = @event
- };
- if (await command.CanInvoke(ctx))
- await command.Invoke(ctx);
- else
- await room.SendMessageEventAsync(
- new RoomMessageEventContent("m.text", "You do not have permission to run this command!"));
- }
- });
await syncHelper.RunSyncLoopAsync(cancellationToken: cancellationToken);
}
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/CommandContext.cs b/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/CommandContext.cs
deleted file mode 100644
index 90a95e4..0000000
--- a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/CommandContext.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using LibMatrix.EventTypes.Spec;
-using LibMatrix.RoomTypes;
-
-namespace LibMatrix.ExampleBot.Bot.Interfaces;
-
-public class CommandContext {
- public GenericRoom Room { get; set; }
- public StateEventResponse MessageEvent { get; set; }
- public string CommandName => (MessageEvent.TypedContent as RoomMessageEventContent).Body.Split(' ')[0][1..];
- public string[] Args => (MessageEvent.TypedContent as RoomMessageEventContent).Body.Split(' ')[1..];
-}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/ICommand.cs b/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/ICommand.cs
deleted file mode 100644
index a6dc8da..0000000
--- a/Utilities/LibMatrix.DevTestBot/Bot/Interfaces/ICommand.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-namespace LibMatrix.ExampleBot.Bot.Interfaces;
-
-public interface ICommand {
- public string Name { get; }
- public string Description { get; }
-
- public Task<bool> CanInvoke(CommandContext ctx) => Task.FromResult(true);
-
- public Task Invoke(CommandContext ctx);
-}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/PingTestBot.cs b/Utilities/LibMatrix.DevTestBot/Bot/PingTestBot.cs
new file mode 100644
index 0000000..e992e3c
--- /dev/null
+++ b/Utilities/LibMatrix.DevTestBot/Bot/PingTestBot.cs
@@ -0,0 +1,125 @@
+using System.Diagnostics.CodeAnalysis;
+using System.Windows.Input;
+using ArcaneLibs.Extensions;
+using LibMatrix.EventTypes.Spec;
+using LibMatrix.Filters;
+using LibMatrix.Helpers;
+using LibMatrix.Homeservers;
+using LibMatrix.Services;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+
+namespace LibMatrix.ExampleBot.Bot;
+
+public class PingTestBot : IHostedService {
+ private readonly HomeserverProviderService _homeserverProviderService;
+ private readonly ILogger<DevTestBot> _logger;
+ private readonly DevTestBotConfiguration _configuration;
+ private readonly IEnumerable<ICommand> _commands;
+
+ public PingTestBot(HomeserverProviderService homeserverProviderService, ILogger<DevTestBot> logger,
+ DevTestBotConfiguration configuration, IServiceProvider services) {
+ logger.LogInformation("{} instantiated!", GetType().Name);
+ _homeserverProviderService = homeserverProviderService;
+ _logger = logger;
+ _configuration = configuration;
+ _logger.LogInformation("Getting commands...");
+ _commands = services.GetServices<ICommand>();
+ _logger.LogInformation("Got {} commands!", _commands.Count());
+ }
+
+ /// <summary>Triggered when the application host is ready to start the service.</summary>
+ /// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
+ [SuppressMessage("ReSharper", "FunctionNeverReturns")]
+ public async Task StartAsync(CancellationToken cancellationToken) {
+ // Directory.GetFiles("bot_data/cache").ToList().ForEach(File.Delete);
+ AuthenticatedHomeserverGeneric hs;
+ try {
+ hs = await _homeserverProviderService.GetAuthenticatedWithToken(_configuration.Homeserver,
+ _configuration.AccessToken);
+ }
+ catch (Exception e) {
+ _logger.LogError("{}", e.Message);
+ throw;
+ }
+
+ var msg = new MessageBuilder().WithRainbowString("Meanwhile, I'm sitting here, still struggling with trying to rainbow. ^^'").Build();
+
+ var syncHelper = new SyncHelper(hs);
+ syncHelper.Filter = new SyncFilter {
+ Room = new SyncFilter.RoomFilter {
+ Timeline = new SyncFilter.RoomFilter.StateFilter() {
+ Limit = 1,
+ Senders = ["@me"]
+ },
+ Rooms = ["!ping-v11:maunium.net"],
+ AccountData = new(types: []),
+ IncludeLeave = false
+ }
+ };
+
+ // await hs.GetRoom("!VJwxdebqoQlhGSEncc:codestorm.net").JoinAsync();
+
+ // foreach (var room in await hs.GetJoinedRooms()) {
+ // if(room.RoomId is "!OGEhHVWSdvArJzumhm:matrix.org") continue;
+ // foreach (var stateEvent in await room.GetStateAsync<List<StateEvent>>("")) {
+ // var _ = stateEvent.GetType;
+ // }
+ // _logger.LogInformation($"Got room state for {room.RoomId}!");
+ // }
+
+ // syncHelper.InviteReceivedHandlers.Add(async Task (args) => {
+ // var inviteEvent =
+ // args.Value.InviteState.Events.FirstOrDefault(x =>
+ // x.Type == "m.room.member" && x.StateKey == hs.UserId);
+ // _logger.LogInformation(
+ // $"Got invite to {args.Key} by {inviteEvent.Sender} with reason: {(inviteEvent.TypedContent as RoomMemberEventContent).Reason}");
+ // if (inviteEvent.Sender.EndsWith(":rory.gay") || inviteEvent.Sender == "@mxidupwitch:the-apothecary.club")
+ // try {
+ // var senderProfile = await hs.GetProfileAsync(inviteEvent.Sender);
+ // await hs.GetRoom(args.Key).JoinAsync(reason: $"I was invited by {senderProfile.DisplayName ?? inviteEvent.Sender}!");
+ // }
+ // catch (Exception e) {
+ // _logger.LogError("{}", e.ToString());
+ // await hs.GetRoom(args.Key).LeaveAsync("I was unable to join the room: " + e);
+ // }
+ // });
+ // Deprecated, using Bot Utils instead:
+ // syncHelper.TimelineEventHandlers.Add(async @event => {
+ // _logger.LogInformation(
+ // "Got timeline event in {}: {}", @event.RoomId, @event.ToJson(false, true));
+ //
+ // var room = hs.GetRoom(@event.RoomId);
+ // // _logger.LogInformation(eventResponse.ToJson(indent: false));
+ // if (@event is not { Sender: "@emma:rory.gay" }) return;
+ // if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message })
+ // if (message is { MessageType: "m.text" } && message.Body.StartsWith(_configuration.Prefix)) {
+ // var command = _commands.FirstOrDefault(x => x.Name == message.Body.Split(' ')[0][_configuration.Prefix.Length..]);
+ // if (command == null) {
+ // await room.SendMessageEventAsync(
+ // new RoomMessageEventContent("m.text", "Command not found!"));
+ // return;
+ // }
+ //
+ // var ctx = new CommandContext {
+ // Room = room,
+ // MessageEvent = @event
+ // };
+ // if (await command.CanInvoke(ctx))
+ // await command.Invoke(ctx);
+ // else
+ // await room.SendMessageEventAsync(
+ // new RoomMessageEventContent("m.text", "You do not have permission to run this command!"));
+ // }
+ // });
+ await syncHelper.RunSyncLoopAsync(cancellationToken: cancellationToken);
+ }
+
+ /// <summary>Triggered when the application host is performing a graceful shutdown.</summary>
+ /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
+ public Task StopAsync(CancellationToken cancellationToken) {
+ _logger.LogInformation("Shutting down bot!");
+ return Task.CompletedTask;
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs b/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs
index 253eb37..fdc7717 100644
--- a/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs
+++ b/Utilities/LibMatrix.DevTestBot/Bot/StartupTasks/ServerRoomSizeCalulator.cs
@@ -1,5 +1,4 @@
using System.Diagnostics.CodeAnalysis;
-using LibMatrix.ExampleBot.Bot.Interfaces;
using LibMatrix.Homeservers;
using LibMatrix.Services;
using Microsoft.Extensions.Hosting;
@@ -11,10 +10,9 @@ public class ServerRoomSizeCalulator : IHostedService {
private readonly HomeserverProviderService _homeserverProviderService;
private readonly ILogger<ServerRoomSizeCalulator> _logger;
private readonly DevTestBotConfiguration _configuration;
- private readonly IEnumerable<ICommand> _commands;
public ServerRoomSizeCalulator(HomeserverProviderService homeserverProviderService, ILogger<ServerRoomSizeCalulator> logger,
- DevTestBotConfiguration configuration, IServiceProvider services) {
+ DevTestBotConfiguration configuration) {
logger.LogInformation("Server room size calculator hosted service instantiated!");
_homeserverProviderService = homeserverProviderService;
_logger = logger;
diff --git a/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj b/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj
index 6518c67..acff3e2 100644
--- a/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj
+++ b/Utilities/LibMatrix.DevTestBot/LibMatrix.DevTestBot.csproj
@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
- <TargetFramework>net8.0</TargetFramework>
+ <TargetFramework>net9.0</TargetFramework>
<LangVersion>preview</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
@@ -18,13 +18,16 @@
</PropertyGroup>
<ItemGroup>
+ <PackageReference Include="ArcaneLibs.StringNormalisation" Version="1.0.0-preview.20250419-174711" Condition="'$(Configuration)' == 'Release'" />
+ <ProjectReference Include="..\..\ArcaneLibs\ArcaneLibs.StringNormalisation\ArcaneLibs.StringNormalisation.csproj" Condition="'$(Configuration)' == 'Debug'"/>
<ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj"/>
+ <ProjectReference Include="..\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj" />
</ItemGroup>
<ItemGroup>
- <PackageReference Include="ArcaneLibs.StringNormalisation" Version="1.0.0-preview7205256004.28c0e5a"/>
- <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0"/>
+ <PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.1"/>
</ItemGroup>
+
<ItemGroup>
<Content Include="appsettings*.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
diff --git a/Utilities/LibMatrix.DevTestBot/Program.cs b/Utilities/LibMatrix.DevTestBot/Program.cs
index daaa65e..7eb74d4 100644
--- a/Utilities/LibMatrix.DevTestBot/Program.cs
+++ b/Utilities/LibMatrix.DevTestBot/Program.cs
@@ -1,30 +1,24 @@
// See https://aka.ms/new-console-template for more information
-using ArcaneLibs;
using LibMatrix.ExampleBot.Bot;
-using LibMatrix.ExampleBot.Bot.Interfaces;
using LibMatrix.Services;
+using LibMatrix.Utilities.Bot;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Console.WriteLine("Hello, World!");
var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => {
- // services.AddScoped<TieredStorageService>(x =>
- // new TieredStorageService(
- // cacheStorageProvider: new FileStorageProvider("bot_data/cache/"),
- // dataStorageProvider: new FileStorageProvider("bot_data/data/")
- // )
- // );
services.AddScoped<DevTestBotConfiguration>();
services.AddRoryLibMatrixServices();
- foreach (var commandClass in ClassCollector<ICommand>.ResolveFromAllAccessibleAssemblies()) {
- Console.WriteLine($"Adding command {commandClass.Name}");
- services.AddScoped(typeof(ICommand), commandClass);
- }
+
+ services.AddMatrixBot()
+ .AddCommandHandler()
+ .DiscoverAllCommands()
+ .WithInviteHandler(ctx => Task.FromResult(ctx.MemberEvent.Sender!.EndsWith(":rory.gay")));
// services.AddHostedService<ServerRoomSizeCalulator>();
- services.AddHostedService<DevTestBot>();
+ services.AddHostedService<PingTestBot>();
}).UseConsoleLifetime().Build();
await host.RunAsync();
\ No newline at end of file
diff --git a/Utilities/LibMatrix.DevTestBot/appsettings.json b/Utilities/LibMatrix.DevTestBot/appsettings.json
index db64c22..815d2a5 100644
--- a/Utilities/LibMatrix.DevTestBot/appsettings.json
+++ b/Utilities/LibMatrix.DevTestBot/appsettings.json
@@ -8,7 +8,7 @@
},
"Bot": {
"Homeserver": "rory.gay",
- "AccessToken": "syt_xxxxxxxxxxxxxxxxx",
- "Prefix": "!"
+ "AccessToken": "syt_xxxxxx_xxxxxxxxxxxxxxxxxxxx_xxxxxx",
+ "Prefix": "$"
}
}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.E2eeTestKit/LibMatrix.E2eeTestKit.csproj b/Utilities/LibMatrix.E2eeTestKit/LibMatrix.E2eeTestKit.csproj
index 4e3a128..78cdb67 100644
--- a/Utilities/LibMatrix.E2eeTestKit/LibMatrix.E2eeTestKit.csproj
+++ b/Utilities/LibMatrix.E2eeTestKit/LibMatrix.E2eeTestKit.csproj
@@ -1,15 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
- <TargetFramework>net8.0</TargetFramework>
+ <TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<ServiceWorkerAssetsManifest>service-worker-assets.js</ServiceWorkerAssetsManifest>
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="8.0.6" />
- <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="8.0.6" PrivateAssets="all" />
+ <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.1" />
+ <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.1" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
diff --git a/Utilities/LibMatrix.E2eeTestKit/Pages/CSTJTest.razor b/Utilities/LibMatrix.E2eeTestKit/Pages/CSTJTest.razor
index 0d01428..2b787b3 100644
--- a/Utilities/LibMatrix.E2eeTestKit/Pages/CSTJTest.razor
+++ b/Utilities/LibMatrix.E2eeTestKit/Pages/CSTJTest.razor
@@ -1,6 +1,5 @@
@page "/CSTJTest"
@using System.Text.Json
-@using System.Text.Json.Nodes
@using LibMatrix.Extensions
<PageTitle>Counter</PageTitle>
diff --git a/Utilities/LibMatrix.FederationTest/.gitignore b/Utilities/LibMatrix.FederationTest/.gitignore
new file mode 100644
index 0000000..4a96773
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/.gitignore
@@ -0,0 +1 @@
+.keys/
diff --git a/Utilities/LibMatrix.FederationTest/Controllers/FederationKeysController.cs b/Utilities/LibMatrix.FederationTest/Controllers/FederationKeysController.cs
new file mode 100644
index 0000000..33d0b99
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/Controllers/FederationKeysController.cs
@@ -0,0 +1,41 @@
+using LibMatrix.Federation.Extensions;
+using LibMatrix.Federation.Utilities;
+using LibMatrix.FederationTest.Services;
+using LibMatrix.Homeservers;
+using Microsoft.AspNetCore.Mvc;
+
+namespace LibMatrix.FederationTest.Controllers;
+
+[ApiController]
+[Route("_matrix/key/v2/")]
+public class FederationKeysController(FederationTestConfiguration config, FederationKeyStore keyStore) {
+ static FederationKeysController() {
+ Console.WriteLine("INFO | FederationKeysController initialized.");
+ }
+
+ private static SignedObject<ServerKeysResponse>? _cachedServerKeysResponse;
+ private static SemaphoreSlim _serverKeyCacheLock = new SemaphoreSlim(1, 1);
+
+ [HttpGet("server")]
+ public async Task<SignedObject<ServerKeysResponse>> GetServerKeys() {
+ await _serverKeyCacheLock.WaitAsync();
+ if (_cachedServerKeysResponse == null || _cachedServerKeysResponse.TypedContent.ValidUntil < DateTime.Now + TimeSpan.FromSeconds(30)) {
+ var keys = keyStore.GetCurrentSigningKey();
+ _cachedServerKeysResponse = new ServerKeysResponse() {
+ ValidUntil = DateTime.Now + TimeSpan.FromMinutes(1),
+ ServerName = config.ServerName,
+ OldVerifyKeys = [],
+ VerifyKeysById = new() {
+ {
+ new() { Algorithm = "ed25519", KeyId = "0" }, new ServerKeysResponse.CurrentVerifyKey() {
+ Key = keys.publicKey.ToUnpaddedBase64(),
+ }
+ }
+ }
+ }.Sign(config.ServerName, new ServerKeysResponse.VersionedKeyId() { Algorithm = "ed25519", KeyId = "0" }, keys.privateKey);
+ }
+ _serverKeyCacheLock.Release();
+
+ return _cachedServerKeysResponse;
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.FederationTest/Controllers/FederationVersionController.cs b/Utilities/LibMatrix.FederationTest/Controllers/FederationVersionController.cs
new file mode 100644
index 0000000..2c3aaa3
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/Controllers/FederationVersionController.cs
@@ -0,0 +1,18 @@
+using LibMatrix.Homeservers;
+using Microsoft.AspNetCore.Mvc;
+
+namespace LibMatrix.FederationTest.Controllers;
+
+[ApiController]
+[Route("_matrix/federation/v1/")]
+public class FederationVersionController : ControllerBase {
+ [HttpGet("version")]
+ public ServerVersionResponse GetVersion() {
+ return new ServerVersionResponse {
+ Server = new() {
+ Name = "LibMatrix.Federation",
+ Version = "0.0.0",
+ }
+ };
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.FederationTest/Controllers/TestController.cs b/Utilities/LibMatrix.FederationTest/Controllers/TestController.cs
new file mode 100644
index 0000000..4a6bc87
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/Controllers/TestController.cs
@@ -0,0 +1,52 @@
+using System.Text.Json.Nodes;
+using ArcaneLibs.Extensions;
+using LibMatrix.Extensions;
+using LibMatrix.Federation;
+using LibMatrix.Federation.Utilities;
+using LibMatrix.FederationTest.Services;
+using LibMatrix.Homeservers;
+using Microsoft.AspNetCore.Mvc;
+
+namespace LibMatrix.FederationTest.Controllers;
+
+[ApiController]
+public class TestController(FederationTestConfiguration config, FederationKeyStore keyStore) : ControllerBase {
+ static TestController() {
+ Console.WriteLine("INFO | TestController initialized.");
+ }
+
+ [HttpGet("/test")]
+ public async Task<JsonObject> GetTest() {
+ var hc = new MatrixHttpClient() {
+ BaseAddress = new Uri("https://matrix.rory.gay")
+ };
+
+ var keyId = new ServerKeysResponse.VersionedKeyId() {
+ Algorithm = "ed25519",
+ KeyId = "0"
+ };
+
+ var signatureData = new XMatrixAuthorizationScheme.XMatrixRequestSignature() {
+ Method = "GET",
+ Uri = "/_matrix/federation/v1/user/devices/@emma:rory.gay",
+ OriginServerName = config.ServerName,
+ DestinationServerName = "rory.gay"
+ }
+ .Sign(config.ServerName, keyId, keyStore.GetCurrentSigningKey().privateKey);
+
+ var signature = signatureData.Signatures[config.ServerName][keyId];
+ var headerValue = new XMatrixAuthorizationScheme.XMatrixAuthorizationHeader() {
+ Origin = config.ServerName,
+ Destination = "rory.gay",
+ Key = keyId,
+ Signature = signature
+ }.ToHeaderValue();
+
+ var req = new HttpRequestMessage(HttpMethod.Get, "/_matrix/federation/v1/user/devices/@emma:rory.gay");
+ req.Headers.Add("Authorization", headerValue);
+
+ var response = await hc.SendAsync(req);
+ var content = await response.Content.ReadFromJsonAsync<JsonObject>();
+ return content!;
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.FederationTest/Controllers/WellKnownController.cs b/Utilities/LibMatrix.FederationTest/Controllers/WellKnownController.cs
new file mode 100644
index 0000000..28fca8d
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/Controllers/WellKnownController.cs
@@ -0,0 +1,19 @@
+using LibMatrix.Services.WellKnownResolver.WellKnownResolvers;
+using Microsoft.AspNetCore.Mvc;
+
+namespace LibMatrix.FederationTest.Controllers;
+
+[ApiController]
+[Route(".well-known/")]
+public class WellKnownController(ILogger<WellKnownController> logger) : ControllerBase {
+ static WellKnownController() {
+ Console.WriteLine("INFO | WellKnownController initialized.");
+ }
+ [HttpGet("matrix/server")]
+ public ServerWellKnown GetMatrixServerWellKnown() {
+ // {Request.Headers["X-Forwarded-Proto"].FirstOrDefault(Request.Scheme)}://
+ return new() {
+ Homeserver = $"{Request.Headers["X-Forwarded-Host"].FirstOrDefault(Request.Host.Host)}:{Request.Headers["X-Forwarded-Port"].FirstOrDefault("443")}",
+ };
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.FederationTest/LibMatrix.FederationTest.csproj b/Utilities/LibMatrix.FederationTest/LibMatrix.FederationTest.csproj
new file mode 100644
index 0000000..c54ba8d
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/LibMatrix.FederationTest.csproj
@@ -0,0 +1,18 @@
+<Project Sdk="Microsoft.NET.Sdk.Web">
+
+ <PropertyGroup>
+ <TargetFramework>net9.0</TargetFramework>
+ <Nullable>enable</Nullable>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <NoDefaultLaunchSettingsFile>True</NoDefaultLaunchSettingsFile>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.5"/>
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\..\LibMatrix.Federation\LibMatrix.Federation.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/Utilities/LibMatrix.FederationTest/Program.cs b/Utilities/LibMatrix.FederationTest/Program.cs
new file mode 100644
index 0000000..adc809f
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/Program.cs
@@ -0,0 +1,34 @@
+using LibMatrix.FederationTest.Services;
+
+var builder = WebApplication.CreateBuilder(args);
+
+// Add services to the container.
+
+builder.Services.AddControllers();
+// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
+builder.Services.AddOpenApi();
+builder.Services.AddHttpLogging(options => {
+ options.LoggingFields = Microsoft.AspNetCore.HttpLogging.HttpLoggingFields.All;
+ options.RequestHeaders.Add("X-Forwarded-Proto");
+ options.RequestHeaders.Add("X-Forwarded-Host");
+ options.RequestHeaders.Add("X-Forwarded-Port");
+});
+
+builder.Services.AddSingleton<FederationTestConfiguration>();
+builder.Services.AddSingleton<FederationKeyStore>();
+
+
+var app = builder.Build();
+
+// Configure the HTTP request pipeline.
+if (true || app.Environment.IsDevelopment()) {
+ app.MapOpenApi();
+}
+
+app.UseAuthorization();
+
+app.MapControllers();
+// app.UseHttpLogging();
+
+
+app.Run();
\ No newline at end of file
diff --git a/Utilities/LibMatrix.FederationTest/Services/FederationKeyStore.cs b/Utilities/LibMatrix.FederationTest/Services/FederationKeyStore.cs
new file mode 100644
index 0000000..f24d14e
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/Services/FederationKeyStore.cs
@@ -0,0 +1,31 @@
+using LibMatrix.FederationTest.Utilities;
+using Org.BouncyCastle.Crypto.Parameters;
+
+namespace LibMatrix.FederationTest.Services;
+
+public class FederationKeyStore(FederationTestConfiguration config) {
+ static FederationKeyStore() {
+ Console.WriteLine("INFO | FederationKeyStore initialized.");
+ }
+
+ private static (Ed25519PrivateKeyParameters privateKey, Ed25519PublicKeyParameters publicKey) currentKeyPair = default;
+ public (Ed25519PrivateKeyParameters privateKey, Ed25519PublicKeyParameters publicKey) GetCurrentSigningKey() {
+ if (currentKeyPair != default) {
+ return currentKeyPair;
+ }
+
+ if(!Directory.Exists(config.KeyStorePath)) Directory.CreateDirectory(config.KeyStorePath);
+
+ var privateKeyPath = Path.Combine(config.KeyStorePath, "signing.key");
+ if (!File.Exists(privateKeyPath)) {
+ var keyPair = Ed25519Utils.GenerateKeyPair();
+ File.WriteAllBytes(privateKeyPath, keyPair.privateKey.GetEncoded());
+ return keyPair;
+ }
+
+ var privateKeyBytes = File.ReadAllBytes(privateKeyPath);
+ var privateKey = Ed25519Utils.LoadPrivateKeyFromEncoded(privateKeyBytes);
+ var publicKey = privateKey.GeneratePublicKey();
+ return currentKeyPair = (privateKey, publicKey);
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.FederationTest/Services/FederationTestConfiguration.cs b/Utilities/LibMatrix.FederationTest/Services/FederationTestConfiguration.cs
new file mode 100644
index 0000000..353ddf5
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/Services/FederationTestConfiguration.cs
@@ -0,0 +1,10 @@
+namespace LibMatrix.FederationTest.Services;
+
+public class FederationTestConfiguration {
+ public FederationTestConfiguration(IConfiguration configurationSection) {
+ configurationSection.GetRequiredSection("FederationTest").Bind(this);
+ }
+
+ public string ServerName { get; set; } = "localhost";
+ public string KeyStorePath { get; set; } = "./.keys";
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.FederationTest/Utilities/Ed25519Utils.cs b/Utilities/LibMatrix.FederationTest/Utilities/Ed25519Utils.cs
new file mode 100644
index 0000000..bb57d51
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/Utilities/Ed25519Utils.cs
@@ -0,0 +1,28 @@
+using Org.BouncyCastle.Crypto.Generators;
+using Org.BouncyCastle.Crypto.Parameters;
+using Org.BouncyCastle.Security;
+
+namespace LibMatrix.FederationTest.Utilities;
+
+public class Ed25519Utils {
+ public static (Ed25519PrivateKeyParameters privateKey, Ed25519PublicKeyParameters publicKey) GenerateKeyPair() {
+ Console.WriteLine("Generating new Ed25519 key pair!");
+ var keyPairGen = new Ed25519KeyPairGenerator();
+ keyPairGen.Init(new Ed25519KeyGenerationParameters(new SecureRandom()));
+ var keyPair = keyPairGen.GenerateKeyPair();
+
+ var privateKey = (Ed25519PrivateKeyParameters)keyPair.Private;
+ var publicKey = (Ed25519PublicKeyParameters)keyPair.Public;
+
+ return (privateKey, publicKey);
+ }
+
+ public static Ed25519PublicKeyParameters LoadPublicKeyFromEncoded(string key) {
+ var keyBytes = Convert.FromBase64String(key);
+ return new Ed25519PublicKeyParameters(keyBytes, 0);
+ }
+
+ public static Ed25519PrivateKeyParameters LoadPrivateKeyFromEncoded(byte[] key) {
+ return new Ed25519PrivateKeyParameters(key, 0);
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.FederationTest/appsettings.Development.json b/Utilities/LibMatrix.FederationTest/appsettings.Development.json
new file mode 100644
index 0000000..b6c6151
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/appsettings.Development.json
@@ -0,0 +1,13 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Information",
+ "Microsoft.AspNetCore.Routing": "Warning"
+ }
+ },
+ "FederationTest": {
+ "ServerName": "libmatrix-fed-test.rory.gay",
+ "KeyStorePath": "./.keys"
+ }
+}
diff --git a/Utilities/LibMatrix.FederationTest/appsettings.json b/Utilities/LibMatrix.FederationTest/appsettings.json
new file mode 100644
index 0000000..10f68b8
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*"
+}
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/AuthController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/AuthController.cs
index 66548e2..d0eaed4 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/AuthController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/AuthController.cs
@@ -1,25 +1,21 @@
using System.Text.Json.Nodes;
using LibMatrix.HomeserverEmulator.Services;
using LibMatrix.Responses;
-using LibMatrix.Services;
using Microsoft.AspNetCore.Mvc;
namespace LibMatrix.HomeserverEmulator.Controllers;
[ApiController]
[Route("/_matrix/client/{version}/")]
-public class AuthController(ILogger<AuthController> logger, UserStore userStore, TokenService tokenService) : ControllerBase {
+public class AuthController(ILogger<AuthController> logger, UserStore userStore, TokenService tokenService, HseConfiguration config) : ControllerBase {
[HttpPost("login")]
public async Task<LoginResponse> Login(LoginRequest request) {
if (!request.Identifier.User.StartsWith('@'))
request.Identifier.User = $"@{request.Identifier.User}:{tokenService.GenerateServerName(HttpContext)}";
- if (request.Identifier.User.EndsWith("localhost"))
- request.Identifier.User = request.Identifier.User.Replace("localhost", tokenService.GenerateServerName(HttpContext));
+ // if (request.Identifier.User.EndsWith("localhost"))
+ // request.Identifier.User = request.Identifier.User.Replace("localhost", tokenService.GenerateServerName(HttpContext));
- var user = await userStore.GetUserById(request.Identifier.User);
- if (user is null) {
- user = await userStore.CreateUser(request.Identifier.User);
- }
+ var user = await userStore.GetUserById(request.Identifier.User) ?? await userStore.CreateUser(request.Identifier.User);
return user.Login();
}
@@ -58,6 +54,79 @@ public class AuthController(ILogger<AuthController> logger, UserStore userStore,
user.AccessTokens.Remove(token);
return new { };
}
+
+ [HttpPost("register")]
+ public async Task<object> Register(JsonObject request, [FromQuery] string kind = "user") {
+ if (kind == "guest") {
+ var user = await userStore.CreateUser(Random.Shared.NextInt64(long.MaxValue).ToString(), kind: "guest");
+ return user.Login();
+ }
+
+ if (request.Count == 0) {
+ return new {
+ session = Guid.NewGuid().ToString(),
+ flows = new {
+ stages = new[] {
+ "m.login.dummy",
+ }
+ }
+ };
+ }
+
+ if (request.ContainsKey("password")) {
+ var parts = request["username"].ToString().Split(':');
+ var localpart = parts[0].TrimStart('@');
+ var user = await userStore.CreateUser($"@{localpart}:{config.ServerName}");
+ var login = user.Login();
+
+ if (request.ContainsKey("initial_device_display_name"))
+ user.AccessTokens[login.AccessToken].DeviceName = request["initial_device_display_name"]!.ToString();
+
+ return login;
+ }
+
+ return new { };
+ }
+
+ [HttpGet("register/available")]
+ public async Task<object> IsUsernameAvailable([FromQuery] string username) {
+ return new {
+ available = await userStore.GetUserById($"@{username}:{config.ServerName}") is null
+ };
+ }
+
+ // [HttpPost("account/deactivate")]
+ // public async Task<object> DeactivateAccount() {
+ // var token = tokenService.GetAccessToken(HttpContext);
+ // var user = await userStore.GetUserByToken(token);
+ // if (user == null)
+ // throw new MatrixException() {
+ // ErrorCode = "M_UNKNOWN_TOKEN",
+ // Error = "No such user"
+ // };
+ //
+ //
+ // return new { };
+ // }
+
+ #region 3PID
+
+ [HttpGet("account/3pid")]
+ public async Task<object> Get3pid() {
+ var token = tokenService.GetAccessToken(HttpContext);
+ var user = await userStore.GetUserByToken(token);
+ if (user == null)
+ throw new MatrixException() {
+ ErrorCode = "M_UNKNOWN_TOKEN",
+ Error = "No such user"
+ };
+
+ return new {
+ threepids = (object[])[]
+ };
+ }
+
+ #endregion
}
public class LoginFlowsResponse {
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/DirectoryController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/DirectoryController.cs
index 52d5932..d497ca6 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/DirectoryController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/DirectoryController.cs
@@ -1,10 +1,9 @@
-using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
-using LibMatrix.EventTypes.Spec.State;
+using ArcaneLibs.Extensions;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.HomeserverEmulator.Services;
using LibMatrix.Homeservers;
using LibMatrix.Responses;
-using LibMatrix.Services;
using Microsoft.AspNetCore.Mvc;
namespace LibMatrix.HomeserverEmulator.Controllers;
@@ -12,6 +11,8 @@ namespace LibMatrix.HomeserverEmulator.Controllers;
[ApiController]
[Route("/_matrix/")]
public class DirectoryController(ILogger<DirectoryController> logger, RoomStore roomStore) : ControllerBase {
+#region Room directory
+
[HttpGet("client/v3/directory/room/{alias}")]
public async Task<AliasResult> GetRoomAliasV3(string alias) {
var match = roomStore._rooms.FirstOrDefault(x =>
@@ -31,4 +32,123 @@ public class DirectoryController(ILogger<DirectoryController> logger, RoomStore
Servers = servers
};
}
+
+ [HttpGet("client/v3/publicRooms")]
+ public async Task<PublicRoomDirectoryResult> GetPublicRooms(int limit = 100, string? server = null, string? since = null) {
+ var rooms = roomStore._rooms.OrderByDescending(x => x.JoinedMembers.Count).AsEnumerable();
+
+ if (since != null) {
+ rooms = rooms.SkipWhile(x => x.RoomId != since).Skip(1);
+ }
+
+ if (server != null) {
+ rooms = rooms.Where(x => x.State.Any(y => y.Type == RoomMemberEventContent.EventId && y.StateKey!.EndsWith(server)));
+ }
+
+ var count = rooms.Count();
+ rooms = rooms.Take(limit);
+
+ return new PublicRoomDirectoryResult() {
+ Chunk = rooms.Select(x => new PublicRoomDirectoryResult.PublicRoomListItem() {
+ RoomId = x.RoomId,
+ Name = x.State.FirstOrDefault(y => y.Type == RoomNameEventContent.EventId)?.RawContent?["name"]?.ToString(),
+ Topic = x.State.FirstOrDefault(y => y.Type == RoomTopicEventContent.EventId)?.RawContent?["topic"]?.ToString(),
+ AvatarUrl = x.State.FirstOrDefault(y => y.Type == RoomAvatarEventContent.EventId)?.RawContent?["url"]?.ToString(),
+ GuestCanJoin = x.State.Any(y => y.Type == RoomGuestAccessEventContent.EventId && y.RawContent?["guest_access"]?.ToString() == "can_join"),
+ NumJoinedMembers = x.JoinedMembers.Count,
+ WorldReadable = x.State.Any(y => y.Type == RoomHistoryVisibilityEventContent.EventId && y.RawContent?["history_visibility"]?.ToString() == "world_readable"),
+ JoinRule = x.State.FirstOrDefault(y => y.Type == RoomJoinRulesEventContent.EventId)?.RawContent?["join_rule"]?.ToString(),
+ CanonicalAlias = x.State.FirstOrDefault(y => y.Type == RoomCanonicalAliasEventContent.EventId)?.RawContent?["alias"]?.ToString()
+ }).ToList(),
+ NextBatch = count > limit ? rooms.Last().RoomId : null,
+ TotalRoomCountEstimate = count
+ };
+ }
+
+ [HttpPost("client/v3/publicRooms")]
+ public async Task<PublicRoomDirectoryResult> GetFilteredPublicRooms([FromBody] PublicRoomDirectoryRequest request, [FromQuery] string? server = null) {
+ var rooms = roomStore._rooms.OrderByDescending(x => x.JoinedMembers.Count).AsEnumerable();
+
+ if (request.Since != null) {
+ rooms = rooms.SkipWhile(x => x.RoomId != request.Since).Skip(1);
+ }
+
+ if (server != null) {
+ rooms = rooms.Where(x => x.State.Any(y => y.Type == RoomMemberEventContent.EventId && y.StateKey!.EndsWith(server)));
+ }
+
+ var count = rooms.Count();
+ rooms = rooms.Take(request.Limit ?? 100);
+
+ return new PublicRoomDirectoryResult() {
+ Chunk = rooms.Select(x => new PublicRoomDirectoryResult.PublicRoomListItem() {
+ RoomId = x.RoomId,
+ Name = x.State.FirstOrDefault(y => y.Type == RoomNameEventContent.EventId)?.RawContent?["name"]?.ToString(),
+ Topic = x.State.FirstOrDefault(y => y.Type == RoomTopicEventContent.EventId)?.RawContent?["topic"]?.ToString(),
+ AvatarUrl = x.State.FirstOrDefault(y => y.Type == RoomAvatarEventContent.EventId)?.RawContent?["url"]?.ToString(),
+ GuestCanJoin = x.State.Any(y => y.Type == RoomGuestAccessEventContent.EventId && y.RawContent?["guest_access"]?.ToString() == "can_join"),
+ NumJoinedMembers = x.JoinedMembers.Count,
+ WorldReadable = x.State.Any(y => y.Type == RoomHistoryVisibilityEventContent.EventId && y.RawContent?["history_visibility"]?.ToString() == "world_readable"),
+ JoinRule = x.State.FirstOrDefault(y => y.Type == RoomJoinRulesEventContent.EventId)?.RawContent?["join_rule"]?.ToString(),
+ CanonicalAlias = x.State.FirstOrDefault(y => y.Type == RoomCanonicalAliasEventContent.EventId)?.RawContent?["alias"]?.ToString()
+ }).ToList(),
+ NextBatch = count > request.Limit ? rooms.Last().RoomId : null,
+ TotalRoomCountEstimate = count
+ };
+ }
+
+#endregion
+
+#region User directory
+
+ [HttpPost("client/v3/user_directory/search")]
+ public async Task<UserDirectoryResponse> SearchUserDirectory([FromBody] UserDirectoryRequest request) {
+ var users = roomStore._rooms
+ .SelectMany(x => x.State.Where(y =>
+ y.Type == RoomMemberEventContent.EventId
+ && y.RawContent?["membership"]?.ToString() == "join"
+ && (y.StateKey!.ContainsAnyCase(request.SearchTerm) || y.RawContent?["displayname"]?.ToString()?.ContainsAnyCase(request.SearchTerm) == true)
+ )
+ )
+ .DistinctBy(x => x.StateKey)
+ .ToList();
+
+ request.Limit ??= 10;
+
+ return new() {
+ Results = users.Select(x => new UserDirectoryResponse.UserDirectoryResult {
+ UserId = x.StateKey!,
+ DisplayName = x.RawContent?["displayname"]?.ToString(),
+ AvatarUrl = x.RawContent?["avatar_url"]?.ToString()
+ }).ToList(),
+ Limited = users.Count > request.Limit
+ };
+ }
+
+#endregion
+}
+
+public class PublicRoomDirectoryRequest {
+ [JsonPropertyName("filter")]
+ public PublicRoomDirectoryFilter Filter { get; set; }
+
+ [JsonPropertyName("include_all_networks")]
+ public bool IncludeAllNetworks { get; set; }
+
+ [JsonPropertyName("limit")]
+ public int? Limit { get; set; }
+
+ [JsonPropertyName("since")]
+ public string? Since { get; set; }
+
+ [JsonPropertyName("third_party_instance_id")]
+ public string? ThirdPartyInstanceId { get; set; }
+
+ public class PublicRoomDirectoryFilter {
+ [JsonPropertyName("generic_search_term")]
+ public string? GenericSearchTerm { get; set; }
+
+ [JsonPropertyName("room_types")]
+ public List<string>? RoomTypes { get; set; }
+ }
}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/HEAdmin/HEAdminController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/HEAdmin/HEAdminController.cs
new file mode 100644
index 0000000..1fb3251
--- /dev/null
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/HEAdmin/HEAdminController.cs
@@ -0,0 +1,18 @@
+using LibMatrix.HomeserverEmulator.Services;
+using Microsoft.AspNetCore.Mvc;
+
+namespace LibMatrix.HomeserverEmulator.Controllers;
+
+[ApiController]
+[Route("/_hse/admin")]
+public class HEAdminController(ILogger<HEAdminController> logger, UserStore userStore, RoomStore roomStore) : ControllerBase {
+ [HttpGet("users")]
+ public async Task<List<UserStore.User>> GetUsers() {
+ return userStore._users.ToList();
+ }
+
+ [HttpGet("rooms")]
+ public async Task<List<RoomStore.Room>> GetRooms() {
+ return roomStore._rooms.ToList();
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/HEClient/HEClientController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/HEClient/HEClientController.cs
new file mode 100644
index 0000000..85e4ddb
--- /dev/null
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/HEClient/HEClientController.cs
@@ -0,0 +1,34 @@
+using ArcaneLibs.Collections;
+using LibMatrix.HomeserverEmulator.Services;
+using LibMatrix.Responses;
+using Microsoft.AspNetCore.Mvc;
+
+namespace LibMatrix.HomeserverEmulator.Controllers;
+
+[ApiController]
+[Route("/_hse/client/v1/external_profiles")]
+public class HEClientController(ILogger<HEClientController> logger, UserStore userStore, TokenService tokenService) : ControllerBase {
+ [HttpGet]
+ public async Task<ObservableDictionary<string, LoginResponse>> GetExternalProfiles() {
+ var token = tokenService.GetAccessToken(HttpContext);
+ var user = await userStore.GetUserByToken(token);
+
+ return user.AuthorizedSessions;
+ }
+
+ [HttpPut("{name}")]
+ public async Task PutExternalProfile(string name, [FromBody] LoginResponse sessionData) {
+ var token = tokenService.GetAccessToken(HttpContext);
+ var user = await userStore.GetUserByToken(token);
+
+ user.AuthorizedSessions[name] = sessionData;
+ }
+
+ [HttpDelete("{name}")]
+ public async Task DeleteExternalProfile(string name) {
+ var token = tokenService.GetAccessToken(HttpContext);
+ var user = await userStore.GetUserByToken(token);
+
+ user.AuthorizedSessions.Remove(name);
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/HEDebug/HEDebugController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/HEDebug/HEDebugController.cs
index 9e0c17c..ce47245 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/HEDebug/HEDebugController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/HEDebug/HEDebugController.cs
@@ -1,18 +1,18 @@
-using LibMatrix.HomeserverEmulator.Services;
-using Microsoft.AspNetCore.Mvc;
-
-namespace LibMatrix.HomeserverEmulator.Controllers;
-
-[ApiController]
-[Route("/_hsEmulator")]
-public class HEDebugController(ILogger<HEDebugController> logger, UserStore userStore, RoomStore roomStore) : ControllerBase {
- [HttpGet("users")]
- public async Task<List<UserStore.User>> GetUsers() {
- return userStore._users.ToList();
- }
-
- [HttpGet("rooms")]
- public async Task<List<RoomStore.Room>> GetRooms() {
- return roomStore._rooms.ToList();
- }
+using LibMatrix.HomeserverEmulator.Services;
+using Microsoft.AspNetCore.Mvc;
+
+namespace LibMatrix.HomeserverEmulator.Controllers;
+
+[ApiController]
+[Route("/_hsEmulator")]
+public class HEDebugController(ILogger<HEDebugController> logger, UserStore userStore, RoomStore roomStore) : ControllerBase {
+ [HttpGet("users")]
+ public async Task<List<UserStore.User>> GetUsers() {
+ return userStore._users.ToList();
+ }
+
+ [HttpGet("rooms")]
+ public async Task<List<RoomStore.Room>> GetRooms() {
+ return roomStore._rooms.ToList();
+ }
}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/KeysController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/KeysController.cs
index 7898a8c..18cccf6 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/KeysController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/KeysController.cs
@@ -11,6 +11,25 @@
// [ApiController]
// [Route("/_matrix/client/{version}/")]
// public class KeysController(ILogger<KeysController> logger, TokenService tokenService, UserStore userStore) : ControllerBase {
+// [HttpPost("keys/upload")]
+// public async Task<object> UploadKeys(DeviceKeysUploadRequest request) {
+// var token = tokenService.GetAccessToken(HttpContext);
+// if (token == null)
+// throw new MatrixException() {
+// ErrorCode = "M_MISSING_TOKEN",
+// Error = "Missing token"
+// };
+//
+// var user = await userStore.GetUserByToken(token);
+// if (user == null)
+// throw new MatrixException() {
+// ErrorCode = "M_UNKNOWN_TOKEN",
+// Error = "No such user"
+// };
+//
+// return new { };
+// }
+//
// [HttpGet("room_keys/version")]
// public async Task<RoomKeysResponse> GetRoomKeys() {
// var token = tokenService.GetAccessToken(HttpContext);
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/LegacyController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/LegacyController.cs
index 1fb427e..245770e 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/LegacyController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/LegacyController.cs
@@ -1,12 +1,8 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Security.Cryptography;
-using System.Text.Json.Nodes;
using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.HomeserverEmulator.Services;
-using LibMatrix.Responses;
-using LibMatrix.Services;
using Microsoft.AspNetCore.Mvc;
namespace LibMatrix.HomeserverEmulator.Controllers;
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Media/MediaController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Media/MediaController.cs
index 7899ada..6048bbb 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Media/MediaController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Media/MediaController.cs
@@ -1,9 +1,9 @@
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
-using ArcaneLibs.Collections;
using LibMatrix.HomeserverEmulator.Services;
using LibMatrix.Services;
using Microsoft.AspNetCore.Mvc;
+#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
namespace LibMatrix.HomeserverEmulator.Controllers.Media;
@@ -13,12 +13,12 @@ public class MediaController(
ILogger<MediaController> logger,
TokenService tokenService,
UserStore userStore,
- HSEConfiguration cfg,
+ HseConfiguration cfg,
HomeserverResolverService hsResolver,
MediaStore mediaStore)
: ControllerBase {
[HttpPost("upload")]
- public async Task<object> UploadMedia([FromHeader(Name = "Content-Type")] string ContentType, [FromQuery] string filename, [FromBody] Stream file) {
+ public async Task<object> UploadMedia([FromHeader(Name = "Content-Type")] string contentType, [FromQuery] string filename, [FromBody] Stream file) {
var token = tokenService.GetAccessTokenOrNull(HttpContext);
if (token == null)
throw new MatrixException() {
@@ -42,6 +42,9 @@ public class MediaController(
[HttpGet("download/{serverName}/{mediaId}")]
public async Task DownloadMedia(string serverName, string mediaId) {
+ Response.Headers["Access-Control-Allow-Origin"] = "*";
+ Response.Headers["Access-Control-Allow-Methods"] = "GET";
+
var stream = await DownloadRemoteMedia(serverName, mediaId);
await stream.CopyToAsync(Response.Body);
}
@@ -56,6 +59,7 @@ public class MediaController(
JsonObject data = new();
using var hc = new HttpClient();
+ logger.LogInformation("Getting URL preview for {}", url);
using var response = await hc.GetAsync(url);
var doc = await response.Content.ReadAsStringAsync();
var match = Regex.Match(doc, "<meta property=\"(.*?)\" content=\"(.*?)\"");
@@ -72,7 +76,9 @@ public class MediaController(
if (cfg.StoreData) {
var path = Path.Combine(cfg.DataStoragePath, "media", serverName, mediaId);
if (!System.IO.File.Exists(path)) {
- var mediaUrl = await hsResolver.ResolveMediaUri(serverName, $"mxc://{serverName}/{mediaId}");
+ // var mediaUrl = await hsResolver.ResolveMediaUri(serverName, $"mxc://{serverName}/{mediaId}");
+ var homeserver = (await hsResolver.ResolveHomeserverFromWellKnown(serverName)).Client;
+ var mediaUrl = homeserver is null ? null : $"{homeserver}/_matrix/media/v3/download/";
if (mediaUrl is null)
throw new MatrixException() {
ErrorCode = "M_NOT_FOUND",
@@ -80,13 +86,16 @@ public class MediaController(
};
using var client = new HttpClient();
var stream = await client.GetStreamAsync(mediaUrl);
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
await using var fs = System.IO.File.Create(path);
await stream.CopyToAsync(fs);
}
return new FileStream(path, FileMode.Open);
}
else {
- var mediaUrl = await hsResolver.ResolveMediaUri(serverName, $"mxc://{serverName}/{mediaId}");
+ // var mediaUrl = await hsResolver.ResolveMediaUri(serverName, $"mxc://{serverName}/{mediaId}");
+ var homeserver = (await hsResolver.ResolveHomeserverFromWellKnown(serverName)).Client;
+ var mediaUrl = homeserver is null ? null : $"{homeserver}/_matrix/media/v3/download/";
if (mediaUrl is null)
throw new MatrixException() {
ErrorCode = "M_NOT_FOUND",
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomMembersController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomMembersController.cs
index 7d735f7..6c57cc4 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomMembersController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomMembersController.cs
@@ -1,4 +1,4 @@
-using LibMatrix.EventTypes.Spec.State;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.HomeserverEmulator.Services;
using Microsoft.AspNetCore.Mvc;
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomStateController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomStateController.cs
index 74c70a3..485c028 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomStateController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomStateController.cs
@@ -2,6 +2,7 @@ using System.Collections.Frozen;
using System.Text.Json.Nodes;
using LibMatrix.HomeserverEmulator.Extensions;
using LibMatrix.HomeserverEmulator.Services;
+using LibMatrix.Responses;
using Microsoft.AspNetCore.Mvc;
namespace LibMatrix.HomeserverEmulator.Controllers.Rooms;
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomTimelineController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomTimelineController.cs
index afd69d1..61195b8 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomTimelineController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomTimelineController.cs
@@ -1,9 +1,10 @@
-using System.Collections.Immutable;
using System.Diagnostics;
using System.Text.Json.Nodes;
using ArcaneLibs;
+using ArcaneLibs.Extensions;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.EventTypes.Spec.State;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
+using LibMatrix.EventTypes.Spec.State.Space;
using LibMatrix.Helpers;
using LibMatrix.HomeserverEmulator.Extensions;
using LibMatrix.HomeserverEmulator.Services;
@@ -20,6 +21,7 @@ public class RoomTimelineController(
TokenService tokenService,
UserStore userStore,
RoomStore roomStore,
+ HseConfiguration hseConfig,
HomeserverProviderService hsProvider) : ControllerBase {
[HttpPut("send/{eventType}/{txnId}")]
public async Task<EventIdResponse> SendMessage(string roomId, string eventType, string txnId, [FromBody] JsonObject content) {
@@ -33,21 +35,21 @@ public class RoomTimelineController(
Error = "Room not found"
};
+ var evt = new StateEvent() {
+ RawContent = content,
+ Type = eventType
+ }.ToStateEvent(user, room);
+
+ if (evt.Type == RoomMessageEventContent.EventId && (evt.TypedContent as RoomMessageEventContent).Body.StartsWith("!hse"))
+ _ = Task.Run(() => HandleHseCommand(evt, room, user));
+
if (!room.JoinedMembers.Any(x => x.StateKey == user.UserId))
throw new MatrixException() {
ErrorCode = "M_FORBIDDEN",
Error = "User is not in the room"
};
- var evt = new StateEvent() {
- RawContent = content,
- Type = eventType
- }.ToStateEvent(user, room);
-
room.Timeline.Add(evt);
- if (evt.Type == RoomMessageEventContent.EventId && (evt.TypedContent as RoomMessageEventContent).Body.StartsWith("!hse"))
- await HandleHseCommand(evt, room, user);
- // else
return new() {
EventId = evt.EventId
@@ -124,9 +126,10 @@ public class RoomTimelineController(
return evt;
}
-
+
[HttpGet("relations/{eventId}")]
- public async Task<RecursedBatchedChunkedStateEventResponse> GetRelations(string roomId, string eventId, [FromQuery] string? dir = "b", [FromQuery] string? from = null, [FromQuery] int? limit = 100, [FromQuery] bool? recurse = false, [FromQuery] string? to = null) {
+ public async Task<RecursedBatchedChunkedStateEventResponse> GetRelations(string roomId, string eventId, [FromQuery] string? dir = "b", [FromQuery] string? from = null,
+ [FromQuery] int? limit = 100, [FromQuery] bool? recurse = false, [FromQuery] string? to = null) {
var token = tokenService.GetAccessToken(HttpContext);
var user = await userStore.GetUserByToken(token);
@@ -156,9 +159,10 @@ public class RoomTimelineController(
Chunk = matchingEvents.ToList()
};
}
-
+
[HttpGet("relations/{eventId}/{relationType}")]
- public async Task<RecursedBatchedChunkedStateEventResponse> GetRelations(string roomId, string eventId, string relationType, [FromQuery] string? dir = "b", [FromQuery] string? from = null, [FromQuery] int? limit = 100, [FromQuery] bool? recurse = false, [FromQuery] string? to = null) {
+ public async Task<RecursedBatchedChunkedStateEventResponse> GetRelations(string roomId, string eventId, string relationType, [FromQuery] string? dir = "b",
+ [FromQuery] string? from = null, [FromQuery] int? limit = 100, [FromQuery] bool? recurse = false, [FromQuery] string? to = null) {
var token = tokenService.GetAccessToken(HttpContext);
var user = await userStore.GetUserByToken(token);
@@ -188,9 +192,10 @@ public class RoomTimelineController(
Chunk = matchingEvents.ToList()
};
}
-
+
[HttpGet("relations/{eventId}/{relationType}/{eventType}")]
- public async Task<RecursedBatchedChunkedStateEventResponse> GetRelations(string roomId, string eventId, string relationType, string eventType, [FromQuery] string? dir = "b", [FromQuery] string? from = null, [FromQuery] int? limit = 100, [FromQuery] bool? recurse = false, [FromQuery] string? to = null) {
+ public async Task<RecursedBatchedChunkedStateEventResponse> GetRelations(string roomId, string eventId, string relationType, string eventType, [FromQuery] string? dir = "b",
+ [FromQuery] string? from = null, [FromQuery] int? limit = 100, [FromQuery] bool? recurse = false, [FromQuery] string? to = null) {
var token = tokenService.GetAccessToken(HttpContext);
var user = await userStore.GetUserByToken(token);
@@ -220,7 +225,7 @@ public class RoomTimelineController(
Chunk = matchingEvents.ToList()
};
}
-
+
private async Task<IEnumerable<StateEventResponse>> GetRelationsInternal(string roomId, string eventId, string dir, string? from, int? limit, bool? recurse, string? to) {
var room = roomStore.GetRoomById(roomId);
var evt = room.Timeline.SingleOrDefault(x => x.EventId == eventId);
@@ -237,7 +242,7 @@ public class RoomTimelineController(
else if (dir == "f") {
relatedEvents = relatedEvents.Take(limit ?? 100);
}
-
+
return relatedEvents;
}
@@ -252,7 +257,8 @@ public class RoomTimelineController(
room.Timeline.Add(new StateEventResponse() {
Type = RoomMessageEventContent.EventId,
TypedContent = content,
- Sender = $"@hse:{tokenService.GenerateServerName(HttpContext)}",
+ // Sender = $"@hse:{tokenService.GenerateServerName(HttpContext)}",
+ Sender = $"@hse:{hseConfig.ServerName}",
RoomId = room.RoomId,
EventId = "$" + string.Join("", Random.Shared.GetItems("abcdefghijklmnopqrstuvwxyzABCDEFGHIJLKMNOPQRSTUVWXYZ0123456789".ToCharArray(), 100)),
OriginServerTs = DateTimeOffset.Now.ToUnixTimeMilliseconds()
@@ -260,12 +266,14 @@ public class RoomTimelineController(
}
private async Task HandleHseCommand(StateEventResponse evt, RoomStore.Room room, UserStore.User user) {
+ logger.LogWarning("Handling HSE command for {0}: {1}", user.UserId, evt.RawContent.ToJson(false, true));
try {
var msgContent = evt.TypedContent as RoomMessageEventContent;
var parts = msgContent.Body.Split('\n')[0].Split(" ");
if (parts.Length < 2) return;
var command = parts[1];
+ Console.WriteLine($"Handling command {command}");
switch (command) {
case "import":
await HandleImportCommand(parts[2..], evt, room, user);
@@ -293,7 +301,7 @@ public class RoomTimelineController(
InternalSendMessage(room, url + "&i=" + i);
if (i % 5000 == 0 || i == 9999) {
- Thread.Sleep(5000);
+ // Thread.Sleep(1000);
do {
InternalSendMessage(room,
@@ -306,6 +314,7 @@ public class RoomTimelineController(
} while (Process.GetCurrentProcess().WorkingSet64 >= 1_024_000_000);
}
}
+
break;
}
case "genrooms": {
@@ -313,7 +322,7 @@ public class RoomTimelineController(
var count = 1000;
for (int i = 0; i < count; i++) {
var crq = new CreateRoomRequest() {
- Name = "Test room",
+ Name = $"Test room {i}",
CreationContent = new() {
["version"] = "11"
},
@@ -334,9 +343,11 @@ public class RoomTimelineController(
}.ToStateEvent(user, room));
}
}
+
var newRoom = roomStore.CreateRoom(crq);
newRoom.AddUser(user.UserId);
}
+
InternalSendMessage(room, $"Generated {count} new rooms in {sw.Elapsed}!");
break;
}
@@ -348,6 +359,21 @@ public class RoomTimelineController(
InternalSendMessage(room,
$"GC memory: {Util.BytesToString(GC.GetTotalMemory(false))}, total process memory: {Util.BytesToString(Process.GetCurrentProcess().WorkingSet64)}");
break;
+ case "leave-all-rooms": {
+ var rooms = roomStore.GetRoomsByMember(user.UserId);
+ foreach (var memberEvt in rooms) {
+ var roomObj = roomStore.GetRoomById(memberEvt.RoomId);
+ roomObj.SetStateInternal(new() {
+ Type = RoomMemberEventContent.EventId,
+ StateKey = user.UserId,
+ TypedContent = new RoomMemberEventContent() {
+ Membership = "leave"
+ },
+ }, senderId: user.UserId);
+ }
+
+ break;
+ }
default:
InternalSendMessage(room, $"Command {command} not found!");
break;
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomsController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomsController.cs
index c24e6e9..9dae2e5 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomsController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomsController.cs
@@ -1,5 +1,4 @@
using System.Text.Json.Serialization;
-using LibMatrix.EventTypes.Spec.State;
using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.HomeserverEmulator.Services;
using LibMatrix.Responses;
@@ -62,7 +61,7 @@ public class RoomsController(ILogger<RoomsController> logger, TokenService token
var room = new RoomStore.Room($"!{Guid.NewGuid()}:{tokenService.GenerateServerName(HttpContext)}");
var eventTypesToTransfer = new[] {
- RoomServerACLEventContent.EventId,
+ RoomServerAclEventContent.EventId,
RoomEncryptionEventContent.EventId,
RoomNameEventContent.EventId,
RoomAvatarEventContent.EventId,
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/SyncController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/SyncController.cs
index 024d071..86c9f6a 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/SyncController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/SyncController.cs
@@ -1,7 +1,7 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.HomeserverEmulator.Extensions;
using LibMatrix.HomeserverEmulator.Services;
using LibMatrix.Responses;
@@ -11,7 +11,7 @@ namespace LibMatrix.HomeserverEmulator.Controllers;
[ApiController]
[Route("/_matrix/client/{version}/")]
-public class SyncController(ILogger<SyncController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore, HSEConfiguration cfg) : ControllerBase {
+public class SyncController(ILogger<SyncController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore, HseConfiguration cfg) : ControllerBase {
[HttpGet("sync")]
[SuppressMessage("ReSharper.DPA", "DPA0011: High execution time of MVC action", Justification = "Endpoint is expected to wait until data is available or timeout.")]
public async Task<SyncResponse> Sync([FromQuery] string? since = null, [FromQuery] int? timeout = 5000) {
@@ -28,17 +28,24 @@ public class SyncController(ILogger<SyncController> logger, TokenService tokenSe
UserStore.User.SessionInfo.UserSyncState newSyncState = new();
SyncResponse syncResp;
- if (string.IsNullOrWhiteSpace(since) || !session.SyncStates.ContainsKey(since))
+ if (string.IsNullOrWhiteSpace(since) || !session.SyncStates.TryGetValue(since, out var syncState))
syncResp = InitialSync(user, session);
else {
- var syncState = session.SyncStates[since];
newSyncState = syncState.Clone();
var newSyncToken = Guid.NewGuid().ToString();
+ long stallTime = 100;
do {
syncResp = IncrementalSync(user, session, syncState);
syncResp.NextBatch = newSyncToken;
- } while (!await HasDataOrStall(syncResp) && sw.ElapsedMilliseconds < timeout);
+
+ var hasData = await HasDataOrStall(syncResp);
+ if (!hasData) {
+ await Task.Delay((int)Math.Min(stallTime, Math.Max(0, (timeout ?? 10) - sw.ElapsedMilliseconds)));
+ stallTime *= 2;
+ }
+ else break;
+ } while (sw.ElapsedMilliseconds < timeout);
if (sw.ElapsedMilliseconds > timeout) {
logger.LogTrace("Sync timed out after {Elapsed}", sw.Elapsed);
@@ -50,6 +57,7 @@ public class SyncController(ILogger<SyncController> logger, TokenService tokenSe
session.SyncStates[syncResp.NextBatch] = RecalculateSyncStates(newSyncState, syncResp);
logger.LogTrace("Responding to sync after {totalElapsed}", sw.Elapsed);
+ // logger.LogTrace(syncResp.ToJson(ignoreNull: true));
return syncResp;
}
@@ -136,6 +144,7 @@ public class SyncController(ILogger<SyncController> logger, TokenService tokenSe
};
// step 1: check previously synced rooms
+ int updatedRooms = 0;
foreach (var (roomId, roomPosition) in syncState.RoomPositions) {
var room = roomStore.GetRoomById(roomId);
if (room == null) {
@@ -148,21 +157,26 @@ public class SyncController(ILogger<SyncController> logger, TokenService tokenSe
var newTimelineEvents = room.Timeline.Skip(roomPosition.TimelinePosition).ToList();
var newAccountDataEvents = room.AccountData[user.UserId].Skip(roomPosition.AccountDataPosition).ToList();
if (newTimelineEvents.Count == 0 && newAccountDataEvents.Count == 0) continue;
+ if (updatedRooms++ >= 50) break; // performance cap
data.Join[room.RoomId] = new() {
State = new(newTimelineEvents.GetCalculatedState()),
- Timeline = new(newTimelineEvents, false)
+ Timeline = new(newTimelineEvents, false),
+ AccountData = new(newAccountDataEvents)
};
}
}
- if (data.Join.Count > 0) return data;
+ if (data.Join.Count > 0) {
+ logger.LogTrace("Found {count} updated rooms", data.Join.Count);
+ return data;
+ }
// step 2: check newly joined rooms
- var untrackedRooms = roomStore._rooms.Where(r => !syncState.RoomPositions.ContainsKey(r.RoomId)).ToList();
+ // var untrackedRooms = roomStore._rooms.Where(r => !syncState.RoomPositions.ContainsKey(r.RoomId)).ToList();
var allJoinedRooms = roomStore.GetRoomsByMember(user.UserId).ToArray();
if (allJoinedRooms.Length == 0) return data;
- var rooms = Random.Shared.GetItems(allJoinedRooms, Math.Min(allJoinedRooms.Length, 50));
+ var rooms = Random.Shared.GetItems(allJoinedRooms, Math.Min(allJoinedRooms.Length, 1));
foreach (var membership in rooms) {
var membershipContent = membership.TypedContent as RoomMemberEventContent ??
throw new InvalidOperationException("Membership event content is not RoomMemberEventContent");
@@ -206,6 +220,10 @@ public class SyncController(ILogger<SyncController> logger, TokenService tokenSe
#endregion
+ private bool HasData(SyncResponse resp) {
+ return resp.Rooms?.Invite?.Count > 0 || resp.Rooms?.Join?.Count > 0 || resp.Rooms?.Leave?.Count > 0;
+ }
+
private async Task<bool> HasDataOrStall(SyncResponse resp) {
// logger.LogTrace("Checking if sync response has data: {resp}", resp.ToJson(indent: false, ignoreNull: true));
// if (resp.AccountData?.Events?.Count > 0) return true;
@@ -240,21 +258,23 @@ public class SyncController(ILogger<SyncController> logger, TokenService tokenSe
// };
var hasData = resp is {
- AccountData: {
- Events: { Count: > 0 }
- }
+ AccountData.Events.Count: > 0
} or {
- Presence: {
- Events: { Count: > 0 }
- }
+ Presence.Events.Count: > 0
} or {
DeviceLists: {
- Changed: { Count: > 0 },
- Left: { Count: > 0 }
+ Changed.Count: > 0,
+ Left.Count: > 0
}
} or {
- ToDevice: {
- Events: { Count: > 0 }
+ ToDevice.Events.Count: > 0
+ } or {
+ Rooms: {
+ Invite.Count: > 0
+ } or {
+ Join.Count: > 0
+ } or {
+ Leave.Count: > 0
}
};
@@ -264,7 +284,7 @@ public class SyncController(ILogger<SyncController> logger, TokenService tokenSe
if (!hasData) {
// logger.LogDebug($"Sync response has no data, stalling for 1000ms: {resp.ToJson(indent: false, ignoreNull: true)}");
- await Task.Delay(10);
+ // await Task.Delay(100);
}
return hasData;
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/AccountDataController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/AccountDataController.cs
index a32d283..41cf62a 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/AccountDataController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/AccountDataController.cs
@@ -1,9 +1,5 @@
using System.Text.Json.Nodes;
-using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
-using LibMatrix.Filters;
using LibMatrix.HomeserverEmulator.Services;
-using LibMatrix.Responses;
using Microsoft.AspNetCore.Mvc;
namespace LibMatrix.HomeserverEmulator.Controllers;
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/FilterController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/FilterController.cs
index bdee7bc..f163a8e 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/FilterController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/FilterController.cs
@@ -1,9 +1,5 @@
-using System.Text.Json.Nodes;
-using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
using LibMatrix.Filters;
using LibMatrix.HomeserverEmulator.Services;
-using LibMatrix.Responses;
using Microsoft.AspNetCore.Mvc;
namespace LibMatrix.HomeserverEmulator.Controllers;
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/ProfileController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/ProfileController.cs
index 98c41da..7afdcb5 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/ProfileController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/ProfileController.cs
@@ -1,9 +1,5 @@
using System.Text.Json.Nodes;
-using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
-using LibMatrix.Filters;
using LibMatrix.HomeserverEmulator.Services;
-using LibMatrix.Responses;
using Microsoft.AspNetCore.Mvc;
namespace LibMatrix.HomeserverEmulator.Controllers;
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/UserController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/UserController.cs
index 2be3896..339e686 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/UserController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/UserController.cs
@@ -1,8 +1,5 @@
-using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
-using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
-using LibMatrix.Filters;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.HomeserverEmulator.Services;
using LibMatrix.Responses;
using Microsoft.AspNetCore.Mvc;
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/VersionsController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/VersionsController.cs
index 0c3bde6..93e4b4f 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/VersionsController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/VersionsController.cs
@@ -1,8 +1,6 @@
-using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using LibMatrix.Homeservers;
using LibMatrix.Responses;
-using LibMatrix.Services;
using Microsoft.AspNetCore.Mvc;
namespace LibMatrix.HomeserverEmulator.Controllers;
@@ -30,6 +28,11 @@ public class VersionsController(ILogger<WellKnownController> logger) : Controlle
"v1.6",
"v1.7",
"v1.8",
+ "v1.9",
+ "v1.10",
+ "v1.11",
+ "v1.12",
+ "v1.13"
},
UnstableFeatures = new()
};
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Controllers/WellKnownController.cs b/Utilities/LibMatrix.HomeserverEmulator/Controllers/WellKnownController.cs
index 97e460d..3cec712 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Controllers/WellKnownController.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Controllers/WellKnownController.cs
@@ -1,32 +1,34 @@
-using System.Text.Json.Nodes;
-using LibMatrix.Services;
-using Microsoft.AspNetCore.Mvc;
-
-namespace LibMatrix.HomeserverEmulator.Controllers;
-
-[ApiController]
-[Route("/.well-known/matrix/")]
-public class WellKnownController(ILogger<WellKnownController> logger) : ControllerBase {
- [HttpGet("client")]
- public JsonObject GetClientWellKnown() {
- var obj = new JsonObject() {
- ["m.homeserver"] = new JsonObject() {
- ["base_url"] = $"{Request.Scheme}://{Request.Host}"
- }
- };
-
- logger.LogInformation("Serving client well-known: {}", obj);
-
- return obj;
- }
- [HttpGet("server")]
- public JsonObject GetServerWellKnown() {
- var obj = new JsonObject() {
- ["m.server"] = $"{Request.Scheme}://{Request.Host}"
- };
-
- logger.LogInformation("Serving server well-known: {}", obj);
-
- return obj;
- }
+using System.Text.Json.Nodes;
+using Microsoft.AspNetCore.Mvc;
+
+namespace LibMatrix.HomeserverEmulator.Controllers;
+
+[ApiController]
+[Route("/.well-known/matrix/")]
+public class WellKnownController(ILogger<WellKnownController> logger) : ControllerBase {
+ [HttpGet("client")]
+ public JsonObject GetClientWellKnown() {
+ var obj = new JsonObject() {
+ ["m.homeserver"] = new JsonObject() {
+ // ["base_url"] = $"{Request.Scheme}://{Request.Host}"
+ ["base_url"] = $"https://{Request.Host}"
+ }
+ };
+
+ logger.LogInformation("Serving client well-known: {}", obj);
+
+ return obj;
+ }
+
+ [HttpGet("server")]
+ public JsonObject GetServerWellKnown() {
+ var obj = new JsonObject() {
+ // ["m.server"] = $"{Request.Scheme}://{Request.Host}"
+ ["m.server"] = $"https://{Request.Host}"
+ };
+
+ logger.LogInformation("Serving server well-known: {}", obj);
+
+ return obj;
+ }
}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.csproj b/Utilities/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.csproj
index a6b6214..5178012 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.csproj
+++ b/Utilities/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.csproj
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
- <TargetFramework>net8.0</TargetFramework>
+ <TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
@@ -11,8 +11,8 @@
<ItemGroup>
<PackageReference Include="EasyCompressor.LZMA" Version="2.0.2" />
- <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.6" />
- <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
+ <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.1" />
+ <PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
</ItemGroup>
<ItemGroup>
@@ -20,4 +20,1015 @@
<!-- <ProjectReference Include="..\..\Utilities\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj"/>-->
</ItemGroup>
+ <ItemGroup>
+ <Folder Include="data\users\" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <_ContentIncludedByDefault Remove="data\rooms\!009948f3-9034-4a24-a748-a6391dd886bd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!00e1caa3-d6bf-4a0a-9793-0cebe26d4a96.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!011ed14b-f495-4c52-9f0f-b0fd0bd72f26.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0151df7a-3b06-4048-8b1c-11ea88987ceb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!017179e2-c121-49c2-ad06-197f4cf39155.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!01830986-341e-4622-a51e-6368a6064c2b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!018a12f5-8ed7-4dbc-9285-2165ae1ca39a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!01951dc5-d87a-4b27-b444-809f4907755b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!01d8efb7-52b3-461d-a95e-f16ca6ca5888.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!01f2c6dd-1bab-40e6-ac62-fcb5abf15e73.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!025c937f-13fd-445f-af46-69bda3d08d02.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!02d2dd0c-e57b-4454-a197-046d81f8d7bb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!02f00a13-d09a-4b42-888f-f6651d7882b8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!031b3eb4-d25d-47ef-b3ce-e06f6f4f154a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!032dd423-f2d3-4f3f-9b8d-10febd9de20b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!03ba6761-0bb4-4bfa-b895-6e4428795410.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!03ce824c-450b-4d13-a8a5-43a6ba4f1da6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!03cfb867-3155-4ef4-8e2a-0939e6837ec2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!03e4b54c-c41e-46e0-b47d-a6486fe524bc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!044df1bc-13a1-4496-9ba3-bcf60d45fbb4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0482a9e8-a7a1-4e66-a98d-1735758f8013.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!04ae0100-c074-4a0b-bb29-5c88b3199fb4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0511d862-353b-4cb9-9392-04eb3d6b756a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!054b1613-1757-438b-bfe9-73b501390617.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!05877fed-59a3-430b-9b04-10d70ca9aef1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!05d2ac50-d014-4e72-93b1-d8e18ee4cf8c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!05e4883f-4784-4a25-9748-d9d8ce4d314e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!06475f48-8175-45e9-8cf0-15741f27ad8f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!06b3a783-949c-42d3-a4d4-813273e3bab0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!07b2ed26-caba-440e-8cb7-172e311c1d78.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!07e9491b-f799-4552-90e7-242413ea69cf.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!08602758-2108-45e5-8f08-baf57f8e90df.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!086b0484-a1ed-4c04-93f7-2f73009570fa.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!08fc4a55-9107-442b-961e-5353203623e0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!091cf52d-7932-4510-974b-c41ef0d05787.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!093a2862-3c0f-487a-bf43-6ae4d7ab9278.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!09925e93-ec19-49bd-ba19-e7b0fd0bd029.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!09f14b3a-21d0-41ed-bb86-1a602b07370e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0a34a93d-db6a-47cf-a5cc-8f9354435ea2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0a71f415-ec9a-40df-b300-c3fb79d4dd13.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0ab184df-be0f-4877-80f8-0aa34d5ad00b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0ad9691a-d4e9-4f4a-8f48-86a8adad7f43.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0afbbfb2-caf0-4829-a7f0-06472c16cb4b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0b6f3cb8-37ed-4a7a-b95c-5d299ac73755.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0ba81dce-f4d6-40fb-84fd-0df52347eb99.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0bd9becb-401f-465a-8b55-f2f20b4cdb78.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0c1f5b9c-4b80-4c83-989d-3dbcffa6f74a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0d7ece98-e347-4082-a9a4-d5e4cd594bf0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0d877be3-7545-49ca-9941-191e3299b7fe.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0dd1c03a-0455-4ffd-9ecb-5777039d4165.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0e3ca29e-0270-4ab9-8b07-c76f4662dcd0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0ea8696f-f527-4e11-916a-69dd9e086d9e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0f08c6a1-47aa-436f-9a44-3fdbd5aff348.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0f6a7cc3-2f2e-49fd-a953-401c9a16c38d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0f9fcf53-412d-452c-bcea-43d6dbb3d705.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0fb1c6b5-8bb9-47e8-8d9b-a126cb5eff7d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0fb79121-1e83-4fe9-8bf9-f8a5ed364efa.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!0fc9886d-ecbf-4525-8f5c-a43fc4dc1b58.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1000acc2-a562-41f0-9f40-6eaf73b99f66.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!100204b5-f690-42b9-a49b-3fc3df91bdb2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!101265f1-eacb-4185-9470-269bf51b1829.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!108535e1-632b-489a-a9e8-e2fcf60d8c83.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!109f5a13-3a9f-4ced-a4a4-b0191a84b7d5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!10c5ff39-6ac2-42a8-8fae-292f01a5cb32.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!111e8be3-72e1-4200-83aa-241c6e98764d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!11381a2e-0b1e-4a56-b53f-0dd2cf65a187.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!114243be-a9f3-4909-bb03-8171eacdf1ee.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!116a3988-1763-45ec-b24c-ebb9e57faf4e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!11a149c7-ee5c-4ada-9145-052976d3ab18.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1214a2eb-57ea-4662-8b32-742678cf130f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!13207273-2393-45a6-8cc9-7c4fbbbc9736.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!133f8b66-d9d5-44e4-95e9-dde76cceee0d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!13ed7c78-7160-4ebd-a84f-7124479d0b3b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!14586508-6e3a-4bc3-a8ac-dbcb177310de.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1459a8ab-3aa5-4619-bb94-7d636f9a4576.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!14cb8826-1b94-4106-b530-0f9609d93679.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1524fc2d-6985-44d4-9d77-08f02e2df93a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1528dc79-229f-4a0a-9433-ca0d8fe81fdc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!15d52bea-102a-4352-92a5-f2817e879083.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!15f05e3c-4694-403a-a95e-10def22cb013.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!161bbd52-f6e8-4ade-a139-27209aab5ca7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!164a1783-6218-4335-aa82-b9db00aa4cf9.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1680277b-9540-43b3-813c-83bce9c2581d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!169d4aca-5385-4df3-afc4-5cc3f94708d3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!16a88afc-09dd-45f8-8202-98bb7a88cef2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!16c80534-e338-45d3-beaf-0e4e93695abb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!16d4b0c1-9bd3-408c-bfb9-48bb8ef7b679.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1709e1bd-5539-40fd-9124-0bfb5c62341f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!17308b64-da60-4966-bf85-409df16d5ec4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1749eb5f-f7ea-4eb0-8a77-7243123bbbf8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1761367d-a128-4ad9-9c7a-acb5a4e5a1b6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!176f30db-9b87-4a06-b3f3-895bd8f41448.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!178abf28-9ac4-432e-bac8-9c75f800fbfa.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!17e1e888-b9e2-4aca-85a2-48e5d1d0b35c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!186cbe4b-c6b2-4e2d-ad85-931c8d078185.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!189c6c4a-fa84-4fb4-bdfc-ab25e959e243.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!18c0440c-5c3e-4c80-8397-95658769c20c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1909d1c2-18e6-4f41-b6d4-01a0350ecb4c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!191141f8-0556-43e3-b982-142854e40385.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1940357b-f2b8-45b9-a830-d35e7f4f46f1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!19ad183e-18f5-41a2-837f-5c440047a0c7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!19b0fc7b-0359-4aa3-9597-29a97145e7cd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!19cb0696-af13-4036-b000-7aa03bef9541.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!19e9f51d-278c-412f-9ecf-cb96a83282c7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1a0767ef-4897-4a87-8d95-9c1446b07780.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1a1e71ce-5f6a-4a9f-a3cf-8f95189eae24.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1a995531-85bc-4f90-b36e-29a1e8620e7e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1b2eb324-6682-4ea3-8377-2e17da2fd996.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1b3c2d02-b76a-449d-a458-15baf8254298.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1b60b136-19a4-4551-b682-b02a6cea94d4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1bc97814-3491-455b-8fc2-ca2916f77813.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1bdf6ed0-cac5-48d2-84ed-83b7f5ef3a42.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1c0450bd-8cb2-487f-9160-3ca95543410f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1c18b32b-c3b2-48ee-8562-bdbc1697adab.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1c273675-9267-46e1-901e-50460328d95a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1ce174af-bd5e-4ae5-ac1e-b71eb4b44594.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1cff0104-9ffa-460c-ae4a-4a4c17e2784f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1d3e4977-6df2-4f69-b8b8-e13ccffdec71.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1d4821a3-f202-46f4-aabf-7fa88387283c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1d6dc82d-978f-4f7f-8514-12f099d4e699.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1e3463cd-408a-4f85-b79f-5f1f9a2f4160.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1e96e1e2-e2d9-4547-90c2-c9311fdc1ffc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1ed2a1ee-ed46-4444-967a-3ad686fee01f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1ee34f83-373b-4508-94a9-3ab61873ecd6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1f1e1492-eef4-4dc3-a5bc-ff2aac6fd10c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1fd36873-80cc-4d2d-95e3-11e3df524dac.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1ff577ed-8eed-41be-a839-2e9985d4ee5b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!1ffe979c-e5c4-4db4-b0d1-c0e615cb76cc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!202568b3-39a9-41a2-a040-bc8845e50449.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!20da7437-06fd-43b3-b5ed-e2f87198daad.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!20f5dbc1-e343-428a-8a76-781193037198.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!210b0c40-0cb3-49bd-8ef5-028cf01499de.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!216fa2ed-abd6-4d1c-b87a-4dba953da630.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2170b28b-1c11-411c-ad8e-1b4d884b509b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!221ecfe5-5d11-44e5-a7f3-ab71ce8c9774.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!231333d5-f5c4-4df4-9d09-814338ff0b36.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!235e6b94-0c1b-409b-881f-f293d356bcd8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2363d819-977b-465a-81a5-d16ab55a2e22.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!23766876-4d3e-421f-a26c-abb822473a1f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!23a77580-70a5-4f71-bf88-383caa4edaba.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!23c45ba3-cd4f-4fa2-b129-948a350d28a9.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!23faa183-1aed-4a7e-937a-6b46768c9e16.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2449949d-7cfe-4680-99d7-97167eea6b52.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!24b54660-10aa-44be-a54b-c7b571d0427c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!24e064e4-b388-4bc9-b379-88e485deab8a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!253ea427-a360-46fa-a1bd-e319055a9bf5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!25f695b3-ee00-4161-ad85-209101aa600c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!25f6ff1e-e9bb-47b9-a9ca-f72f7c5ac797.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!26089b3d-c318-4d35-af3e-255eef32bc7e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!267a5f9e-1dac-4b5f-89cf-d0f1741aedf1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!26879a0f-d760-440b-be38-c70ba711e016.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!26a15ed6-2da6-4796-8526-d63385e62189.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!270af0c6-1496-46af-91f6-9977aeefeef1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!27897886-242b-4f28-a79c-9c71b787a956.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!27adc88d-bda5-4888-b6bd-9691f55f3a3b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2830fdb4-947f-4f7a-aac1-c793f84c2d7b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!285a2bfa-8e59-4613-bc4f-f0300ed990a7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!293d9933-de29-455f-9a89-aa1b131afc2b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!296bf7a9-68fc-47b7-9c6c-eab873a25565.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2987c88d-23fe-43bc-99bf-a57fd0f13675.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2987f9ed-ae51-42f2-b0c6-6ae736646360.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!29ecae78-49d0-4b07-98ab-ab75527f68be.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2a763c96-c63b-4332-9ed6-dc7e842a0440.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2af2278f-aa89-43d8-88bb-f20480ff9c58.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2b1e1b17-babd-4e87-a119-16ceefa61be3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2bbf11fc-ff3d-476a-beb6-4f0b515c93ea.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2bd0be39-ea9f-4c56-9faf-cdf5b1f3c079.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2bec4090-07ec-440a-908a-a722168fb4e7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2c2e3e2e-50d8-4440-86a9-9047ff752cdf.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2ca6f22d-34b9-4ca5-ad14-c96abc6c17e8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2ce029f3-f023-44af-94dd-06390e68198d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2ce31ed9-b818-4b70-86bc-2e41a7d71b3d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2ce9adde-2a0b-4a87-bfee-74f262cc73fc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2cfe6d51-ddea-4915-8e5f-21a74df2bfac.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2d00f9bc-0fd3-4da9-a254-a90e61c15067.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2d87b8b1-0ca6-416c-acba-3349b6a2a514.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2dac26f3-01e8-4aa6-817e-2a89cc59290d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2dc32058-e0b1-4e46-8c5f-a46a60fe85ad.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2e0a9a01-5bc5-432e-81c7-378a9b35ead4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2e1facae-b5c7-4a96-ad59-a15a28da15a4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2e5640d9-8e1a-42e9-b630-a869ea6c44c1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2eaf153a-d5a2-40b3-9d59-a0424133003a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2ee4350b-006e-4d2b-9b71-87b8ac202e6e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2ee9c481-dbbf-4230-8d4c-d8dc11bec46c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2f61cf24-2da9-4050-8d71-ff96cfd478c8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2f709dd0-2acf-4553-9d3f-1b3e7d7e9a3b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2fe91768-c1ff-4360-9dc0-ea052da98d4a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!2ffad0b7-fa7f-4b88-97c9-54830b4f460c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3047fc05-26c5-4649-8fc5-6d83afd9d42c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!31197c74-10be-46d2-b36a-e2b96d22d57b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3142892e-219c-470d-80f3-0d7e5c34150f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!31a3f8cf-614b-4b08-a61e-52290f3a197b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!31cf85c8-3c6d-492e-b43f-4d0a8c2a055a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!31d505c2-817f-4e4a-88bb-710ca54869ed.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!31f9f8d9-e3d5-4c77-805c-3cdcd4d1a140.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!321a0118-d05e-4d95-901f-b7929e65628c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!324aac37-6820-45e3-8b14-21a21334a718.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3288ee08-56ae-4371-8fcc-fae09bb29053.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!33d6862e-cf55-499d-963f-93a9e393cc5d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!33ed93c1-91f9-4a3c-b55d-35c927a034d1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!344ceb77-d29b-49b0-a328-0104c35f233f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!34a06da6-fecf-401e-9dbc-1a072b0da618.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!34b6371c-977d-410d-b3c8-920b1fda6b84.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!34c9fb4b-912e-4d0c-a593-cc072b07376d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!34f7fd18-78f4-47fe-b0e9-28f0181aef28.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!35334b1b-0748-4ae6-b290-2b9d952a0cc6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!353ec49e-5261-49d9-b701-0073818dd29a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!35d3f72b-29c9-42ca-adb0-89302521cc58.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!35dc7a95-211f-4383-a123-466555ca192d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!35ebd4e9-69a9-44d2-a152-426330bac118.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!36132c8e-a7eb-4a04-866c-b97d95fd51d6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!362d1839-0159-465d-9a81-faf0f4b9a223.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!365e92dc-d8ea-4e86-8d42-0aacb460e98f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3780fe5d-358d-4b32-8f29-fba7cdada78c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!379a776d-54c8-4eee-bef4-0492e1b05e3a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3866c302-ce01-4ffb-8b7b-4d83bab72ca4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!38cfc692-cd7b-43b0-b242-4d4445b750d8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!391d087a-62d9-4a38-ab28-d58aa9c6e970.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!39392d41-09c3-4a2f-90c2-52a8805ea39c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!394c788f-640f-4ac9-9d54-10607998b486.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3964e3d1-7f92-45e8-b24b-7ab15013891d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!39bccce2-b78c-4cf9-8428-308793b32e71.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3a446fce-8d08-4ce7-819a-f2f316dc0153.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3a5b7b5e-a7d1-4515-977c-59f968f7c132.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3a6a92be-939f-4820-9366-dc485d46dc4c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3b08bd24-dd41-4fe6-8a73-5e696201f5ac.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3baa7569-6cd3-4a38-a9d9-be6bda89f5ef.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3be0678a-feb2-47ab-8b1c-bbc4d78dc171.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3c0a0580-8152-4bdf-a511-26ba9f32857b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3c19888e-ab9d-408d-90ad-4bb92b2bdbf2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3c353341-5051-40b5-b97c-ad7284dfda13.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3c6b7be3-d937-4f2b-a251-14b0814af9ee.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3c95c9ef-6ca0-4f22-a4c2-82581f5ce566.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3cf1cd63-6e1d-41f8-b38b-99919923445a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3d69d242-b996-4912-b637-b2ff675b019d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3d69d419-4f1f-420f-a86d-8be471e522e5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3dd5ace5-70f3-443f-a77b-f2b3efc8b6a4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3ddd3d20-ae93-4448-8b65-38ce0cdf64b3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3ead0dc7-f117-4478-a8e1-28bd33969d65.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3fd47b87-b7f0-4aac-87f5-7370282cadca.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!3fe3728d-6531-4b01-ab58-bbd17cc8edca.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!401b32b9-cd18-4da1-ab56-02470a6ca453.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!40cf93b8-ac5e-47a1-ae71-998ad27ca189.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!40e14dc3-d16b-400d-8c13-dbf2d5ca90ee.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!40ef037d-369d-4e0b-9dfe-582bc9f73525.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!40f5792b-73a0-48fa-82cf-c13e0b8469d2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!41a0a70a-a5e1-41cd-bad4-dc1b371172fb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!41a7775c-cf14-4060-b897-ebba44d643ac.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!41bf7a42-68a4-4df3-8006-cf8524d3dae6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!41fb0617-119f-4fa3-b813-ff80a5c6b817.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!42a66b22-60c7-45db-a17d-f78822e758b0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!42dbf858-050f-49c6-82f9-5bfecbe77cfb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!43510534-019c-43e9-a9fe-ae868411967c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4383cd84-9f31-4779-a798-a1a237d3efc9.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!43d322d3-42a7-4f27-ade1-7886fe5c955e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!442e840f-fc88-4fd3-8932-4943c8753360.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!44684574-21b6-4ca1-a8cc-2fe11e459ca5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!44b00d92-c007-493a-85c8-ee0dd43fbfe0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!44d3ca18-311a-44a8-9fff-8912c7ecac60.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!451aff08-e181-45b6-a78a-c594f0fa056c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!452cbd9e-1d72-4e84-83dd-b42449f05baf.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!45600fdd-f784-42f6-a514-7f1e34e5c745.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!45afbb30-3ab4-43ab-90ac-f5b902c70557.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!45daabc6-cd56-4052-b6eb-8663f8b8dbe2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!45ff7d79-4e27-40d2-93ee-8b24f78e89ec.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!461b5b97-1d25-4171-bb20-aa925d72bce6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!462b0be0-065f-44e3-96a6-3e67179d6674.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!46430d1f-b496-48d0-b5bc-5de79cadf175.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!46962d6e-92b2-4245-8a03-b10d38546911.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!46efb743-ab87-4ac7-9682-c3fcd15ed92c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!47199b5c-57c0-4aa4-bbfb-20d5c70212af.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4719ae4d-008f-4191-89e8-6c15f31c1fb7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4723262f-5574-4a31-bb74-57ec1e0651ab.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4776dea5-e0fd-4421-be38-c671999842e3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!478f85ae-4468-49ef-8d22-4d4d05570fae.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!47ef9d8c-24ad-44a4-ba40-526716184725.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!48f5f5eb-6fd5-480c-9658-c23e2952b81c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4909420b-44e9-4a00-9c97-3b8d61a0a1ef.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4917c167-f8bc-4416-bafc-37d2fa05537d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!491dcbbb-5398-4520-a6a8-71ff45dfbb49.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!49636e8f-be76-4105-ab9e-90e9bc6855d3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!496f12b0-20f6-4388-a078-74e31c9c8db8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!49a0ed75-a6ab-4005-ace4-a9cf6351cbcd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!49a133d9-a891-4d85-b46d-da7b7160c1f6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4a43c56b-93f7-4ce2-9cc9-eadb58f38487.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4a65073e-7651-45d6-b501-e9437434fcac.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4a850743-1c6a-4f08-a580-a2ec5d91845c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4b1244f7-ca4e-4833-b500-c9a377dbb7ca.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4b15fb46-8496-49c5-8f6d-bf9c7daa6793.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4b33efd9-b324-40c9-bfdc-3c1970b86195.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4b358236-7bd5-4fe1-be79-5b6d0985e112.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4b466e87-444d-437b-a830-14c0cb6fe2f4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4b6f50dd-a934-44a5-9925-004e6a89a779.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4b82a600-3b76-4865-a422-517b6155034c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4bf9b456-2028-42d5-bec8-53f046eae7a7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4c0351ae-e696-40a6-857d-45b82fc4f9a6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4c262d60-7c86-47ad-b6b7-17e3ee5d2b65.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4c2c29be-4591-4ff7-acd0-bb5f13225315.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4c65cfdc-3c2c-469f-b204-a71f50ee3a11.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4c6d07db-ed39-41a5-b489-89f77ae4c67f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4cd1a8da-c3fa-4feb-ba5e-b93131f33729.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4d180222-335e-4c40-8e61-abd709ddbfa0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4d528a08-13d1-4d0a-8f69-d870f1245a9a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4da181a0-9cee-44ce-a2db-9acdb2154fac.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4dbdaa18-bf2a-46a7-9fa5-272a503fcd57.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4e0cc5d6-eca3-4cd2-af5a-0a5e472a9a40.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4e42d7d0-b511-42ec-8888-858bd10b4413.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4e478383-798e-4f22-b4a9-919b0609267f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4eec4377-98a0-40fa-ba06-be2777d6a463.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4f68be5d-749f-4ae2-bf17-ff248c6c47b0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4f863192-0991-4618-975e-55772df49772.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!4ff69980-0724-49c8-b885-ee5c86aee9f1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!500d38f4-f55e-4091-8bbe-806c9bbec2df.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!50340cb9-b71e-4748-9dbd-80d5e2ab4533.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!508ade04-1815-49b3-bd31-81a9da598277.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!50a458ad-1ab0-4da8-8175-b90e1f987b09.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5107d457-b1a4-464a-93ce-452a5aaab204.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!514dbafe-7499-410b-aa6b-9a3cfc39ed94.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!527b3e69-4a28-4cac-a358-c204444f499d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!528ca094-7692-4a01-b1a3-0790926d5544.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!528ce4fb-8249-4d3f-9743-a1dc9bba8829.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5296546d-7aab-4e5d-9d4a-027966246645.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!529c7af7-691e-4480-b88d-f4c424c30610.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!52a3ae7e-0653-46b1-8052-8cf1cf17da95.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!52a3e47b-0213-4872-9bfa-94ac62c92698.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!52c624d8-2ed5-40eb-b3ca-cfc19cdc8e71.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!52d1bfcd-3d9a-4469-8fa1-413491ca75ac.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!52d49ea6-a9b2-4332-b712-46a9fe47e7cf.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!530618be-416e-4281-bdf4-432cca2ba154.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!53205a54-7175-4adf-9362-9e83d27a1414.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!53219c8d-ab96-486c-8d72-32c08d8d1e14.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!536e266b-8b25-4a1b-a5f5-6778399c90b4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!53869421-9475-4607-9ef9-efd4af0d3b98.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!53ed8360-33f8-4539-9f27-ebee01d3cfdc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!541ac3af-938d-4d2d-87ec-d40a7d51f949.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!54385af9-0e23-44dd-bc4d-2bf6362da26c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5457ed85-c48c-4ccf-8905-44751b42225f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!545e67e1-1744-4937-9bf1-a9666a903a0f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!54cf9e45-e833-4e90-9fef-7b49da74dd8a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5540a57e-b315-407a-ba5a-e41be9436b3b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!555a5486-947b-414e-a500-5248395bcd97.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!55cc236a-7120-4b8d-b990-afb7f6386e2d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!56624f0c-b9d6-4107-8c1b-e238ab6d1182.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!56805a47-39e7-4b6f-9f1c-d6762a70e655.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5691c070-0e79-44c6-8c01-2fb0031df8af.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!56a13e14-6a26-443e-ad58-84c7f8703ca5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!56eea411-09d9-4339-b21e-dcbceca22a8b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!570f1dfe-8829-4593-bef0-f42230b519ef.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!580a90be-62cd-4679-bdd7-1b28f9934b0d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!580f5147-ea97-432d-ad40-42cfcb3cf2e6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5890f4c0-88ad-4800-8232-d67b3da9b9d8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!58e03112-fd39-4e87-9b8b-fe8e9a92cc94.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!590ae097-0b16-4a6c-8a3d-fbfe6d56224a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!593c6e1e-de58-4cbc-a933-9eeedad35cc4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5994b78b-a10e-4a43-87b4-9c2c313f3c9d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!59e04135-5a7e-4c38-91e8-6e3213c384df.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5a165c73-27a7-449a-9a8a-94c377e78d92.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5a176a47-1bae-411f-86c4-5ce9a434878c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5a6465c4-ca0a-4ff5-a3c9-60be0e2485ee.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5a8bf716-15e5-40a6-8d4e-d4c6cdef49cd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5a9e4fd6-0206-4fcd-85e2-aeb0414c223a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5ab45d5f-316c-4519-8552-30222f670430.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5b777c93-d41b-448c-b14c-4f8e6bdf0956.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5be6fb36-dffc-4ffe-a553-f164714f6370.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5c0c8af0-e2e6-436f-867c-ea652a0c8a4d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5c191dd2-a708-4bec-be43-12a392460ffc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5c6d36dd-07fc-4421-bcf5-48008c49b592.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5cb2c113-40fe-45c2-97db-786ac0003a69.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5cd92388-abf1-40ff-82c8-f8b448680114.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5cf9dec3-bc79-4d2b-b12d-49132108abc2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5d022dfa-9ac2-4396-9683-f6f32c8afffd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5d65c2b7-a08d-40d2-ac79-2675933e0594.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5d743f7c-884e-4ab5-ab60-caa95ab2a935.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5db3bc2b-39d2-4ecf-8c70-e009243c0e1e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5ddf0dd3-5782-444e-9610-093b736ddfc8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5dfb804d-d608-4b1f-9cd5-d3bd8a4d767c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5e439239-b615-4827-822c-d2c16adf909f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5e61773b-5593-4752-867e-7c0555d89b35.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5e79c9b9-c28a-4cd4-a1e5-29c32987a56e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5e97d736-2d04-4c28-9692-bc22b6a2fcfc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5e9eb177-ead9-4476-8418-567c01b4ab87.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5ea34f5c-48ba-4100-b56b-0592cb44a691.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5f3f177c-9e7a-4471-8c2b-b9c82196ac29.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5f64dd66-fec7-4e6a-a356-ed786534481c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5f975c45-c190-4aa1-9f04-20301c3ce827.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5fed32d8-3433-4fef-a31a-d07dd279f505.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!5ff2de80-5117-4132-be8e-fb640c017658.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!608b89e8-29cc-408c-94a0-332f4d5fa220.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!60b22989-525c-43d6-a2e5-d4763c7c35cd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!60b51119-3f74-4ee7-8382-022b876627dc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!60c64de3-a206-4ec7-a471-6231e2a87ad8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6103ef62-4d3f-4c45-b8c5-917479681fe4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6114533a-571b-4678-bd70-282e33652305.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!61334577-4c4b-4f15-a044-4e5b37ca99fb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6161938b-41a6-490b-9fc8-80549584b3c3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6162d9db-7522-44e7-aa6b-5cf919d931c7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6163f333-883f-47e6-b9cd-2ab8f58253ec.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!616f742e-7a02-4b87-9ca8-ad1ab6424ada.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!61a27993-72d2-4f6b-9f33-fc05b83b9a92.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!61b1bd3c-6cb4-43ba-850c-4f008020cf75.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!61b2b409-7935-4a49-a77b-b8385651afb1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!623b5349-f07d-4124-a018-ea4203f0f584.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!623c857d-300e-4b82-a7c9-841ad3ff5720.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!625b9cb6-df51-4d54-953c-f0d903286af9.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!627ac2fa-8384-4c2d-b14a-57cadffa9307.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!629fa0a6-d0de-46cb-8670-c3b78b5b026c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!62ecec36-777b-4e75-a8e2-ecc1b5acc989.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!636119e3-4107-441a-bb92-ac39aa04e28a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!63821479-398e-4f03-bef1-e050ee0cc7e5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!63d0ca04-40c0-465e-b31f-52c008241771.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!63d4aa81-eadf-4d81-913b-64e26851d093.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!63f904f6-a1cc-474a-a43b-06ec3d07191e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6443867d-f5b3-4a85-8df1-57aaac003dd8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!648fe408-e54a-40e1-b148-b97162fd6c61.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!64954fab-f87f-4cb7-9bf0-88829f91b25f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!649e9af2-3160-4a44-9bd7-ecc909f51f69.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!64a42e40-2bd3-4b35-915c-2034abd3fb37.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!64fd2ab6-fdad-4299-8278-61769de3c386.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!655e242b-68d7-4c73-b053-5a398ef9daa0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!66097526-6373-42e8-8d7f-9930899d42ad.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6613b5ce-70b0-4286-824e-6cdd5504e5d2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!663e92df-0e24-483d-aad0-7f8745b7eedc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!66d37076-cdc3-4a7d-82fb-2d53dd9a083d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!66ea76e7-2fec-4397-bada-48783193a2f0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!67345f81-971a-481d-92a5-c93a89168247.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!674e4ac2-fa73-4707-b8ae-5c179c076c51.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6794ef03-6d4d-4c47-8285-a37cdba4d64e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!67cd0076-0a88-470a-be4f-796239108eef.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!67d57362-ce3e-496b-929b-a8da87cd3862.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!68422c19-788b-4dea-acfb-5e49f4800990.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!68467b77-4a4b-408a-ada2-41ac4613dffc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!68b476dd-95a5-4e4e-b202-35b81e5a3731.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!694b53f0-000e-4c58-8f80-0ef9076cbeb8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!69906978-ce3e-4f70-b89a-380c69b13982.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!69bb2ff8-6db7-40d8-b45a-ef101cd969fa.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!69e5c80f-58f2-4615-8044-86af98bf3086.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!69eef5e8-ab54-4eb0-8e69-5198a4dd45d1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6a3216f7-5afd-42a4-b021-02dfb397321e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6a54ee0a-5567-4e89-ac6d-c2902bc4fdf8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6a5ecdeb-e183-45b3-8a30-7bbc3545aa27.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6a9002da-8c11-4e6f-8ad3-15d79111ddcd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6b81c752-01e9-458f-b261-bf8d4688166b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6b8a143f-ccc9-472e-b077-bcc0e044fe36.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6b9cc525-e7ea-4fe0-aa3a-5ffd31d5faad.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6bcb38c1-4958-4e3a-bdd5-32f52b58a3f7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6bf138cc-5bfa-4fd0-9c04-c2d5f072ccd5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6d840bfb-0045-463a-b226-727c278f155f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6d93ea42-f79c-4385-bd9b-5e0fba1a5909.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6de3378e-baae-45a3-8a84-03ec11148bc3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6e49ac34-422c-42d2-9c77-305b68a0ac54.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6e7c7434-fd9f-42ae-8cc4-aba1e2ff18aa.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6e9d7e45-865c-4867-9f4d-0e96f3921c35.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6ee08cd7-3540-489f-9c6b-674b298737d6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6f7a879e-b2cf-4a20-bec5-5c09de93c4ad.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!6f829ba4-b4e3-433c-a860-8e186e30ac85.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!70c4999f-08e3-4aea-8973-ebc3389c5e35.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!70ddde73-376f-4562-a097-b1424f2cd70e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!70edd37a-7220-437c-9619-26748a492a3a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!714e6e75-7832-45ef-af06-bf66039166f8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!719db094-4cb1-4cb7-be57-3bbbf6e34ec7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!72315498-eb3b-44a3-a008-c2d46463daeb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!724a70f3-b99a-457c-a074-b5899daaa4d5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7285b815-f6cf-4cb8-904a-1fcee299d77e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7295f5f1-1342-408f-99d8-d2c10bc86f23.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!736868b2-3f5a-4688-b391-790b7d5fc5e3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!73ad57ab-b839-4fec-9af8-814115c27e68.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!73fbafd6-ca4d-4f7d-bf00-b2c878f36891.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!73ff3e24-d56f-4bd4-91d1-e95725bb5139.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!74eb5bd8-4757-4263-9a6c-e77c9c2ae6f7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!756e9840-5e66-4d10-b93b-7a7b6cf38832.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7571dd3c-e54a-4c39-87c0-33cbaeaf9648.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!75d61410-1198-40d6-9a2b-3c5da0c3ac92.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!75e6c3a8-5e47-491b-82f3-0c7000df0f2c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!760b828c-374b-466c-b27d-39b04a2af257.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!761ee42c-bb77-43bd-ac52-46a1a00a833e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!76fa27b9-c343-4c79-b500-7821f787592b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!76fb2de5-6c22-45ad-a984-e15fd2f4b93c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7767a63d-7556-4b2d-a91b-485df33a6889.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7784e064-fdab-429a-8505-042653461c7a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!77dc5e61-c8e0-4be7-b604-4e1e2ed5fafc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!77ebb6f7-97d9-4846-91b4-208396eb89e5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!781a5078-228d-4a04-8371-0071970a913f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!783efa63-029a-48bc-9d7f-789811a1c43e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!786de287-e4ac-4269-90ee-0f8d1c99e2c3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!787d6c56-a077-447d-958a-1183108265af.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!794406d4-3ad0-4436-af85-3320115799fb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!79519d6d-83b9-4bd8-bbe9-f85296401068.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!79da8d0b-947a-44f4-8b63-213d4a276eba.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7a2d5031-ff86-41f2-bb18-204ddfd631aa.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7a452301-05b9-4114-b5dd-ed8de24c97ad.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7a48212d-d1a2-4680-9bff-f6dc2e322c03.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7a4d1809-bf26-4ee3-8c9b-8de0470fb883.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7a67a249-01d7-4cd2-b885-c18781d1b2a0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7a9dfabc-f519-4adb-ba00-2dd6c2827e08.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7ab35026-dfda-471f-baee-3c0c8ea03eeb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7ae7061a-0931-438a-b905-c1e54f48c474.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7afb9033-4f15-421a-981e-f4161d006e85.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7b59eec6-53fc-4b9d-8c5b-6f3ecc5a4ebe.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7b7d15a8-aa1c-4044-a759-2947b9131324.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7bc0b3a0-f830-43b7-81a7-a31c52fafe16.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7bd17e98-bf49-45ab-b1a7-bd6d85035a07.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7bd5547f-aac6-469d-892a-53f3f9f71d0b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7c4f45e1-02d4-4e48-ba3e-4a637f3790db.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7ccaf774-35b4-4116-ba95-69316b85dd35.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7d27f50f-1d49-4293-834f-3663e16a98cb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7d42d75a-7c2b-4fa7-9031-c7cb005f1967.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7d488e6f-f188-46aa-a140-22fd49e22f0b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7d7f7373-0ad2-460d-9b46-c2d57eca8e04.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7d823240-f3bc-40b8-9e7f-c6f1b77918e7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7d980a7a-6d46-4034-8f1a-d119b4350f05.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7df9eacf-941a-4828-a262-6d132c095dcd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7e4d28ed-c284-4354-a018-78072c374052.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7e79d4b3-fbee-487a-93bb-786d259d8c10.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7e8eda49-46ee-435e-9a90-717192068160.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7f3ec66a-08ea-4461-ad43-d5309502ad88.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7f515865-7563-459f-9f89-ec4649ccf6da.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7f9e76ad-7803-44fc-ad43-24c1fd7f2914.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7fe13852-666c-49eb-a91f-da36122a1794.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7feecbb9-b6db-40a7-9e06-05a025a39d7c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!7ff3ec0a-f857-467f-bf42-242056982142.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!80213af7-e194-429b-9a88-043c0c556e4d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!80336cab-19d9-4cc6-a81c-b34063b8b87d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!809abe8b-7091-4df1-9229-1749ceda56c1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!80e7ff58-53e1-473a-9a29-ff5e4f033f1d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!80f697d5-8f52-467b-9526-f4709689c5a2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!810287ef-4020-42c4-9a00-2c22552b409f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8179f1be-f633-4867-b554-055946a9c9fe.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!819c4318-5c18-41ad-8bf7-7148cbdc94ca.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!81bf0e44-2afc-4adb-8906-b912d7324dea.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!81c501b2-21cc-43d6-bc92-a4619ebc3d02.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8240981d-9292-4c82-b263-3d478bff5064.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!826ff981-e71a-42c8-97b2-95e36dcf2b5b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!828c8579-9c75-43b7-aef3-3436516361df.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!82aca1f3-e6a0-4eb0-9850-0b4225383cdf.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!82e303df-50e3-4d96-a685-ff4f8b4b2ebd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!82e9aa2e-4cec-4325-8901-5db37fdfd0c7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!82f61d00-9565-412d-8dbd-71677ce2b9bd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!82fd4e98-e5f6-4b4e-a63e-778f37d95e70.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8309da6c-6419-4d42-9700-c510705f6611.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!830e080b-c885-44af-ad2f-06ca60fcbf8d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!83531791-e6c8-46cb-81b5-474e0a2aa330.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!83ec3f44-cd1f-4300-8af7-d2b5c6aa1379.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!846d6318-3637-49f6-ad26-3ad5f7a72e6b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!848aede3-f8aa-4f24-a4d7-6ee8f5862ea3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!84baf477-3e1d-4af9-afcd-a1c6480dd897.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!84cba453-dc0a-4db0-8663-bebe9b729d42.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!84d82be2-4f5a-4a4b-9709-e81253736f47.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!851fef2f-538f-4b64-ad62-46d399c0b9fe.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!85529642-880e-43e6-b628-5d83ee0a3499.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8569d782-7a72-4a08-ac99-48364a0664ee.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!85724c05-e2bf-45b8-859e-c27ba22d6c06.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8610348f-6220-48be-af80-c2e3e3bcaadb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8614e7a3-8af0-45f8-bab1-f3c5b3c988aa.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8666776a-5c94-4480-aba5-fa03c9610b60.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!86aab75b-c414-4ee9-a248-69481d8970d5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!86c30f5a-174a-4ead-900a-01b8f6549833.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!86c3b3e4-dd53-4362-97b0-f813406b7e93.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8708eb0d-45fa-44a1-a933-daa7f037d6fb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8769b30e-93fd-4878-8630-6cd79bf37e3f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!87b12842-e6cf-4edb-adeb-d04d9052ffbc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!87bf5cff-f62e-4f7f-9bcb-f095bd027ad5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!880f5cac-8b76-4be0-b6a4-9a5b1a76d7cb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8863ecac-3c8f-4c49-9651-9daf581c3661.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!887df1bd-70a8-4ee7-acaa-14944486a0f9.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!888fadf9-58d1-4147-bac8-e192d87728db.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!88c986fd-f3dc-4fb1-a36b-2c31aac6e82e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!893de46f-fd7c-45b4-b161-64875029bed7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!897dfd06-82e4-46a4-9534-05f09078c8f0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!89824cb3-e607-486b-aed9-a56ae41b6a28.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!89a36790-14d5-47a8-954e-cd8df0cc735f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8a4ce707-c4d8-4416-8111-03670b92da13.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8a5b653f-2bc6-416e-ba2d-881b9f891e32.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8a5e4f44-5a35-464c-b465-5310afbb21be.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8ae39bc3-8ce8-4e10-9baf-34771e6af458.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8af94adb-44cd-44f4-8d94-c6d9a495c826.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8b371195-6702-439f-950f-f71e2ee233bd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8b7bd3b0-5063-4881-88bc-5dbdd029202e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8bc1e90e-c2ea-4a08-ac4a-c1bbf7421f30.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8c74a87c-03ad-4f75-b928-b7c9e01c0cea.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8d00edda-9300-4834-acb9-b4fccb581886.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8d3461c2-0ba7-41d6-bdcc-3b1f37109334.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8d8a7616-affe-4ed2-9d41-d5b9a3a5ad4b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8dc2a80b-7e5f-4eaf-9b7a-4b59b5979078.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8e345f62-0a2b-4399-9815-4420681fdcd6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8e583211-dd76-438e-b980-c64e99a3db2d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8e6157b9-51dc-467e-be1a-ed2ccc50cb7d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8e8a5d26-9841-491d-80dc-9a1ed1a03ca4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8edc03ed-f541-4147-b780-dc5d771bb2db.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8f913ee0-31a1-439c-9f91-b476b6cc8595.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8f9a93d3-3222-469a-8c25-1ca5bc7e98e1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!8fb8ac48-f2b6-45b8-98bd-daa519d242dc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!918fb788-49a9-45ff-afed-7e5a274a00dd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!91a34035-db1e-471a-b69c-ad3c1e7f86ab.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!91c7d204-3bae-4d5b-ac03-015206ff86df.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!91da77d8-35ec-4894-b17c-dd9b787abcfd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!91fcd66a-a3d5-4452-a7c4-5bc8c7634727.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!933fc143-21d1-41a1-b2e4-1259485693e2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!93407142-ad96-4e20-a7b0-23781ea069b5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!93579f05-47b3-428e-954f-637ca1a635cf.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!93c6717d-79a9-4f5a-b447-a4d148ce55e3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!940c863f-ca7a-418d-86ad-0f561a7a5cc7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!958ce060-b2f6-49dc-96cc-7203cb6e4048.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!95c24965-59d9-4197-b203-9d28fef41c32.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!95c24d4a-510b-40f9-8703-e82ce2aacf17.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!95ce6440-c5a3-4c78-a40f-0a6bdbe8f11c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9640253d-cbe6-4e63-832f-c8c5862646d3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!96b66bf2-632e-499b-b51a-dffe3d74b7cc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!976989b0-3036-499e-ae81-1614a027db98.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!976fd366-5337-46ce-b252-cf7afa0c3368.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!978060e7-a3b5-48c8-b2cd-d186fcd1c9b6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9799cb4e-dcba-465f-9c75-49f3ef5f1acd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!97abdb0a-a490-4528-8b7c-0f3dcf7b4325.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!984d09f3-a2f6-46b6-9fa8-61860a74f85a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!98c77d4e-fccb-45c2-8a02-6ee2a5415fa2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!98f30fc1-da53-403e-9e2d-6034b50c2f9c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9903fc3e-0984-4dce-aa04-3f4dac0f541f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9918eae5-18bb-4aca-8963-a0fe59d9e781.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!991f85e0-6f1e-4d5c-8019-d856349e14b2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!99770653-f825-43f4-b0f5-edf87aa4023d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!999bd22f-b7b0-494d-b5e9-4b7c824d3382.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9a0f8e15-86e1-4e7a-8b9e-961cafc45629.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9a66a615-7ae6-4952-ae92-efaafb819cbc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9b54e996-fda5-4e27-af77-d876eb7f9f7e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9b56b840-1819-409e-b6fa-66919471c651.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9b70d17b-8976-4368-afb3-51df6e632860.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9bd82993-74a9-453f-9764-1b3ad5ac7f9c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9c385667-6e21-4ee9-b010-f5dfbce33062.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9c38ece0-a2f3-4ad8-a171-5e8ffc161350.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9c5a1e44-8cdc-426a-bc9b-aa6f6c74e3da.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9c719a62-7841-4e25-8b93-ee59f7c20233.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9c7fac0d-445e-4a84-b7d5-45ff59c027e8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9cacdd4f-d708-4357-9ac3-175f64b7b163.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9d64cdc2-c11a-4185-af80-377fd2ffde6f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9d72af86-5de2-457e-b03c-8e8c9acf1d72.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9d991242-911f-4b3d-9d3e-657c09dabd11.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9ddb6a8c-45a9-41e6-99da-eff96797c186.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9de8324c-ce97-4a13-9962-0057c558bd19.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9df30072-b3c9-404d-b773-bf9ef89858ef.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9df59639-d274-42c3-bac2-93809e5baa22.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9e2765f1-9e81-4164-926a-776c17efcee8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9e5359b0-024f-4ebe-969f-672a199c5b73.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9e62b6f9-23ca-47dc-adef-22c908593a21.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9e806174-f27a-4fd0-b419-73a20fb1bc17.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9f04c67d-e38f-4ab3-8cf6-4dcc2d4dcd7f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9f52feb2-65ae-4652-9fb9-d7efdd78a259.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!9f95db47-94b6-43b9-9094-f523295f14a4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a0574842-95ef-4402-b003-514936196fc6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a07c9e8a-27ad-4a53-9aa1-b4cc17a031f3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a0d73922-5fe4-4631-b0f3-0b6724d66e17.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a0d9e00f-87e7-4168-ae85-472f7e162dda.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a1025da4-a811-4068-8416-16202f7e899c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a1dc84cb-462f-4183-95f8-5203c4080be5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a2116151-c4ee-4f0e-8d25-cd582c2a2751.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a2248fa0-e9a8-4742-94ee-00b919cd5368.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a25a6e7a-e7fa-467b-b26e-0b80d16e9617.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a2e8690c-17ac-492e-a0e0-b56fa854f91c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a31148c2-7b4c-467f-91fc-0362b8a340f2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a339bd4d-dec7-44b9-873f-a28fc6b451bc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a3555a97-c6cc-45ed-bb72-b20061cd7e58.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a36b9b6c-f204-42fb-9cdb-e71c6207e82e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a38286fb-fbc1-45a7-ac24-1b30f49c2f9e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a3d2b5e3-2de6-42e3-bcfb-67dfe8e5ae1b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a3d2d4f0-d27a-4dff-a16e-cf8f6ab078c6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a440aa7e-13c3-47b5-a707-7c825260ab2a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a45a3767-fa8f-4450-9d3f-4b620878039d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a4a49991-8cff-4045-8cd2-c9fa5ccc6ed7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a4e3366d-7408-4a05-825b-4510bce62b4a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a5194fad-bbaa-4f01-b5b4-78f3347398b1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a5274826-976e-42ba-9cb5-439c4f780b99.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a5abe2dd-6ba4-4c54-9401-9b88fa83cf39.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a5c46de7-eeef-431a-8b35-b71fcf81d12e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a5fa0d25-4d76-444f-81e8-00028f2c07f4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a6a4b783-b5c5-40b0-8237-052c81bb7c38.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a6bdf3c4-5b6a-4eeb-8eca-bdc14058a8ae.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a6c5b19f-560b-4e98-acbf-e6646194fe2a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a6dfa64d-5f6d-4d3e-b92a-bb78fc41db89.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a6f4c62c-1ae7-4bb9-902d-8ee9b282c72d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a70a38d9-cf3e-4e5b-8501-c964ab7cf20d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a76461bb-23c8-4344-a932-34f602d873bf.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a764ac61-393f-4d3d-a45d-314768f99380.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a7710298-8c29-421e-a758-2de643aec29f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a77ec1c5-4d57-439c-921d-8e116de97214.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a7b1cfec-7d6a-4a88-9c21-db876816ab34.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a7cb2ce6-4777-4e26-b420-deff47f05fdc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a7d07d48-5235-45ef-b673-a38f2289db4b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a7d3ed16-2c24-4b3e-8cdc-d36826460fae.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!a8fd042e-ce3c-446e-beca-00aef4418597.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!aa2d7528-a27a-47ca-ba4b-72fd12946f17.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!aa45208c-ebc2-428d-8af7-e893f7378169.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!aaffe828-6a01-4a5f-a081-04f7606df81a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ab61fbf0-ccfe-4ada-8772-dff5c3a02247.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ab90ed9b-50e3-4031-9393-24fe8e992fd7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!acad28d3-9f1b-442e-bc4e-dd7622f91fae.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!acca7ef4-f7d3-4b7f-8c9d-ab00dd4b6645.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ad0c5018-db28-4851-a03f-d94497e059f1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ad258585-b8b1-4a5d-a67c-c2e6d7d95be2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ad38071e-4ff5-4fbc-bb94-3f22963b44c1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ae865b74-d384-47cf-bda0-e30c42c99d2e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ae8d8426-24c3-4465-822f-8abe89e9712d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!aee0f24c-933d-459c-9a3a-a6e2bb506e05.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!af3abfac-532e-4a28-8214-3468dfa95e5d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!af40349f-0b62-474e-90e8-d5f6142245fc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!aff2e91e-3b3c-4cac-bba9-6f2876dbf441.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b078e4f2-a8f1-4792-9fa3-03f2ffbb1fc2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b0c2ebf1-94c8-449c-9c0c-ebb237de45e2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b111a966-160c-480f-b0d9-a17e14777e4a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b12bbc43-f6c0-4115-89c1-69635bc76306.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b1e32c37-a825-4f3a-9c2b-766cc0ce82d3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b241102d-a7c9-40ab-adbb-ed4b3d80e489.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b25b1552-cf53-4079-9710-20163fb0a69a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b2767de4-2c85-4923-aa2d-57997602c958.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b27f17da-3788-477e-a9d9-666316736922.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b2a5072b-65f8-4e01-acdf-4575d9707dd3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b2e0de4b-42c8-4e71-a4f3-141e77a9700c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b2eb4fdb-5e67-49ed-b181-ebc9cad9418c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b34de8cd-f3c8-4478-ace1-c10f9bff4e96.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b3acf88b-80d0-44c0-abee-6dec4fbdedbe.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b3c3ed1c-8b2a-4884-96c9-ad76bf6e7735.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b3f6d482-5e18-42de-a0f2-baa60d02ab8c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b441a095-ab08-4c8d-8771-1a678336e46d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b554a46a-e88b-411d-8362-e4b63783a693.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b5772f29-ab76-4fd8-90b6-8841dcc0c4b4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b5f6dc35-fdf4-465b-bc91-3d4dda471752.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b6df2f90-8cf9-4bb1-8ec9-71a0c89f6943.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b7bb67df-d7b5-413c-9483-34b3547127ad.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b7ffcc98-4fca-4103-8c68-8020671345f2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b800cf2f-bd31-45ce-90ef-11044a266ccb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b8d90e48-18fb-4764-b31b-4773c77ce0b3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b922d766-d56f-4800-b6fb-3c81caf0a38b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b96639ae-9710-4803-8b39-9df0ba604ee2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b972ff9e-0f0d-4ec4-9846-3a09ab769eea.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b9760753-53dc-4463-827f-7ab25328d939.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b9a089be-25ca-40b5-8a57-a69956ebd8a1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!b9fb2acf-d5f8-49f4-bcf4-3bcc576a3b62.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ba401d49-e243-43b7-9f45-c82b6ce3814a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ba4f8e33-4721-4f51-ba69-41bef6d7d8a6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ba53504e-701f-4420-9c34-75998e4f512e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bb7ba32c-d61e-42b7-b8ae-e8c4386847ac.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bb7de660-24fc-4d72-88b1-03203e16fc38.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bb813719-a991-4ad4-b6c4-54ea1121a0fa.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bc138419-ee0e-4ba8-ad06-7b229e104dc8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bc3ab790-1d1a-498f-b870-668c925a54de.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bc66e53d-231b-4888-a46a-4ce01002dede.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bc7bc0bc-1144-4c19-a084-1d30057d9a83.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bcc03393-28e7-43db-9650-2b79bdcef35e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bd070c4c-3406-435a-8c86-c4ec56075fff.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bd79c444-2083-490e-85f9-95f701276c1c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bd946a3d-2de3-4d86-9c7d-3250c3120271.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bdf8a01d-b98d-4e22-9035-8ef6cf97f755.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!be1db8f7-31a2-48f8-9696-af290e33c783.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!be4cf1c9-df85-40c1-868e-aaee070ee786.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!be610b60-599b-492e-8ec5-f8f3e6586c7c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bf0d5113-12a6-4428-ad9f-ef42cab9fbb2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bf5f197d-ff0d-49ac-b23a-71a9f24002a0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bf6a8ef8-9dc8-4e6e-b373-d2823c1891f8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bf7194ed-55ae-4e1a-92bd-8157c6996fb6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bf7b453f-f0d3-4ebe-bd90-a9d65386a9e8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bf85b825-183a-458e-9fd3-eaf4a415fc9d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!bfda8075-aef9-4372-8c0e-971b78f31c3e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c046ab99-345e-4da0-a3c8-0b8e28c8413e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c0471a4b-bafd-4a59-9d5b-9733bae2570d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c06eea48-21ea-4ff8-9e0e-4f65c2ca27be.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c09d2c8f-3484-4711-aa25-83072d1c3e14.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c0a19744-d67b-4a63-a084-45a654dbd375.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c134c4a0-ffd1-43ad-a9c9-bf5f4a2d53cd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c1436235-896b-4e82-b146-5b5e592c497d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c18984db-4fde-4f92-bdb2-3dd6b3999e6d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c195e1d3-1885-4ebe-894a-e0904ebe926e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c1a8707b-63d7-4936-b36c-d05ac2ebaa2c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c250d917-ee64-4e90-a6d2-651f2b2a2d88.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c26c228e-7235-4c28-a843-5813a313708b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c2aca3c6-d019-4b90-a7ae-bf52243a87be.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c3001c06-6095-4a91-949e-7679ea3dc2b1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c3348754-0a43-49fc-9c6a-9d3d5919bc38.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c3621a39-9518-4245-a40e-0bc8301bccd3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c4a6bd63-fd2e-4e1a-8f4c-bffff882cfc5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c594a37d-d3ff-425c-bacd-ec27840e072f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c5bd5714-fd0a-408a-8e35-fd915039e3f8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c5d427c8-f341-498b-b223-a3181e4d063a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c5f3ce90-7bc9-4566-9122-26b76f7a5b82.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c60655c1-3c28-4abe-acbf-4a1f75d0c2b1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c60e70cb-b5d3-4a55-b901-c0674e5eeb2b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c6368aa1-bd5e-4079-bcf0-b703ef01efb7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c6afec49-f553-42a7-a1e5-649f03c1a9c4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c6d378ad-cfa5-46f5-971d-2a5c4f98a58b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c78375ba-9d68-4232-855a-dc2caff25dff.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c7902733-21c6-4766-bb64-eaeeecd4db89.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c7dccfe0-bf72-41a0-b1d6-90c2f19fecc1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c7e9ef5c-6997-4cbf-83a0-3f4989843881.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c7f047f0-2e9f-4ecb-8162-63fc1896df62.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c85ad497-2928-448e-85d7-5b79822db861.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c87c6ea4-9637-48ad-9e42-0c7ba695d282.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c8d11a3f-4490-48c9-be9d-676feae9eb93.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c8e6fc0c-3c97-44f2-9a28-ddd498ae66cf.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!c9c8f194-886f-47ba-9fe6-9ff098a4f4d6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ca867141-5304-46a8-a2b4-c067b725af37.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ca89c627-c193-4f39-8364-4238cf3cc840.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cb3632d2-c7aa-4600-a10a-b7a16fce03fb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cb82ab3d-591d-494a-9979-a2727bc5626f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cb95e28e-7611-4243-98eb-bcb5d91a1440.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cb9659d4-0c9a-442d-b61d-ae5d6f068dc3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cbb66134-f183-47d2-8147-530f332ef71e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cc4f6155-951c-4d35-ab65-a1aaef2f4a18.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cc710b9d-e9c6-43c3-8199-3a1d1565cb85.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cc781b54-415b-4ced-8fc1-83dadb298354.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ccbdcb78-905b-4a3f-bf84-b574d700d827.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cd044782-4b57-4b87-a422-69263d7f8265.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cd518557-08a0-4081-83f5-d97655d92682.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cd8acfbf-98e3-4c8e-b357-ed2e91f6dab3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cde74e59-5080-4b65-8e79-01dfba4c6d18.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ce0216dd-9102-4f47-8846-d7ebeb0dcd00.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ce6c2e13-491c-4382-a3e8-6c4c05100ac3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ce7014c2-83e0-4e99-8bb2-046bdf39f048.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ce711e5a-ff55-46ab-81ae-38e10a068802.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cec78c8d-372b-4d8e-8c8e-a57272f65076.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cf510c51-11a0-4849-a72d-fbd19eed48bd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cf5f7944-dfdc-4e66-9e9c-37efe31eb558.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cfa0fb00-d325-48af-9b8e-0b6b4511b870.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!cfc61302-0225-45d3-aaab-97482ea12090.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d045de20-8e6f-4bc4-bd08-55a26d7c7389.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d053e218-2768-4ddf-bede-ad442f09b640.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d0ed4630-bb46-4a2f-adc4-e80b0b5fff96.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d10775bf-c0b8-44b2-8f66-b08087d04a2b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d18be333-3e3e-435b-89dd-427bc6363062.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d22bee42-784c-4514-9cf8-8deb26d59a47.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d23be372-cb1b-4c05-8bd2-0ee06410b4b2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d265564e-e623-4abb-a4d8-190370fb3b38.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d26ddf63-75fc-48d2-ac42-07d671ebce7f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d30ca369-1e7d-40bb-9d0d-1c8c3660e954.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d3273daf-a9b0-4959-b260-01432187448c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d33bb1c7-ac15-4216-a505-2d76262518c4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d383a4e1-6299-46cc-8663-02a9023cf9c1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d3be721c-bac2-4e28-bfdb-08aff335c0a6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d438f303-39d9-4192-9086-9f80d2758a95.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d49393c0-b749-4021-9014-e1547d92b706.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d4a89799-91c9-48db-ad06-f3f9596be9ce.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d4bf9709-af5b-4911-803c-044c4fd55e2b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d4c36ca5-37b3-4524-88d2-8dccfb78fdce.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d539f896-49b2-4f3c-91f4-a09f3880a084.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d5ad52e6-adef-4978-ad2e-9e8752b50862.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d5dce4bf-1f4b-4749-84d8-b810cc8dd696.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d61b5f7c-12e5-4bb1-a68a-7ef989aa2c4c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d6a53b5d-bddf-4ae8-a209-886e16e72ce9.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d6bacf38-0765-4261-95a2-71c10352de6c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d6c44000-0ed2-41d3-9ffa-9f15695279b1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d6d26b7e-be16-4927-acfd-e7caf6eb21bb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d6d4a170-d644-4302-80d1-8f6131713b1c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d74867ce-7807-45a8-b030-35d6e64cfbe0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d74bca5a-1521-442e-87f3-3752bce676d5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d7d39ea5-a57a-4c36-99a6-8dc9a6cf3997.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d8039263-c790-42e0-9259-10161305b10c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d8c19a32-07b5-4616-bf6c-0664d2c6023d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d9118d53-0acb-47f9-9475-d5ec4f8d3bc1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d933cf65-9047-4d4f-81bc-8abcd6c338ea.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d95e5f97-1a22-4ae2-b554-5dee707b4895.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!d983e058-2c7e-4711-ad92-6331e6b822c3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!da61e076-280d-4532-b76b-df3e49a99c39.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!dac02dbb-8cc7-4792-b96a-de2f6bc5375c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!dae742c7-dfb0-446a-a509-58e99e25c836.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!db4f2d65-2d09-4d2e-a25b-f25b4419e87a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!db9b1115-3dc3-4144-849f-f460b51d9d75.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!dbd402bd-9985-4b34-98ff-221fe63786f6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!dbf45ed5-7b39-4a55-9a32-3647a375b3ac.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!dcf54a40-5ee2-45ec-9466-6acceda82493.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ddf1bd0b-814b-4282-86b3-9be7f428218d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ddfed76b-dd25-46e4-a375-dcba0138c06f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!de5b1570-b28e-494b-83d1-416e5cdea3e3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!de5bb326-f9d5-4b47-b72b-c242dc2001f3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!decab043-01e1-4e48-b3d5-4906937c4b05.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!decc785c-12d2-4519-91b5-7ee133c243fd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ded508f6-716f-47fa-af07-1bc51e02011e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!def0c346-1d37-4fb5-94f9-6a60adfcaf28.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!df4406bf-991b-4629-80bb-81b398b6efc4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!df63f51f-0b81-499b-92e6-bec76301b2a7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!dfdab292-e4e1-4ec8-9f33-5772b72e94ec.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e0a9a21a-5531-48e0-811a-a0c500d74773.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e0ba39a4-0ff0-4d7a-a9ef-a912a7eec9a5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e1b15766-67e9-4def-97fe-f85df1534ec5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e2100b51-5cd7-4fb2-9f4a-9fa53ca36631.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e25d2c90-e67e-4de1-80ef-4c3d2fc8d390.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e25e8fe0-0255-4540-9671-97a405fe5c9a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e28ba2cb-9086-4232-84c2-23edeefc39e3.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e2c7f584-bcbe-43b7-8afb-67ce6d20c12c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e2fa5556-3258-4e0e-9c89-f864f172be90.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e2fbeb66-bd5e-40b0-a8c7-fe3aa89c9322.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e380a8d3-316b-432f-aa9c-7828f76db67c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e3a1236e-d962-4a23-8a9e-1408e3bf2a3f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e488ffdd-f384-41ca-bd3a-4b39bb94d612.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e4ae4070-6afd-4265-8346-369fa1152975.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e4b752c0-eff0-401d-a638-d04e2e3b6d9e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e4fe59c3-ea66-42ed-ae48-f79502a29089.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e511c2da-ac81-46bb-80a2-cb6c96f8bdc7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e54a68fb-35ee-463e-adc3-3860b0009430.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e57f9d10-e29b-4d35-937c-ffd3d4c1f836.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e5af2e4c-6ebe-406b-8546-ed74864bc2f6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e65f0abb-6c8e-461d-9179-63f7d12f17bd.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e6cd4d3f-8fb9-4863-ba38-ba11eda1678c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e7662a5e-a03f-4cf1-b146-24016265f243.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e784d386-7e5a-46c8-9eed-c82b7b76f8f7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e79d0c3f-b28e-436a-8548-291c44971bc0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e86555a7-663b-4015-82fc-8419d18e4dfc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e865fa7d-3ef3-43c2-b795-d7800aba783f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e8f4f551-a625-4629-a761-fc8a8c43155e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e93d0da0-2748-4684-bf03-f172d66308e7.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!e9586638-033d-4bf7-bf12-1dc34049ea68.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ea24a093-a472-489b-8e23-54969e6e5301.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ea4529ac-405a-46a0-a3da-b7b3626ff077.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ea47d3eb-792a-4ba4-97c9-69f0a3c57731.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!eabdab62-a67f-4278-832b-798b43f74084.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!eb377b96-8b92-498e-a9a0-29649def6c09.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ebb7bca0-6d0d-483c-a5da-8604b9247ce6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ebbc7459-8a49-4551-815a-0cd82d4bff76.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ebf932bb-81e8-42a1-80f4-130ca6c63579.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ec199ae7-14da-43ec-9ae2-fd642f9b494d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ec326a41-3e29-42a8-b03a-0aa67a291a6f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ecbdbee3-c469-46f0-840f-2c8defa0d489.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ecd9f0ab-3e20-457c-8f1f-21fbac6b4580.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ecdd7831-ba15-4137-93e2-14339d7b0075.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ed44b30c-87cc-44e2-b2b9-d980d1804dd2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ed889161-7f2b-4e35-a2db-172ea6bd6b8b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ed9760e9-39fa-45a3-904e-89a003b24346.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ed9d3267-95c0-4fec-b687-882c98e0a990.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!edabb2ee-09b1-460f-b718-04c6578b2530.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!edadd699-5e5e-49be-a4c9-7eee94036a03.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ee0b072d-cb98-486d-95bc-a205e861ca4b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ee5a8c9c-e03c-46f5-821d-5109413a2f67.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ee65ca66-0d4e-4a8b-a7f9-825b05a6b1d5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ee96c3b4-e8dd-483e-ab60-eb2d3187332a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!eeb86305-cd5e-4a08-a573-17f3f316cc84.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!eef8b7e4-8616-41d8-88c7-0cc316fdab15.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ef30f611-473d-471a-87a2-76e5ebf87e81.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ef6ad6cd-ef80-43a4-97ae-46fec076933c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f077b013-67c4-4390-bda5-b818e4369b2d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f08a25f5-8a88-41f7-8a85-bcd166612307.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f0a3f6ab-cd54-4820-9378-648c1167e803.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f0ab6959-16c0-43a1-a779-1061dd46318a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f0bf3c1c-0589-4007-b6cc-e70bc76f4539.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f0ea32a1-2c37-44a3-8266-e2983739b247.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f0ed4b69-505c-4423-ad4a-f588edf85983.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f0ee301e-1140-4b84-ac93-3ceede0f5090.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f1144f3d-ed1e-42c9-aaaa-8cfc936d4961.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f1206f9b-00ec-4479-9de4-19eb62ec2ca2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f187a57f-b9ec-4409-8533-7672b56a4437.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f1fb620c-967c-4f30-878a-e17fb1ede7ac.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f244a993-0ae3-4091-b866-7a2ef326ea73.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f2956010-fcaa-4474-947a-3d77d889e3af.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f337e441-1f89-401e-b9d5-560a7f210011.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f35a9de0-3bf9-49f7-806c-d30d192a8c7d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f3790c7f-c6d9-49bf-b2ce-636236e0d46c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f3a60a02-30a7-468b-81bf-13add7646fd8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f3fd25f4-4ec1-452a-a724-9d39c00f2904.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f443ea90-2902-44fb-bbbc-66d97e3cc67c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f4558fd1-8e24-456d-b283-902f6ff29a10.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f45b1d36-ff13-412f-b17f-a64ee194df2a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f464e756-7e8a-4b18-8785-9d5f54ac25d5.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f470fb58-ca47-41cb-acdf-a615f0b82d3f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f48693d8-60e4-49b6-820e-ad6150c26965.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f4ad97d6-f54e-4d7f-bf27-61d7a4eec94c.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f4e70d71-1c25-4407-840c-0442c50fd16b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f591cd2c-4da9-44e2-ab78-4802e06bca19.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f5dbd7a0-4fcc-4497-a23d-3d6f52c1e62b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f5fd4678-6a69-493b-9a10-d66d03bc3f4a.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f60c1baf-033d-46ba-be73-dd9cce98ad58.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f61575c7-93e2-4e91-8cd8-48a6b7c95b9e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f69039d7-90b4-42b4-9950-bfd155095924.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f69253de-b613-4026-829d-b2586ed27986.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f6984628-b745-447c-ad5a-f70b6434ebc6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f6b83ee2-2cf5-49c2-873a-22ebbd5e64d2.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f6e0edc0-0912-4242-9f8d-96df82e93ae9.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f7a624dc-40ea-4412-bf05-e5aed8ba75df.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f7e17e14-747f-4ba7-bdfc-be68d898fb53.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f865a40b-c6f7-4db2-9327-ff48a524100e.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f9623569-329b-44d7-b71e-b8afb4a9e5d8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f96597bc-ca74-410c-9eab-41b5055d7f77.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!f9a24a87-d4c7-4d36-ba82-f953ec8d5ca0.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fa291d6c-434e-4ba4-abee-b26bc573a954.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fa65f5d0-cbb3-4953-85ee-fafe5b155b2f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fa97b46a-3a11-46cb-977f-e898ac1fc544.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fb8501d7-1fda-460b-b9ae-344e976f2f6d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fb918d1b-2419-4242-adba-f947d84b0f1b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fbd80379-e48b-42c6-9936-37d42f4ad4f1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fbe34067-7807-4f3b-b228-a17cc23edb78.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fbed909d-3d2b-45fc-b05d-2daf52a3c1c4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fc2334f2-952b-4b8a-9d38-ff42f758ee64.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fc346ac3-47a9-4a56-97c1-465e582c261d.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fcabe18c-b801-4c93-a700-1c39b428957f.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fcf53b6c-9b21-480b-8a7a-7200f00e83d1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fd2fd43d-f4c7-4e0e-b31c-4a9a2232b5d6.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fd389908-05d5-4505-b350-598878fe9120.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fd9cf1a1-4bcb-437f-b481-8b85c704e7dc.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fe2b9d32-94cd-436c-97bf-bc44006fc7e1.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!fe5a6674-ac51-46a6-ba84-928ec8fdf6bb.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ff20bf31-83b5-46ef-9ae5-2c15be948c22.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ff30dfd7-0c9c-47c7-b992-4fbef3b97bed.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ff76473e-e874-424f-84b4-496ae7814131.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ff95f473-3648-45cd-886c-8c700018d78b.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ffa69c54-30d9-4777-bfe9-a5a3309b60a4.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ffbaeac3-6204-4714-b014-2b6e4a3d2a21.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ffc46a54-d0dd-4a3c-bd21-cd89d8a31b69.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ffda8b8c-baf0-4938-bda5-12d30ef39fe8.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ffe1fed4-8e49-4584-8f74-a1f9a58b70ed.json" />
+ <_ContentIncludedByDefault Remove="data\rooms\!ffffc7e7-4b1e-40a9-9f24-ebd95267e758.json" />
+ <_ContentIncludedByDefault Remove="data\users\@emma:hse.localhost\tokens.json" />
+ <_ContentIncludedByDefault Remove="data\users\@emma:hse.localhost\user.json" />
+ </ItemGroup>
+
</Project>
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Program.cs b/Utilities/LibMatrix.HomeserverEmulator/Program.cs
index 9ea6fce..c72df5a 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Program.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Program.cs
@@ -1,7 +1,6 @@
using System.Net.Mime;
using System.Text.Json.Serialization;
using LibMatrix;
-using LibMatrix.HomeserverEmulator.Extensions;
using LibMatrix.HomeserverEmulator.Services;
using LibMatrix.Services;
using Microsoft.AspNetCore.Diagnostics;
@@ -32,7 +31,7 @@ builder.Services.AddSwaggerGen(c => {
});
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
-builder.Services.AddSingleton<HSEConfiguration>();
+builder.Services.AddSingleton<HseConfiguration>();
builder.Services.AddSingleton<UserStore>();
builder.Services.AddSingleton<RoomStore>();
builder.Services.AddSingleton<MediaStore>();
@@ -77,7 +76,7 @@ app.UseExceptionHandler(exceptionHandlerApp => {
var exceptionHandlerPathFeature =
context.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature?.Error is not null)
- Console.WriteLine(exceptionHandlerPathFeature.Error.ToString()!);
+ Console.WriteLine(exceptionHandlerPathFeature.Error.ToString());
if (exceptionHandlerPathFeature?.Error is MatrixException mxe) {
context.Response.StatusCode = mxe.ErrorCode switch {
@@ -86,14 +85,14 @@ app.UseExceptionHandler(exceptionHandlerApp => {
_ => StatusCodes.Status500InternalServerError
};
context.Response.ContentType = MediaTypeNames.Application.Json;
- await context.Response.WriteAsync(mxe.GetAsJson()!);
+ await context.Response.WriteAsync(mxe.GetAsJson());
}
else {
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = MediaTypeNames.Application.Json;
await context.Response.WriteAsync(new MatrixException() {
ErrorCode = "M_UNKNOWN",
- Error = exceptionHandlerPathFeature?.Error.ToString()
+ Error = exceptionHandlerPathFeature?.Error?.ToString() ?? "Unknown error"
}.GetAsJson());
}
});
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Services/HSEConfiguration.cs b/Utilities/LibMatrix.HomeserverEmulator/Services/HSEConfiguration.cs
index 73b0d23..04ce050 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Services/HSEConfiguration.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Services/HSEConfiguration.cs
@@ -4,12 +4,12 @@ using ArcaneLibs.Extensions;
namespace LibMatrix.HomeserverEmulator.Services;
-public class HSEConfiguration {
- private static ILogger<HSEConfiguration> _logger;
- public static HSEConfiguration Current { get; set; }
+public class HseConfiguration {
+ private static ILogger<HseConfiguration> _logger;
+ public static HseConfiguration Current { get; set; }
[RequiresUnreferencedCode("Uses reflection binding")]
- public HSEConfiguration(ILogger<HSEConfiguration> logger, IConfiguration config, HostBuilderContext host) {
+ public HseConfiguration(ILogger<HseConfiguration> logger, IConfiguration config, HostBuilderContext host) {
Current = this;
_logger = logger;
logger.LogInformation("Loading configuration for environment: {}...", host.HostingEnvironment.EnvironmentName);
@@ -22,13 +22,15 @@ public class HSEConfiguration {
_logger.LogInformation("Configuration loaded: {}", this.ToJson());
}
- public string CacheStoragePath { get; set; }
+ public required string CacheStoragePath { get; set; }
- public string DataStoragePath { get; set; }
+ public required string DataStoragePath { get; set; }
- public bool StoreData { get; set; } = true;
+ public required bool StoreData { get; set; } = true;
+
+ public required string ServerName { get; set; } = "localhost";
- public bool UnknownSyncTokenIsInitialSync { get; set; } = true;
+ public required bool UnknownSyncTokenIsInitialSync { get; set; } = true;
private static string ExpandPath(string path, bool retry = true) {
_logger.LogInformation("Expanding path `{}`", path);
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Services/MediaStore.cs b/Utilities/LibMatrix.HomeserverEmulator/Services/MediaStore.cs
index 00f2a42..7945d3a 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Services/MediaStore.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Services/MediaStore.cs
@@ -4,18 +4,18 @@ using LibMatrix.Services;
namespace LibMatrix.HomeserverEmulator.Services;
public class MediaStore {
- private readonly HSEConfiguration _config;
+ private readonly HseConfiguration _config;
private readonly HomeserverResolverService _hsResolver;
- private List<MediaInfo> index = new();
+ private List<MediaInfo> _mediaIndex = new();
- public MediaStore(HSEConfiguration config, HomeserverResolverService hsResolver) {
+ public MediaStore(HseConfiguration config, HomeserverResolverService hsResolver) {
_config = config;
_hsResolver = hsResolver;
if (config.StoreData) {
var path = Path.Combine(config.DataStoragePath, "media");
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
if (File.Exists(Path.Combine(path, "index.json")))
- index = JsonSerializer.Deserialize<List<MediaInfo>>(File.ReadAllText(Path.Combine(path, "index.json")));
+ _mediaIndex = JsonSerializer.Deserialize<List<MediaInfo>>(File.ReadAllText(Path.Combine(path, "index.json")));
}
else
Console.WriteLine("Data storage is disabled, not loading rooms from disk");
@@ -36,7 +36,9 @@ public class MediaStore {
if (_config.StoreData) {
var path = Path.Combine(_config.DataStoragePath, "media", serverName, mediaId);
if (!File.Exists(path)) {
- var mediaUrl = await _hsResolver.ResolveMediaUri(serverName, $"mxc://{serverName}/{mediaId}");
+ // var mediaUrl = await _hsResolver.ResolveMediaUri(serverName, $"mxc://{serverName}/{mediaId}");
+ var homeserver = (await _hsResolver.ResolveHomeserverFromWellKnown(serverName)).Client;
+ var mediaUrl = homeserver is null ? null : $"{homeserver}/_matrix/media/v3/download/";
if (mediaUrl is null)
throw new MatrixException() {
ErrorCode = "M_NOT_FOUND",
@@ -50,7 +52,9 @@ public class MediaStore {
return new FileStream(path, FileMode.Open);
}
else {
- var mediaUrl = await _hsResolver.ResolveMediaUri(serverName, $"mxc://{serverName}/{mediaId}");
+ // var mediaUrl = await _hsResolver.ResolveMediaUri(serverName, $"mxc://{serverName}/{mediaId}");
+ var homeserver = (await _hsResolver.ResolveHomeserverFromWellKnown(serverName)).Client;
+ var mediaUrl = homeserver is null ? null : $"{homeserver}/_matrix/media/v3/download/";
if (mediaUrl is null)
throw new MatrixException() {
ErrorCode = "M_NOT_FOUND",
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Services/PaginationTokenResolverService.cs b/Utilities/LibMatrix.HomeserverEmulator/Services/PaginationTokenResolverService.cs
index 0128ba6..0603a2d 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Services/PaginationTokenResolverService.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Services/PaginationTokenResolverService.cs
@@ -35,15 +35,15 @@ public class PaginationTokenResolverService(ILogger<PaginationTokenResolverServi
}
}
- public async Task<StateEventResponse?> ResolveTokenToEvent(string token, RoomStore.Room room) {
+ public Task<StateEventResponse?> ResolveTokenToEvent(string token, RoomStore.Room room) {
if (token.StartsWith('$')) {
//we have an event ID
logger.LogTrace("ResolveTokenToEvent(EventId({token}), Room({room})): searching for event...", token, room.RoomId);
var evt = room.Timeline.SingleOrDefault(x => x.EventId == token);
- if (evt is not null) return evt;
+ if (evt is not null) return Task.FromResult(evt);
logger.LogTrace("ResolveTokenToEvent({token}, Room({room})): event not in requested room...", token, room.RoomId);
- return null;
+ return Task.FromResult<StateEventResponse?>(null);
}
else {
// we have a sync token
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Services/RoomStore.cs b/Utilities/LibMatrix.HomeserverEmulator/Services/RoomStore.cs
index 5cdc3ab..b6fe7c2 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Services/RoomStore.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Services/RoomStore.cs
@@ -2,13 +2,12 @@ using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
-using System.Collections.Specialized;
using System.Text.Json;
using System.Text.Json.Nodes;
using ArcaneLibs;
using ArcaneLibs.Collections;
using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.HomeserverEmulator.Controllers.Rooms;
using LibMatrix.Responses;
@@ -19,14 +18,14 @@ public class RoomStore {
public ConcurrentBag<Room> _rooms = new();
private FrozenDictionary<string, Room> _roomsById = FrozenDictionary<string, Room>.Empty;
- public RoomStore(ILogger<RoomStore> logger, HSEConfiguration config) {
+ public RoomStore(ILogger<RoomStore> logger, HseConfiguration config) {
_logger = logger;
if (config.StoreData) {
var path = Path.Combine(config.DataStoragePath, "rooms");
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
foreach (var file in Directory.GetFiles(path)) {
var room = JsonSerializer.Deserialize<Room>(File.ReadAllText(file));
- if (room is not null) _rooms.Add(room);
+ if (room is not null && room.State.Any(x => x.Type == RoomCreateEventContent.EventId)) _rooms.Add(room);
}
}
else
@@ -35,25 +34,8 @@ public class RoomStore {
RebuildIndexes();
}
- private SemaphoreSlim a = new(1, 1);
private void RebuildIndexes() {
- // a.Wait();
- // lock (_roomsById)
- // _roomsById = new ConcurrentDictionary<string, Room>(_rooms.ToDictionary(u => u.RoomId));
- // foreach (var room in _rooms) {
- // _roomsById.AddOrUpdate(room.RoomId, room, (key, old) => room);
- // }
- //
- // var roomsArr = _rooms.ToArray();
- // foreach (var (id, room) in _roomsById) {
- // if (!roomsArr.Any(x => x.RoomId == id))
- // _roomsById.TryRemove(id, out _);
- // }
-
- // _roomsById = new ConcurrentDictionary<string, Room>(_rooms.ToDictionary(u => u.RoomId));
_roomsById = _rooms.ToFrozenDictionary(u => u.RoomId);
-
- // a.Release();
}
public Room? GetRoomById(string roomId, bool createIfNotExists = false) {
@@ -64,18 +46,19 @@ public class RoomStore {
if (!createIfNotExists)
return null;
- return CreateRoom(new() { });
+ return CreateRoom(new());
}
public Room CreateRoom(CreateRoomRequest request, UserStore.User? user = null) {
var room = new Room(roomId: $"!{Guid.NewGuid().ToString()}");
var newCreateEvent = new StateEvent() {
Type = RoomCreateEventContent.EventId,
- RawContent = new() { }
+ RawContent = new()
};
foreach (var (key, value) in request.CreationContent) {
newCreateEvent.RawContent[key] = value.DeepClone();
+ Console.WriteLine($"RawContent[{key}] = {value.DeepClone().ToJson(ignoreNull: true)}");
}
if (user != null) {
@@ -137,7 +120,7 @@ public class RoomStore {
public Room(string roomId) {
if (string.IsNullOrWhiteSpace(roomId)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(roomId));
- if (roomId[0] != '!') throw new ArgumentException("Room ID must start with !", nameof(roomId));
+ if (roomId[0] != '!') throw new ArgumentException($"Room ID must start with '!', provided value: {roomId ?? "null"}", nameof(roomId));
RoomId = roomId;
Timeline = new();
AccountData = new();
@@ -207,7 +190,7 @@ public class RoomStore {
: JsonSerializer.Deserialize<JsonObject>(JsonSerializer.Serialize(request.TypedContent)))
};
Timeline.Add(state);
- if(state.StateKey != null)
+ if (state.StateKey != null)
RebuildState();
return state;
}
@@ -226,32 +209,36 @@ public class RoomStore {
}
// public async Task SaveDebounced() {
- // if (!HSEConfiguration.Current.StoreData) return;
- // await _debounceCts.CancelAsync();
- // _debounceCts = new CancellationTokenSource();
- // try {
- // await Task.Delay(250, _debounceCts.Token);
- // // Ensure all state events are in the timeline
- // State.Where(s => !Timeline.Contains(s)).ToList().ForEach(s => Timeline.Add(s));
- // var path = Path.Combine(HSEConfiguration.Current.DataStoragePath, "rooms", $"{RoomId}.json");
- // Console.WriteLine($"Saving room {RoomId} to {path}!");
- // await File.WriteAllTextAsync(path, this.ToJson(ignoreNull: true));
- // }
- // catch (TaskCanceledException) { }
+ // if (!HSEConfiguration.Current.StoreData) return;
+ // await _debounceCts.CancelAsync();
+ // _debounceCts = new CancellationTokenSource();
+ // try {
+ // await Task.Delay(250, _debounceCts.Token);
+ // // Ensure all state events are in the timeline
+ // State.Where(s => !Timeline.Contains(s)).ToList().ForEach(s => Timeline.Add(s));
+ // var path = Path.Combine(HSEConfiguration.Current.DataStoragePath, "rooms", $"{RoomId}.json");
+ // Console.WriteLine($"Saving room {RoomId} to {path}!");
+ // await File.WriteAllTextAsync(path, this.ToJson(ignoreNull: true));
+ // }
+ // catch (TaskCanceledException) { }
// }
private SemaphoreSlim saveSemaphore = new(1, 1);
+ private CancellationTokenSource _saveCts = new();
+
public async Task SaveDebounced() {
Task.Run(async () => {
- await saveSemaphore.WaitAsync();
+ // await saveSemaphore.WaitAsync();
+ await _saveCts.CancelAsync();
+ _saveCts = new();
try {
- var path = Path.Combine(HSEConfiguration.Current.DataStoragePath, "rooms", $"{RoomId}.json");
- Console.WriteLine($"Saving room {RoomId} to {path}!");
- await File.WriteAllTextAsync(path, this.ToJson(ignoreNull: true));
+ var path = Path.Combine(HseConfiguration.Current.DataStoragePath, "rooms", $"{RoomId}.json");
+ // Console.WriteLine($"Saving room {RoomId} to {path}!");
+ await File.WriteAllTextAsync(path, this.ToJson(ignoreNull: true), _saveCts.Token);
}
finally {
- saveSemaphore.Release();
+ // saveSemaphore.Release();
}
});
}
diff --git a/Utilities/LibMatrix.HomeserverEmulator/Services/UserStore.cs b/Utilities/LibMatrix.HomeserverEmulator/Services/UserStore.cs
index 4ce9f92..7f211e3 100644
--- a/Utilities/LibMatrix.HomeserverEmulator/Services/UserStore.cs
+++ b/Utilities/LibMatrix.HomeserverEmulator/Services/UserStore.cs
@@ -5,7 +5,6 @@ using System.Text.Json.Nodes;
using ArcaneLibs;
using ArcaneLibs.Collections;
using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec.State;
using LibMatrix.Filters;
using LibMatrix.Responses;
@@ -13,12 +12,14 @@ namespace LibMatrix.HomeserverEmulator.Services;
public class UserStore {
public ConcurrentBag<User> _users = new();
+ private readonly HseConfiguration _config;
private readonly RoomStore _roomStore;
- public UserStore(HSEConfiguration config, RoomStore roomStore) {
+ public UserStore(HseConfiguration config, RoomStore roomStore) {
+ _config = config;
_roomStore = roomStore;
if (config.StoreData) {
- var dataDir = Path.Combine(HSEConfiguration.Current.DataStoragePath, "users");
+ var dataDir = Path.Combine(HseConfiguration.Current.DataStoragePath, "users");
if (!Directory.Exists(dataDir)) Directory.CreateDirectory(dataDir);
foreach (var userId in Directory.GetDirectories(dataDir)) {
var tokensDir = Path.Combine(dataDir, userId, "tokens.json");
@@ -64,12 +65,15 @@ public class UserStore {
};
}
- public async Task<User> CreateUser(string userId, Dictionary<string, object>? profile = null) {
+ public async Task<User> CreateUser(string userId, Dictionary<string, object>? profile = null, string kind = "user") {
profile ??= new();
- if (!profile.ContainsKey("displayname")) profile.Add("displayname", userId.Split(":")[0]);
+ var parts = userId.Split(":");
+ var localPart = parts[0].TrimStart('@');
+ if (!profile.ContainsKey("displayname")) profile.Add("displayname", localPart);
if (!profile.ContainsKey("avatar_url")) profile.Add("avatar_url", null);
var user = new User() {
- UserId = userId,
+ UserId = $"@{localPart}:{_config.ServerName}",
+ IsGuest = kind == "guest",
AccountData = new() {
new StateEventResponse() {
Type = "im.vector.analytics",
@@ -80,7 +84,22 @@ public class UserStore {
new StateEventResponse() {
Type = "im.vector.web.settings",
RawContent = new JsonObject() {
- ["developerMode"] = true
+ ["developerMode"] = true,
+ ["alwaysShowTimestamps"] = true,
+ ["SpotlightSearch.showNsfwPublicRooms"] = true,
+
+ }
+ },
+ new() {
+ Type = "im.vector.setting.integration_provisioning",
+ RawContent = new JsonObject() {
+ ["enabled"] = false
+ }
+ },
+ new() {
+ Type = "m.identity_server",
+ RawContent = new JsonObject() {
+ ["base_url"] = null
}
},
}
@@ -118,7 +137,7 @@ public class UserStore {
private ObservableDictionary<string, object> _profile;
private ObservableCollection<StateEventResponse> _accountData;
private ObservableDictionary<string, RoomKeysResponse> _roomKeys;
- private ObservableDictionary<string, AuthorizedSession> _authorizedSessions;
+ private ObservableDictionary<string, LoginResponse> _authorizedSessions;
public string UserId {
get => _userId;
@@ -175,7 +194,7 @@ public class UserStore {
}
}
- public ObservableDictionary<string, AuthorizedSession> AuthorizedSessions {
+ public ObservableDictionary<string, LoginResponse> AuthorizedSessions {
get => _authorizedSessions;
set {
if (value == _authorizedSessions) return;
@@ -185,13 +204,15 @@ public class UserStore {
}
}
+ public bool IsGuest { get; set; }
+
public async Task SaveDebounced() {
- if (!HSEConfiguration.Current.StoreData) return;
+ if (!HseConfiguration.Current.StoreData) return;
await _debounceCts.CancelAsync();
_debounceCts = new CancellationTokenSource();
try {
await Task.Delay(250, _debounceCts.Token);
- var dataDir = Path.Combine(HSEConfiguration.Current.DataStoragePath, "users", _userId);
+ var dataDir = Path.Combine(HseConfiguration.Current.DataStoragePath, "users", _userId);
if (!Directory.Exists(dataDir)) Directory.CreateDirectory(dataDir);
var tokensDir = Path.Combine(dataDir, "tokens.json");
var path = Path.Combine(dataDir, $"user.json");
@@ -205,6 +226,7 @@ public class UserStore {
public class SessionInfo {
public string DeviceId { get; set; } = Guid.NewGuid().ToString();
+ public string DeviceName { get; set; } = "Unnamed device";
public Dictionary<string, UserSyncState> SyncStates { get; set; } = new();
public class UserSyncState {
@@ -241,10 +263,5 @@ public class UserStore {
UserId = UserId
};
}
-
- public class AuthorizedSession {
- public string Homeserver { get; set; }
- public string AccessToken { get; set; }
- }
}
}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.JsonSerializerContextGenerator/LibMatrix.JsonSerializerContextGenerator.csproj b/Utilities/LibMatrix.JsonSerializerContextGenerator/LibMatrix.JsonSerializerContextGenerator.csproj
index 35cb9f8..486b6b6 100644
--- a/Utilities/LibMatrix.JsonSerializerContextGenerator/LibMatrix.JsonSerializerContextGenerator.csproj
+++ b/Utilities/LibMatrix.JsonSerializerContextGenerator/LibMatrix.JsonSerializerContextGenerator.csproj
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>net8.0</TargetFramework>
+ <TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<OutputType>exe</OutputType>
diff --git a/Utilities/LibMatrix.TestDataGenerator/LibMatrix.TestDataGenerator.csproj b/Utilities/LibMatrix.TestDataGenerator/LibMatrix.TestDataGenerator.csproj
index 879693e..b054aba 100644
--- a/Utilities/LibMatrix.TestDataGenerator/LibMatrix.TestDataGenerator.csproj
+++ b/Utilities/LibMatrix.TestDataGenerator/LibMatrix.TestDataGenerator.csproj
@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
- <TargetFramework>net8.0</TargetFramework>
+ <TargetFramework>net9.0</TargetFramework>
<LangVersion>preview</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
@@ -17,7 +17,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0"/>
+ <PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.1"/>
</ItemGroup>
<ItemGroup>
<Content Include="appsettings*.json">
@@ -27,6 +27,6 @@
<ItemGroup>
<ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj"/>
<ProjectReference Include="..\..\Utilities\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj"/>
- <ProjectReference Include="..\LibMatrix.Tests\LibMatrix.Tests.csproj"/>
+ <ProjectReference Include="..\..\Tests\LibMatrix.Tests\LibMatrix.Tests.csproj"/>
</ItemGroup>
</Project>
diff --git a/Utilities/LibMatrix.TestDataGenerator/Program.cs b/Utilities/LibMatrix.TestDataGenerator/Program.cs
index 2583817..f3750a8 100644
--- a/Utilities/LibMatrix.TestDataGenerator/Program.cs
+++ b/Utilities/LibMatrix.TestDataGenerator/Program.cs
@@ -2,6 +2,7 @@
using LibMatrix.Services;
using LibMatrix.Utilities.Bot;
+using LibMatrix.Utilities.Bot.AppServices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using TestDataGenerator.Bot;
diff --git a/Utilities/LibMatrix.Utilities.Bot/AppServiceConfiguration.cs b/Utilities/LibMatrix.Utilities.Bot/AppServices/AppServiceConfiguration.cs
index afda89e..6dc76f6 100644
--- a/Utilities/LibMatrix.Utilities.Bot/AppServiceConfiguration.cs
+++ b/Utilities/LibMatrix.Utilities.Bot/AppServices/AppServiceConfiguration.cs
@@ -1,24 +1,48 @@
-namespace LibMatrix.Utilities.Bot;
+using System.Text.Json.Serialization;
+
+namespace LibMatrix.Utilities.Bot.AppServices;
public class AppServiceConfiguration {
- public string Id { get; set; } = null!;
- public string? Url { get; set; } = null!;
- public string SenderLocalpart { get; set; } = null!;
- public string AppserviceToken { get; set; } = null!;
- public string HomeserverToken { get; set; } = null!;
- public List<string>? Protocols { get; set; } = null!;
- public bool? RateLimited { get; set; } = null!;
+ [JsonPropertyName("id")]
+ public string Id { get; set; }
+
+ [JsonPropertyName("url")]
+ public string? Url { get; set; }
+
+ [JsonPropertyName("sender_localpart")]
+ public string SenderLocalpart { get; set; }
+
+ [JsonPropertyName("as_token")]
+ public string AppserviceToken { get; set; }
+
+ [JsonPropertyName("hs_token")]
+ public string HomeserverToken { get; set; }
- public AppserviceNamespaces Namespaces { get; set; } = null!;
+ [JsonPropertyName("protocols")]
+ public List<string>? Protocols { get; set; }
+
+ [JsonPropertyName("rate_limited")]
+ public bool? RateLimited { get; set; }
+
+ [JsonPropertyName("namespaces")]
+ public AppserviceNamespaces Namespaces { get; set; }
public class AppserviceNamespaces {
+ [JsonPropertyName("users")]
public List<AppserviceNamespace>? Users { get; set; } = null;
+
+ [JsonPropertyName("aliases")]
public List<AppserviceNamespace>? Aliases { get; set; } = null;
+
+ [JsonPropertyName("rooms")]
public List<AppserviceNamespace>? Rooms { get; set; } = null;
public class AppserviceNamespace {
+ [JsonPropertyName("exclusive")]
public bool Exclusive { get; set; }
- public string Regex { get; set; } = null!;
+
+ [JsonPropertyName("regex")]
+ public string Regex { get; set; }
}
}
diff --git a/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs b/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs
deleted file mode 100644
index 621c1ee..0000000
--- a/Utilities/LibMatrix.Utilities.Bot/BotCommandInstaller.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-using ArcaneLibs;
-using LibMatrix.EventTypes.Spec.State;
-using LibMatrix.Homeservers;
-using LibMatrix.Responses;
-using LibMatrix.Services;
-using LibMatrix.Utilities.Bot.Interfaces;
-using LibMatrix.Utilities.Bot.Services;
-using Microsoft.Extensions.DependencyInjection;
-
-namespace LibMatrix.Utilities.Bot;
-
-public static class BotCommandInstaller {
- public static BotInstaller AddMatrixBot(this IServiceCollection services) {
- return new BotInstaller(services).AddMatrixBot();
- }
-}
-
-public class BotInstaller(IServiceCollection services) {
- public BotInstaller AddMatrixBot() {
- services.AddSingleton<LibMatrixBotConfiguration>();
-
- services.AddScoped<AuthenticatedHomeserverGeneric>(x => {
- var config = x.GetService<LibMatrixBotConfiguration>() ?? throw new Exception("No configuration found!");
- var hsProvider = x.GetService<HomeserverProviderService>() ?? throw new Exception("No homeserver provider found!");
- var hs = hsProvider.GetAuthenticatedWithToken(config.Homeserver, config.AccessToken).Result;
-
- return hs;
- });
-
- return this;
- }
-
- public BotInstaller AddCommandHandler() {
- Console.WriteLine("Adding command handler...");
- services.AddHostedService<CommandListenerHostedService>();
- return this;
- }
-
- public BotInstaller DiscoverAllCommands() {
- foreach (var commandClass in ClassCollector<ICommand>.ResolveFromAllAccessibleAssemblies()) {
- Console.WriteLine($"Adding command {commandClass.Name}");
- services.AddScoped(typeof(ICommand), commandClass);
- }
-
- return this;
- }
- public BotInstaller AddCommands(IEnumerable<Type> commandClasses) {
- foreach (var commandClass in commandClasses) {
- if(!commandClass.IsAssignableTo(typeof(ICommand)))
- throw new Exception($"Type {commandClass.Name} is not assignable to ICommand!");
- Console.WriteLine($"Adding command {commandClass.Name}");
- services.AddScoped(typeof(ICommand), commandClass);
- }
-
- return this;
- }
-
- public BotInstaller WithInviteHandler(Func<InviteHandlerHostedService.InviteEventArgs, Task> inviteHandler) {
- services.AddSingleton(inviteHandler);
- services.AddHostedService<InviteHandlerHostedService>();
- return this;
- }
-
- public BotInstaller WithCommandResultHandler(Func<CommandResult, Task> commandResultHandler) {
- services.AddSingleton(commandResultHandler);
- return this;
- }
-}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.Utilities.Bot/BotServiceInstaller.cs b/Utilities/LibMatrix.Utilities.Bot/BotServiceInstaller.cs
new file mode 100644
index 0000000..ff0bc9e
--- /dev/null
+++ b/Utilities/LibMatrix.Utilities.Bot/BotServiceInstaller.cs
@@ -0,0 +1,98 @@
+using ArcaneLibs;
+using LibMatrix.Homeservers;
+using LibMatrix.Services;
+using LibMatrix.Utilities.Bot.AppServices;
+using LibMatrix.Utilities.Bot.Interfaces;
+using LibMatrix.Utilities.Bot.Services;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace LibMatrix.Utilities.Bot;
+
+public static class BotServiceInstallerExtensions {
+ public static BotServiceInstaller AddMatrixBot(this IServiceCollection services) {
+ return new BotServiceInstaller(services).AddMatrixBot();
+ }
+}
+
+public class BotServiceInstaller(IServiceCollection services) {
+ public BotServiceInstaller AddMatrixBot() {
+ services.AddSingleton<LibMatrixBotConfiguration>();
+
+ services.AddSingleton<AuthenticatedHomeserverGeneric>(x => {
+ var config = x.GetService<LibMatrixBotConfiguration>() ?? throw new Exception("No configuration found!");
+ var hsProvider = x.GetService<HomeserverProviderService>() ?? throw new Exception("No homeserver provider found!");
+
+ if (x.GetService<AppServiceConfiguration>() is AppServiceConfiguration appsvcConfig)
+ config.AccessToken = appsvcConfig.AppserviceToken;
+ else if (Environment.GetEnvironmentVariable("LIBMATRIX_ACCESS_TOKEN_PATH") is string path)
+ config.AccessTokenPath = path;
+
+ if (string.IsNullOrWhiteSpace(config.AccessToken) && string.IsNullOrWhiteSpace(config.AccessTokenPath))
+ throw new Exception("Unable to add bot service without an access token or access token path!");
+
+ if (!string.IsNullOrWhiteSpace(config.AccessTokenPath)) {
+ var token = File.ReadAllText(config.AccessTokenPath);
+ config.AccessToken = token.Trim();
+ }
+
+ var hs = hsProvider.GetAuthenticatedWithToken(config.Homeserver, config.AccessToken).Result;
+
+ return hs;
+ });
+
+ return this;
+ }
+
+ public BotServiceInstaller AddCommandHandler() {
+ Console.WriteLine("Adding command handler...");
+ services.AddSingleton(s => s.GetRequiredService<LibMatrixBotConfiguration>().CommandListener
+ ?? throw new Exception("Command handling is enabled, but configuration is missing the LibMatrixBot:CommandListener configuration section!")
+ );
+ services.AddHostedService<CommandListenerHostedService>();
+ return this;
+ }
+
+ public BotServiceInstaller DiscoverAllCommands() {
+ foreach (var commandClass in ClassCollector<ICommand>.ResolveFromAllAccessibleAssemblies()) {
+ Console.WriteLine($"Adding command {commandClass.Name}");
+ services.AddScoped(typeof(ICommand), commandClass);
+ }
+
+ return this;
+ }
+
+ public BotServiceInstaller AddCommands(IEnumerable<Type> commandClasses) {
+ foreach (var commandClass in commandClasses) {
+ if (!commandClass.IsAssignableTo(typeof(ICommand)))
+ throw new Exception($"Type {commandClass.Name} is not assignable to ICommand!");
+ Console.WriteLine($"Adding command {commandClass.Name}");
+ services.AddScoped(typeof(ICommand), commandClass);
+ }
+
+ return this;
+ }
+
+ public BotServiceInstaller WithCommandResultHandler(Func<CommandResult, Task> commandResultHandler) {
+ services.AddSingleton(commandResultHandler);
+ return this;
+ }
+
+ public BotServiceInstaller WithInviteHandler(Func<RoomInviteContext, Task> inviteHandler) {
+ services.AddSingleton(inviteHandler);
+ services.AddSingleton(s => s.GetRequiredService<LibMatrixBotConfiguration>().InviteListener
+ ?? throw new Exception("Invite handling is enabled, but configuration is missing the LibMatrixBot:InviteListener configuration section!")
+ );
+ services.AddHostedService<InviteHandlerHostedService>();
+ return this;
+ }
+
+ public BotServiceInstaller WithInviteHandler<T>() where T : class, IRoomInviteHandler {
+ services.AddSingleton<T>();
+ services.AddSingleton<Func<RoomInviteContext, Task>>(sp => sp.GetRequiredService<T>().HandleInviteAsync);
+ services.AddSingleton(s => s.GetRequiredService<LibMatrixBotConfiguration>().InviteListener
+ ?? throw new Exception("Invite handling is enabled, but configuration is missing the LibMatrixBot:InviteListener configuration section!")
+ );
+ services.AddHostedService<InviteHandlerHostedService>();
+ return this;
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.Utilities.Bot/Commands/AliassesCommand.cs b/Utilities/LibMatrix.Utilities.Bot/Commands/AliassesCommand.cs
index 5c9c480..9107c4c 100644
--- a/Utilities/LibMatrix.Utilities.Bot/Commands/AliassesCommand.cs
+++ b/Utilities/LibMatrix.Utilities.Bot/Commands/AliassesCommand.cs
@@ -1,4 +1,3 @@
-using System.Collections.Frozen;
using System.Text;
using LibMatrix.EventTypes.Spec;
using LibMatrix.Helpers;
diff --git a/Utilities/LibMatrix.Utilities.Bot/Commands/HelpCommand.cs b/Utilities/LibMatrix.Utilities.Bot/Commands/HelpCommand.cs
index 0abc76b..f29d6e9 100644
--- a/Utilities/LibMatrix.Utilities.Bot/Commands/HelpCommand.cs
+++ b/Utilities/LibMatrix.Utilities.Bot/Commands/HelpCommand.cs
@@ -1,6 +1,3 @@
-using System.Collections.Frozen;
-using System.Text;
-using LibMatrix.EventTypes.Spec;
using LibMatrix.Helpers;
using LibMatrix.Utilities.Bot.Interfaces;
using Microsoft.Extensions.DependencyInjection;
@@ -9,7 +6,7 @@ namespace LibMatrix.Utilities.Bot.Commands;
public class HelpCommand(IServiceProvider services) : ICommand {
public string Name { get; } = "help";
- public string[]? Aliases { get; } = new[] { "?" };
+ public string[]? Aliases { get; } = ["?"];
public string Description { get; } = "Displays this help message";
public bool Unlisted { get; }
diff --git a/Utilities/LibMatrix.Utilities.Bot/Commands/PingCommand.cs b/Utilities/LibMatrix.Utilities.Bot/Commands/PingCommand.cs
index 76e48f5..ff41b70 100644
--- a/Utilities/LibMatrix.Utilities.Bot/Commands/PingCommand.cs
+++ b/Utilities/LibMatrix.Utilities.Bot/Commands/PingCommand.cs
@@ -5,9 +5,29 @@ namespace LibMatrix.Utilities.Bot.Commands;
public class PingCommand : ICommand {
public string Name { get; } = "ping";
- public string[]? Aliases { get; } = [ ];
+ public string[]? Aliases { get; } = [];
public string Description { get; } = "Pong!";
public bool Unlisted { get; }
- public async Task Invoke(CommandContext ctx) => await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: "pong!"));
+ public async Task Invoke(CommandContext ctx) {
+ var latency = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - ctx.MessageEvent.OriginServerTs;
+ await ctx.Room.SendMessageEventAsync(new RoomMessageEventContent(body: $"Pong! ({latency} ms)") {
+ AdditionalData = new() {
+ // maubot ping compatibility
+ ["pong"] = new {
+ ms = latency,
+ from = ctx.Homeserver.ServerName,
+ ping = ctx.MessageEvent.EventId
+ },
+ },
+ RelatesTo = new() {
+ RelationType = "xyz.maubot.pong",
+ EventId = ctx.MessageEvent.EventId,
+ AdditionalData = new() {
+ ["ms"] = latency!,
+ ["from"] = ctx.Homeserver.ServerName
+ }
+ }
+ });
+ }
}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.Utilities.Bot/Configuration/CommandListenerConfiguration.cs b/Utilities/LibMatrix.Utilities.Bot/Configuration/CommandListenerConfiguration.cs
new file mode 100644
index 0000000..e3026cd
--- /dev/null
+++ b/Utilities/LibMatrix.Utilities.Bot/Configuration/CommandListenerConfiguration.cs
@@ -0,0 +1,24 @@
+using System.Diagnostics.CodeAnalysis;
+using LibMatrix.Filters;
+
+namespace LibMatrix.Utilities.Bot.Configuration;
+
+[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global", Justification = "Configuration")]
+[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global", Justification = "Configuration")]
+public class CommandListenerSyncConfiguration {
+ // public SyncFilter? Filter { get; set; }
+ public TimeSpan? MinimumSyncTime { get; set; }
+ public int? Timeout { get; set; }
+ public string? Presence { get; set; }
+ // public bool InitialSyncOnStartup { get; set; }
+}
+
+[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global", Justification = "Configuration")]
+[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global", Justification = "Configuration")]
+public class CommandListenerConfiguration {
+ public CommandListenerSyncConfiguration SyncConfiguration { get; set; } = new();
+
+ public required List<string> Prefixes { get; set; }
+ public bool MentionPrefix { get; set; }
+ public bool SelfCommandsOnly { get; set; }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.Utilities.Bot/Configuration/InviteListenerConfiguration.cs b/Utilities/LibMatrix.Utilities.Bot/Configuration/InviteListenerConfiguration.cs
new file mode 100644
index 0000000..7fce400
--- /dev/null
+++ b/Utilities/LibMatrix.Utilities.Bot/Configuration/InviteListenerConfiguration.cs
@@ -0,0 +1,20 @@
+using System.Diagnostics.CodeAnalysis;
+using LibMatrix.Filters;
+
+namespace LibMatrix.Utilities.Bot.Configuration;
+
+[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global", Justification = "Configuration")]
+[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global", Justification = "Configuration")]
+public class InviteListenerSyncConfiguration {
+ public SyncFilter? Filter { get; set; }
+ public TimeSpan? MinimumSyncTime { get; set; }
+ public int? Timeout { get; set; }
+ public string? Presence { get; set; }
+ public bool InitialSyncOnStartup { get; set; }
+}
+
+[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global", Justification = "Configuration")]
+[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global", Justification = "Configuration")]
+public class InviteListenerConfiguration {
+ public InviteListenerSyncConfiguration SyncConfiguration { get; set; } = new();
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.Utilities.Bot/Configuration/LibMatrixBotConfiguration.cs b/Utilities/LibMatrix.Utilities.Bot/Configuration/LibMatrixBotConfiguration.cs
new file mode 100644
index 0000000..cd272e0
--- /dev/null
+++ b/Utilities/LibMatrix.Utilities.Bot/Configuration/LibMatrixBotConfiguration.cs
@@ -0,0 +1,17 @@
+using LibMatrix.Utilities.Bot.Configuration;
+using Microsoft.Extensions.Configuration;
+
+namespace LibMatrix.Utilities.Bot;
+
+public class LibMatrixBotConfiguration {
+ public LibMatrixBotConfiguration(IConfiguration config) => config.GetRequiredSection("LibMatrixBot").Bind(this);
+ public string Homeserver { get; set; }
+ public string? AccessToken { get; set; }
+ public string? AccessTokenPath { get; set; }
+ public string? LogRoom { get; set; }
+
+ public string? Presence { get; set; }
+
+ public InviteListenerConfiguration? InviteListener { get; set; }
+ public CommandListenerConfiguration? CommandListener { get; set; }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs b/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs
index c6abde2..71ecbed 100644
--- a/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs
+++ b/Utilities/LibMatrix.Utilities.Bot/Interfaces/CommandContext.cs
@@ -1,5 +1,6 @@
using LibMatrix.EventTypes.Spec;
using LibMatrix.Homeservers;
+using LibMatrix.Responses;
using LibMatrix.RoomTypes;
namespace LibMatrix.Utilities.Bot.Interfaces;
diff --git a/Utilities/LibMatrix.Utilities.Bot/Interfaces/ICommand.cs b/Utilities/LibMatrix.Utilities.Bot/Interfaces/ICommand.cs
index 941d69e..7b4afa9 100644
--- a/Utilities/LibMatrix.Utilities.Bot/Interfaces/ICommand.cs
+++ b/Utilities/LibMatrix.Utilities.Bot/Interfaces/ICommand.cs
@@ -1,7 +1,3 @@
-using System.Collections.Frozen;
-using System.Collections.Immutable;
-using Microsoft.Extensions.DependencyInjection;
-
namespace LibMatrix.Utilities.Bot.Interfaces;
public interface ICommand {
diff --git a/Utilities/LibMatrix.Utilities.Bot/Interfaces/IRoomInviteHandler.cs b/Utilities/LibMatrix.Utilities.Bot/Interfaces/IRoomInviteHandler.cs
new file mode 100644
index 0000000..a25ca4a
--- /dev/null
+++ b/Utilities/LibMatrix.Utilities.Bot/Interfaces/IRoomInviteHandler.cs
@@ -0,0 +1,5 @@
+namespace LibMatrix.Utilities.Bot.Interfaces;
+
+public interface IRoomInviteHandler {
+ public Task HandleInviteAsync(RoomInviteContext invite);
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.Utilities.Bot/Interfaces/RoomInviteContext.cs b/Utilities/LibMatrix.Utilities.Bot/Interfaces/RoomInviteContext.cs
new file mode 100644
index 0000000..380c1c7
--- /dev/null
+++ b/Utilities/LibMatrix.Utilities.Bot/Interfaces/RoomInviteContext.cs
@@ -0,0 +1,71 @@
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
+using LibMatrix.Homeservers;
+using LibMatrix.Responses;
+
+namespace LibMatrix.Utilities.Bot.Interfaces;
+
+public class RoomInviteContext {
+ public required string RoomId { get; init; }
+ public required AuthenticatedHomeserverGeneric Homeserver { get; init; }
+ public required StateEventResponse MemberEvent { get; init; }
+ public required SyncResponse.RoomsDataStructure.InvitedRoomDataStructure InviteData { get; init; }
+
+ public async Task<string> TryGetInviterNameAsync() {
+ var name = InviteData.InviteState?.Events?
+ .FirstOrDefault(evt => evt is { Type: RoomMemberEventContent.EventId } && evt.StateKey == MemberEvent.Sender)?
+ .ContentAs<RoomMemberEventContent>()?.DisplayName;
+
+ if (!string.IsNullOrWhiteSpace(name))
+ return name;
+
+ try {
+ await Homeserver.GetProfileAsync(MemberEvent.Sender!);
+ }
+ catch {
+ //ignored
+ }
+
+ return MemberEvent.Sender!;
+ }
+
+ public async Task<string> TryGetRoomNameAsync() {
+ // try to get room name from invite state
+ var name = InviteData.InviteState?.Events?
+ .FirstOrDefault(evt => evt is { Type: RoomNameEventContent.EventId, StateKey: "" })?
+ .ContentAs<RoomNameEventContent>()?.Name;
+
+ if (!string.IsNullOrWhiteSpace(name))
+ return name;
+
+ // try to get room alias
+ var alias = InviteData.InviteState?.Events?
+ .FirstOrDefault(evt => evt is { Type: RoomCanonicalAliasEventContent.EventId, StateKey: "" })?
+ .ContentAs<RoomCanonicalAliasEventContent>()?.Alias;
+
+ if (!string.IsNullOrWhiteSpace(alias))
+ return alias;
+
+ // try to get room name via public previews
+ try {
+ name = await Homeserver.GetRoom(RoomId).GetNameOrFallbackAsync();
+ if (name != RoomId && !string.IsNullOrWhiteSpace(name))
+ return name;
+ }
+ catch {
+ //ignored
+ }
+
+ // fallback to room alias via public previews
+ try {
+ alias = (await Homeserver.GetRoom(RoomId).GetCanonicalAliasAsync())?.Alias;
+ if (!string.IsNullOrWhiteSpace(alias))
+ return alias;
+ }
+ catch {
+ //ignored
+ }
+
+ // fall back to room ID
+ return RoomId;
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.Utilities.Bot/LibMatrix.Utilities.Bot.csproj b/Utilities/LibMatrix.Utilities.Bot/LibMatrix.Utilities.Bot.csproj
index 6e67373..bbb0a65 100644
--- a/Utilities/LibMatrix.Utilities.Bot/LibMatrix.Utilities.Bot.csproj
+++ b/Utilities/LibMatrix.Utilities.Bot/LibMatrix.Utilities.Bot.csproj
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <TargetFramework>net8.0</TargetFramework>
+ <TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
@@ -12,9 +12,9 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
- <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0"/>
- <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
+ <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.1" />
+ <PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.1" />
+ <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.1" />
</ItemGroup>
diff --git a/Utilities/LibMatrix.Utilities.Bot/LibMatrixBotConfiguration.cs b/Utilities/LibMatrix.Utilities.Bot/LibMatrixBotConfiguration.cs
deleted file mode 100644
index 245442f..0000000
--- a/Utilities/LibMatrix.Utilities.Bot/LibMatrixBotConfiguration.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using LibMatrix.Utilities.Bot.Interfaces;
-using Microsoft.Extensions.Configuration;
-
-namespace LibMatrix.Utilities.Bot;
-
-public class LibMatrixBotConfiguration {
- public LibMatrixBotConfiguration(IConfiguration config) => config.GetRequiredSection("LibMatrixBot").Bind(this);
- public string Homeserver { get; set; }
- public string AccessToken { get; set; }
- public List<string> Prefixes { get; set; }
- public bool MentionPrefix { get; set; }
- public string? LogRoom { get; set; }
-}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs b/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs
index 601e598..d0a93a4 100644
--- a/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs
+++ b/Utilities/LibMatrix.Utilities.Bot/Services/CommandListenerHostedService.cs
@@ -1,10 +1,11 @@
-using System.Reflection.Metadata;
+using System.Collections.Frozen;
using ArcaneLibs.Extensions;
using LibMatrix.EventTypes.Spec;
-using LibMatrix.EventTypes.Spec.State;
+using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Filters;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
+using LibMatrix.Utilities.Bot.Configuration;
using LibMatrix.Utilities.Bot.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
@@ -12,93 +13,119 @@ using Microsoft.Extensions.Logging;
namespace LibMatrix.Utilities.Bot.Services;
-public class CommandListenerHostedService : IHostedService {
- private readonly AuthenticatedHomeserverGeneric _hs;
- private readonly ILogger<CommandListenerHostedService> _logger;
- private readonly IEnumerable<ICommand> _commands;
- private readonly LibMatrixBotConfiguration _config;
- private readonly Func<CommandResult, Task>? _commandResultHandler;
+public class CommandListenerHostedService(
+ AuthenticatedHomeserverGeneric hs,
+ ILogger<CommandListenerHostedService> logger,
+ IServiceProvider services,
+ LibMatrixBotConfiguration botConfig,
+ CommandListenerConfiguration config,
+ Func<CommandResult, Task>? commandResultHandler = null
+)
+ : IHostedService {
+ private FrozenSet<ICommand> _commands = null!;
private Task? _listenerTask;
-
- public CommandListenerHostedService(AuthenticatedHomeserverGeneric hs, ILogger<CommandListenerHostedService> logger, IServiceProvider services,
- LibMatrixBotConfiguration config, Func<CommandResult, Task>? commandResultHandler = null) {
- logger.LogInformation("{} instantiated!", GetType().Name);
- _hs = hs;
- _logger = logger;
- _config = config;
- _commandResultHandler = commandResultHandler;
- _logger.LogInformation("Getting commands...");
- _commands = services.GetServices<ICommand>();
- _logger.LogInformation("Got {} commands!", _commands.Count());
- }
+ private readonly CancellationTokenSource _cts = new();
+ private long _startupTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
/// <summary>Triggered when the application host is ready to start the service.</summary>
/// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
public Task StartAsync(CancellationToken cancellationToken) {
- _listenerTask = Run(cancellationToken);
- _logger.LogInformation("Command listener started (StartAsync)!");
+ _listenerTask = Run(_cts.Token);
+ logger.LogInformation("Getting commands...");
+ _commands = services.GetServices<ICommand>().ToFrozenSet();
+ logger.LogInformation("Got {} commands!", _commands.Count);
+ logger.LogInformation("Command listener started (StartAsync)!");
return Task.CompletedTask;
}
private async Task? Run(CancellationToken cancellationToken) {
- _logger.LogInformation("Starting command listener!");
- var filter = await _hs.NamedCaches.FilterCache.GetOrSetValueAsync("gay.rory.libmatrix.utilities.bot.command_listener_syncfilter.dev2", new SyncFilter() {
- AccountData = new SyncFilter.EventFilter(notTypes: ["*"], limit: 1),
- Presence = new SyncFilter.EventFilter(notTypes: ["*"]),
- Room = new SyncFilter.RoomFilter() {
- AccountData = new SyncFilter.RoomFilter.StateFilter(notTypes: ["*"]),
- Ephemeral = new SyncFilter.RoomFilter.StateFilter(notTypes: ["*"]),
- State = new SyncFilter.RoomFilter.StateFilter(notTypes: ["*"]),
- Timeline = new SyncFilter.RoomFilter.StateFilter(types: ["m.room.message"], notSenders: [_hs.WhoAmI.UserId]),
- }
- });
+ logger.LogInformation("Starting command listener!");
+ var filter = await hs.NamedCaches.FilterCache.GetOrSetValueAsync("gay.rory.libmatrix.utilities.bot.command_listener_syncfilter.dev3" + (config.SelfCommandsOnly),
+ new SyncFilter() {
+ AccountData = new SyncFilter.EventFilter(notTypes: ["*"], limit: 1),
+ Presence = new SyncFilter.EventFilter(notTypes: ["*"]),
+ Room = new SyncFilter.RoomFilter() {
+ AccountData = new SyncFilter.RoomFilter.StateFilter(notTypes: ["*"]),
+ Ephemeral = new SyncFilter.RoomFilter.StateFilter(notTypes: ["*"]),
+ State = new SyncFilter.RoomFilter.StateFilter(notTypes: ["*"]),
+ Timeline = new SyncFilter.RoomFilter.StateFilter(types: ["m.room.message"],
+ notSenders: config.SelfCommandsOnly ? null : [hs.WhoAmI.UserId],
+ senders: config.SelfCommandsOnly ? [hs.WhoAmI.UserId] : null
+ ),
+ }
+ });
- var syncHelper = new SyncHelper(_hs, _logger) {
- Timeout = 300_000,
- FilterId = filter
+ var syncHelper = new SyncHelper(hs, logger) {
+ FilterId = filter,
+ Timeout = config.SyncConfiguration.Timeout ?? 30_000,
+ MinimumDelay = config.SyncConfiguration.MinimumSyncTime ?? TimeSpan.Zero,
+ SetPresence = config.SyncConfiguration.Presence ?? botConfig.Presence,
};
- syncHelper.TimelineEventHandlers.Add(async @event => {
- try {
- var room = _hs.GetRoom(@event.RoomId);
- // _logger.LogInformation(eventResponse.ToJson(indent: false));
- if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message })
- if (message is { MessageType: "m.text" }) {
- var usedPrefix = await GetUsedPrefix(@event);
- if (usedPrefix is null) return;
- var res = await InvokeCommand(@event, usedPrefix);
- await (_commandResultHandler?.Invoke(res) ?? HandleResult(res));
+ syncHelper.SyncReceivedHandlers.Add(async sync => {
+ logger.LogInformation("Sync received!");
+ foreach (var roomResp in sync.Rooms?.Join ?? []) {
+ if (roomResp.Value.Timeline?.Events is null) continue;
+ foreach (var @event in roomResp.Value.Timeline.Events) {
+ @event.RoomId = roomResp.Key;
+ if (config.SelfCommandsOnly && @event.Sender != hs.WhoAmI.UserId) continue;
+ if (@event.OriginServerTs < _startupTime) continue; // ignore events older than startup time
+
+ try {
+ if (@event is { Type: "m.room.message", TypedContent: RoomMessageEventContent message })
+ if (message is { MessageType: "m.text" }) {
+ var usedPrefix = await GetUsedPrefix(@event);
+ if (usedPrefix is null) return;
+ var res = await InvokeCommand(@event, usedPrefix);
+ await (commandResultHandler?.Invoke(res) ?? HandleResult(res));
+ }
}
- }
- catch (Exception e) {
- _logger.LogError(e, "Error in command listener!");
+ catch (Exception e) {
+ logger.LogError(e, "Error in command listener!");
+ Console.WriteLine(@event.ToJson(ignoreNull: false, indent: true));
+ var fakeResult = new CommandResult() {
+ Result = CommandResult.CommandResultType.Failure_Exception,
+ Exception = e,
+ Success = false,
+ Context = new() {
+ Homeserver = hs,
+ CommandName = "[CommandListener.SyncHandler]",
+ Room = hs.GetRoom(roomResp.Key),
+ Args = [],
+ MessageEvent = @event
+ }
+ };
+ await (commandResultHandler?.Invoke(fakeResult) ?? HandleResult(fakeResult));
+ }
+ }
}
});
- await syncHelper.RunSyncLoopAsync(cancellationToken: cancellationToken);
+
+ await syncHelper.RunSyncLoopAsync(cancellationToken: _cts.Token);
}
/// <summary>Triggered when the application host is performing a graceful shutdown.</summary>
/// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
public async Task StopAsync(CancellationToken cancellationToken) {
- _logger.LogInformation("Shutting down command listener!");
+ logger.LogInformation("Shutting down command listener!");
if (_listenerTask is null) {
- _logger.LogError("Could not shut down command listener task because it was null!");
+ logger.LogError("Could not shut down command listener task because it was null!");
return;
}
- await _listenerTask.WaitAsync(cancellationToken);
+ await _cts.CancelAsync();
}
private async Task<string?> GetUsedPrefix(StateEventResponse evt) {
var messageContent = evt.TypedContent as RoomMessageEventContent;
var message = messageContent!.BodyWithoutReplyFallback;
- var prefix = _config.Prefixes.OrderByDescending(x => x.Length).FirstOrDefault(message.StartsWith);
- if (prefix is null && _config.MentionPrefix) {
- var profile = await _hs.GetProfileAsync(_hs.WhoAmI.UserId);
- var roomProfile = await _hs.GetRoom(evt.RoomId!).GetStateAsync<RoomMemberEventContent>(RoomMemberEventContent.EventId, _hs.WhoAmI.UserId);
- if (message.StartsWith(_hs.WhoAmI.UserId + ": ")) prefix = profile.DisplayName + ": "; // `@bot:server.xyz: `
- else if (message.StartsWith(_hs.WhoAmI.UserId + " ")) prefix = profile.DisplayName + " "; // `@bot:server.xyz `
+ var prefix = config.Prefixes.OrderByDescending(x => x.Length).FirstOrDefault(message.StartsWith);
+ if (prefix is null && config.MentionPrefix) {
+ var profile = await hs.GetProfileAsync(hs.WhoAmI.UserId);
+ var roomProfile = await hs.GetRoom(evt.RoomId!).GetStateAsync<RoomMemberEventContent>(RoomMemberEventContent.EventId, hs.WhoAmI.UserId);
+ if (message.StartsWith(hs.WhoAmI.UserId + ": ")) prefix = profile.DisplayName + ": "; // `@bot:server.xyz: `
+ else if (message.StartsWith(hs.WhoAmI.UserId + " ")) prefix = profile.DisplayName + " "; // `@bot:server.xyz `
else if (!string.IsNullOrWhiteSpace(roomProfile?.DisplayName) && message.StartsWith(roomProfile.DisplayName + ": "))
prefix = roomProfile.DisplayName + ": "; // `local bot: `
else if (!string.IsNullOrWhiteSpace(roomProfile?.DisplayName) && message.StartsWith(roomProfile.DisplayName + " "))
@@ -112,21 +139,27 @@ public class CommandListenerHostedService : IHostedService {
private async Task<CommandResult> InvokeCommand(StateEventResponse evt, string usedPrefix) {
var message = evt.TypedContent as RoomMessageEventContent;
- var room = _hs.GetRoom(evt.RoomId!);
+ var room = hs.GetRoom(evt.RoomId!);
var commandWithoutPrefix = message.BodyWithoutReplyFallback[usedPrefix.Length..].Trim();
+ var usedCommand = _commands
+ .SelectMany<ICommand, string>(x => [x.Name, ..x.Aliases ?? []])
+ .OrderByDescending(x => x.Length)
+ .FirstOrDefault(commandWithoutPrefix.StartsWith);
+ var args =
+ usedCommand == null || commandWithoutPrefix.Length <= usedCommand.Length
+ ? []
+ : commandWithoutPrefix[(usedCommand.Length + 1)..].Split(' ').SelectMany(x => x.Split('\n')).ToArray();
var ctx = new CommandContext {
Room = room,
- MessageEvent = @evt,
- Homeserver = _hs,
- Args = commandWithoutPrefix.Split(' ').Length == 1 ? [] : commandWithoutPrefix.Split(' ')[1..],
- CommandName = commandWithoutPrefix.Split(' ')[0]
+ MessageEvent = evt,
+ Homeserver = hs,
+ Args = args,
+ CommandName = usedCommand ?? commandWithoutPrefix.Split(' ')[0]
};
try {
- var command = _commands.SingleOrDefault(x => x.Name == commandWithoutPrefix.Split(' ')[0] || x.Aliases?.Contains(commandWithoutPrefix.Split(' ')[0]) == true);
+ var command = _commands.SingleOrDefault(x => x.Name == ctx.CommandName || x.Aliases?.Contains(ctx.CommandName) == true);
if (command == null) {
- await room.SendMessageEventAsync(
- new RoomMessageEventContent("m.notice", $"Command \"{ctx.CommandName}\" not found!"));
return new() {
Success = false,
Result = CommandResult.CommandResultType.Failure_InvalidCommand,
diff --git a/Utilities/LibMatrix.Utilities.Bot/Services/InviteListenerHostedService.cs b/Utilities/LibMatrix.Utilities.Bot/Services/InviteListenerHostedService.cs
index 7c5cc44..99491a8 100644
--- a/Utilities/LibMatrix.Utilities.Bot/Services/InviteListenerHostedService.cs
+++ b/Utilities/LibMatrix.Utilities.Bot/Services/InviteListenerHostedService.cs
@@ -1,86 +1,91 @@
-using System.Reflection.Metadata;
-using ArcaneLibs.Extensions;
-using LibMatrix.EventTypes.Spec;
+using System.Diagnostics.CodeAnalysis;
using LibMatrix.Filters;
using LibMatrix.Helpers;
using LibMatrix.Homeservers;
-using LibMatrix.Responses;
+using LibMatrix.Utilities.Bot.Configuration;
using LibMatrix.Utilities.Bot.Interfaces;
-using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace LibMatrix.Utilities.Bot.Services;
-public class InviteHandlerHostedService : IHostedService {
- private readonly AuthenticatedHomeserverGeneric _hs;
- private readonly ILogger<InviteHandlerHostedService> _logger;
- private readonly Func<InviteEventArgs, Task> _inviteHandler;
-
+public class InviteHandlerHostedService(
+ ILogger<InviteHandlerHostedService> logger,
+ AuthenticatedHomeserverGeneric hs,
+ LibMatrixBotConfiguration botConfig,
+ InviteListenerConfiguration config,
+ Func<RoomInviteContext, Task> inviteHandler
+) : IHostedService {
private Task? _listenerTask;
+ private CancellationTokenSource _cts = new();
- public InviteHandlerHostedService(AuthenticatedHomeserverGeneric hs, ILogger<InviteHandlerHostedService> logger,
- Func<InviteEventArgs, Task> inviteHandler) {
- logger.LogInformation("{} instantiated!", GetType().Name);
- _hs = hs;
- _logger = logger;
- _inviteHandler = inviteHandler;
- }
+ private readonly SyncHelper _syncHelper = new(hs, logger) {
+ Timeout = config.SyncConfiguration.Timeout ?? 30_000,
+ MinimumDelay = config.SyncConfiguration.MinimumSyncTime ?? TimeSpan.Zero,
+ SetPresence = config.SyncConfiguration.Presence ?? botConfig.Presence
+ };
/// <summary>Triggered when the application host is ready to start the service.</summary>
/// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
public Task StartAsync(CancellationToken cancellationToken) {
_listenerTask = Run(cancellationToken);
- _logger.LogInformation("Command listener started (StartAsync)!");
return Task.CompletedTask;
}
private async Task? Run(CancellationToken cancellationToken) {
- _logger.LogInformation("Starting invite listener!");
- var filter = await _hs.NamedCaches.FilterCache.GetOrSetValueAsync("gay.rory.libmatrix.utilities.bot.command_listener_syncfilter.dev2", new SyncFilter() {
- AccountData = new SyncFilter.EventFilter(notTypes: ["*"], limit: 1),
- Presence = new SyncFilter.EventFilter(notTypes: ["*"]),
- Room = new SyncFilter.RoomFilter() {
- AccountData = new SyncFilter.RoomFilter.StateFilter(notTypes: ["*"]),
- Ephemeral = new SyncFilter.RoomFilter.StateFilter(notTypes: ["*"]),
- State = new SyncFilter.RoomFilter.StateFilter(notTypes: ["*"]),
- Timeline = new SyncFilter.RoomFilter.StateFilter(types: ["m.room.message"], notSenders: [_hs.WhoAmI.UserId]),
- }
- });
+ logger.LogInformation("Starting invite listener!");
+ var nextBatchFile = $"inviteHandler.{hs.WhoAmI.UserId}.{hs.WhoAmI.DeviceId}.nextBatch";
+ if (config.SyncConfiguration.Filter is not null) {
+ _syncHelper.Filter = config.SyncConfiguration.Filter;
+ }
+ else {
+ _syncHelper.FilterId = await hs.NamedCaches.FilterCache.GetOrSetValueAsync("gay.rory.libmatrix.utilities.bot.invite_listener_syncfilter.dev0", new SyncFilter() {
+ AccountData = SyncFilter.EventFilter.Empty,
+ Presence = SyncFilter.EventFilter.Empty,
+ Room = new SyncFilter.RoomFilter {
+ AccountData = SyncFilter.RoomFilter.StateFilter.Empty,
+ Ephemeral = SyncFilter.RoomFilter.StateFilter.Empty,
+ State = SyncFilter.RoomFilter.StateFilter.Empty,
+ Timeline = new SyncFilter.RoomFilter.StateFilter(types: [], notSenders: [hs.WhoAmI.UserId]),
+ IncludeLeave = false
+ }
+ });
+ }
- var syncHelper = new SyncHelper(_hs, _logger) {
- Timeout = 300_000,
- FilterId = filter
- };
- syncHelper.InviteReceivedHandlers.Add(async invite => {
- _logger.LogInformation("Received invite to room {}", invite.Key);
+ if (File.Exists(nextBatchFile) && !config.SyncConfiguration.InitialSyncOnStartup) {
+ _syncHelper.Since = await File.ReadAllTextAsync(nextBatchFile, cancellationToken);
+ }
- var inviteEventArgs = new InviteEventArgs() {
+ _syncHelper.InviteReceivedHandlers.Add(async invite => {
+ logger.LogInformation("Received invite to room {}", invite.Key);
+ var inviteEventArgs = new RoomInviteContext() {
RoomId = invite.Key,
- MemberEvent = invite.Value.InviteState.Events.First(x => x.Type == "m.room.member" && x.StateKey == _hs.WhoAmI.UserId),
- Homeserver = _hs
+ InviteData = invite.Value,
+ MemberEvent = invite.Value.InviteState?.Events?.First(x => x.Type == "m.room.member" && x.StateKey == hs.WhoAmI.UserId)
+ ?? throw new LibMatrixException() {
+ ErrorCode = LibMatrixException.ErrorCodes.M_NOT_FOUND,
+ Error = "Room invite doesn't contain a membership event!"
+ },
+ Homeserver = hs
};
- await _inviteHandler(inviteEventArgs);
+ await inviteHandler(inviteEventArgs);
});
- await syncHelper.RunSyncLoopAsync(cancellationToken: cancellationToken);
+ if (!config.SyncConfiguration.InitialSyncOnStartup)
+ _syncHelper.SyncReceivedHandlers.Add(sync => File.WriteAllTextAsync(nextBatchFile, sync.NextBatch, cancellationToken));
+ await _syncHelper.RunSyncLoopAsync(cancellationToken: _cts.Token);
}
/// <summary>Triggered when the application host is performing a graceful shutdown.</summary>
/// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
public async Task StopAsync(CancellationToken cancellationToken) {
- _logger.LogInformation("Shutting down invite listener!");
+ logger.LogInformation("Shutting down invite listener!");
if (_listenerTask is null) {
- _logger.LogError("Could not shut down invite listener task because it was null!");
+ logger.LogError("Could not shut down invite listener task because it was null!");
return;
}
- await _listenerTask.WaitAsync(cancellationToken);
- }
-
- public class InviteEventArgs {
- public string RoomId { get; set; }
- public StateEventResponse MemberEvent { get; set; }
- public AuthenticatedHomeserverGeneric Homeserver { get; set; }
+ await _cts.CancelAsync();
}
}
\ No newline at end of file
|