about summary refs log tree commit diff
path: root/LibMatrix/Services/HomeserverResolverService.cs
blob: 75545db47d89f5dfa2e05e13bf468040f0a6a54f (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
using System.Text.Json;
using ArcaneLibs.Extensions;
using LibMatrix.Extensions;
using Microsoft.Extensions.Logging;

namespace LibMatrix.Services;

public class HomeserverResolverService(ILogger<HomeserverResolverService>? logger = null) {
    private readonly MatrixHttpClient _httpClient = new();

    private static readonly Dictionary<string, string> _wellKnownCache = new();
    private static readonly Dictionary<string, SemaphoreSlim> _wellKnownSemaphores = new();

    public async Task<string> ResolveHomeserverFromWellKnown(string homeserver) {
        if (homeserver is null) throw new ArgumentNullException(nameof(homeserver));
        if(_wellKnownCache.TryGetValue(homeserver, out var known)) return known;
        logger?.LogInformation("Resolving homeserver: {}", homeserver);
        var res = await _resolveHomeserverFromWellKnown(homeserver);
        if (!res.StartsWith("http")) res = "https://" + res;
        if (res.EndsWith(":443")) res = res[..^4];
        return res;
    }

    private async Task<string> _resolveHomeserverFromWellKnown(string homeserver) {
        if (homeserver is null) throw new ArgumentNullException(nameof(homeserver));
        var sem = _wellKnownSemaphores.GetOrCreate(homeserver, _ => new SemaphoreSlim(1, 1));
        if(_wellKnownCache.TryGetValue(homeserver, out var wellKnown)) return wellKnown;
        await sem.WaitAsync();
        if (_wellKnownCache.TryGetValue(homeserver, out var known)) {
            sem.Release();
            return known;
        }

        string? result = null;
        logger?.LogInformation("Attempting to resolve homeserver: {}", homeserver);
        result ??= await _tryResolveFromClientWellknown(homeserver);
        result ??= await _tryResolveFromServerWellknown(homeserver);
        result ??= await _tryCheckIfDomainHasHomeserver(homeserver);

        if (result is null) throw new InvalidDataException($"Failed to resolve homeserver for {homeserver}! Is it online and configured correctly?");

        //success!
        logger?.LogInformation("Resolved homeserver: {} -> {}", homeserver, result);
        _wellKnownCache[homeserver] = result;
        sem.Release();
        return result;
    }

    private async Task<string?> _tryResolveFromClientWellknown(string homeserver) {
        if (!homeserver.StartsWith("http")) homeserver = "https://" + homeserver;
        if (await _httpClient.CheckSuccessStatus($"{homeserver}/.well-known/matrix/client")) {
            var resp = await _httpClient.GetFromJsonAsync<JsonElement>($"{homeserver}/.well-known/matrix/client");
            var hs = resp.GetProperty("m.homeserver").GetProperty("base_url").GetString();
            return hs;
        }

        logger?.LogInformation("No client well-known...");
        return null;
    }

    private async Task<string?> _tryResolveFromServerWellknown(string homeserver) {
        if (!homeserver.StartsWith("http")) homeserver = "https://" + homeserver;
        if (await _httpClient.CheckSuccessStatus($"{homeserver}/.well-known/matrix/server")) {
            var resp = await _httpClient.GetFromJsonAsync<JsonElement>($"{homeserver}/.well-known/matrix/server");
            var hs = resp.GetProperty("m.server").GetString();
            return hs;
        }

        logger?.LogInformation("No server well-known...");
        return null;
    }

    private async Task<string?> _tryCheckIfDomainHasHomeserver(string homeserver) {
        logger?.LogInformation("Checking if {} hosts a homeserver...", homeserver);
        if (await _httpClient.CheckSuccessStatus($"{homeserver}/_matrix/client/versions"))
            return homeserver;
        logger?.LogInformation("No homeserver on shortname...");
        return null;
    }

    private async Task<string?> _tryCheckIfSubDomainHasHomeserver(string homeserver, string subdomain) {
        homeserver = homeserver.Replace("https://", $"https://{subdomain}.");
        return await _tryCheckIfDomainHasHomeserver(homeserver);
    }

    public async Task<string?> ResolveMediaUri(string homeserver, string mxc) {
        if (homeserver is null) throw new ArgumentNullException(nameof(homeserver));
        if (mxc is null) throw new ArgumentNullException(nameof(mxc));
        if (!mxc.StartsWith("mxc://")) throw new InvalidDataException("mxc must start with mxc://");
        homeserver = await ResolveHomeserverFromWellKnown(homeserver);
        return mxc.Replace("mxc://", $"{homeserver}/_matrix/media/v3/download/");
    }
}