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
|