summary refs log tree commit diff
path: root/MxApiExtensions/Controllers/GenericProxyController.cs
blob: 3481914465c92feda56cccde5595d39f6f96c9fb (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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using MxApiExtensions.Classes.LibMatrix;
using MxApiExtensions.Services;

namespace MxApiExtensions.Controllers;

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

    public GenericController(ILogger<GenericController> logger, MxApiExtensionsConfiguration config, AuthenticationService authenticationService,
        AuthenticatedHomeserverProviderService authenticatedHomeserverProviderService) {
        _logger = logger;
        _config = config;
        _authenticationService = authenticationService;
        _authenticatedHomeserverProviderService = authenticatedHomeserverProviderService;
    }

    [HttpGet]
    public async Task Proxy([FromQuery] string? access_token, string? _) {
        try {
            access_token ??= _authenticationService.GetToken(fail: false);
            var mxid = await _authenticationService.GetMxidFromToken(fail: false);
            var hs = await _authenticatedHomeserverProviderService.GetHomeserver();

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

            //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 hs._httpClient.GetAsync($"{Request.Path}{Request.QueryString}");

            if (resp.Content is null) {
                throw new MxApiMatrixException {
                    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 (MxApiMatrixException e) {
            _logger.LogError(e, "Matrix error");
            Response.StatusCode = StatusCodes.Status500InternalServerError;
            Response.ContentType = "application/json";

            await Response.WriteAsync(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 ??= _authenticationService.GetToken(fail: false);
            var mxid = await _authenticationService.GetMxidFromToken(fail: false);
            var hs = await _authenticatedHomeserverProviderService.GetHomeserver();

            _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 hs._httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, $"{Request.Path}{Request.QueryString}") {
                Method = HttpMethod.Post,
                Content = new StreamContent(Request.Body)
            });

            if (resp.Content is null) {
                throw new MxApiMatrixException {
                    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 (MxApiMatrixException 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();
        }
    }

    [HttpPut]
    public async Task ProxyPut([FromQuery] string? access_token, string _) {
        try {
            access_token ??= _authenticationService.GetToken(fail: false);
            var mxid = await _authenticationService.GetMxidFromToken(fail: false);
            var hs = await _authenticatedHomeserverProviderService.GetHomeserver();

            _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 hs._httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Put, $"{Request.Path}{Request.QueryString}") {
                Method = HttpMethod.Put,
                Content = new StreamContent(Request.Body)
            });

            if (resp.Content is null) {
                throw new MxApiMatrixException {
                    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 (MxApiMatrixException 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();
        }
    }
}