summary refs log tree commit diff
path: root/MxApiExtensions/Controllers/GenericProxyController.cs
blob: f0ad4e7f72d9883e7f6035e4439ff225d3576e59 (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;

namespace MxApiExtensions.Controllers;

[ApiController]
[Route("/{*_}")]
public class GenericController : ControllerBase {
    private readonly ILogger<GenericController> _logger;
    private readonly CacheConfiguration _config;
    private readonly Auth _auth;
    private static Dictionary<string, string> _tokenMap = new();

    public GenericController(ILogger<GenericController> logger, CacheConfiguration config, Auth auth) {
        _logger = logger;
        _config = config;
        _auth = auth;
    }

    [HttpGet]
    public async Task Proxy([FromQuery] string? access_token, string _) {
        try {
            access_token ??= _auth.GetToken(fail: false);
            var mxid = _auth.GetUserId(fail: false);

            _logger.LogInformation("Proxying request for {}: {}{}", mxid, Request.Path, Request.QueryString);

            using var hc = new HttpClient();
            hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
            hc.Timeout = TimeSpan.FromMinutes(10);
            //remove access_token from query string
            Request.QueryString = new QueryString(
                Request.QueryString.Value
                    .Replace("&access_token", "access_token")
                    .Replace($"access_token={access_token}", "")
            );

            var resp = await hc.GetAsync($"{_config.Homeserver}{Request.Path}{Request.QueryString}");

            if (resp.Content is null) {
                throw new MatrixException {
                    ErrorCode = "M_UNKNOWN",
                    Error = "No content in response"
                };
            }

            Response.StatusCode = (int)resp.StatusCode;
            Response.ContentType = resp.Content.Headers.ContentType?.ToString() ?? "application/json";
            await Response.StartAsync();
            await using var stream = await resp.Content.ReadAsStreamAsync();
            await stream.CopyToAsync(Response.Body);
            await Response.Body.FlushAsync();
            await Response.CompleteAsync();

        }
        catch (MatrixException e) {
            _logger.LogError(e, "Matrix error");
            Response.StatusCode = StatusCodes.Status500InternalServerError;
            Response.ContentType = "application/json";

            await Response.WriteAsJsonAsync(e.GetAsJson());
            await Response.CompleteAsync();
        }
        catch (Exception e) {
            _logger.LogError(e, "Unhandled error");
            Response.StatusCode = StatusCodes.Status500InternalServerError;
            Response.ContentType = "text/plain";

            await Response.WriteAsync(e.ToString());
            await Response.CompleteAsync();
        }
    }

    [HttpPost]
    public async Task ProxyPost([FromQuery] string? access_token, string _) {
        try {
            access_token ??= _auth.GetToken(fail: false);
            var mxid = _auth.GetUserId(fail: false);

            _logger.LogInformation("Proxying request for {}: {}{}", mxid, Request.Path, Request.QueryString);

            using var hc = new HttpClient();
            hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
            hc.Timeout = TimeSpan.FromMinutes(10);
            //remove access_token from query string
            Request.QueryString = new QueryString(
                Request.QueryString.Value
                    .Replace("&access_token", "access_token")
                    .Replace($"access_token={access_token}", "")
            );

            var resp = await hc.SendAsync(new HttpRequestMessage {
                Method = HttpMethod.Post,
                RequestUri = new Uri($"{_config.Homeserver}{Request.Path}{Request.QueryString}"),
                Content = new StreamContent(Request.Body)
            });

            if (resp.Content is null) {
                throw new MatrixException {
                    ErrorCode = "M_UNKNOWN",
                    Error = "No content in response"
                };
            }

            Response.StatusCode = (int)resp.StatusCode;
            Response.ContentType = resp.Content.Headers.ContentType?.ToString() ?? "application/json";
            await Response.StartAsync();
            await using var stream = await resp.Content.ReadAsStreamAsync();
            await stream.CopyToAsync(Response.Body);
            await Response.Body.FlushAsync();
            await Response.CompleteAsync();

        }
        catch (MatrixException e) {
            _logger.LogError(e, "Matrix error");
            Response.StatusCode = StatusCodes.Status500InternalServerError;
            Response.ContentType = "application/json";

            await Response.WriteAsJsonAsync(e.GetAsJson());
            await Response.CompleteAsync();
        }
        catch (Exception e) {
            _logger.LogError(e, "Unhandled error");
            Response.StatusCode = StatusCodes.Status500InternalServerError;
            Response.ContentType = "text/plain";

            await Response.WriteAsync(e.ToString());
            await Response.CompleteAsync();
        }
    }
}