about summary refs log tree commit diff
path: root/Tests/LibMatrix.HomeserverEmulator/Controllers/Rooms/RoomTimelineController.cs
blob: c9bdb57ed925893d7ec034bf40b9ec022b4f30dc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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}")]
public class RoomTimelineController(ILogger<RoomTimelineController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore) : ControllerBase {
    [HttpPut("send/{eventType}/{txnId}")]
    public async Task<EventIdResponse> SendMessage(string roomId, string eventType, string txnId, [FromBody] JsonObject content) {
        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 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);

        return new() {
            EventId = evt.EventId
        };
    }
}