about summary refs log tree commit diff
path: root/Tests
diff options
context:
space:
mode:
Diffstat (limited to 'Tests')
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/.gitignore1
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/AuthController.cs69
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/DirectoryController.cs34
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/HEDebug/HEDebugController.cs18
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/KeysController.cs103
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/LegacyController.cs56
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/Media/MediaController.cs99
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomAccountDataController.cs78
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomMembersController.cs79
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomStateController.cs113
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomTimelineController.cs432
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomsController.cs139
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/SyncController.cs272
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/ThirdParty/ThirdPartyController.cs25
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/Users/AccountDataController.cs68
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/Users/FilterController.cs46
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/Users/ProfileController.cs52
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/Users/UserController.cs80
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/VersionsController.cs96
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Controllers/WellKnownController.cs32
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Extensions/EventExtensions.cs24
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.csproj23
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.http6
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Program.cs117
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Properties/launchSettings.json32
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Services/HSEConfiguration.cs57
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Services/MediaStore.cs64
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Services/PaginationTokenResolverService.cs54
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Services/RoomStore.cs308
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Services/TokenService.cs29
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/Services/UserStore.cs250
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/appsettings.Development.json12
-rw-r--r--Tests/LibMatrix.HomeserverEmulator/appsettings.json41
-rw-r--r--Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs91
-rw-r--r--Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs14
-rw-r--r--Tests/LibMatrix.Tests/Config.cs37
-rw-r--r--Tests/LibMatrix.Tests/DataTests/WhoAmITests.cs2
-rw-r--r--Tests/LibMatrix.Tests/Fixtures/TestFixture.cs29
-rw-r--r--Tests/LibMatrix.Tests/LibMatrix.Tests.csproj16
-rw-r--r--Tests/LibMatrix.Tests/Tests/AuthMediaTests.cs11
-rw-r--r--Tests/LibMatrix.Tests/Tests/AuthTests.cs15
-rw-r--r--Tests/LibMatrix.Tests/Tests/CanonicalJsonTests.cs49
-rw-r--r--Tests/LibMatrix.Tests/Tests/HomeserverResolverTests/ClientWellKnownResolverTests.cs41
-rw-r--r--Tests/LibMatrix.Tests/Tests/LegacyHomeserverResolverTests.cs36
-rw-r--r--Tests/LibMatrix.Tests/Tests/RemoteHomeserverTests.cs (renamed from Tests/LibMatrix.Tests/Tests/ResolverTest.cs)39
-rw-r--r--Tests/LibMatrix.Tests/Tests/RoomTests.cs248
-rw-r--r--Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/OtherRoomTests.cs101
-rw-r--r--Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomAvatarTests.cs27
-rw-r--r--Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomNameTests.cs42
-rw-r--r--Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomTopicTests.cs27
-rw-r--r--Tests/LibMatrix.Tests/Tests/RoomTests/RoomEventTests.cs (renamed from Tests/LibMatrix.Tests/Tests/RoomEventTests.cs)60
-rw-r--r--Tests/LibMatrix.Tests/Tests/RoomTests/RoomMembershipTests.cs174
-rw-r--r--Tests/LibMatrix.Tests/Tests/RoomTests/RoomTests.cs316
-rw-r--r--Tests/LibMatrix.Tests/Tests/RoomTests/SpaceTests.cs97
-rw-r--r--Tests/LibMatrix.Tests/Tests/TestCleanup.cs74
-rw-r--r--Tests/TestDataGenerator/Bot/DataFetcher.cs59
-rw-r--r--Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs9
-rw-r--r--Tests/TestDataGenerator/Program.cs27
-rw-r--r--Tests/TestDataGenerator/Properties/launchSettings.json25
-rw-r--r--Tests/TestDataGenerator/TestDataGenerator.csproj32
-rw-r--r--Tests/TestDataGenerator/appsettings.Development.json18
-rw-r--r--Tests/TestDataGenerator/appsettings.json9
62 files changed, 1077 insertions, 3557 deletions
diff --git a/Tests/LibMatrix.HomeserverEmulator/.gitignore b/Tests/LibMatrix.HomeserverEmulator/.gitignore
deleted file mode 100644

index 8fce603..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/.gitignore +++ /dev/null
@@ -1 +0,0 @@ -data/ diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/AuthController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/AuthController.cs deleted file mode 100644
index 66548e2..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/AuthController.cs +++ /dev/null
@@ -1,69 +0,0 @@ -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 { - [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)); - - var user = await userStore.GetUserById(request.Identifier.User); - if (user is null) { - user = await userStore.CreateUser(request.Identifier.User); - } - - return user.Login(); - } - - [HttpGet("login")] - public async Task<LoginFlowsResponse> GetLoginFlows() { - return new LoginFlowsResponse { - Flows = ((string[]) [ - "m.login.password", - "m.login.recaptcha", - "m.login.sso", - "m.login.email.identity", - "m.login.msisdn", - "m.login.dummy", - "m.login.registration_token", - ]).Select(x => new LoginFlowsResponse.LoginFlow { Type = x }).ToList() - }; - } - - [HttpPost("logout")] - public async Task<object> Logout() { - 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" - }; - - if (!user.AccessTokens.ContainsKey(token)) - throw new MatrixException() { - ErrorCode = MatrixException.ErrorCodes.M_NOT_FOUND, - Error = "Token not found" - }; - - user.AccessTokens.Remove(token); - return new { }; - } -} - -public class LoginFlowsResponse { - public required List<LoginFlow> Flows { get; set; } - - public class LoginFlow { - public required string Type { get; set; } - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/DirectoryController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/DirectoryController.cs deleted file mode 100644
index 52d5932..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/DirectoryController.cs +++ /dev/null
@@ -1,34 +0,0 @@ -using System.Text.Json.Nodes; -using System.Text.Json.Serialization; -using LibMatrix.EventTypes.Spec.State; -using LibMatrix.HomeserverEmulator.Services; -using LibMatrix.Homeservers; -using LibMatrix.Responses; -using LibMatrix.Services; -using Microsoft.AspNetCore.Mvc; - -namespace LibMatrix.HomeserverEmulator.Controllers; - -[ApiController] -[Route("/_matrix/")] -public class DirectoryController(ILogger<DirectoryController> logger, RoomStore roomStore) : ControllerBase { - [HttpGet("client/v3/directory/room/{alias}")] - public async Task<AliasResult> GetRoomAliasV3(string alias) { - var match = roomStore._rooms.FirstOrDefault(x => - x.State.Any(y => y.Type == RoomCanonicalAliasEventContent.EventId && y.StateKey == "" && y.RawContent?["alias"]?.ToString() == alias)); - - if (match == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - var servers = match.State.Where(x => x.Type == RoomMemberEventContent.EventId && x.RawContent?["membership"]?.ToString() == "join") - .Select(x => x.StateKey!.Split(':', 2)[1]).ToList(); - - return new() { - RoomId = match.RoomId, - Servers = servers - }; - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/HEDebug/HEDebugController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/HEDebug/HEDebugController.cs deleted file mode 100644
index 9e0c17c..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/HEDebug/HEDebugController.cs +++ /dev/null
@@ -1,18 +0,0 @@ -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/Tests/LibMatrix.HomeserverEmulator/Controllers/KeysController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/KeysController.cs deleted file mode 100644
index 7898a8c..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/KeysController.cs +++ /dev/null
@@ -1,103 +0,0 @@ -// using System.Security.Cryptography; -// using System.Text.Json.Nodes; -// using System.Text.Json.Serialization; -// 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 KeysController(ILogger<KeysController> logger, TokenService tokenService, UserStore userStore) : ControllerBase { -// [HttpGet("room_keys/version")] -// public async Task<RoomKeysResponse> GetRoomKeys() { -// 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" -// }; -// -// if (user.RoomKeys is not { Count: > 0 }) -// throw new MatrixException() { -// ErrorCode = "M_NOT_FOUND", -// Error = "No keys found" -// }; -// -// return user.RoomKeys.Values.Last(); -// } -// -// [HttpPost("room_keys/version")] -// public async Task<RoomKeysResponse> UploadRoomKeys(RoomKeysRequest 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" -// }; -// -// var roomKeys = new RoomKeysResponse { -// Version = Guid.NewGuid().ToString(), -// Etag = Guid.NewGuid().ToString(), -// Algorithm = request.Algorithm, -// AuthData = request.AuthData -// }; -// user.RoomKeys.Add(roomKeys.Version, roomKeys); -// return roomKeys; -// } -// -// [HttpPost("keys/device_signing/upload")] -// public async Task<object> UploadDeviceSigning(JsonObject 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 { }; -// } -// } -// -// public class DeviceSigningRequest { -// public CrossSigningKey? MasterKey { get; set; } -// public CrossSigningKey? SelfSigningKey { get; set; } -// public CrossSigningKey? UserSigningKey { get; set; } -// -// public class CrossSigningKey { -// [JsonPropertyName("keys")] -// public Dictionary<string, string> Keys { get; set; } -// -// [JsonPropertyName("signatures")] -// public Dictionary<string, Dictionary<string, string>> Signatures { get; set; } -// -// [JsonPropertyName("usage")] -// public List<string> Usage { get; set; } -// -// [JsonPropertyName("user_id")] -// public string UserId { get; set; } -// } -// } \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/LegacyController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/LegacyController.cs deleted file mode 100644
index 1fb427e..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/LegacyController.cs +++ /dev/null
@@ -1,56 +0,0 @@ -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.HomeserverEmulator.Services; -using LibMatrix.Responses; -using LibMatrix.Services; -using Microsoft.AspNetCore.Mvc; - -namespace LibMatrix.HomeserverEmulator.Controllers; - -[ApiController] -[Route("/_matrix/client/{version}/")] -public class LegacyController(ILogger<LegacyController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore) : ControllerBase { - [HttpGet("rooms/{roomId}/initialSync")] - [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<object> Sync([FromRoute] string roomId, [FromQuery] int limit = 20) { - var sw = Stopwatch.StartNew(); - var token = tokenService.GetAccessTokenOrNull(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" - }; - var room = roomStore.GetRoomById(roomId); - if (room is null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found." - }; - var accountData = room.AccountData.GetOrCreate(user.UserId, _ => []); - var membership = room.State.FirstOrDefault(x => x.Type == "m.room.member" && x.StateKey == user.UserId); - var timelineChunk = room.Timeline.TakeLast(limit).ToList(); - return new { - account_data = accountData, - membership = (membership?.TypedContent as RoomMemberEventContent)?.Membership ?? "leave", - room_id = room.RoomId, - state = room.State.ToList(), - visibility = "public", - messages = new PaginatedChunkedStateEventResponse() { - Chunk = timelineChunk, - End = timelineChunk.Last().EventId, - Start = timelineChunk.Count >= limit ? timelineChunk.First().EventId : null - } - }; - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/Media/MediaController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/Media/MediaController.cs deleted file mode 100644
index 7899ada..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/Media/MediaController.cs +++ /dev/null
@@ -1,99 +0,0 @@ -using System.Text.Json.Nodes; -using System.Text.RegularExpressions; -using ArcaneLibs.Collections; -using LibMatrix.HomeserverEmulator.Services; -using LibMatrix.Services; -using Microsoft.AspNetCore.Mvc; - -namespace LibMatrix.HomeserverEmulator.Controllers.Media; - -[ApiController] -[Route("/_matrix/media/{version}/")] -public class MediaController( - ILogger<MediaController> logger, - TokenService tokenService, - UserStore userStore, - 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) { - var token = tokenService.GetAccessTokenOrNull(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" - }; - - var mediaId = Guid.NewGuid().ToString(); - var media = new { - content_uri = $"mxc://{tokenService.GenerateServerName(HttpContext)}/{mediaId}" - }; - return media; - } - - [HttpGet("download/{serverName}/{mediaId}")] - public async Task DownloadMedia(string serverName, string mediaId) { - var stream = await DownloadRemoteMedia(serverName, mediaId); - await stream.CopyToAsync(Response.Body); - } - - [HttpGet("thumbnail/{serverName}/{mediaId}")] - public async Task DownloadThumbnail(string serverName, string mediaId) { - await DownloadMedia(serverName, mediaId); - } - - [HttpGet("preview_url")] - public async Task<JsonObject> GetPreviewUrl([FromQuery] string url) { - JsonObject data = new(); - - using var hc = new HttpClient(); - using var response = await hc.GetAsync(url); - var doc = await response.Content.ReadAsStringAsync(); - var match = Regex.Match(doc, "<meta property=\"(.*?)\" content=\"(.*?)\""); - - while (match.Success) { - data[match.Groups[1].Value] = match.Groups[2].Value; - match = match.NextMatch(); - } - - return data; - } - - private async Task<Stream> DownloadRemoteMedia(string serverName, string mediaId) { - 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}"); - if (mediaUrl is null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Media not found" - }; - using var client = new HttpClient(); - var stream = await client.GetStreamAsync(mediaUrl); - 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}"); - if (mediaUrl is null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Media not found" - }; - using var client = new HttpClient(); - return await client.GetStreamAsync(mediaUrl); - } - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomAccountDataController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomAccountDataController.cs deleted file mode 100644
index bac803f..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomAccountDataController.cs +++ /dev/null
@@ -1,78 +0,0 @@ -using System.Text.Json.Serialization; -using LibMatrix.HomeserverEmulator.Services; -using Microsoft.AspNetCore.Mvc; - -namespace LibMatrix.HomeserverEmulator.Controllers.Rooms; - -[ApiController] -[Route("/_matrix/client/{version}/rooms/{roomId}")] -public class RoomAccountDataController(ILogger<RoomAccountDataController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore) : ControllerBase { - [HttpPost("read_markers")] - public async Task<object> SetReadMarkers(string roomId, [FromBody] ReadMarkersData data) { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token); - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - if (!room.JoinedMembers.Any(x => x.StateKey == user.UserId)) - throw new MatrixException() { - ErrorCode = "M_FORBIDDEN", - Error = "User is not in the room" - }; - - if (!room.ReadMarkers.ContainsKey(user.UserId)) - room.ReadMarkers[user.UserId] = new(); - - if (data.FullyRead != null) - room.ReadMarkers[user.UserId].FullyRead = data.FullyRead; - if (data.Read != null) - room.ReadMarkers[user.UserId].Read = data.Read; - if (data.ReadPrivate != null) - room.ReadMarkers[user.UserId].ReadPrivate = data.ReadPrivate; - - if (!room.AccountData.ContainsKey(user.UserId)) - room.AccountData[user.UserId] = new(); - - room.AccountData[user.UserId].Add(new StateEventResponse() { - Type = "m.fully_read", - StateKey = user.UserId, - RawContent = new() { - ["event_id"] = data.FullyRead - } - }); - - room.AccountData[user.UserId].Add(new StateEventResponse() { - Type = "m.read", - StateKey = user.UserId, - RawContent = new() { - ["event_id"] = data.Read - } - }); - - room.AccountData[user.UserId].Add(new StateEventResponse() { - Type = "m.read.private", - StateKey = user.UserId, - RawContent = new() { - ["event_id"] = data.ReadPrivate - } - }); - - return data; - } -} - -public class ReadMarkersData { - [JsonPropertyName("m.fully_read")] - public string? FullyRead { get; set; } - - [JsonPropertyName("m.read")] - public string? Read { get; set; } - - [JsonPropertyName("m.read.private")] - public string? ReadPrivate { get; set; } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomMembersController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomMembersController.cs deleted file mode 100644
index 7d735f7..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomMembersController.cs +++ /dev/null
@@ -1,79 +0,0 @@ -using LibMatrix.EventTypes.Spec.State; -using LibMatrix.HomeserverEmulator.Services; -using Microsoft.AspNetCore.Mvc; - -namespace LibMatrix.HomeserverEmulator.Controllers.Rooms; - -[ApiController] -[Route("/_matrix/client/{version}/rooms/{roomId}/")] -public class RoomMembersController( - ILogger<RoomMembersController> logger, - TokenService tokenService, - UserStore userStore, - RoomStore roomStore, - PaginationTokenResolverService paginationTokenResolver) : ControllerBase { - [HttpGet("members")] - public async Task<List<StateEventResponse>> GetMembers(string roomId, string? at = null, string? membership = null, string? not_membership = null) { - var token = tokenService.GetAccessTokenOrNull(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" - }; - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - var members = room.Timeline.Where(x => x.Type == "m.room.member" && x.StateKey != null).ToList(); - - if (membership != null) - members = members.Where(x => (x.TypedContent as RoomMemberEventContent)?.Membership == membership).ToList(); - - if (not_membership != null) - members = members.Where(x => (x.TypedContent as RoomMemberEventContent)?.Membership != not_membership).ToList(); - - if (at != null) { - StateEventResponse? evt = null; - if (at.StartsWith('$')) - evt = await paginationTokenResolver.ResolveTokenToEvent(at, room); - - if (evt is null) { - var time = await paginationTokenResolver.ResolveTokenToTimestamp(at); - evt = room.Timeline.LastOrDefault(x => x.OriginServerTs <= time); - if (evt is null) { - logger.LogWarning("Sent empty list of members for room {roomId} at {at}, because there were no events at this time!", roomId, at); - return []; - } - } - else if (!room.Timeline.Contains(evt)) { - evt = room.Timeline.LastOrDefault(x => x.OriginServerTs <= evt.OriginServerTs); - if (evt is null) { - logger.LogWarning("Sent empty list of members for room {roomId} at {at}, because there were no events at this time!", roomId, at); - return []; - } - } - - // evt = room.Timeline.FirstOrDefault(x => x.EventId == at); - if (evt == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Event not found" - }; - - members = members.Where(x => x.OriginServerTs <= evt.OriginServerTs).ToList(); - } - - return members; - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomStateController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomStateController.cs deleted file mode 100644
index 74c70a3..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomStateController.cs +++ /dev/null
@@ -1,113 +0,0 @@ -using System.Collections.Frozen; -using System.Text.Json.Nodes; -using LibMatrix.HomeserverEmulator.Extensions; -using LibMatrix.HomeserverEmulator.Services; -using Microsoft.AspNetCore.Mvc; - -namespace LibMatrix.HomeserverEmulator.Controllers.Rooms; - -[ApiController] -[Route("/_matrix/client/{version}/rooms/{roomId}/state")] -public class RoomStateController(ILogger<RoomStateController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore) : ControllerBase { - [HttpGet("")] - public async Task<FrozenSet<StateEventResponse>> GetState(string roomId) { - var token = tokenService.GetAccessTokenOrNull(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" - }; - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - return room.State; - } - - [HttpGet("{eventType}")] - public async Task<object?> GetState(string roomId, string eventType, [FromQuery] string format = "client") { - return await GetState(roomId, eventType, "", format); - } - - [HttpGet("{eventType}/{stateKey}")] - public async Task<object?> GetState(string roomId, string eventType, string stateKey, [FromQuery] string format = "client") { - var token = tokenService.GetAccessTokenOrNull(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" - }; - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - var stateEvent = room.State.FirstOrDefault(x => x.Type == eventType && x.StateKey == stateKey); - if (stateEvent == null) { - Console.WriteLine($"Event not found in room {roomId} matching {eventType}/{stateKey}"); - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Event not found" - }; - } - - // return stateEvent; - return format == "event" ? stateEvent : stateEvent.RawContent; - } - - [HttpPut("{eventType}")] - public async Task<EventIdResponse> SetState(string roomId, string eventType, [FromBody] JsonObject? request) { - return await SetState(roomId, eventType, "", request); - } - - [HttpPut("{eventType}/{stateKey}")] - public async Task<EventIdResponse> SetState(string roomId, string eventType, string stateKey, [FromBody] JsonObject? request) { - var token = tokenService.GetAccessTokenOrNull(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" - }; - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - var evt = room.SetStateInternal(new StateEvent() { Type = eventType, StateKey = stateKey, RawContent = request }.ToStateEvent(user, room)); - evt.Type = eventType; - evt.StateKey = stateKey; - return new EventIdResponse() { - EventId = evt.EventId ?? throw new InvalidOperationException("EventId is null") - }; - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomTimelineController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomTimelineController.cs deleted file mode 100644
index afd69d1..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomTimelineController.cs +++ /dev/null
@@ -1,432 +0,0 @@ -using System.Collections.Immutable; -using System.Diagnostics; -using System.Text.Json.Nodes; -using ArcaneLibs; -using LibMatrix.EventTypes.Spec; -using LibMatrix.EventTypes.Spec.State; -using LibMatrix.Helpers; -using LibMatrix.HomeserverEmulator.Extensions; -using LibMatrix.HomeserverEmulator.Services; -using LibMatrix.Responses; -using LibMatrix.Services; -using Microsoft.AspNetCore.Mvc; - -namespace LibMatrix.HomeserverEmulator.Controllers.Rooms; - -[ApiController] -[Route("/_matrix/client/{version}/rooms/{roomId}")] -public class RoomTimelineController( - ILogger<RoomTimelineController> logger, - TokenService tokenService, - UserStore userStore, - RoomStore roomStore, - HomeserverProviderService hsProvider) : ControllerBase { - [HttpPut("send/{eventType}/{txnId}")] - public async Task<EventIdResponse> SendMessage(string roomId, string eventType, string txnId, [FromBody] JsonObject content) { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token); - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - 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 - }; - } - - [HttpGet("messages")] - public async Task<MessagesResponse> GetMessages(string roomId, [FromQuery] string? from = null, [FromQuery] string? to = null, [FromQuery] int limit = 100, - [FromQuery] string? dir = "b") { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token); - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - if (!room.JoinedMembers.Any(x => x.StateKey == user.UserId)) - throw new MatrixException() { - ErrorCode = "M_FORBIDDEN", - Error = "User is not in the room" - }; - - if (dir == "b") { - var timeline = room.Timeline.TakeLast(limit).ToList(); - return new() { - Start = timeline.First().EventId, - End = timeline.Last().EventId, - Chunk = timeline.AsEnumerable().Reverse().ToList(), - State = timeline.GetCalculatedState() - }; - } - else if (dir == "f") { - var timeline = room.Timeline.Take(limit).ToList(); - return new() { - Start = timeline.First().EventId, - End = room.Timeline.Last() == timeline.Last() ? null : timeline.Last().EventId, - Chunk = timeline - }; - } - else - throw new MatrixException() { - ErrorCode = "M_BAD_REQUEST", - Error = $"Invalid direction '{dir}'" - }; - } - - [HttpGet("event/{eventId}")] - public async Task<StateEventResponse> GetEvent(string roomId, string eventId) { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token); - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - if (!room.JoinedMembers.Any(x => x.StateKey == user.UserId)) - throw new MatrixException() { - ErrorCode = "M_FORBIDDEN", - Error = "User is not in the room" - }; - - var evt = room.Timeline.SingleOrDefault(x => x.EventId == eventId); - if (evt == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Event not found" - }; - - 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) { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token); - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - if (!room.JoinedMembers.Any(x => x.StateKey == user.UserId)) - throw new MatrixException() { - ErrorCode = "M_FORBIDDEN", - Error = "User is not in the room" - }; - - var evt = room.Timeline.SingleOrDefault(x => x.EventId == eventId); - if (evt == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Event not found" - }; - - var matchingEvents = await GetRelationsInternal(roomId, eventId, dir, from, limit, recurse, to); - - return new() { - 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) { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token); - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - if (!room.JoinedMembers.Any(x => x.StateKey == user.UserId)) - throw new MatrixException() { - ErrorCode = "M_FORBIDDEN", - Error = "User is not in the room" - }; - - var evt = room.Timeline.SingleOrDefault(x => x.EventId == eventId); - if (evt == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Event not found" - }; - - var matchingEvents = await GetRelationsInternal(roomId, eventId, dir, from, limit, recurse, to); - - return new() { - 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) { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token); - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - if (!room.JoinedMembers.Any(x => x.StateKey == user.UserId)) - throw new MatrixException() { - ErrorCode = "M_FORBIDDEN", - Error = "User is not in the room" - }; - - var evt = room.Timeline.SingleOrDefault(x => x.EventId == eventId); - if (evt == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Event not found" - }; - - var matchingEvents = await GetRelationsInternal(roomId, eventId, dir, from, limit, recurse, to); - - return new() { - 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); - if (evt == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Event not found" - }; - - var relatedEvents = room.Timeline.Where(x => x.RawContent?["m.relates_to"]?["event_id"]?.GetValue<string>() == eventId); - if (dir == "b") { - relatedEvents = relatedEvents.TakeLast(limit ?? 100); - } - else if (dir == "f") { - relatedEvents = relatedEvents.Take(limit ?? 100); - } - - return relatedEvents; - } - -#region Commands - - private void InternalSendMessage(RoomStore.Room room, string content) { - InternalSendMessage(room, new MessageBuilder().WithBody(content).Build()); - } - - private void InternalSendMessage(RoomStore.Room room, RoomMessageEventContent content) { - logger.LogInformation("Sending internal message: {content}", content.Body); - room.Timeline.Add(new StateEventResponse() { - Type = RoomMessageEventContent.EventId, - TypedContent = content, - Sender = $"@hse:{tokenService.GenerateServerName(HttpContext)}", - RoomId = room.RoomId, - EventId = "$" + string.Join("", Random.Shared.GetItems("abcdefghijklmnopqrstuvwxyzABCDEFGHIJLKMNOPQRSTUVWXYZ0123456789".ToCharArray(), 100)), - OriginServerTs = DateTimeOffset.Now.ToUnixTimeMilliseconds() - }); - } - - private async Task HandleHseCommand(StateEventResponse evt, RoomStore.Room room, UserStore.User user) { - try { - var msgContent = evt.TypedContent as RoomMessageEventContent; - var parts = msgContent.Body.Split('\n')[0].Split(" "); - if (parts.Length < 2) return; - - var command = parts[1]; - switch (command) { - case "import": - await HandleImportCommand(parts[2..], evt, room, user); - break; - case "import-nheko-profiles": - await HandleImportNhekoProfilesCommand(parts[2..], evt, room, user); - break; - case "clear-sync-states": - foreach (var (token, session) in user.AccessTokens) { - session.SyncStates.Clear(); - InternalSendMessage(room, $"Cleared sync states for {token}."); - } - - break; - case "rsp": { - await Task.Delay(1000); - var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJLKMNOPQRSTUVWXYZ0123456789"; - for (int i = 0; i < 10000; i++) { - // await Task.Delay(100); - // InternalSendMessage(room, $"https://music.youtube.com/watch?v=90oZtyvavSk&i={i}"); - var url = $"https://music.youtube.com/watch?v="; - for (int j = 0; j < 11; j++) { - url += chars[Random.Shared.Next(chars.Length)]; - } - - InternalSendMessage(room, url + "&i=" + i); - if (i % 5000 == 0 || i == 9999) { - Thread.Sleep(5000); - - do { - InternalSendMessage(room, - $"Current GC memory: {Util.BytesToString(GC.GetTotalMemory(false))}, total process memory: {Util.BytesToString(Process.GetCurrentProcess().WorkingSet64)}"); - GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, true, true); - GC.WaitForPendingFinalizers(); - InternalSendMessage(room, - $"GC memory: {Util.BytesToString(GC.GetTotalMemory(false))}, total process memory: {Util.BytesToString(Process.GetCurrentProcess().WorkingSet64)}"); - await Task.Delay(5000); - } while (Process.GetCurrentProcess().WorkingSet64 >= 1_024_000_000); - } - } - break; - } - case "genrooms": { - var sw = Stopwatch.StartNew(); - var count = 1000; - for (int i = 0; i < count; i++) { - var crq = new CreateRoomRequest() { - Name = "Test room", - CreationContent = new() { - ["version"] = "11" - }, - InitialState = [] - }; - - if (Random.Shared.Next(100) > 75) { - crq.CreationContent["type"] = "m.space"; - foreach (var item in Random.Shared.GetItems(roomStore._rooms.ToArray(), 50)) { - crq.InitialState!.Add(new StateEvent() { - Type = "m.space.child", - StateKey = item.RoomId, - TypedContent = new SpaceChildEventContent() { - Suggested = true, - AutoJoin = true, - Via = new List<string>() - } - }.ToStateEvent(user, room)); - } - } - var newRoom = roomStore.CreateRoom(crq); - newRoom.AddUser(user.UserId); - } - InternalSendMessage(room, $"Generated {count} new rooms in {sw.Elapsed}!"); - break; - } - case "gc": - InternalSendMessage(room, - $"Current GC memory: {Util.BytesToString(GC.GetTotalMemory(false))}, total process memory: {Util.BytesToString(Process.GetCurrentProcess().WorkingSet64)}"); - GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, true, true); - GC.WaitForPendingFinalizers(); - InternalSendMessage(room, - $"GC memory: {Util.BytesToString(GC.GetTotalMemory(false))}, total process memory: {Util.BytesToString(Process.GetCurrentProcess().WorkingSet64)}"); - break; - default: - InternalSendMessage(room, $"Command {command} not found!"); - break; - } - } - catch (Exception ex) { - InternalSendMessage(room, $"An error occurred: {ex.Message}"); - } - } - - private async Task HandleImportNhekoProfilesCommand(string[] args, StateEventResponse evt, RoomStore.Room room, UserStore.User user) { - var msgContent = evt.TypedContent as RoomMessageEventContent; - var parts = msgContent.Body.Split('\n'); - - var data = parts.Where(x => x.Contains(@"\auth\access_token") || x.Contains(@"\auth\home_server")).ToList(); - if (data.Count < 2) { - InternalSendMessage(room, "Invalid data."); - return; - } - - foreach (var line in data) { - var processedLine = line.Replace("\\\\", "\\").Replace("\\_", "_"); - - if (!processedLine.Contains(@"\auth\")) continue; - var profile = processedLine.Split(@"\auth\")[0]; - if (!user.AuthorizedSessions.ContainsKey(profile)) - user.AuthorizedSessions.Add(profile, new()); - if (processedLine.Contains(@"home_server")) { - var server = processedLine.Split('=')[1]; - user.AuthorizedSessions[profile].Homeserver = server; - } - else if (processedLine.Contains(@"access_token")) { - var token = processedLine.Split('=')[1]; - user.AuthorizedSessions[profile].AccessToken = token; - } - } - - foreach (var (key, session) in user.AuthorizedSessions.ToList()) { - if (string.IsNullOrWhiteSpace(session.Homeserver) || string.IsNullOrWhiteSpace(session.AccessToken)) { - InternalSendMessage(room, $"Invalid profile {key}"); - user.AuthorizedSessions.Remove(key); - continue; - } - - InternalSendMessage(room, $"Got profile {key} with server {session.AccessToken}"); - } - } - - private async Task HandleImportCommand(string[] args, StateEventResponse evt, RoomStore.Room room, UserStore.User user) { - var roomId = args[0]; - var profile = args[1]; - - InternalSendMessage(room, $"Importing room {roomId} through profile {profile}..."); - if (!user.AuthorizedSessions.ContainsKey(profile)) { - InternalSendMessage(room, $"Profile {profile} not found."); - return; - } - - var userProfile = user.AuthorizedSessions[profile]; - - InternalSendMessage(room, $"Authenticating with {userProfile.Homeserver}..."); - var hs = await hsProvider.GetAuthenticatedWithToken(userProfile.Homeserver, userProfile.AccessToken); - InternalSendMessage(room, $"Authenticated with {userProfile.Homeserver}."); - var hsRoom = hs.GetRoom(roomId); - - InternalSendMessage(room, $"Starting import..."); - var internalRoom = new RoomStore.Room(roomId); - - var timeline = hsRoom.GetManyMessagesAsync(limit: int.MaxValue, dir: "b", chunkSize: 100000); - await foreach (var resp in timeline) { - internalRoom.Timeline = new(resp.Chunk.AsEnumerable().Reverse().Concat(internalRoom.Timeline)); - InternalSendMessage(room, $"Imported {resp.Chunk.Count} events. Now up to a total of {internalRoom.Timeline.Count} events."); - } - - InternalSendMessage(room, $"Import complete. Saving and inserting user"); - roomStore.AddRoom(internalRoom); - internalRoom.AddUser(user.UserId); - InternalSendMessage(room, $"Import complete. Room is now available."); - } - -#endregion -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomsController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomsController.cs deleted file mode 100644
index c24e6e9..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomsController.cs +++ /dev/null
@@ -1,139 +0,0 @@ -using System.Text.Json.Serialization; -using LibMatrix.EventTypes.Spec.State; -using LibMatrix.EventTypes.Spec.State.RoomInfo; -using LibMatrix.HomeserverEmulator.Services; -using LibMatrix.Responses; -using LibMatrix.RoomTypes; -using Microsoft.AspNetCore.Mvc; - -namespace LibMatrix.HomeserverEmulator.Controllers.Rooms; - -[ApiController] -[Route("/_matrix/client/{version}/")] -public class RoomsController(ILogger<RoomsController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore) : ControllerBase { - //createRoom - [HttpPost("createRoom")] - public async Task<RoomIdResponse> CreateRoom([FromBody] CreateRoomRequest request) { - var token = tokenService.GetAccessTokenOrNull(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" - }; - - // var room = new RoomStore.Room($"!{Guid.NewGuid()}:{tokenService.GenerateServerName(HttpContext)}"); - var room = roomStore.CreateRoom(request, user); - - return new() { - RoomId = room.RoomId - }; - } - - [HttpPost("rooms/{roomId}/upgrade")] - public async Task<object> UpgradeRoom(string roomId, [FromBody] UpgradeRoomRequest request) { - var token = tokenService.GetAccessTokenOrNull(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" - }; - - var oldRoom = roomStore.GetRoomById(roomId); - if (oldRoom == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - var room = new RoomStore.Room($"!{Guid.NewGuid()}:{tokenService.GenerateServerName(HttpContext)}"); - - var eventTypesToTransfer = new[] { - RoomServerACLEventContent.EventId, - RoomEncryptionEventContent.EventId, - RoomNameEventContent.EventId, - RoomAvatarEventContent.EventId, - RoomTopicEventContent.EventId, - RoomGuestAccessEventContent.EventId, - RoomHistoryVisibilityEventContent.EventId, - RoomJoinRulesEventContent.EventId, - RoomPowerLevelEventContent.EventId, - }; - - var createEvent = room.SetStateInternal(new() { - Type = RoomCreateEventContent.EventId, - RawContent = new() { - ["creator"] = user.UserId - } - }); - - oldRoom.State.Where(x => eventTypesToTransfer.Contains(x.Type)).ToList().ForEach(x => room.SetStateInternal(x)); - - room.AddUser(user.UserId); - - // user.Rooms.Add(room.RoomId, room); - return new { - replacement_room = room.RoomId - }; - } - - public class ReasonBody { - [JsonPropertyName("reason")] - public string? Reason { get; set; } - } - [HttpPost("rooms/{roomId}/leave")] // TODO: implement - public async Task<object> LeaveRoom(string roomId, [FromBody] ReasonBody body) { - var token = tokenService.GetAccessTokenOrNull(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" - }; - - var room = roomStore.GetRoomById(roomId); - if (room == null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Room not found" - }; - - room.SetStateInternal(new() { - Type = RoomMemberEventContent.EventId, - TypedContent = new RoomMemberEventContent() { - Membership = "leave", - Reason = body.Reason - }, - StateKey = user.UserId - }); - - logger.LogTrace($"User {user.UserId} left room {room.RoomId}"); - return new { - room_id = room.RoomId - }; - } -} - -public class UpgradeRoomRequest { - [JsonPropertyName("new_version")] - public required string NewVersion { get; set; } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/SyncController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/SyncController.cs deleted file mode 100644
index 024d071..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/SyncController.cs +++ /dev/null
@@ -1,272 +0,0 @@ -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using ArcaneLibs.Extensions; -using LibMatrix.EventTypes.Spec.State; -using LibMatrix.HomeserverEmulator.Extensions; -using LibMatrix.HomeserverEmulator.Services; -using LibMatrix.Responses; -using Microsoft.AspNetCore.Mvc; - -namespace LibMatrix.HomeserverEmulator.Controllers; - -[ApiController] -[Route("/_matrix/client/{version}/")] -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) { - var sw = Stopwatch.StartNew(); - 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" - }; - var session = user.AccessTokens[token]; - UserStore.User.SessionInfo.UserSyncState newSyncState = new(); - - SyncResponse syncResp; - if (string.IsNullOrWhiteSpace(since) || !session.SyncStates.ContainsKey(since)) - syncResp = InitialSync(user, session); - else { - var syncState = session.SyncStates[since]; - newSyncState = syncState.Clone(); - - var newSyncToken = Guid.NewGuid().ToString(); - do { - syncResp = IncrementalSync(user, session, syncState); - syncResp.NextBatch = newSyncToken; - } while (!await HasDataOrStall(syncResp) && sw.ElapsedMilliseconds < timeout); - - if (sw.ElapsedMilliseconds > timeout) { - logger.LogTrace("Sync timed out after {Elapsed}", sw.Elapsed); - return new() { - NextBatch = since - }; - } - } - - session.SyncStates[syncResp.NextBatch] = RecalculateSyncStates(newSyncState, syncResp); - logger.LogTrace("Responding to sync after {totalElapsed}", sw.Elapsed); - return syncResp; - } - - private UserStore.User.SessionInfo.UserSyncState RecalculateSyncStates(UserStore.User.SessionInfo.UserSyncState newSyncState, SyncResponse sync) { - logger.LogTrace("Updating sync state"); - var syncStateRecalcSw = Stopwatch.StartNew(); - foreach (var (roomId, roomData) in sync.Rooms?.Join ?? []) { - if (!newSyncState.RoomPositions.ContainsKey(roomId)) - newSyncState.RoomPositions[roomId] = new(); - var state = newSyncState.RoomPositions[roomId]; - - state.TimelinePosition += roomData.Timeline?.Events?.Count ?? 0; - state.LastTimelineEventId = roomData.Timeline?.Events?.LastOrDefault()?.EventId ?? state.LastTimelineEventId; - state.AccountDataPosition += roomData.AccountData?.Events?.Count ?? 0; - state.Joined = true; - } - - foreach (var (roomId, _) in sync.Rooms?.Invite ?? []) { - if (!newSyncState.RoomPositions.ContainsKey(roomId)) - newSyncState.RoomPositions[roomId] = new() { - Joined = false - }; - } - - foreach (var (roomId, _) in sync.Rooms?.Leave ?? []) { - if (newSyncState.RoomPositions.ContainsKey(roomId)) - newSyncState.RoomPositions.Remove(roomId); - } - - logger.LogTrace("Updated sync state in {Elapsed}", syncStateRecalcSw.Elapsed); - - return newSyncState; - } - -#region Initial Sync parts - - private SyncResponse InitialSync(UserStore.User user, UserStore.User.SessionInfo session) { - var response = new SyncResponse() { - NextBatch = Guid.NewGuid().ToString(), - DeviceOneTimeKeysCount = new(), - AccountData = new(events: user.AccountData.ToList()) - }; - - session.SyncStates.Add(response.NextBatch, new()); - - var rooms = roomStore._rooms.Where(x => x.State.Any(y => y.Type == "m.room.member" && y.StateKey == user.UserId)).ToList(); - foreach (var room in rooms) { - response.Rooms ??= new(); - response.Rooms.Join ??= new(); - - response.Rooms.Join[room.RoomId] = new() { - State = new(room.State.ToList()), - Timeline = new(events: room.Timeline.ToList(), limited: false), - AccountData = new(room.AccountData.GetOrCreate(user.UserId, _ => []).ToList()) - }; - } - - return response; - } - - private SyncResponse.RoomsDataStructure.JoinedRoomDataStructure GetInitialSyncRoomData(RoomStore.Room room, UserStore.User user) { - return new() { - State = new(room.State.ToList()), - Timeline = new(room.Timeline.ToList(), false), - AccountData = new(room.AccountData.GetOrCreate(user.UserId, _ => []).ToList()) - }; - } - -#endregion - - private SyncResponse IncrementalSync(UserStore.User user, UserStore.User.SessionInfo session, UserStore.User.SessionInfo.UserSyncState syncState) { - return new SyncResponse { - Rooms = GetIncrementalSyncRooms(user, session, syncState) - }; - } - -#region Incremental Sync parts - - private SyncResponse.RoomsDataStructure GetIncrementalSyncRooms(UserStore.User user, UserStore.User.SessionInfo session, UserStore.User.SessionInfo.UserSyncState syncState) { - SyncResponse.RoomsDataStructure data = new() { - Join = [], - Invite = [], - Leave = [] - }; - - // step 1: check previously synced rooms - foreach (var (roomId, roomPosition) in syncState.RoomPositions) { - var room = roomStore.GetRoomById(roomId); - if (room == null) { - // room no longer exists - data.Leave[roomId] = new(); - continue; - } - - if (roomPosition.Joined) { - 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; - data.Join[room.RoomId] = new() { - State = new(newTimelineEvents.GetCalculatedState()), - Timeline = new(newTimelineEvents, false) - }; - } - } - - if (data.Join.Count > 0) return data; - - // step 2: check newly joined rooms - 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)); - foreach (var membership in rooms) { - var membershipContent = membership.TypedContent as RoomMemberEventContent ?? - throw new InvalidOperationException("Membership event content is not RoomMemberEventContent"); - var room = roomStore.GetRoomById(membership.RoomId!); - //handle leave - if (syncState.RoomPositions.TryGetValue(membership.RoomId!, out var syncPosition)) { - // logger.LogTrace("Found sync position {roomId} {value}", room.RoomId, syncPosition.ToJson(indent: false, ignoreNull: false)); - - if (membershipContent.Membership == "join") { - var newTimelineEvents = room.Timeline.Skip(syncPosition.TimelinePosition).ToList(); - var newAccountDataEvents = room.AccountData[user.UserId].Skip(syncPosition.AccountDataPosition).ToList(); - if (newTimelineEvents.Count == 0 && newAccountDataEvents.Count == 0) continue; - data.Join[room.RoomId] = new() { - State = new(newTimelineEvents.GetCalculatedState()), - Timeline = new(newTimelineEvents, false) - }; - } - } - else { - //syncPosisition = null - if (membershipContent.Membership == "join") { - var joinData = data.Join[membership.RoomId!] = new() { - State = new(room.State.ToList()), - Timeline = new(events: room.Timeline.ToList(), limited: false), - AccountData = new(room.AccountData.GetOrCreate(user.UserId, _ => []).ToList()) - }; - } - } - } - - //handle nonexistant rooms - foreach (var roomId in syncState.RoomPositions.Keys) { - if (!roomStore._rooms.Any(x => x.RoomId == roomId)) { - data.Leave[roomId] = new(); - session.SyncStates[session.SyncStates.Last().Key].RoomPositions.Remove(roomId); - } - } - - return data; - } - -#endregion - - 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; - // if (resp.Rooms?.Invite?.Count > 0) return true; - // if (resp.Rooms?.Join?.Count > 0) return true; - // if (resp.Rooms?.Leave?.Count > 0) return true; - // if (resp.Presence?.Events?.Count > 0) return true; - // if (resp.DeviceLists?.Changed?.Count > 0) return true; - // if (resp.DeviceLists?.Left?.Count > 0) return true; - // if (resp.ToDevice?.Events?.Count > 0) return true; - // - // var hasData = - // resp is not { - // AccountData: null or { - // Events: null or { Count: 0 } - // }, - // Rooms: null or { - // Invite: null or { Count: 0 }, - // Join: null or { Count: 0 }, - // Leave: null or { Count: 0 } - // }, - // Presence: null or { - // Events: null or { Count: 0 } - // }, - // DeviceLists: null or { - // Changed: null or { Count: 0 }, - // Left: null or { Count: 0 } - // }, - // ToDevice: null or { - // Events: null or { Count: 0 } - // } - // }; - - var hasData = resp is { - AccountData: { - Events: { Count: > 0 } - } - } or { - Presence: { - Events: { Count: > 0 } - } - } or { - DeviceLists: { - Changed: { Count: > 0 }, - Left: { Count: > 0 } - } - } or { - ToDevice: { - Events: { Count: > 0 } - } - }; - - if (!hasData) { - // hasData = - } - - if (!hasData) { - // logger.LogDebug($"Sync response has no data, stalling for 1000ms: {resp.ToJson(indent: false, ignoreNull: true)}"); - await Task.Delay(10); - } - - return hasData; - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/ThirdParty/ThirdPartyController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/ThirdParty/ThirdPartyController.cs deleted file mode 100644
index ff006df..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/ThirdParty/ThirdPartyController.cs +++ /dev/null
@@ -1,25 +0,0 @@ -using LibMatrix.HomeserverEmulator.Services; -using Microsoft.AspNetCore.Mvc; - -namespace LibMatrix.HomeserverEmulator.Controllers.ThirdParty; - -[ApiController] -[Route("/_matrix/client/{version}/thirdparty/")] -public class ThirdPartyController(ILogger<ThirdPartyController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore) : ControllerBase { - [HttpGet("protocols")] - public async Task<object> GetProtocols() { - return new { }; - } - - [HttpGet("location")] - public async Task<List<object>> GetLocations([FromQuery] string alias) { - // TODO: implement - return []; - } - - [HttpGet("location/{protocol}")] - public async Task<List<object>> GetLocation([FromRoute] string protocol) { - // TODO: implement - return []; - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/AccountDataController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/AccountDataController.cs deleted file mode 100644
index a32d283..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/AccountDataController.cs +++ /dev/null
@@ -1,68 +0,0 @@ -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; - -[ApiController] -[Route("/_matrix/client/{version}/")] -public class AccountDataController(ILogger<AccountDataController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore) : ControllerBase { - [HttpGet("user/{mxid}/account_data/{type}")] - public async Task<object> GetAccountData(string type) { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token, false); - if (user is null) - throw new MatrixException() { - ErrorCode = "M_UNAUTHORIZED", - Error = "Invalid token." - }; - - var value = user.AccountData.FirstOrDefault(x => x.Type == type); - if (value is null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Key not found." - }; - return value; - } - - [HttpPut("user/{mxid}/account_data/{type}")] - public async Task<object> SetAccountData(string type, [FromBody] JsonObject data) { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token, false); - if (user is null) - throw new MatrixException() { - ErrorCode = "M_UNAUTHORIZED", - Error = "Invalid token." - }; - - user.AccountData.Add(new() { - Type = type, - RawContent = data - }); - return data; - } - - // specialised account data... - [HttpGet("pushrules")] - public async Task<object> GetPushRules() { - var token = tokenService.GetAccessToken(HttpContext); - if (token is null) - throw new MatrixException() { - ErrorCode = "M_UNAUTHORIZED", - Error = "No token passed." - }; - - var user = await userStore.GetUserByToken(token, false); - if (user is null) - throw new MatrixException() { - ErrorCode = "M_UNAUTHORIZED", - Error = "Invalid token." - }; - return new { }; - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/FilterController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/FilterController.cs deleted file mode 100644
index bdee7bc..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/FilterController.cs +++ /dev/null
@@ -1,46 +0,0 @@ -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; - -[ApiController] -[Route("/_matrix/client/{version}/")] -public class FilterController(ILogger<FilterController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore) : ControllerBase { - [HttpPost("user/{mxid}/filter")] - public async Task<object> CreateFilter(string mxid, [FromBody] SyncFilter filter) { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token, false); - if (user is null) - throw new MatrixException() { - ErrorCode = "M_UNAUTHORIZED", - Error = "Invalid token." - }; - var filterId = Guid.NewGuid().ToString(); - user.Filters[filterId] = filter; - return new { - filter_id = filterId - }; - } - - [HttpGet("user/{mxid}/filter/{filterId}")] - public async Task<SyncFilter> GetFilter(string mxid, string filterId) { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token, false); - if (user is null) - throw new MatrixException() { - ErrorCode = "M_UNAUTHORIZED", - Error = "Invalid token." - }; - if (!user.Filters.ContainsKey(filterId)) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Filter not found." - }; - return user.Filters[filterId]; - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/ProfileController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/ProfileController.cs deleted file mode 100644
index 98c41da..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/ProfileController.cs +++ /dev/null
@@ -1,52 +0,0 @@ -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; - -[ApiController] -[Route("/_matrix/client/{version}/")] -public class ProfileController(ILogger<ProfileController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore) : ControllerBase { - [HttpGet("profile/{userId}")] - public async Task<IDictionary<string, object>> GetProfile(string userId) { - var user = await userStore.GetUserById(userId, false); - if (user is null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "User not found." - }; - return user.Profile; - } - - [HttpGet("profile/{userId}/{key}")] - public async Task<object> GetProfile(string userId, string key) { - var user = await userStore.GetUserById(userId, false); - if (user is null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "User not found." - }; - if (!user.Profile.TryGetValue(key, out var value)) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Key not found." - }; - return value; - } - - [HttpPut("profile/{userId}/{key}")] - public async Task<object> SetProfile(string userId, string key, [FromBody] JsonNode value) { - var user = await userStore.GetUserById(userId, false); - if (user is null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "User not found." - }; - user.Profile[key] = value[key]?.AsObject(); - return value; - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/UserController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/UserController.cs deleted file mode 100644
index 2be3896..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/Users/UserController.cs +++ /dev/null
@@ -1,80 +0,0 @@ -using System.Text.Json.Nodes; -using System.Text.Json.Serialization; -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; - -[ApiController] -[Route("/_matrix/client/{version}/")] -public class UserController(ILogger<UserController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore) : ControllerBase { - [HttpGet("account/whoami")] - public async Task<WhoAmIResponse> Login() { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token, Random.Shared.Next(101) <= 10, tokenService.GenerateServerName(HttpContext)); - if (user is null) - throw new MatrixException() { - ErrorCode = "M_UNKNOWN_TOKEN", - Error = "Invalid token." - }; - var whoAmIResponse = new WhoAmIResponse { - UserId = user.UserId - }; - return whoAmIResponse; - } - - [HttpGet("joined_rooms")] - public async Task<object> GetJoinedRooms() { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token, false); - if (user is null) - throw new MatrixException() { - ErrorCode = "M_UNAUTHORIZED", - Error = "Invalid token." - }; - // return user.JoinedRooms; - - return new { - joined_rooms = roomStore._rooms.Where(r => - r.State.Any(s => s.StateKey == user.UserId && s.Type == RoomMemberEventContent.EventId && (s.TypedContent as RoomMemberEventContent).Membership == "join") - ).Select(r => r.RoomId).ToList() - }; - } - - [HttpGet("devices")] - public async Task<DevicesResponse> GetDevices() { - var token = tokenService.GetAccessToken(HttpContext); - var user = await userStore.GetUserByToken(token, false); - if (user is null) - throw new MatrixException() { - ErrorCode = "M_UNAUTHORIZED", - Error = "Invalid token." - }; - return new() { - Devices = user.AccessTokens.Select(x=>new DevicesResponse.Device() { - DeviceId = x.Value.DeviceId, - DisplayName = x.Value.DeviceId - }).ToList() - }; - } - - public class DevicesResponse { - [JsonPropertyName("devices")] - public List<Device> Devices { get; set; } - - public class Device { - [JsonPropertyName("device_id")] - public string DeviceId { get; set; } - [JsonPropertyName("display_name")] - public string DisplayName { get; set; } - [JsonPropertyName("last_seen_ip")] - public string LastSeenIp { get; set; } - [JsonPropertyName("last_seen_ts")] - public long LastSeenTs { get; set; } - } - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/VersionsController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/VersionsController.cs deleted file mode 100644
index 0c3bde6..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/VersionsController.cs +++ /dev/null
@@ -1,96 +0,0 @@ -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; - -[ApiController] -[Route("/_matrix/")] -public class VersionsController(ILogger<WellKnownController> logger) : ControllerBase { - [HttpGet("client/versions")] - public async Task<ClientVersionsResponse> GetClientVersions() { - var clientVersions = new ClientVersionsResponse { - Versions = new() { - "r0.0.1", - "r0.1.0", - "r0.2.0", - "r0.3.0", - "r0.4.0", - "r0.5.0", - "r0.6.0", - "r0.6.1", - "v1.1", - "v1.2", - "v1.3", - "v1.4", - "v1.5", - "v1.6", - "v1.7", - "v1.8", - }, - UnstableFeatures = new() - }; - return clientVersions; - } - - [HttpGet("federation/v1/version")] - public async Task<ServerVersionResponse> GetServerVersions() { - var clientVersions = new ServerVersionResponse() { - Server = new() { - Name = "LibMatrix.HomeserverEmulator", - Version = "0.0.0" - } - }; - return clientVersions; - } - - [HttpGet("client/{version}/capabilities")] - public async Task<CapabilitiesResponse> GetCapabilities() { - var caps = new CapabilitiesResponse() { - Capabilities = new() { - ChangePassword = new() { - Enabled = false - }, - RoomVersions = new() { - Default = "11", - Available = [] - } - } - }; - - for (int i = 0; i < 15; i++) { - caps.Capabilities.RoomVersions.Available.Add(i.ToString(), "stable"); - } - - return caps; - } -} - -public class CapabilitiesResponse { - [JsonPropertyName("capabilities")] - public CapabilitiesContent Capabilities { get; set; } - - public class CapabilitiesContent { - [JsonPropertyName("m.room_versions")] - public RoomVersionsContent RoomVersions { get; set; } - - [JsonPropertyName("m.change_password")] - public ChangePasswordContent ChangePassword { get; set; } - - public class ChangePasswordContent { - [JsonPropertyName("enabled")] - public bool Enabled { get; set; } - } - - public class RoomVersionsContent { - [JsonPropertyName("default")] - public string Default { get; set; } - - [JsonPropertyName("available")] - public Dictionary<string, string> Available { get; set; } - } - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Controllers/WellKnownController.cs b/Tests/LibMatrix.HomeserverEmulator/Controllers/WellKnownController.cs deleted file mode 100644
index 97e460d..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Controllers/WellKnownController.cs +++ /dev/null
@@ -1,32 +0,0 @@ -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; - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Extensions/EventExtensions.cs b/Tests/LibMatrix.HomeserverEmulator/Extensions/EventExtensions.cs deleted file mode 100644
index d938b1b..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Extensions/EventExtensions.cs +++ /dev/null
@@ -1,24 +0,0 @@ -using LibMatrix.HomeserverEmulator.Services; - -namespace LibMatrix.HomeserverEmulator.Extensions; - -public static class EventExtensions { - public static StateEventResponse ToStateEvent(this StateEvent stateEvent, UserStore.User user, RoomStore.Room room) { - return new StateEventResponse { - RawContent = stateEvent.RawContent, - EventId = "$" + string.Join("", Random.Shared.GetItems("abcdefghijklmnopqrstuvwxyzABCDEFGHIJLKMNOPQRSTUVWXYZ0123456789".ToCharArray(), 100)), - RoomId = room.RoomId, - Sender = user.UserId, - StateKey = stateEvent.StateKey, - Type = stateEvent.Type, - OriginServerTs = DateTimeOffset.Now.ToUnixTimeMilliseconds() - }; - } - - public static List<StateEventResponse> GetCalculatedState(this IEnumerable<StateEventResponse> events) { - return events.Where(s => s.StateKey != null) - .OrderByDescending(s => s.OriginServerTs) - .DistinctBy(x => (x.Type, x.StateKey)) - .ToList(); - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.csproj b/Tests/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.csproj deleted file mode 100644
index a6b6214..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.csproj +++ /dev/null
@@ -1,23 +0,0 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> - - <PropertyGroup> - <TargetFramework>net8.0</TargetFramework> - <Nullable>enable</Nullable> - <ImplicitUsings>enable</ImplicitUsings> - <InvariantGlobalization>true</InvariantGlobalization> - <LangVersion>preview</LangVersion> - <GenerateDocumentationFile>true</GenerateDocumentationFile> - </PropertyGroup> - - <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" /> - </ItemGroup> - - <ItemGroup> - <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj"/> -<!-- <ProjectReference Include="..\..\Utilities\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj"/>--> - </ItemGroup> - -</Project> diff --git a/Tests/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.http b/Tests/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.http deleted file mode 100644
index 01d5fcc..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/LibMatrix.HomeserverEmulator.http +++ /dev/null
@@ -1,6 +0,0 @@ -@LibMatrix.HomeserverEmulator_HostAddress = http://localhost:5298 - -GET {{LibMatrix.HomeserverEmulator_HostAddress}}/weatherforecast/ -Accept: application/json - -### diff --git a/Tests/LibMatrix.HomeserverEmulator/Program.cs b/Tests/LibMatrix.HomeserverEmulator/Program.cs deleted file mode 100644
index 9ea6fce..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Program.cs +++ /dev/null
@@ -1,117 +0,0 @@ -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; -using Microsoft.AspNetCore.Http.Timeouts; -using Microsoft.AspNetCore.Mvc; -using Microsoft.OpenApi.Models; - -var builder = WebApplication.CreateBuilder(args); - -builder.Services.Configure<ApiBehaviorOptions>(options => -{ - options.SuppressModelStateInvalidFilter = true; -}); - -builder.Services.AddControllers(options => { - options.MaxValidationDepth = null; - options.MaxIAsyncEnumerableBufferLimit = 100; -}).AddJsonOptions(options => { options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; }); - -builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(c => { - c.SwaggerDoc("v1", new OpenApiInfo() { - Version = "v1", - Title = "Rory&::LibMatrix.HomeserverEmulator", - Description = "Partial Matrix homeserver implementation" - }); - c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "LibMatrix.HomeserverEmulator.xml")); -}); - -builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); -builder.Services.AddSingleton<HSEConfiguration>(); -builder.Services.AddSingleton<UserStore>(); -builder.Services.AddSingleton<RoomStore>(); -builder.Services.AddSingleton<MediaStore>(); - -builder.Services.AddScoped<TokenService>(); - -builder.Services.AddSingleton<HomeserverProviderService>(); -builder.Services.AddSingleton<HomeserverResolverService>(); -builder.Services.AddSingleton<PaginationTokenResolverService>(); - -builder.Services.AddRequestTimeouts(x => { - x.DefaultPolicy = new RequestTimeoutPolicy { - Timeout = TimeSpan.FromMinutes(10), - WriteTimeoutResponse = async context => { - context.Response.StatusCode = 504; - context.Response.ContentType = "application/json"; - await context.Response.StartAsync(); - await context.Response.WriteAsJsonAsync(new MatrixException() { - ErrorCode = "M_TIMEOUT", - Error = "Request timed out" - }.GetAsJson()); - await context.Response.CompleteAsync(); - } - }; -}); -builder.Services.AddCors(options => { - options.AddPolicy( - "Open", - policy => policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); -}); -var app = builder.Build(); - -// Configure the HTTP request pipeline. -if (app.Environment.IsDevelopment() || true) { - app.UseSwagger(); - app.UseSwaggerUI(); -} - -app.UseCors("Open"); -app.UseExceptionHandler(exceptionHandlerApp => { - exceptionHandlerApp.Run(async context => { - var exceptionHandlerPathFeature = - context.Features.Get<IExceptionHandlerPathFeature>(); - if (exceptionHandlerPathFeature?.Error is not null) - Console.WriteLine(exceptionHandlerPathFeature.Error.ToString()!); - - if (exceptionHandlerPathFeature?.Error is MatrixException mxe) { - context.Response.StatusCode = mxe.ErrorCode switch { - "M_NOT_FOUND" => StatusCodes.Status404NotFound, - "M_UNAUTHORIZED" => StatusCodes.Status401Unauthorized, - _ => StatusCodes.Status500InternalServerError - }; - context.Response.ContentType = MediaTypeNames.Application.Json; - 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() - }.GetAsJson()); - } - }); -}); - -app.UseAuthorization(); - -app.MapControllers(); - -app.Map("/_matrix/{*_}", (HttpContext ctx, ILogger<Program> logger) => { - logger.LogWarning("Client hit non-existing route: {Method} {Path}{Query}", ctx.Request.Method, ctx.Request.Path, ctx.Request.Query); - // Console.WriteLine($"Client hit non-existing route: {ctx.Request.Method} {ctx.Request.Path}"); - ctx.Response.StatusCode = StatusCodes.Status404NotFound; - ctx.Response.ContentType = MediaTypeNames.Application.Json; - return ctx.Response.WriteAsJsonAsync(new MatrixException() { - ErrorCode = MatrixException.ErrorCodes.M_UNRECOGNISED, - Error = "Endpoint not implemented" - }); -}); - -app.Run(); \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Properties/launchSettings.json b/Tests/LibMatrix.HomeserverEmulator/Properties/launchSettings.json deleted file mode 100644
index 4ddf341..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Properties/launchSettings.json +++ /dev/null
@@ -1,32 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:9169", - "sslPort": 44321 - } - }, - "profiles": { - "Development": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": false, - "launchUrl": "swagger", - "applicationUrl": "http://localhost:5298", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "Local": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": false, - "applicationUrl": "http://localhost:5298", - "environmentVariables": { - "DOTNET_ENVIRONMENT": "Local" - } - } - } -} diff --git a/Tests/LibMatrix.HomeserverEmulator/Services/HSEConfiguration.cs b/Tests/LibMatrix.HomeserverEmulator/Services/HSEConfiguration.cs deleted file mode 100644
index 73b0d23..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Services/HSEConfiguration.cs +++ /dev/null
@@ -1,57 +0,0 @@ -using System.Collections; -using System.Diagnostics.CodeAnalysis; -using ArcaneLibs.Extensions; - -namespace LibMatrix.HomeserverEmulator.Services; - -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) { - Current = this; - _logger = logger; - logger.LogInformation("Loading configuration for environment: {}...", host.HostingEnvironment.EnvironmentName); - config.GetSection("HomeserverEmulator").Bind(this); - if (StoreData) { - DataStoragePath = ExpandPath(DataStoragePath ?? throw new NullReferenceException("DataStoragePath is not set")); - CacheStoragePath = ExpandPath(CacheStoragePath ?? throw new NullReferenceException("CacheStoragePath is not set")); - } - - _logger.LogInformation("Configuration loaded: {}", this.ToJson()); - } - - public string CacheStoragePath { get; set; } - - public string DataStoragePath { get; set; } - - public bool StoreData { get; set; } = true; - - public bool UnknownSyncTokenIsInitialSync { get; set; } = true; - - private static string ExpandPath(string path, bool retry = true) { - _logger.LogInformation("Expanding path `{}`", path); - - if (path.StartsWith('~')) { - path = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), path[1..]); - } - - Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().OrderByDescending(x => x.Key.ToString()!.Length).ToList().ForEach(x => { - path = path.Replace($"${x.Key}", x.Value.ToString()); - }); - - _logger.LogInformation("Expanded path to `{}`", path); - var tries = 0; - while (retry && path.ContainsAnyOf("~$".Split())) { - if (tries++ > 100) - throw new Exception($"Path `{path}` contains unrecognised environment variables"); - path = ExpandPath(path, false); - } - - if(path.StartsWith("./")) - path = Path.Join(Directory.GetCurrentDirectory(), path[2..].Replace("/", Path.DirectorySeparatorChar.ToString())); - - return path; - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Services/MediaStore.cs b/Tests/LibMatrix.HomeserverEmulator/Services/MediaStore.cs deleted file mode 100644
index 00f2a42..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Services/MediaStore.cs +++ /dev/null
@@ -1,64 +0,0 @@ -using System.Text.Json; -using LibMatrix.Services; - -namespace LibMatrix.HomeserverEmulator.Services; - -public class MediaStore { - private readonly HSEConfiguration _config; - private readonly HomeserverResolverService _hsResolver; - private List<MediaInfo> index = new(); - - 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"))); - } - else - Console.WriteLine("Data storage is disabled, not loading rooms from disk"); - } - - // public async Task<object> UploadMedia(string userId, string mimeType, Stream stream, string? filename = null) { - // var mediaId = $"mxc://{Guid.NewGuid().ToString()}"; - // var path = Path.Combine(_config.DataStoragePath, "media", mediaId); - // if (!Directory.Exists(path)) Directory.CreateDirectory(path); - // var file = Path.Combine(path, filename ?? "file"); - // await using var fs = File.Create(file); - // await stream.CopyToAsync(fs); - // index.Add(new() { }); - // return media; - // } - - public async Task<Stream> GetRemoteMedia(string serverName, string mediaId) { - 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}"); - if (mediaUrl is null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Media not found" - }; - using var client = new HttpClient(); - var stream = await client.GetStreamAsync(mediaUrl); - await using var fs = File.Create(path); - await stream.CopyToAsync(fs); - } - return new FileStream(path, FileMode.Open); - } - else { - var mediaUrl = await _hsResolver.ResolveMediaUri(serverName, $"mxc://{serverName}/{mediaId}"); - if (mediaUrl is null) - throw new MatrixException() { - ErrorCode = "M_NOT_FOUND", - Error = "Media not found" - }; - using var client = new HttpClient(); - return await client.GetStreamAsync(mediaUrl); - } - } - public class MediaInfo { } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Services/PaginationTokenResolverService.cs b/Tests/LibMatrix.HomeserverEmulator/Services/PaginationTokenResolverService.cs deleted file mode 100644
index 0128ba6..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Services/PaginationTokenResolverService.cs +++ /dev/null
@@ -1,54 +0,0 @@ -namespace LibMatrix.HomeserverEmulator.Services; - -public class PaginationTokenResolverService(ILogger<PaginationTokenResolverService> logger, RoomStore roomStore, UserStore userStore) { - public async Task<long?> ResolveTokenToTimestamp(string token) { - logger.LogTrace("ResolveTokenToTimestamp({token})", token); - if (token.StartsWith('$')) { - //we have an event ID - foreach (var room in roomStore._rooms) { - var evt = await ResolveTokenToEvent(token, room); - if (evt is not null) return evt.OriginServerTs; - } - - // event not found - throw new NotImplementedException(); - } - else { - // we have a sync token - foreach (var user in userStore._users) { - foreach (var (_, session) in user.AccessTokens) { - if (!session.SyncStates.TryGetValue(token, out var syncState)) continue; - long? maxTs = 0; - foreach (var room in syncState.RoomPositions) { - var roomObj = roomStore.GetRoomById(room.Key); - if (roomObj is null) - continue; - var ts = roomObj.Timeline.Last().OriginServerTs; - if (ts > maxTs) maxTs = ts; - } - - return maxTs; - } - } - - throw new NotImplementedException(); - } - } - - public async 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; - logger.LogTrace("ResolveTokenToEvent({token}, Room({room})): event not in requested room...", token, room.RoomId); - return null; - } - else { - // we have a sync token - logger.LogTrace("ResolveTokenToEvent(SyncToken({token}), Room({room}))", token, room.RoomId); - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Services/RoomStore.cs b/Tests/LibMatrix.HomeserverEmulator/Services/RoomStore.cs deleted file mode 100644
index 5cdc3ab..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Services/RoomStore.cs +++ /dev/null
@@ -1,308 +0,0 @@ -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.HomeserverEmulator.Controllers.Rooms; -using LibMatrix.Responses; - -namespace LibMatrix.HomeserverEmulator.Services; - -public class RoomStore { - private readonly ILogger<RoomStore> _logger; - public ConcurrentBag<Room> _rooms = new(); - private FrozenDictionary<string, Room> _roomsById = FrozenDictionary<string, Room>.Empty; - - 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); - } - } - else - Console.WriteLine("Data storage is disabled, not loading rooms from disk"); - - 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) { - if (_roomsById.TryGetValue(roomId, out var room)) { - return room; - } - - if (!createIfNotExists) - return null; - - 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() { } - }; - - foreach (var (key, value) in request.CreationContent) { - newCreateEvent.RawContent[key] = value.DeepClone(); - } - - if (user != null) { - newCreateEvent.RawContent["creator"] = user.UserId; - var createEvent = room.SetStateInternal(newCreateEvent, user: user); - createEvent.Sender = user.UserId; - - room.SetStateInternal(new() { - Type = RoomMemberEventContent.EventId, - StateKey = user.UserId, - TypedContent = new RoomMemberEventContent() { - Membership = "join", - AvatarUrl = (user.Profile.GetOrNull("avatar_url") as JsonObject)?.GetOrNull("avatar_url")?.GetValue<string>(), - DisplayName = (user.Profile.GetOrNull("displayname") as string) - } - }, user: user); - } - - if (!string.IsNullOrWhiteSpace(request.Name)) - room.SetStateInternal(new StateEvent() { - Type = RoomNameEventContent.EventId, - TypedContent = new RoomNameEventContent() { - Name = request.Name - } - }); - - if (!string.IsNullOrWhiteSpace(request.RoomAliasName)) - room.SetStateInternal(new StateEvent() { - Type = RoomCanonicalAliasEventContent.EventId, - TypedContent = new RoomCanonicalAliasEventContent() { - Alias = $"#{request.RoomAliasName}:localhost" - } - }); - - foreach (var stateEvent in request.InitialState ?? []) { - room.SetStateInternal(stateEvent); - } - - _rooms.Add(room); - // _roomsById.TryAdd(room.RoomId, room); - RebuildIndexes(); - return room; - } - - public Room AddRoom(Room room) { - _rooms.Add(room); - RebuildIndexes(); - - return room; - } - - public class Room : NotifyPropertyChanged { - private CancellationTokenSource _debounceCts = new(); - private ObservableCollection<StateEventResponse> _timeline; - private ObservableDictionary<string, List<StateEventResponse>> _accountData; - private ObservableDictionary<string, ReadMarkersData> _readMarkers; - private FrozenSet<StateEventResponse> _stateCache; - private int _timelineHash; - - 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)); - RoomId = roomId; - Timeline = new(); - AccountData = new(); - ReadMarkers = new(); - } - - public string RoomId { get; set; } - - public FrozenSet<StateEventResponse> State => _timelineHash == _timeline.GetHashCode() ? _stateCache : RebuildState(); - - public ObservableCollection<StateEventResponse> Timeline { - get => _timeline; - set { - if (Equals(value, _timeline)) return; - _timeline = new(value); - _timeline.CollectionChanged += (sender, args) => { - // we dont want to do this as it's rebuilt when the state is accessed - - // if (args.Action == NotifyCollectionChangedAction.Add) { - // foreach (StateEventResponse state in args.NewItems) { - // if (state.StateKey is not null) - // // we want state to be deduplicated by type and key, and we want the latest state to be the one that is returned - // RebuildState(); - // } - // } - - SaveDebounced(); - }; - // RebuildState(); - OnPropertyChanged(); - } - } - - public ObservableDictionary<string, List<StateEventResponse>> AccountData { - get => _accountData; - set { - if (Equals(value, _accountData)) return; - _accountData = new(value); - _accountData.CollectionChanged += (sender, args) => SaveDebounced(); - OnPropertyChanged(); - } - } - - public ImmutableList<StateEventResponse> JoinedMembers => - State.Where(s => s is { Type: RoomMemberEventContent.EventId, TypedContent: RoomMemberEventContent { Membership: "join" } }).ToImmutableList(); - - public ObservableDictionary<string, ReadMarkersData> ReadMarkers { - get => _readMarkers; - set { - if (Equals(value, _readMarkers)) return; - _readMarkers = new(value); - _readMarkers.CollectionChanged += (sender, args) => SaveDebounced(); - OnPropertyChanged(); - } - } - - internal StateEventResponse SetStateInternal(StateEvent request, string? senderId = null, UserStore.User? user = null) { - var state = request as StateEventResponse ?? new StateEventResponse() { - Type = request.Type, - StateKey = request.StateKey ?? "", - EventId = "$" + Guid.NewGuid().ToString(), - RoomId = RoomId, - OriginServerTs = DateTimeOffset.Now.ToUnixTimeMilliseconds(), - Sender = user?.UserId ?? senderId ?? "", - RawContent = request.RawContent ?? (request.TypedContent is not null - ? new JsonObject() - : JsonSerializer.Deserialize<JsonObject>(JsonSerializer.Serialize(request.TypedContent))) - }; - Timeline.Add(state); - if(state.StateKey != null) - RebuildState(); - return state; - } - - public StateEventResponse AddUser(string userId) { - var state = SetStateInternal(new() { - Type = RoomMemberEventContent.EventId, - StateKey = userId, - TypedContent = new RoomMemberEventContent() { - Membership = "join" - }, - }); - - state.Sender = userId; - return state; - } - - // 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) { } - // } - - private SemaphoreSlim saveSemaphore = new(1, 1); - - public async Task SaveDebounced() { - Task.Run(async () => { - await saveSemaphore.WaitAsync(); - 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)); - } - finally { - saveSemaphore.Release(); - } - }); - } - - private SemaphoreSlim stateRebuildSemaphore = new(1, 1); - - private FrozenSet<StateEventResponse> RebuildState() { - stateRebuildSemaphore.Wait(); - while (true) - try { - Console.WriteLine($"Rebuilding state for room {RoomId}"); - // ReSharper disable once RedundantEnumerableCastCall - This sometimes happens when the collection is modified during enumeration - List<StateEventResponse>? timeline = null; - lock (_timeline) { - timeline = Timeline.OfType<StateEventResponse>().ToList(); - } - - foreach (var evt in timeline) { - if (evt == null) { - throw new InvalidOperationException("Event is null"); - } - - if (evt.EventId == null) { - evt.EventId = "$" + Guid.NewGuid(); - } - else if (!evt.EventId.StartsWith('$')) { - evt.EventId = "$" + evt.EventId; - Console.WriteLine($"Sanitised invalid event ID {evt.EventId}"); - } - } - - _stateCache = timeline //.Where(s => s.Type == state.Type && s.StateKey == state.StateKey) - .Where(x => x.StateKey != null) - .OrderByDescending(s => s.OriginServerTs) - .DistinctBy(x => (x.Type, x.StateKey)) - .ToFrozenSet(); - - _timelineHash = _timeline.GetHashCode(); - stateRebuildSemaphore.Release(); - return _stateCache; - } - finally { } - } - } - - public List<StateEventResponse> GetRoomsByMember(string userId) { - // return _rooms - // // .Where(r => r.State.Any(s => s.Type == RoomMemberEventContent.EventId && s.StateKey == userId)) - // .Select(r => (Room: r, MemberEvent: r.State.SingleOrDefault(s => s.Type == RoomMemberEventContent.EventId && s.StateKey == userId))) - // .Where(r => r.MemberEvent != null) - // .ToDictionary(x => x.Room, x => x.MemberEvent!); - return _rooms.SelectMany(r => r.State.Where(s => s.Type == RoomMemberEventContent.EventId && s.StateKey == userId)).ToList(); - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Services/TokenService.cs b/Tests/LibMatrix.HomeserverEmulator/Services/TokenService.cs deleted file mode 100644
index cf79aae..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Services/TokenService.cs +++ /dev/null
@@ -1,29 +0,0 @@ -namespace LibMatrix.HomeserverEmulator.Services; - -public class TokenService{ - public string? GetAccessTokenOrNull(HttpContext ctx) { - //qry - if (ctx.Request.Query.TryGetValue("access_token", out var token)) { - return token; - } - //header - if (ctx.Request.Headers.TryGetValue("Authorization", out var auth)) { - var parts = auth.ToString().Split(' '); - if (parts is ["Bearer", _]) { - return parts[1]; - } - } - return null; - } - - public string GetAccessToken(HttpContext ctx) { - return GetAccessTokenOrNull(ctx) ?? throw new MatrixException() { - ErrorCode = MatrixException.ErrorCodes.M_UNKNOWN_TOKEN, - Error = "Missing token" - }; - } - - public string? GenerateServerName(HttpContext ctx) { - return ctx.Request.Host.ToString(); - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/Services/UserStore.cs b/Tests/LibMatrix.HomeserverEmulator/Services/UserStore.cs deleted file mode 100644
index 4ce9f92..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/Services/UserStore.cs +++ /dev/null
@@ -1,250 +0,0 @@ -using System.Collections.Concurrent; -using System.Collections.ObjectModel; -using System.Text.Json; -using System.Text.Json.Nodes; -using ArcaneLibs; -using ArcaneLibs.Collections; -using ArcaneLibs.Extensions; -using LibMatrix.EventTypes.Spec.State; -using LibMatrix.Filters; -using LibMatrix.Responses; - -namespace LibMatrix.HomeserverEmulator.Services; - -public class UserStore { - public ConcurrentBag<User> _users = new(); - private readonly RoomStore _roomStore; - - public UserStore(HSEConfiguration config, RoomStore roomStore) { - _roomStore = roomStore; - if (config.StoreData) { - 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"); - var path = Path.Combine(dataDir, userId, $"user.json"); - - var user = JsonSerializer.Deserialize<User>(File.ReadAllText(path)); - user!.AccessTokens = JsonSerializer.Deserialize<ObservableDictionary<string, User.SessionInfo>>(File.ReadAllText(tokensDir))!; - _users.Add(user); - } - - Console.WriteLine($"Loaded {_users.Count} users from disk"); - } - else { - Console.WriteLine("Data storage is disabled, not loading users from disk"); - } - } - - public async Task<User?> GetUserById(string userId, bool createIfNotExists = false) { - if (_users.Any(x => x.UserId == userId)) - return _users.First(x => x.UserId == userId); - - if (!createIfNotExists) - return null; - - return await CreateUser(userId); - } - - public async Task<User?> GetUserByTokenOrNull(string token, bool createIfNotExists = false, string? serverName = null) { - if (_users.Any(x => x.AccessTokens.ContainsKey(token))) - return _users.First(x => x.AccessTokens.ContainsKey(token)); - - if (!createIfNotExists) - return null; - if (string.IsNullOrWhiteSpace(serverName)) throw new NullReferenceException("Server name was not passed"); - var uid = $"@{Guid.NewGuid().ToString()}:{serverName}"; - return await CreateUser(uid); - } - - public async Task<User> GetUserByToken(string token, bool createIfNotExists = false, string? serverName = null) { - return await GetUserByTokenOrNull(token, createIfNotExists, serverName) ?? throw new MatrixException() { - ErrorCode = MatrixException.ErrorCodes.M_UNKNOWN_TOKEN, - Error = "Invalid token." - }; - } - - public async Task<User> CreateUser(string userId, Dictionary<string, object>? profile = null) { - profile ??= new(); - if (!profile.ContainsKey("displayname")) profile.Add("displayname", userId.Split(":")[0]); - if (!profile.ContainsKey("avatar_url")) profile.Add("avatar_url", null); - var user = new User() { - UserId = userId, - AccountData = new() { - new StateEventResponse() { - Type = "im.vector.analytics", - RawContent = new JsonObject() { - ["pseudonymousAnalyticsOptIn"] = false - }, - }, - new StateEventResponse() { - Type = "im.vector.web.settings", - RawContent = new JsonObject() { - ["developerMode"] = true - } - }, - } - }; - user.Profile.AddRange(profile); - _users.Add(user); - if (!_roomStore._rooms.IsEmpty) - foreach (var item in Random.Shared.GetItems(_roomStore._rooms.ToArray(), Math.Min(_roomStore._rooms.Count, 400))) { - item.AddUser(userId); - } - - int random = Random.Shared.Next(10); - for (int i = 0; i < random; i++) { - var room = _roomStore.CreateRoom(new()); - room.AddUser(userId); - } - - return user; - } - - public class User : NotifyPropertyChanged { - public User() { - AccessTokens = new(); - Filters = new(); - Profile = new(); - AccountData = new(); - RoomKeys = new(); - AuthorizedSessions = new(); - } - - private CancellationTokenSource _debounceCts = new(); - private string _userId; - private ObservableDictionary<string, SessionInfo> _accessTokens; - private ObservableDictionary<string, SyncFilter> _filters; - private ObservableDictionary<string, object> _profile; - private ObservableCollection<StateEventResponse> _accountData; - private ObservableDictionary<string, RoomKeysResponse> _roomKeys; - private ObservableDictionary<string, AuthorizedSession> _authorizedSessions; - - public string UserId { - get => _userId; - set => SetField(ref _userId, value); - } - - public ObservableDictionary<string, SessionInfo> AccessTokens { - get => _accessTokens; - set { - if (value == _accessTokens) return; - _accessTokens = new(value); - _accessTokens.CollectionChanged += async (sender, args) => await SaveDebounced(); - OnPropertyChanged(); - } - } - - public ObservableDictionary<string, SyncFilter> Filters { - get => _filters; - set { - if (value == _filters) return; - _filters = new(value); - _filters.CollectionChanged += async (sender, args) => await SaveDebounced(); - OnPropertyChanged(); - } - } - - public ObservableDictionary<string, object> Profile { - get => _profile; - set { - if (value == _profile) return; - _profile = new(value); - _profile.CollectionChanged += async (sender, args) => await SaveDebounced(); - OnPropertyChanged(); - } - } - - public ObservableCollection<StateEventResponse> AccountData { - get => _accountData; - set { - if (value == _accountData) return; - _accountData = new(value); - _accountData.CollectionChanged += async (sender, args) => await SaveDebounced(); - OnPropertyChanged(); - } - } - - public ObservableDictionary<string, RoomKeysResponse> RoomKeys { - get => _roomKeys; - set { - if (value == _roomKeys) return; - _roomKeys = new(value); - _roomKeys.CollectionChanged += async (sender, args) => await SaveDebounced(); - OnPropertyChanged(); - } - } - - public ObservableDictionary<string, AuthorizedSession> AuthorizedSessions { - get => _authorizedSessions; - set { - if (value == _authorizedSessions) return; - _authorizedSessions = new(value); - _authorizedSessions.CollectionChanged += async (sender, args) => await SaveDebounced(); - OnPropertyChanged(); - } - } - - public async Task SaveDebounced() { - 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); - if (!Directory.Exists(dataDir)) Directory.CreateDirectory(dataDir); - var tokensDir = Path.Combine(dataDir, "tokens.json"); - var path = Path.Combine(dataDir, $"user.json"); - Console.WriteLine($"Saving user {_userId} to {path}!"); - await File.WriteAllTextAsync(path, this.ToJson(ignoreNull: true)); - await File.WriteAllTextAsync(tokensDir, AccessTokens.ToJson(ignoreNull: true)); - } - catch (TaskCanceledException) { } - catch (InvalidOperationException) { } // We don't care about 100% data safety, this usually happens when something is updated while serialising - } - - public class SessionInfo { - public string DeviceId { get; set; } = Guid.NewGuid().ToString(); - public Dictionary<string, UserSyncState> SyncStates { get; set; } = new(); - - public class UserSyncState { - public Dictionary<string, SyncRoomPosition> RoomPositions { get; set; } = new(); - public string FilterId { get; set; } - public DateTime SyncStateCreated { get; set; } = DateTime.Now; - - public class SyncRoomPosition { - public int TimelinePosition { get; set; } - public string LastTimelineEventId { get; set; } - public int AccountDataPosition { get; set; } - public bool Joined { get; set; } - } - - public UserSyncState Clone() { - return new() { - FilterId = FilterId, - RoomPositions = RoomPositions.ToDictionary(x => x.Key, x => new SyncRoomPosition() { - TimelinePosition = x.Value.TimelinePosition, - AccountDataPosition = x.Value.AccountDataPosition - }) - }; - } - } - } - - public LoginResponse Login() { - var session = new SessionInfo(); - AccessTokens.Add(Guid.NewGuid().ToString(), session); - SaveDebounced(); - return new LoginResponse() { - AccessToken = AccessTokens.Keys.Last(), - DeviceId = session.DeviceId, - UserId = UserId - }; - } - - public class AuthorizedSession { - public string Homeserver { get; set; } - public string AccessToken { get; set; } - } - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.HomeserverEmulator/appsettings.Development.json b/Tests/LibMatrix.HomeserverEmulator/appsettings.Development.json deleted file mode 100644
index f14522d..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/appsettings.Development.json +++ /dev/null
@@ -1,12 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Information", - "Microsoft.AspNetCore.Routing": "Warning", - "Microsoft.AspNetCore.Mvc": "Warning" - } - }, - "HomeserverEmulator": { - } -} diff --git a/Tests/LibMatrix.HomeserverEmulator/appsettings.json b/Tests/LibMatrix.HomeserverEmulator/appsettings.json deleted file mode 100644
index b16968a..0000000 --- a/Tests/LibMatrix.HomeserverEmulator/appsettings.json +++ /dev/null
@@ -1,41 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*", - // Configuration for the proxy - "MxApiExtensions": { - // WARNING: this exposes user tokens to servers listed here, which could be a security risk - // Only list servers you trust! - // Keep in mind that token conflicts can occur between servers! - "AuthHomeservers": [ - "rory.gay", - "conduit.rory.gay" - ], - // List of administrator MXIDs for the proxy, this allows them to use administrative and debug endpoints - "Admins": [ - "@emma:rory.gay", - "@emma:conduit.rory.gay" - ], - "FastInitialSync": { - "Enabled": true, - "UseRoomInfoCache": true - }, - "Cache": { - "RoomInfo": { - "BaseTtl": "00:01:00", - "ExtraTtlPerState": "00:00:00.1000000" - } - }, - "DefaultUserConfiguration": { - "ProtocolChanges": { - "DisableThreads": false, - "DisableVoip": false, - "AutoFollowTombstones": false - } - } - } -} diff --git a/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs b/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs
index 13b5c1b..6878b44 100644 --- a/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs +++ b/Tests/LibMatrix.Tests/Abstractions/HomeserverAbstraction.cs
@@ -2,72 +2,81 @@ using ArcaneLibs.Extensions; using LibMatrix.Homeservers; using LibMatrix.Responses; using LibMatrix.Services; -using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Logging; +using Xunit.Abstractions; namespace LibMatrix.Tests.Abstractions; -public static class HomeserverAbstraction { - private static HomeserverResolverService _hsResolver = new HomeserverResolverService(NullLogger<HomeserverResolverService>.Instance); - private static HomeserverProviderService _hsProvider = new HomeserverProviderService(NullLogger<HomeserverProviderService>.Instance, _hsResolver); +public class HomeserverAbstraction(HomeserverProviderService _hsProvider, Config _config, ILogger<HomeserverAbstraction> _logger) { + // private static readonly HomeserverResolverService _hsResolver = new HomeserverResolverService(NullLogger<HomeserverResolverService>.Instance); + // private static readonly HomeserverProviderService _hsProvider = new HomeserverProviderService(NullLogger<HomeserverProviderService>.Instance, _hsResolver); + + private static AuthenticatedHomeserverGeneric? ConfiguredHomeserver { get; set; } + private static readonly SemaphoreSlim _lock = new(1, 1); + + public async Task<AuthenticatedHomeserverGeneric> GetConfiguredHomeserver(ITestOutputHelper? testOutputHelper = null) { + Assert.False(string.IsNullOrWhiteSpace(_config.TestHomeserver)); + Assert.False(string.IsNullOrWhiteSpace(_config.TestUsername)); + Assert.False(string.IsNullOrWhiteSpace(_config.TestPassword)); + + _logger.LogDebug("Using homeserver '{0}' with login '{1}' '{2}", _config.TestHomeserver, _config.TestUsername, _config.TestPassword); + testOutputHelper?.WriteLine($"Using homeserver '{_config.TestHomeserver}' with login '{_config.TestUsername}' '{_config.TestPassword}'"); - public static async Task<AuthenticatedHomeserverGeneric> GetHomeserver() { - var rhs = await _hsProvider.GetRemoteHomeserver("matrixunittests.rory.gay"); - var username = "@f1a2d2d6-1924-421b-91d0-893b347b2a49:matrixunittests.rory.gay"; - var password = "d6d782d6-8bc9-4fac-9cd8-78e101b4298b"; + await _lock.WaitAsync(); + if (ConfiguredHomeserver is not null) { + _lock.Release(); + return ConfiguredHomeserver; + } + + var rhs = await _hsProvider.GetRemoteHomeserver(_config.TestHomeserver); + LoginResponse reg; try { - reg = await rhs.LoginAsync(username, password); + reg = await rhs.LoginAsync(_config.TestUsername, _config.TestPassword); } catch (MatrixException e) { if (e.ErrorCode == "M_FORBIDDEN") { await rhs.RegisterAsync(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Unit tests!"); - reg = await rhs.RegisterAsync(username, password, "Unit tests!"); + reg = await rhs.RegisterAsync(_config.TestUsername, _config.TestPassword, "Unit tests!"); } else throw new Exception("Failed to register", e); } var hs = await _hsProvider.GetAuthenticatedWithToken(reg.Homeserver, reg.AccessToken); - //var rooms = await hs.GetJoinedRooms(); - - // var disbandRoomTasks = rooms.Select(async room => { - // // await room.DisbandRoomAsync(); - // await room.LeaveAsync(); - // await room.ForgetAsync(); - // return room; - // }).ToList(); - // await Task.WhenAll(disbandRoomTasks); - - // foreach (var room in rooms) { - // // await room.DisbandRoomAsync(); - // await room.LeaveAsync(); - // await room.ForgetAsync(); - // } + ConfiguredHomeserver = hs; + _lock.Release(); return hs; } - public static async Task<AuthenticatedHomeserverGeneric> GetRandomHomeserver() { - var rhs = await _hsProvider.GetRemoteHomeserver("matrixunittests.rory.gay"); - var reg = await rhs.RegisterAsync(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Unit tests!"); + public async Task<AuthenticatedHomeserverGeneric> GetNewHomeserver() { + Assert.False(string.IsNullOrWhiteSpace(_config.TestHomeserver)); + var username = Guid.NewGuid().ToString(); + var password = Guid.NewGuid().ToString(); + + _logger.LogDebug("Creating new homeserver '{0}' with login '{1}' '{2}'", _config.TestHomeserver, username, password); + + var rhs = await _hsProvider.GetRemoteHomeserver(_config.TestHomeserver); + var reg = await rhs.RegisterAsync(username, password, "Unit tests!"); var hs = await _hsProvider.GetAuthenticatedWithToken(reg.Homeserver, reg.AccessToken); - - // var rooms = await hs.GetJoinedRooms(); - // - // var disbandRoomTasks = rooms.Select(async room => { - // // await room.DisbandRoomAsync(); - // await room.LeaveAsync(); - // await room.ForgetAsync(); - // return room; - // }).ToList(); - // await Task.WhenAll(disbandRoomTasks); - + return hs; } - public static async IAsyncEnumerable<AuthenticatedHomeserverGeneric> GetRandomHomeservers(int count = 1) { + public async IAsyncEnumerable<AuthenticatedHomeserverGeneric> GetNewHomeservers(int count = 1) { var createRandomUserTasks = Enumerable .Range(0, count) - .Select(_ => GetRandomHomeserver()).ToAsyncEnumerable(); + .Select(_ => GetNewHomeserver()).ToAsyncEnumerable(); await foreach (var hs in createRandomUserTasks) yield return hs; } + + public async Task<(string username, string password, string token)> GetKnownCredentials() { + Assert.False(string.IsNullOrWhiteSpace(_config.TestHomeserver)); + var rhs = await _hsProvider.GetRemoteHomeserver(_config.TestHomeserver); + + var username = _config.TestUsername; + var password = _config.TestPassword; + var reg = await rhs.RegisterAsync(username, password, "Unit tests!"); + return ("", "", ""); + } } \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs b/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs
index 2a380fc..b1176ca 100644 --- a/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs +++ b/Tests/LibMatrix.Tests/Abstractions/RoomAbstraction.cs
@@ -1,6 +1,6 @@ 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; @@ -16,28 +16,28 @@ public static class RoomAbstraction { }; crq.InitialState ??= new List<StateEvent>(); crq.InitialState.Add(new StateEvent() { - Type = "m.room.topic", + Type = RoomTopicEventContent.EventId, StateKey = "", TypedContent = new RoomTopicEventContent() { Topic = "LibMatrix Test Room " + DateTime.Now.ToString("O") } }); crq.InitialState.Add(new StateEvent() { - Type = "m.room.name", + Type = RoomNameEventContent.EventId, StateKey = "", TypedContent = new RoomNameEventContent() { Name = "LibMatrix Test Room " + DateTime.Now.ToString("O") } }); crq.InitialState.Add(new StateEvent() { - Type = "m.room.avatar", + Type = RoomAvatarEventContent.EventId, StateKey = "", TypedContent = new RoomAvatarEventContent() { Url = "mxc://conduit.rory.gay/r9KiT0f9eQbv8pv4RxwBZFuzhfKjGWHx" } }); crq.InitialState.Add(new StateEvent() { - Type = "m.room.aliases", + Type = RoomAliasEventContent.EventId, StateKey = "", TypedContent = new RoomAliasEventContent() { Aliases = Enumerable @@ -52,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); @@ -96,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 ddbf705..b59b238 100644 --- a/Tests/LibMatrix.Tests/Config.cs +++ b/Tests/LibMatrix.Tests/Config.cs
@@ -1,18 +1,41 @@ +using Microsoft.Extensions.Configuration; + namespace LibMatrix.Tests; public class Config { + public Config(IConfiguration? config) { + config.GetSection("Configuration").Bind(this); + } + public string? TestHomeserver { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_HOMESERVER") ?? null; - public string? TestUsername { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_USERNAME") ?? null; - public string? TestPassword { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_PASSWORD") ?? null; - public string? TestRoomId { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_ROOM_ID") ?? null; - public string? TestRoomAlias { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_ROOM_ALIAS") ?? null; + public string? TestUsername { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_USERNAME") ?? Guid.NewGuid().ToString(); + + public string? TestPassword { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_PASSWORD") ?? Guid.NewGuid().ToString(); + // public string? TestRoomId { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_ROOM_ID") ?? null; + // public string? TestRoomAlias { get; set; } = Environment.GetEnvironmentVariable("LIBMATRIX_TEST_ROOM_ALIAS") ?? null; - public Dictionary<string, string> ExpectedHomeserverMappings { get; set; } = new() { + public Dictionary<string, string> ExpectedHomeserverClientMappings { get; set; } = new() { { "matrix.org", "https://matrix-client.matrix.org" }, - { "rory.gay", "https://matrix.rory.gay" } + { "rory.gay", "https://matrix.rory.gay" }, + { "feline.support", "https://matrix.feline.support" }, + { "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" } + }; + + public Dictionary<string, string> ExpectedHomeserverFederationMappings { get; set; } = new() { + { "rory.gay", "https://matrix.rory.gay:443" }, + { "matrix.org", "https://matrix-federation.matrix.org:443" }, + { "feline.support", "https://matrix.feline.support:8448" }, + { "transfem.dev", "https://matrix.transfem.dev:443" }, + { "the-apothecary.club", "https://the-apothecary.club:443" }, + { "nixos.org", "https://matrix.nixos.org:443" }, + { "fedora.im", "https://fedora.ems.host:443" } }; public Dictionary<string, string> ExpectedAliasMappings { get; set; } = new() { - { "#libmatrix:rory.gay", "!tuiLEoMqNOQezxILzt:rory.gay" } + { "#libmatrix:rory.gay", "!tuiLEoMqNOQezxILzt:rory.gay" }, + { "#matrix:matrix.org", "!OGEhHVWSdvArJzumhm:matrix.org" } }; } \ No newline at end of file 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 35c8704..e3c4388 100644 --- a/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs +++ b/Tests/LibMatrix.Tests/Fixtures/TestFixture.cs
@@ -1,5 +1,5 @@ -using ArcaneLibs.Extensions; using LibMatrix.Services; +using LibMatrix.Tests.Abstractions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Xunit.Microsoft.DependencyInjection; @@ -8,24 +8,19 @@ using Xunit.Microsoft.DependencyInjection.Abstracts; namespace LibMatrix.Tests.Fixtures; public class TestFixture : TestBedFixture { - protected override void AddServices(IServiceCollection services, IConfiguration? configuration) { - services.AddSingleton<TieredStorageService>(x => - new TieredStorageService( - null, - null - ) - ); + protected override void AddServices(IServiceCollection services, IConfiguration configuration) { + // services.AddSingleton<TieredStorageService>(x => + // new TieredStorageService( + // null, + // null + // ) + // ); + services.AddSingleton(configuration); services.AddRoryLibMatrixServices(); - - services.AddSingleton<Config>(config => { - var conf = new Config(); - configuration?.GetSection("Configuration").Bind(conf); - - File.WriteAllText("configuration.json", conf.ToJson()); - - return conf; - }); + services.AddLogging(); + services.AddSingleton<HomeserverAbstraction>(); + services.AddSingleton<Config>(); } protected override ValueTask DisposeAsyncCore() diff --git a/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj b/Tests/LibMatrix.Tests/LibMatrix.Tests.csproj
index 095985a..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.1" /> - <PackageReference Include="Xunit.Microsoft.DependencyInjection" Version="8.1.0" /> - <PackageReference Include="xunit.runner.visualstudio" Version="2.8.1"> + <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 b2f5627..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; @@ -14,19 +13,19 @@ public class AuthMediaTests : TestBed<TestFixture> { private readonly HomeserverResolverService _resolver; private readonly Config _config; private readonly HomeserverProviderService _provider; + private readonly HomeserverAbstraction _hsAbstraction; public AuthMediaTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { _fixture = fixture; _resolver = _fixture.GetService<HomeserverResolverService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}"); _config = _fixture.GetService<Config>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(Config)}"); _provider = _fixture.GetService<HomeserverProviderService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverProviderService)}"); + _hsAbstraction = _fixture.GetService<HomeserverAbstraction>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverAbstraction)}"); } - private async Task<AuthenticatedHomeserverGeneric> GetHomeserver() => await HomeserverAbstraction.GetHomeserver(); - [Fact] public async Task UploadFileAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var mxcUri = await hs.UploadFile("test", "LibMatrix test file".AsBytes()); Assert.NotNull(mxcUri); @@ -34,7 +33,7 @@ public class AuthMediaTests : TestBed<TestFixture> { [Fact] public async Task DownloadFileAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var mxcUri = await hs.UploadFile("test", "LibMatrix test file".AsBytes()); Assert.NotNull(mxcUri); @@ -48,7 +47,7 @@ public class AuthMediaTests : TestBed<TestFixture> { [SkippableFact(typeof(LibMatrixException))] // This test will fail if the homeserver does not support URL previews public async Task GetUrlPreviewAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var preview = await hs.GetUrlPreviewAsync("https://matrix.org"); Assert.NotNull(preview); diff --git a/Tests/LibMatrix.Tests/Tests/AuthTests.cs b/Tests/LibMatrix.Tests/Tests/AuthTests.cs
index 3ffadf0..69e6231 100644 --- a/Tests/LibMatrix.Tests/Tests/AuthTests.cs +++ b/Tests/LibMatrix.Tests/Tests/AuthTests.cs
@@ -1,4 +1,5 @@ using LibMatrix.Services; +using LibMatrix.Tests.Abstractions; using LibMatrix.Tests.DataTests; using LibMatrix.Tests.Fixtures; using Xunit.Abstractions; @@ -7,18 +8,16 @@ using Xunit.Microsoft.DependencyInjection.Abstracts; namespace LibMatrix.Tests.Tests; public class AuthTests : TestBed<TestFixture> { - private readonly TestFixture _fixture; - private readonly HomeserverResolverService _resolver; private readonly Config _config; private readonly HomeserverProviderService _provider; + private readonly HomeserverAbstraction _hsAbstraction; public AuthTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { - _fixture = fixture; - _resolver = _fixture.GetService<HomeserverResolverService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}"); _config = _fixture.GetService<Config>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(Config)}"); _provider = _fixture.GetService<HomeserverProviderService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverProviderService)}"); + _hsAbstraction = _fixture.GetService<HomeserverAbstraction>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverAbstraction)}"); } - + [Fact] public async Task LoginWithPassword() { Assert.False(string.IsNullOrWhiteSpace(_config.TestHomeserver), $"{nameof(_config.TestHomeserver)} must be set in appsettings!"); @@ -34,9 +33,7 @@ public class AuthTests : TestBed<TestFixture> { var login = await _provider.Login(_config.TestHomeserver!, username, password); Assert.NotNull(login); - var hs = await _provider.GetAuthenticatedWithToken(_config.TestHomeserver!, login.AccessToken); - Assert.NotNull(hs); - await hs.Logout(); + Assert.NotNull(login.AccessToken); } [Fact] @@ -63,7 +60,7 @@ public class AuthTests : TestBed<TestFixture> { [Fact] public async Task RegisterAsync() { - var rhs = await _provider.GetRemoteHomeserver("matrixunittests.rory.gay"); + var rhs = await _provider.GetRemoteHomeserver(_config.TestHomeserver); var reg = await rhs.RegisterAsync(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "Unit tests!"); Assert.NotNull(reg); Assert.NotNull(reg.AccessToken); diff --git a/Tests/LibMatrix.Tests/Tests/CanonicalJsonTests.cs b/Tests/LibMatrix.Tests/Tests/CanonicalJsonTests.cs new file mode 100644
index 0000000..b6bde71 --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/CanonicalJsonTests.cs
@@ -0,0 +1,49 @@ +using System.Collections.Frozen; +using System.Diagnostics; +using System.Text.Json; +using LibMatrix.Extensions; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests; + +public class CanonicalJsonTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : TestBed<TestFixture>(testOutputHelper, fixture) { + // Test cases from https://spec.matrix.org/v1.11/appendices/#examples + private static readonly FrozenDictionary<string, string> testCases = new Dictionary<string, string>() { + ["{}"] = "{}", + ["{\n \"one\": 1,\n \"two\": \"Two\"\n}\n"] = "{\"one\":1,\"two\":\"Two\"}", + ["{\n \"b\": \"2\",\n \"a\": \"1\"\n}\n"] = "{\"a\":\"1\",\"b\":\"2\"}", + ["{\"b\":\"2\",\"a\":\"1\"}"] = "{\"a\":\"1\",\"b\":\"2\"}", + ["{\n \"auth\": {\n \"success\": true,\n \"mxid\": \"@john.doe:example.com\",\n \"profile\": {\n \"display_name\": \"John Doe\",\n \"three_pids\": [\n {\n \"medium\": \"email\",\n \"address\": \"[email protected]\"\n },\n {\n \"medium\": \"msisdn\",\n \"address\": \"123456789\"\n }\n ]\n }\n }\n}\n"] = + "{\"auth\":{\"mxid\":\"@john.doe:example.com\",\"profile\":{\"display_name\":\"John Doe\",\"three_pids\":[{\"address\":\"[email protected]\",\"medium\":\"email\"},{\"address\":\"123456789\",\"medium\":\"msisdn\"}]},\"success\":true}}", + ["{\n \"a\": \"日本語\"\n}\n"] = "{\"a\":\"日本語\"}", + ["{\n \"本\": 2,\n \"日\": 1\n}\n"] = "{\"日\":1,\"本\":2}", + ["{\n \"a\": \"\\u65E5\"\n}\n"] = "{\"a\":\"日\"}", + ["{\n \"a\": null\n}\n"] = "{\"a\":null}", + ["{\n \"a\": -0,\n \"b\": 1e10\n}\n"] = "{\"a\":0,\"b\":10000000000}" + }.ToFrozenDictionary(); + + [Fact] + public void SpecTests() { + var i = 0; + foreach (var (input, expected) in testCases) { + var deserialised = JsonSerializer.Deserialize<Dictionary<string, object>>(input); + var actual = CanonicalJsonSerializer.Serialize(deserialised); + Assert.Equal(expected, actual); + // testOutputHelper.WriteLine($"Test case {i++} successful!"); + } + } + + [Fact] + public void RepeatTests() { + var sw = Stopwatch.StartNew(); + for (int i = 0; i < 1_000_000; i++) { + SpecTests(); + if (i % 10000 == 0) { + testOutputHelper.WriteLine($"{i} loops successful! Delta: {sw.Elapsed}"); + sw.Restart(); + } + } + } +} \ No newline at end of file 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/LegacyHomeserverResolverTests.cs b/Tests/LibMatrix.Tests/Tests/LegacyHomeserverResolverTests.cs new file mode 100644
index 0000000..20dc4fb --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/LegacyHomeserverResolverTests.cs
@@ -0,0 +1,36 @@ +using LibMatrix.Services; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests; + +public class LegacyHomeserverResolverTests : TestBed<TestFixture> { + private readonly Config _config; + private readonly HomeserverResolverService _resolver; + + 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)}"); + } + + [Fact] + public async Task ResolveServerClient() { + var tasks = _config.ExpectedHomeserverClientMappings.Select(async mapping => { + var server = await _resolver.ResolveHomeserverFromWellKnown(mapping.Key); + Assert.Equal(mapping.Value, server.Client); + return server; + }).ToList(); + await Task.WhenAll(tasks); + } + + [Fact] + public async Task ResolveServerServer() { + var tasks = _config.ExpectedHomeserverFederationMappings.Select(async mapping => { + var server = await _resolver.ResolveHomeserverFromWellKnown(mapping.Key); + Assert.Equal(mapping.Value, server.Server); + return server; + }).ToList(); + await Task.WhenAll(tasks); + } +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/ResolverTest.cs b/Tests/LibMatrix.Tests/Tests/RemoteHomeserverTests.cs
index 700aa96..20f975e 100644 --- a/Tests/LibMatrix.Tests/Tests/ResolverTest.cs +++ b/Tests/LibMatrix.Tests/Tests/RemoteHomeserverTests.cs
@@ -5,43 +5,44 @@ using Xunit.Microsoft.DependencyInjection.Abstracts; namespace LibMatrix.Tests.Tests; -public class ResolverTest : TestBed<TestFixture> { +public class RemoteHomeserverTests : TestBed<TestFixture> { private readonly TestFixture _fixture; private readonly HomeserverResolverService _resolver; private readonly Config _config; private readonly HomeserverProviderService _provider; - public ResolverTest(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { + public RemoteHomeserverTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { _fixture = fixture; _resolver = _fixture.GetService<HomeserverResolverService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}"); _config = _fixture.GetService<Config>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(Config)}"); _provider = _fixture.GetService<HomeserverProviderService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverProviderService)}"); } - [Fact] - public async Task ResolveServer() { - foreach (var (domain, expected) in _config.ExpectedHomeserverMappings) { - var server = await _resolver.ResolveHomeserverFromWellKnown(domain); - Assert.Equal(expected, server.Client); - } - } - - [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); - } + // [Fact] + // public async Task ResolveMedia() { + // var hs = await _provider.GetRemoteHomeserver("matrix.org"); + // var media = hs.ResolveMediaUri("mxc://matrix.org/eqwrRZRoPpNbcMeUwyXAuVRo"); + // + // Assert.Equal("https://matrix-client.matrix.org/_matrix/media/v3/download/matrix.org/eqwrRZRoPpNbcMeUwyXAuVRo", media); + // } [Fact] public async Task ResolveRoomAliasAsync() { - var hs = await _provider.GetRemoteHomeserver("matrix.org"); - var alias = await hs.ResolveRoomAliasAsync("#matrix:matrix.org"); - Assert.Equal("!OGEhHVWSdvArJzumhm:matrix.org", alias.RoomId); + // var hs = await _provider.GetRemoteHomeserver("matrix.org"); + // var alias = await hs.ResolveRoomAliasAsync("#matrix:matrix.org"); + // Assert.Equal("!OGEhHVWSdvArJzumhm:matrix.org", alias.RoomId); + var tasks = _config.ExpectedAliasMappings.Select(async mapping => { + var hs = await _provider.GetRemoteHomeserver("matrix.org"); + var alias = await hs.ResolveRoomAliasAsync(mapping.Key); + Assert.Equal(mapping.Value, alias.RoomId); + return alias; + }).ToList(); + await Task.WhenAll(tasks); } [Fact] public async Task GetClientVersionsAsync() { - var hs = await _provider.GetRemoteHomeserver("matrix.org"); + var hs = await _provider.GetRemoteHomeserver(_config.TestHomeserver); var versions = await hs.GetClientVersionsAsync(); Assert.NotNull(versions); } diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests.cs deleted file mode 100644
index 4c8dcb4..0000000 --- a/Tests/LibMatrix.Tests/Tests/RoomTests.cs +++ /dev/null
@@ -1,248 +0,0 @@ -using System.Text; -using LibMatrix.EventTypes.Spec.State; -using LibMatrix.Homeservers; -using LibMatrix.Responses; -using LibMatrix.Services; -using LibMatrix.Tests.Abstractions; -using LibMatrix.Tests.Fixtures; -using Xunit.Abstractions; -using Xunit.Microsoft.DependencyInjection.Abstracts; - -namespace LibMatrix.Tests.Tests; - -public class RoomTests : TestBed<TestFixture> { - private readonly TestFixture _fixture; - private readonly HomeserverResolverService _resolver; - private readonly Config _config; - private readonly HomeserverProviderService _provider; - - public RoomTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { - _fixture = fixture; - _resolver = _fixture.GetService<HomeserverResolverService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}"); - _config = _fixture.GetService<Config>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(Config)}"); - _provider = _fixture.GetService<HomeserverProviderService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverProviderService)}"); - } - - private async Task<AuthenticatedHomeserverGeneric> GetHomeserver() => await HomeserverAbstraction.GetHomeserver(); - - [Fact] - public async Task GetJoinedRoomsAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - //make 100 rooms - var createRoomTasks = Enumerable.Range(0, 10).Select(_ => RoomAbstraction.GetTestRoom(hs)).ToList(); - await Task.WhenAll(createRoomTasks); - - var rooms = await hs.GetJoinedRooms(); - Assert.NotNull(rooms); - Assert.NotEmpty(rooms); - Assert.All(rooms, Assert.NotNull); - Assert.True(rooms.Count >= 10, "Not enough rooms were found"); - - await hs.Logout(); - } - - [Fact] - public async Task GetMembersAsync() { - Assert.True(StateEvent.KnownStateEventTypes is { Count: > 0 }, "StateEvent.KnownStateEventTypes is empty!"); - Assert.True(StateEvent.KnownStateEventTypesByName is { Count: > 0 }, "StateEvent.KnownStateEventTypesByName is empty!"); - - var hs = await HomeserverAbstraction.GetHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - var members = room.GetMembersEnumerableAsync(); - Assert.NotNull(members); - var hitMembers = false; - await foreach (var member in members) { - Assert.NotNull(member); - Assert.NotNull(member.StateKey); - Assert.NotEmpty(member.StateKey); - Assert.NotNull(member.Sender); - Assert.NotEmpty(member.Sender); - Assert.NotNull(member.RawContent); - Assert.NotEmpty(member.RawContent); - Assert.NotNull(member.TypedContent); - Assert.IsType<RoomMemberEventContent>(member.TypedContent); - var content = (RoomMemberEventContent)member.TypedContent; - Assert.NotNull(content); - Assert.NotNull(content.Membership); - Assert.NotEmpty(content.Membership); - hitMembers = true; - } - - Assert.True(hitMembers, "No members were found in the room"); - } - - [Fact] - public async Task JoinAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - var id = await room.JoinAsync(); - Assert.NotNull(id); - Assert.NotNull(id.RoomId); - Assert.NotEmpty(id.RoomId); - } - - [Fact] - public async Task ForgetAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - await room.ForgetAsync(); - } - - [Fact] - public async Task LeaveAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - await room.LeaveAsync(); - } - - [Fact] - public async Task KickAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var hs2 = await HomeserverAbstraction.GetRandomHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - await room.InviteUserAsync(hs2.UserId, "Unit test!"); - await hs2.GetRoom(room.RoomId).JoinAsync(); - await room.KickAsync(hs2.UserId, "test"); - var banState = await room.GetStateAsync<RoomMemberEventContent>("m.room.member", hs2.UserId); - Assert.NotNull(banState); - Assert.Equal("leave", banState.Membership); - } - - [Fact] - public async Task BanAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var hs2 = await HomeserverAbstraction.GetRandomHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - await room.BanAsync(hs2.UserId, "test"); - var banState = await room.GetStateAsync<RoomMemberEventContent>("m.room.member", hs2.UserId); - Assert.NotNull(banState); - Assert.Equal("ban", banState.Membership); - } - - [Fact] - public async Task UnbanAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var hs2 = await HomeserverAbstraction.GetRandomHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - await room.BanAsync(hs2.UserId, "test"); - var banState = await room.GetStateAsync<RoomMemberEventContent>("m.room.member", hs2.UserId); - Assert.NotNull(banState); - Assert.Equal("ban", banState.Membership); - await room.UnbanAsync(hs2.UserId); - var unbanState = await room.GetStateAsync<RoomMemberEventContent>("m.room.member", hs2.UserId); - Assert.NotNull(unbanState); - Assert.Equal("leave", unbanState.Membership); - } - - [SkippableFact(typeof(MatrixException))] - public async Task SendStateEventAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - - await room.SendStateEventAsync("gay.rory.libmatrix.unit_tests", new UserProfileResponse() { - DisplayName = "wee_woo", - AvatarUrl = "no" - }); - await room.SendStateEventAsync("gay.rory.libmatrix.unit_tests", "state_key_maybe", new UserProfileResponse() { - DisplayName = "wee_woo", - AvatarUrl = "yes" - }); - } - - [SkippableFact(typeof(MatrixException))] - public async Task SendAndGetStateEventAsync() { - await SendStateEventAsync(); - var hs = await HomeserverAbstraction.GetHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - - await room.SendStateEventAsync("gay.rory.libmatrix.unit_tests", new UserProfileResponse() { - DisplayName = "wee_woo", - AvatarUrl = "no" - }); - await room.SendStateEventAsync("gay.rory.libmatrix.unit_tests", "state_key_maybe", new UserProfileResponse() { - DisplayName = "wee_woo", - AvatarUrl = "yes" - }); - - var state1 = await room.GetStateAsync<UserProfileResponse>("gay.rory.libmatrix.unit_tests"); - Assert.NotNull(state1); - Assert.NotNull(state1.DisplayName); - Assert.NotEmpty(state1.DisplayName); - Assert.NotNull(state1.AvatarUrl); - Assert.NotEmpty(state1.AvatarUrl); - Assert.Equal("wee_woo", state1.DisplayName); - Assert.Equal("no", state1.AvatarUrl); - - var state2 = await room.GetStateAsync<UserProfileResponse>("gay.rory.libmatrix.unit_tests", "state_key_maybe"); - Assert.NotNull(state2); - Assert.NotNull(state2.DisplayName); - Assert.NotEmpty(state2.DisplayName); - Assert.NotNull(state2.AvatarUrl); - Assert.NotEmpty(state2.AvatarUrl); - Assert.Equal("wee_woo", state2.DisplayName); - Assert.Equal("yes", state2.AvatarUrl); - } - - [Fact] - public async Task DisbandAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - - await room.PermanentlyBrickRoomAsync(); - } - - [Fact] - public async Task SendFileAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - - var res = await room.SendFileAsync("test.txt", new MemoryStream(Encoding.UTF8.GetBytes("This test was written by Emma [it/its], member of the Rory& system." + - "\nIf you are reading this on matrix, it means the unit test for uploading a file works!"))); - Assert.NotNull(res); - Assert.NotNull(res.EventId); - } - - [Fact] - public async Task GetSpaceChildrenAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var space = await RoomAbstraction.GetTestSpace(hs, 2, false, 1); - Assert.NotNull(space); - var children = space.GetChildrenAsync(); - Assert.NotNull(children); - var found = 0; - await foreach (var room in children) found++; - Assert.Equal(2, found); - } - - [Fact] - public async Task InviteAndJoinAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - var otherUsers = HomeserverAbstraction.GetRandomHomeservers(15); - Assert.NotNull(room); - - // var expectedCount = 1; - - var tasks = new List<Task>(); - await foreach (var otherUser in otherUsers) - tasks.Add(Task.Run(async () => { - await room.InviteUserAsync(otherUser.UserId); - await otherUser.GetRoom(room.RoomId).JoinAsync(); - })); - await Task.WhenAll(tasks); - - var states = await room.GetMembersListAsync(false); - Assert.Equal(16, states.Count); - } -} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/OtherRoomTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/OtherRoomTests.cs new file mode 100644
index 0000000..1ae195d --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/OtherRoomTests.cs
@@ -0,0 +1,101 @@ +using LibMatrix.Tests.Abstractions; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests.BasicRoomEventTests; + +public class OtherRoomTests : TestBed<TestFixture> { + private readonly HomeserverAbstraction _hsAbstraction; + + public OtherRoomTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { + _hsAbstraction = _fixture.GetService<HomeserverAbstraction>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverAbstraction)}"); + } + + [SkippableFact(typeof(MatrixException))] + public async Task GetCanonicalAliasAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + var alias = await room.GetCanonicalAliasAsync(); + Assert.NotNull(alias); + Assert.NotNull(alias.Alias); + Assert.NotEmpty(alias.Alias); + } + + [Fact] + public async Task GetJoinRuleAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + var rule = await room.GetJoinRuleAsync(); + Assert.NotNull(rule); + Assert.NotNull(rule.JoinRuleValue); + Assert.NotEmpty(rule.JoinRuleValue); + } + + [Fact] + public async Task GetHistoryVisibilityAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + var visibility = await room.GetHistoryVisibilityAsync(); + Assert.NotNull(visibility); + Assert.NotNull(visibility.HistoryVisibility); + Assert.NotEmpty(visibility.HistoryVisibility); + } + + [Fact] + public async Task GetGuestAccessAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + try { + var access = await room.GetGuestAccessAsync(); + Assert.NotNull(access); + Assert.NotNull(access.GuestAccess); + Assert.NotEmpty(access.GuestAccess); + } + catch (Exception e) { + if (e is not MatrixException exception) throw; + Assert.Equal("M_NOT_FOUND", exception.ErrorCode); + } + } + + [Fact] + public async Task GetCreateEventAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + var create = await room.GetCreateEventAsync(); + Assert.NotNull(create); + Assert.NotNull(create.Creator); + Assert.NotEmpty(create.RoomVersion!); + } + + [Fact] + public async Task GetRoomType() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + await room.GetRoomType(); + } + + [Fact] + public async Task GetPowerLevelsAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + var power = await room.GetPowerLevelsAsync(); + Assert.NotNull(power); + Assert.NotNull(power.Ban); + Assert.NotNull(power.Kick); + Assert.NotNull(power.Invite); + Assert.NotNull(power.Redact); + Assert.NotNull(power.StateDefault); + Assert.NotNull(power.EventsDefault); + Assert.NotNull(power.UsersDefault); + Assert.NotNull(power.Users); + // Assert.NotNull(power.Events); + } +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomAvatarTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomAvatarTests.cs new file mode 100644
index 0000000..78f007c --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomAvatarTests.cs
@@ -0,0 +1,27 @@ +using LibMatrix.Tests.Abstractions; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests.BasicRoomEventTests; + +public class RoomAvatarTests : TestBed<TestFixture> { + private readonly HomeserverAbstraction _hsAbstraction; + + public RoomAvatarTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { + _hsAbstraction = _fixture.GetService<HomeserverAbstraction>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverAbstraction)}"); + } + + [SkippableFact(typeof(MatrixException))] + public async Task GetAvatarUrlAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + var url = await room.GetAvatarUrlAsync(); + Assert.NotNull(url); + Assert.NotNull(url.Url); + Assert.NotEmpty(url.Url); + + await room.LeaveAsync(); + } +} \ 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 new file mode 100644
index 0000000..7f53b08 --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomNameTests.cs
@@ -0,0 +1,42 @@ +using LibMatrix.EventTypes.Spec.State.RoomInfo; +using LibMatrix.Tests.Abstractions; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests.BasicRoomEventTests; + +public class RoomNameTests : TestBed<TestFixture> { + private readonly HomeserverAbstraction _hsAbstraction; + + public RoomNameTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { + _hsAbstraction = _fixture.GetService<HomeserverAbstraction>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverAbstraction)}"); + } + + [Fact] + public async Task GetNameAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + var name = await room.GetNameAsync(); + Assert.NotNull(name); + Assert.NotEmpty(name); + + await room.LeaveAsync(); + } + + [Fact] + public async Task SetNameAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + var name = Guid.NewGuid().ToString(); + await room.SendStateEventAsync(RoomNameEventContent.EventId, new RoomNameEventContent { Name = name }); + var newName = await room.GetNameAsync(); + Assert.Equal(name, newName); + + await room.LeaveAsync(); + } +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomTopicTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomTopicTests.cs new file mode 100644
index 0000000..6610035 --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/RoomTests/BasicRoomEventTests/RoomTopicTests.cs
@@ -0,0 +1,27 @@ +using LibMatrix.Tests.Abstractions; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests.BasicRoomEventTests; + +public class RoomTopicTests : TestBed<TestFixture> { + private readonly HomeserverAbstraction _hsAbstraction; + + public RoomTopicTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { + _hsAbstraction = _fixture.GetService<HomeserverAbstraction>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverAbstraction)}"); + } + + [SkippableFact(typeof(MatrixException))] + public async Task GetTopicAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + var topic = await room.GetTopicAsync(); + Assert.NotNull(topic); + Assert.NotNull(topic.Topic); + Assert.NotEmpty(topic.Topic); + + await room.LeaveAsync(); + } +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/RoomEventTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/RoomEventTests.cs
index 932909f..97f4525 100644 --- a/Tests/LibMatrix.Tests/Tests/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; @@ -8,23 +6,16 @@ using Xunit.Microsoft.DependencyInjection.Abstracts; namespace LibMatrix.Tests.Tests; public class RoomEventTests : TestBed<TestFixture> { - private readonly TestFixture _fixture; - private readonly HomeserverResolverService _resolver; - private readonly Config _config; - private readonly HomeserverProviderService _provider; + private readonly HomeserverAbstraction _hsAbstraction; public RoomEventTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { - _fixture = fixture; - _resolver = _fixture.GetService<HomeserverResolverService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}"); - _config = _fixture.GetService<Config>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(Config)}"); - _provider = _fixture.GetService<HomeserverProviderService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverProviderService)}"); + _hsAbstraction = _fixture.GetService<HomeserverAbstraction>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverAbstraction)}"); } - private async Task<AuthenticatedHomeserverGeneric> GetHomeserver() => await HomeserverAbstraction.GetHomeserver(); - [Fact] public async Task GetNameAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); Assert.NotNull(room); var name = await room.GetNameAsync(); @@ -34,7 +25,7 @@ public class RoomEventTests : TestBed<TestFixture> { [SkippableFact(typeof(MatrixException))] public async Task GetTopicAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var room = await RoomAbstraction.GetTestRoom(hs); Assert.NotNull(room); var topic = await room.GetTopicAsync(); @@ -44,19 +35,8 @@ public class RoomEventTests : TestBed<TestFixture> { } [SkippableFact(typeof(MatrixException))] - public async Task GetAliasesAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); - var room = await RoomAbstraction.GetTestRoom(hs); - Assert.NotNull(room); - var aliases = await room.GetAliasesAsync(); - Assert.NotNull(aliases); - Assert.NotEmpty(aliases); - Assert.All(aliases, Assert.NotNull); - } - - [SkippableFact(typeof(MatrixException))] public async Task GetCanonicalAliasAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var room = await RoomAbstraction.GetTestRoom(hs); Assert.NotNull(room); var alias = await room.GetCanonicalAliasAsync(); @@ -67,40 +47,46 @@ public class RoomEventTests : TestBed<TestFixture> { [SkippableFact(typeof(MatrixException))] public async Task GetAvatarUrlAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var room = await RoomAbstraction.GetTestRoom(hs); Assert.NotNull(room); var url = await room.GetAvatarUrlAsync(); Assert.NotNull(url); Assert.NotNull(url.Url); Assert.NotEmpty(url.Url); + + await room.LeaveAsync(); } [Fact] public async Task GetJoinRuleAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var room = await RoomAbstraction.GetTestRoom(hs); Assert.NotNull(room); var rule = await room.GetJoinRuleAsync(); Assert.NotNull(rule); Assert.NotNull(rule.JoinRuleValue); Assert.NotEmpty(rule.JoinRuleValue); + + await room.LeaveAsync(); } [Fact] public async Task GetHistoryVisibilityAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var room = await RoomAbstraction.GetTestRoom(hs); Assert.NotNull(room); var visibility = await room.GetHistoryVisibilityAsync(); Assert.NotNull(visibility); Assert.NotNull(visibility.HistoryVisibility); Assert.NotEmpty(visibility.HistoryVisibility); + + await room.LeaveAsync(); } [Fact] public async Task GetGuestAccessAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var room = await RoomAbstraction.GetTestRoom(hs); Assert.NotNull(room); try { @@ -113,30 +99,36 @@ public class RoomEventTests : TestBed<TestFixture> { if (e is not MatrixException exception) throw; Assert.Equal("M_NOT_FOUND", exception.ErrorCode); } + + await room.LeaveAsync(); } [Fact] public async Task GetCreateEventAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var room = await RoomAbstraction.GetTestRoom(hs); Assert.NotNull(room); var create = await room.GetCreateEventAsync(); Assert.NotNull(create); Assert.NotNull(create.Creator); Assert.NotEmpty(create.RoomVersion!); + + await room.LeaveAsync(); } [Fact] public async Task GetRoomType() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var room = await RoomAbstraction.GetTestRoom(hs); Assert.NotNull(room); await room.GetRoomType(); + + await room.LeaveAsync(); } [Fact] public async Task GetPowerLevelsAsync() { - var hs = await HomeserverAbstraction.GetHomeserver(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); var room = await RoomAbstraction.GetTestRoom(hs); Assert.NotNull(room); var power = await room.GetPowerLevelsAsync(); @@ -150,5 +142,7 @@ public class RoomEventTests : TestBed<TestFixture> { Assert.NotNull(power.UsersDefault); Assert.NotNull(power.Users); // Assert.NotNull(power.Events); + + await room.LeaveAsync(); } } \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests/RoomMembershipTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/RoomMembershipTests.cs new file mode 100644
index 0000000..8419518 --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/RoomTests/RoomMembershipTests.cs
@@ -0,0 +1,174 @@ +using ArcaneLibs.Extensions; +using LibMatrix.EventTypes.Spec.State.RoomInfo; +using LibMatrix.Homeservers; +using LibMatrix.Tests.Abstractions; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests; + +public class RoomMembershipTests : TestBed<TestFixture> { + private readonly HomeserverAbstraction _hsAbstraction; + + public RoomMembershipTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { + _hsAbstraction = _fixture.GetService<HomeserverAbstraction>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverAbstraction)}"); + } + + [Fact] + public async Task GetMembersAsync() { + Assert.True(StateEvent.KnownStateEventTypes is { Count: > 0 }, "StateEvent.KnownStateEventTypes is empty!"); + Assert.True(StateEvent.KnownStateEventTypesByName is { Count: > 0 }, "StateEvent.KnownStateEventTypesByName is empty!"); + + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + var members = room.GetMembersEnumerableAsync(); + Assert.NotNull(members); + var hitMembers = false; + await foreach (var member in members) { + Assert.NotNull(member); + Assert.NotNull(member.StateKey); + Assert.NotEmpty(member.StateKey); + Assert.NotNull(member.Sender); + Assert.NotEmpty(member.Sender); + Assert.NotNull(member.RawContent); + Assert.NotEmpty(member.RawContent); + Assert.NotNull(member.TypedContent); + Assert.IsType<RoomMemberEventContent>(member.TypedContent); + var content = (RoomMemberEventContent)member.TypedContent; + Assert.NotNull(content); + Assert.NotNull(content.Membership); + Assert.NotEmpty(content.Membership); + hitMembers = true; + } + + Assert.True(hitMembers, "No members were found in the room"); + + await room.LeaveAsync(); + } + + [Fact] + public async Task JoinAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(_testOutputHelper); + var hs2 = await _hsAbstraction.GetNewHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + await room.SendStateEventAsync(RoomJoinRulesEventContent.EventId, new RoomJoinRulesEventContent() { + JoinRule = RoomJoinRulesEventContent.JoinRules.Public + }); + // var id = await room.JoinAsync(); + var id = await hs2.GetRoom(room.RoomId).JoinAsync(); + Assert.NotNull(id); + Assert.NotNull(id.RoomId); + Assert.NotEmpty(id.RoomId); + + await room.LeaveAsync(); + } + + [Fact] + public async Task ForgetAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + await room.ForgetAsync(); + } + + [Fact] + public async Task LeaveAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + await room.LeaveAsync(); + } + + [Fact] + public async Task KickAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var hs2 = await _hsAbstraction.GetNewHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + await room.InviteUserAsync(hs2.UserId, "Unit test!"); + await hs2.GetRoom(room.RoomId).JoinAsync(); + await room.KickAsync(hs2.UserId, "test"); + var banState = await room.GetStateAsync<RoomMemberEventContent>("m.room.member", hs2.UserId); + Assert.NotNull(banState); + Assert.Equal("leave", banState.Membership); + Assert.Equal("test", banState.Reason); + + await room.LeaveAsync(); + } + + [Fact] + public async Task BanAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var hs2 = await _hsAbstraction.GetNewHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + await room.BanAsync(hs2.UserId, "test"); + var banState = await room.GetStateAsync<RoomMemberEventContent>("m.room.member", hs2.UserId); + Assert.NotNull(banState); + Assert.Equal("ban", banState.Membership); + + await room.LeaveAsync(); + } + + [Fact] + public async Task UnbanAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var hs2 = await _hsAbstraction.GetNewHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + await room.BanAsync(hs2.UserId, "test"); + var banState = await room.GetStateAsync<RoomMemberEventContent>("m.room.member", hs2.UserId); + Assert.NotNull(banState); + Assert.Equal("ban", banState.Membership); + await room.UnbanAsync(hs2.UserId, "testing"); + + var unbanState = await room.GetStateAsync<RoomMemberEventContent>("m.room.member", hs2.UserId); + Assert.NotNull(unbanState); + Assert.Equal("leave", unbanState.Membership); + Assert.Equal("testing", unbanState.Reason); + + await room.LeaveAsync(); + } + + [Fact] + public async Task InviteAndJoinAsync() { + int count = 5; + + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + var otherUsers = _hsAbstraction.GetNewHomeservers(count); + Assert.NotNull(room); + + // var expectedCount = 1; + + // var tasks = new List<Task>(); + // await foreach (var otherUser in otherUsers) + // tasks.AddRange([ + // room.InviteUserAsync(otherUser.UserId), + // otherUser.GetRoom(room.RoomId).JoinAsync() + // ]); + + Dictionary<AuthenticatedHomeserverGeneric, Task> tasks = new(); + await foreach (var otherUser in otherUsers) { + _testOutputHelper.WriteLine($"Inviting {otherUser.UserId} to {room.RoomId}"); + tasks.Add(otherUser, room.InviteUserAsync(otherUser.UserId, "Unit test!")); + } + + await foreach (var otherUser in tasks.ToAsyncEnumerable()) { + _testOutputHelper.WriteLine($"Joining {otherUser.UserId} to {room.RoomId}"); + await otherUser.GetRoom(room.RoomId).JoinAsync(reason: "Unit test!"); + } + + var states = await room.GetMembersListAsync(); + Assert.Equal(count + 1, states.Count); + + await room.LeaveAsync(); + await foreach (var authenticatedHomeserverGeneric in otherUsers) + { + await authenticatedHomeserverGeneric.GetRoom(room.RoomId).LeaveAsync(); + } + } +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests/RoomTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/RoomTests.cs new file mode 100644
index 0000000..7801ed0 --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/RoomTests/RoomTests.cs
@@ -0,0 +1,316 @@ +using System.Text; +using ArcaneLibs.Extensions; +using LibMatrix.EventTypes.Spec; +using LibMatrix.EventTypes.Spec.State.RoomInfo; +using LibMatrix.Responses; +using LibMatrix.Tests.Abstractions; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests; + +public class RoomTests : TestBed<TestFixture> { + private readonly HomeserverAbstraction _hsAbstraction; + + public RoomTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { + _hsAbstraction = _fixture.GetService<HomeserverAbstraction>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverAbstraction)}"); + } + + [Fact] + public async Task GetJoinedRoomsAsync() { + var hs = await _hsAbstraction.GetNewHomeserver(); + //make 100 rooms + var createRoomTasks = Enumerable.Range(0, 10).Select(_ => RoomAbstraction.GetTestRoom(hs)).ToList(); + await Task.WhenAll(createRoomTasks); + + var rooms = await hs.GetJoinedRooms(); + Assert.NotNull(rooms); + Assert.NotEmpty(rooms); + Assert.All(rooms, Assert.NotNull); + // Assert.True(rooms.Count >= 10, "Not enough rooms were found"); + Assert.Equal(10, rooms.Count); + await hs.Logout(); + } + + [Fact] + public async Task GetMembersAsync() { + Assert.True(StateEvent.KnownStateEventTypes is { Count: > 0 }, "StateEvent.KnownStateEventTypes is empty!"); + Assert.True(StateEvent.KnownStateEventTypesByName is { Count: > 0 }, "StateEvent.KnownStateEventTypesByName is empty!"); + + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + var members = room.GetMembersEnumerableAsync(); + Assert.NotNull(members); + var hitMembers = false; + await foreach (var member in members) { + Assert.NotNull(member); + Assert.NotNull(member.StateKey); + Assert.NotEmpty(member.StateKey); + Assert.NotNull(member.Sender); + Assert.NotEmpty(member.Sender); + Assert.NotNull(member.RawContent); + Assert.NotEmpty(member.RawContent); + Assert.NotNull(member.TypedContent); + Assert.IsType<RoomMemberEventContent>(member.TypedContent); + var content = (RoomMemberEventContent)member.TypedContent; + Assert.NotNull(content); + Assert.NotNull(content.Membership); + Assert.NotEmpty(content.Membership); + hitMembers = true; + } + + Assert.True(hitMembers, "No members were found in the room"); + + await room.LeaveAsync(); + } + + [SkippableFact(typeof(MatrixException))] + public async Task SendStateEventAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + await room.SendStateEventAsync("gay.rory.libmatrix.unit_tests", new UserProfileResponse() { + DisplayName = "wee_woo", + AvatarUrl = "no" + }); + await room.SendStateEventAsync("gay.rory.libmatrix.unit_tests", "state_key_maybe", new UserProfileResponse() { + DisplayName = "wee_woo", + AvatarUrl = "yes" + }); + + await room.LeaveAsync(); + } + + [SkippableFact(typeof(MatrixException))] + public async Task SendAndGetStateEventAsync() { + await SendStateEventAsync(); + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + await room.SendStateEventAsync("gay.rory.libmatrix.unit_tests", new UserProfileResponse() { + DisplayName = "wee_woo", + AvatarUrl = "no" + }); + await room.SendStateEventAsync("gay.rory.libmatrix.unit_tests", "state_key_maybe", new UserProfileResponse() { + DisplayName = "wee_woo", + AvatarUrl = "yes" + }); + + var state1 = await room.GetStateAsync<UserProfileResponse>("gay.rory.libmatrix.unit_tests"); + Assert.NotNull(state1); + Assert.NotNull(state1.DisplayName); + Assert.NotEmpty(state1.DisplayName); + Assert.NotNull(state1.AvatarUrl); + Assert.NotEmpty(state1.AvatarUrl); + Assert.Equal("wee_woo", state1.DisplayName); + Assert.Equal("no", state1.AvatarUrl); + + var state2 = await room.GetStateAsync<UserProfileResponse>("gay.rory.libmatrix.unit_tests", "state_key_maybe"); + Assert.NotNull(state2); + Assert.NotNull(state2.DisplayName); + Assert.NotEmpty(state2.DisplayName); + Assert.NotNull(state2.AvatarUrl); + Assert.NotEmpty(state2.AvatarUrl); + Assert.Equal("wee_woo", state2.DisplayName); + Assert.Equal("yes", state2.AvatarUrl); + + await room.LeaveAsync(); + } + + [Fact] + public async Task DisbandAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + await room.PermanentlyBrickRoomAsync(); + + await room.LeaveAsync(); + } + + [Fact] + public async Task SendFileAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + var res = await room.SendFileAsync("test.txt", new MemoryStream(Encoding.UTF8.GetBytes("This test was written by Emma [it/its], member of the Rory& system." + + "\nIf you are reading this on matrix, it means the unit test for uploading a file works!"))); + Assert.NotNull(res); + Assert.NotNull(res.EventId); + + await room.LeaveAsync(); + } + + [Fact] + public async Task GetFullStateAsListAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + var state = await room.GetFullStateAsListAsync(); + Assert.NotNull(state); + Assert.NotEmpty(state); + Assert.All(state, Assert.NotNull); + Assert.All(state, s => { + Assert.NotNull(s.EventId); + Assert.NotEmpty(s.EventId); + Assert.NotNull(s.Sender); + Assert.NotEmpty(s.Sender); + Assert.NotNull(s.RawContent); + Assert.NotNull(s.TypedContent); + }); + + await room.LeaveAsync(); + } + + [SkippableFact(typeof(LibMatrixException))] + public async Task GetStateEventAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + var state = await room.GetStateEventAsync("m.room.name"); + Assert.NotNull(state); + Assert.NotNull(state.EventId); + Assert.NotEmpty(state.EventId); + Assert.NotNull(state.Sender); + Assert.NotEmpty(state.Sender); + Assert.NotNull(state.RawContent); + Assert.NotEmpty(state.RawContent); + Assert.NotNull(state.TypedContent); + + await room.LeaveAsync(); + } + + [Fact] + public async Task GetStateEventIdAsync() { + var hs = await _hsAbstraction.GetNewHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + var state = await room.GetStateEventIdAsync("m.room.name"); + Assert.NotNull(state); + Assert.NotEmpty(state); + + await room.LeaveAsync(); + } + + [SkippableFact(typeof(LibMatrixException))] + public async Task GetStateEventOrNullAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + var state = await room.GetStateEventOrNullAsync("m.room.name"); + Assert.NotNull(state); + Assert.NotNull(state.EventId); + Assert.NotEmpty(state.EventId); + Assert.NotNull(state.Sender); + Assert.NotEmpty(state.Sender); + Assert.NotNull(state.RawContent); + Assert.NotEmpty(state.RawContent); + Assert.NotNull(state.TypedContent); + + await room.LeaveAsync(); + } + + [Fact] + public async Task GetMessagesAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + var messages = await room.GetMessagesAsync(); + Assert.NotNull(messages); + Assert.NotNull(messages.Chunk); + Assert.NotEmpty(messages.Chunk); + Assert.All(messages.Chunk, Assert.NotNull); + Assert.All(messages.Chunk, m => { + Assert.NotNull(m.EventId); + Assert.NotEmpty(m.EventId); + Assert.NotNull(m.Sender); + Assert.NotEmpty(m.Sender); + Assert.NotNull(m.RawContent); + Assert.NotNull(m.TypedContent); + }); + + await room.LeaveAsync(); + + await File.WriteAllTextAsync("test.json", messages.ToJson()); + } + + [Fact] + public async Task GetManyMessagesAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + var messages = room.GetManyMessagesAsync(chunkSize: 2); + await foreach (var resp in messages) { + Assert.NotNull(resp); + Assert.NotNull(resp.Chunk); + // Assert.NotEmpty(resp.Chunk); + Assert.All(resp.Chunk, Assert.NotNull); + Assert.All(resp.Chunk, m => { + Assert.NotNull(m.EventId); + Assert.NotEmpty(m.EventId); + Assert.NotNull(m.Sender); + Assert.NotEmpty(m.Sender); + Assert.NotNull(m.RawContent); + Assert.NotNull(m.TypedContent); + }); + } + + await room.LeaveAsync(); + } + + [Fact] + public async Task SendMessageEventAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + var res = await room.SendMessageEventAsync(new RoomMessageEventContent(body: "This test was written by Emma [it/its], member of the Rory& system." + + "\nIf you are reading this on matrix, it means the unit test for sending a message works!", messageType: "m.text")); + Assert.NotNull(res); + Assert.NotNull(res.EventId); + + await room.LeaveAsync(); + } + + [Fact] + public async Task InviteUsersAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var room = await RoomAbstraction.GetTestRoom(hs); + Assert.NotNull(room); + + var users = _hsAbstraction.GetNewHomeservers(32).ToBlockingEnumerable().ToList(); + Assert.NotNull(users); + Assert.NotEmpty(users); + Assert.All(users, Assert.NotNull); + Assert.All(users, u => { + Assert.NotNull(u); + Assert.NotNull(u.UserId); + Assert.NotEmpty(u.UserId); + }); + + await room.InviteUsersAsync(users.Select(u => u.UserId)); + var members = await room.GetMembersListAsync(); + Assert.NotNull(members); + Assert.NotEmpty(members); + Assert.All(members, Assert.NotNull); + Assert.All(members, m => { + Assert.NotNull(m); + Assert.NotNull(m.StateKey); + Assert.NotEmpty(m.StateKey); + }); + Assert.All(users, u => Assert.Contains(u.UserId, members.Select(m => m.StateKey))); + + await room.LeaveAsync(); + } +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/RoomTests/SpaceTests.cs b/Tests/LibMatrix.Tests/Tests/RoomTests/SpaceTests.cs new file mode 100644
index 0000000..be8076a --- /dev/null +++ b/Tests/LibMatrix.Tests/Tests/RoomTests/SpaceTests.cs
@@ -0,0 +1,97 @@ +using ArcaneLibs.Extensions; +using LibMatrix.EventTypes.Spec.State.Space; +using LibMatrix.Responses; +using LibMatrix.RoomTypes; +using LibMatrix.Tests.Abstractions; +using LibMatrix.Tests.Fixtures; +using Xunit.Abstractions; +using Xunit.Microsoft.DependencyInjection.Abstracts; + +namespace LibMatrix.Tests.Tests; + +public class SpaceTests : TestBed<TestFixture> { + private readonly HomeserverAbstraction _hsAbstraction; + + public SpaceTests(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { + _hsAbstraction = _fixture.GetService<HomeserverAbstraction>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverAbstraction)}"); + } + + [Fact] + public async Task AddChildAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var crq = new CreateRoomRequest() { + Name = "Test space" + }; + crq.CreationContent["type"] = SpaceRoom.TypeName; + var space = (await hs.CreateRoom(crq)).AsSpace(); + + var child = await hs.CreateRoom(new CreateRoomRequest() { + Name = "Test child" + }); + + await space.AddChildAsync(child); + + //validate children + var children = space.GetChildrenAsync().ToBlockingEnumerable().ToList(); + Assert.NotNull(children); + Assert.NotEmpty(children); + Assert.Single(children, x => x.RoomId == child.RoomId); + } + + [Fact] + public async Task AddChildByIdAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var crq = new CreateRoomRequest() { + Name = "Test space" + }; + crq.CreationContent["type"] = SpaceRoom.TypeName; + var space = (await hs.CreateRoom(crq)).AsSpace(); + + var child = await hs.CreateRoom(new CreateRoomRequest() { + Name = "Test child" + }); + + await space.AddChildByIdAsync(child.RoomId); + + //validate children + var children = space.GetChildrenAsync().ToBlockingEnumerable().ToList(); + Assert.NotNull(children); + Assert.NotEmpty(children); + Assert.Single(children, x => x.RoomId == child.RoomId); + } + + [Fact] + public async Task GetChildrenAsync() { + var hs = await _hsAbstraction.GetConfiguredHomeserver(); + var expectedChildren = Enumerable.Range(0, 10).Select(async _ => { + var room = await hs.CreateRoom(new CreateRoomRequest() { + Name = "Test child" + }); + return room; + }).ToAsyncEnumerable().ToBlockingEnumerable().ToList(); + + var crq = new CreateRoomRequest() { + Name = "Test space", + InitialState = expectedChildren.Select(c => new StateEvent() { + Type = "m.space.child", + StateKey = c.RoomId, + TypedContent = new SpaceChildEventContent() { + Via = new List<string> { + c.RoomId.Split(":")[1] + } + } + }).ToList() + }; + crq.CreationContent["type"] = SpaceRoom.TypeName; + var space = (await hs.CreateRoom(crq)).AsSpace(); + + var children = space.GetChildrenAsync().ToBlockingEnumerable().ToList(); + Assert.NotNull(children); + Assert.NotEmpty(children); + Assert.Equal(expectedChildren.Count, children.Count); + foreach (var expectedChild in expectedChildren) + { + Assert.Single(children, x => x.RoomId == expectedChild.RoomId); + } + } +} \ No newline at end of file diff --git a/Tests/LibMatrix.Tests/Tests/TestCleanup.cs b/Tests/LibMatrix.Tests/Tests/TestCleanup.cs deleted file mode 100644
index d9bea94..0000000 --- a/Tests/LibMatrix.Tests/Tests/TestCleanup.cs +++ /dev/null
@@ -1,74 +0,0 @@ -// using System.Diagnostics; -// using LibMatrix.Helpers; -// using LibMatrix.Services; -// using LibMatrix.Tests.Abstractions; -// using LibMatrix.Tests.Fixtures; -// using Microsoft.Extensions.Logging; -// using Xunit.Abstractions; -// using Xunit.Microsoft.DependencyInjection.Abstracts; -// -// namespace LibMatrix.Tests.Tests; -// -// public class TestCleanup : TestBed<TestFixture> { -// // private readonly TestFixture _fixture; -// private readonly HomeserverResolverService _resolver; -// private readonly Config _config; -// private readonly HomeserverProviderService _provider; -// private readonly ILogger<TestCleanup> _logger; -// -// public TestCleanup(ITestOutputHelper testOutputHelper, TestFixture fixture) : base(testOutputHelper, fixture) { -// // _fixture = fixture; -// _resolver = _fixture.GetService<HomeserverResolverService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverResolverService)}"); -// _config = _fixture.GetService<Config>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(Config)}"); -// _provider = _fixture.GetService<HomeserverProviderService>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(HomeserverProviderService)}"); -// _logger = _fixture.GetService<ILogger<TestCleanup>>(_testOutputHelper) ?? throw new InvalidOperationException($"Failed to get {nameof(ILogger<TestCleanup>)}"); -// } -// -// [Fact] -// public async Task Cleanup() { -// Assert.False(string.IsNullOrWhiteSpace(_config.TestHomeserver), $"{nameof(_config.TestHomeserver)} must be set in appsettings!"); -// Assert.False(string.IsNullOrWhiteSpace(_config.TestUsername), $"{nameof(_config.TestUsername)} must be set in appsettings!"); -// Assert.False(string.IsNullOrWhiteSpace(_config.TestPassword), $"{nameof(_config.TestPassword)} must be set in appsettings!"); -// -// var hs = await HomeserverAbstraction.GetHomeserver(); -// Assert.NotNull(hs); -// -// var syncHelper = new SyncHelper(hs, _logger) { -// Timeout = 3000 -// }; -// _testOutputHelper.WriteLine("Starting sync loop"); -// var cancellationTokenSource = new CancellationTokenSource(); -// var sw = Stopwatch.StartNew(); -// syncHelper.SyncReceivedHandlers.Add(async response => { -// if (sw.ElapsedMilliseconds >= 3000) { -// _testOutputHelper.WriteLine("Cancelling sync loop"); -// -// var tasks = (await hs.GetJoinedRooms()).Select(async room => { -// _logger.LogInformation("Leaving room: {}", room.RoomId); -// await room.LeaveAsync(); -// await room.ForgetAsync(); -// return room; -// }).ToList(); -// await Task.WhenAll(tasks); -// -// cancellationTokenSource.Cancel(); -// } -// -// sw.Restart(); -// if (response.Rooms?.Leave is { Count: > 0 }) { -// // foreach (var room in response.Rooms.Leave) { -// // await hs.GetRoom(room.Key).ForgetAsync(); -// // } -// var tasks = response.Rooms.Leave.Select(async room => { -// await hs.GetRoom(room.Key).ForgetAsync(); -// return room; -// }).ToList(); -// await Task.WhenAll(tasks); -// } -// }); -// await syncHelper.RunSyncLoopAsync(cancellationToken: cancellationTokenSource.Token); -// -// Assert.NotNull(hs); -// await hs.Logout(); -// } -// } \ No newline at end of file diff --git a/Tests/TestDataGenerator/Bot/DataFetcher.cs b/Tests/TestDataGenerator/Bot/DataFetcher.cs deleted file mode 100644
index 66b8a03..0000000 --- a/Tests/TestDataGenerator/Bot/DataFetcher.cs +++ /dev/null
@@ -1,59 +0,0 @@ -using ArcaneLibs.Extensions; -using LibMatrix.EventTypes.Spec; -using LibMatrix.Homeservers; -using LibMatrix.RoomTypes; -using LibMatrix.Utilities.Bot; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; - -#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously - -namespace TestDataGenerator.Bot; - -public class DataFetcher(AuthenticatedHomeserverGeneric hs, ILogger<DataFetcher> logger, LibMatrixBotConfiguration botConfiguration) : IHostedService { - private Task? _listenerTask; - - private GenericRoom? _logRoom; - - /// <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 async Task StartAsync(CancellationToken cancellationToken) { - _listenerTask = Run(cancellationToken); - logger.LogInformation("Bot started!"); - } - - private async Task Run(CancellationToken cancellationToken) { - Directory.GetFiles("bot_data/cache").ToList().ForEach(File.Delete); - _logRoom = hs.GetRoom(botConfiguration.LogRoom!); - - await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: "Test data collector started!")); - await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: "Fetching rooms...")); - - var rooms = await hs.GetJoinedRooms(); - await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: $"Fetched {rooms.Count} rooms!")); - - await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: "Fetching room data...")); - - var roomAliasTasks = rooms.Select(room => room.GetCanonicalAliasAsync()).ToAsyncEnumerable(); - List<Task<(string, string)>> aliasResolutionTasks = new(); - await foreach (var @event in roomAliasTasks) - if (@event?.Alias != null) { - await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: $"Fetched room alias {@event.Alias}!")); - aliasResolutionTasks.Add(Task.Run(async () => { - var alias = await hs.ResolveRoomAliasAsync(@event.Alias); - return (@event.Alias, alias.RoomId); - }, cancellationToken)); - } - - var aliasResolutionTaskEnumerator = aliasResolutionTasks.ToAsyncEnumerable(); - await foreach (var result in aliasResolutionTaskEnumerator) - await _logRoom.SendMessageEventAsync(new RoomMessageEventContent(body: $"Resolved room alias {result.Item1} to {result.Item2}!")); - } - - /// <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 bot!"); - _listenerTask?.Dispose(); - } -} \ No newline at end of file diff --git a/Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs b/Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs deleted file mode 100644
index 4f53a2a..0000000 --- a/Tests/TestDataGenerator/Bot/DataFetcherConfiguration.cs +++ /dev/null
@@ -1,9 +0,0 @@ -using Microsoft.Extensions.Configuration; - -namespace TestDataGenerator.Bot; - -public class DataFetcherConfiguration { - public DataFetcherConfiguration(IConfiguration config) => config.GetRequiredSection("DataFetcher").Bind(this); - - // public string -} \ No newline at end of file diff --git a/Tests/TestDataGenerator/Program.cs b/Tests/TestDataGenerator/Program.cs deleted file mode 100644
index 2583817..0000000 --- a/Tests/TestDataGenerator/Program.cs +++ /dev/null
@@ -1,27 +0,0 @@ -// See https://aka.ms/new-console-template for more information - -using LibMatrix.Services; -using LibMatrix.Utilities.Bot; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using TestDataGenerator.Bot; - -Console.WriteLine("Hello, World!"); - -var host = Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => { - services.AddScoped<TieredStorageService>(_ => - new TieredStorageService( - new FileStorageProvider("bot_data/cache/"), - new FileStorageProvider("bot_data/data/") - ) - ); - // services.AddSingleton<DataFetcherConfiguration>(); - services.AddSingleton<AppServiceConfiguration>(); - - services.AddRoryLibMatrixServices(); - services.AddMatrixBot();//.AddCommandHandler().AddCommands([typeof()]); - - services.AddHostedService<DataFetcher>(); -}).UseConsoleLifetime().Build(); - -await host.RunAsync(); \ No newline at end of file diff --git a/Tests/TestDataGenerator/Properties/launchSettings.json b/Tests/TestDataGenerator/Properties/launchSettings.json deleted file mode 100644
index 6c504ff..0000000 --- a/Tests/TestDataGenerator/Properties/launchSettings.json +++ /dev/null
@@ -1,25 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/launchsettings.json", - "profiles": { - "Default": { - "commandName": "Project", - "dotnetRunMessages": true, - "environmentVariables": { - } - }, - "Development": { - "commandName": "Project", - "dotnetRunMessages": true, - "environmentVariables": { - "DOTNET_ENVIRONMENT": "Development" - } - }, - "Local config": { - "commandName": "Project", - "dotnetRunMessages": true, - "environmentVariables": { - "DOTNET_ENVIRONMENT": "Local" - } - } - } -} diff --git a/Tests/TestDataGenerator/TestDataGenerator.csproj b/Tests/TestDataGenerator/TestDataGenerator.csproj deleted file mode 100644
index 879693e..0000000 --- a/Tests/TestDataGenerator/TestDataGenerator.csproj +++ /dev/null
@@ -1,32 +0,0 @@ -<Project Sdk="Microsoft.NET.Sdk"> - - <PropertyGroup> - <OutputType>Exe</OutputType> - <TargetFramework>net8.0</TargetFramework> - <LangVersion>preview</LangVersion> - <ImplicitUsings>enable</ImplicitUsings> - <Nullable>enable</Nullable> - <PublishAot>false</PublishAot> - <InvariantGlobalization>true</InvariantGlobalization> - <!-- <PublishTrimmed>true</PublishTrimmed>--> - <!-- <PublishReadyToRun>true</PublishReadyToRun>--> - <!-- <PublishSingleFile>true</PublishSingleFile>--> - <!-- <PublishReadyToRunShowWarnings>true</PublishReadyToRunShowWarnings>--> - <!-- <PublishTrimmedShowLinkerSizeComparison>true</PublishTrimmedShowLinkerSizeComparison>--> - <!-- <PublishTrimmedShowLinkerSizeComparisonWarnings>true</PublishTrimmedShowLinkerSizeComparisonWarnings>--> - </PropertyGroup> - - <ItemGroup> - <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0"/> - </ItemGroup> - <ItemGroup> - <Content Include="appsettings*.json"> - <CopyToOutputDirectory>Always</CopyToOutputDirectory> - </Content> - </ItemGroup> - <ItemGroup> - <ProjectReference Include="..\..\LibMatrix\LibMatrix.csproj"/> - <ProjectReference Include="..\..\Utilities\LibMatrix.Utilities.Bot\LibMatrix.Utilities.Bot.csproj"/> - <ProjectReference Include="..\LibMatrix.Tests\LibMatrix.Tests.csproj"/> - </ItemGroup> -</Project> diff --git a/Tests/TestDataGenerator/appsettings.Development.json b/Tests/TestDataGenerator/appsettings.Development.json deleted file mode 100644
index 38c45c4..0000000 --- a/Tests/TestDataGenerator/appsettings.Development.json +++ /dev/null
@@ -1,18 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } - }, - "LibMatrixBot": { - // The homeserver to connect to - "Homeserver": "rory.gay", - // The access token to use - "AccessToken": "syt_xxxxxxxxxxxxxxxxx", - // The command prefix - "Prefix": "?", - "LogRoom": "!xxxxxxxxxxxxxxxxxxxxxx:example.com" - } -} diff --git a/Tests/TestDataGenerator/appsettings.json b/Tests/TestDataGenerator/appsettings.json deleted file mode 100644
index e203e94..0000000 --- a/Tests/TestDataGenerator/appsettings.json +++ /dev/null
@@ -1,9 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } - } -}