about summary refs log tree commit diff
path: root/Utilities/LibMatrix.HomeserverEmulator/Controllers/Users/AccountDataController.cs
blob: a32d283e53f43e33b57ce785bb411952f54861da (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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 { };
    }
}