about summary refs log tree commit diff
path: root/LibMatrix/Homeservers/RemoteHomeServer.cs
blob: 8cd7ad79dded2349a7781a65cc068e51c8259e9c (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
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Web;
using ArcaneLibs.Extensions;
using LibMatrix.Extensions;
using LibMatrix.Responses;
using LibMatrix.Services;

namespace LibMatrix.Homeservers;

public class RemoteHomeserver(string baseUrl) {
    public static async Task<RemoteHomeserver?> TryCreate(string baseUrl, string? proxy = null) {
        try {
            return await Create(baseUrl, proxy);
        }
        catch (Exception e) {
            Console.WriteLine($"Failed to create homeserver {baseUrl}: {e.Message}");
            return null;
        }
    }

    public static async Task<RemoteHomeserver> Create(string baseUrl, string? proxy = null) {
        if (string.IsNullOrWhiteSpace(proxy))
            proxy = null;
        var homeserver = new RemoteHomeserver(baseUrl);
        homeserver.WellKnownUris = await new HomeserverResolverService().ResolveHomeserverFromWellKnown(baseUrl);
        if (string.IsNullOrWhiteSpace(homeserver.WellKnownUris.Client))
            Console.WriteLine($"Failed to resolve homeserver client URI for {baseUrl}");
        if (string.IsNullOrWhiteSpace(homeserver.WellKnownUris.Server))
            Console.WriteLine($"Failed to resolve homeserver server URI for {baseUrl}");

        Console.WriteLine(homeserver.WellKnownUris.ToJson(ignoreNull: false));

        homeserver.ClientHttpClient = new MatrixHttpClient {
            BaseAddress = new Uri(proxy ?? homeserver.WellKnownUris.Client ?? throw new InvalidOperationException($"Failed to resolve homeserver client URI for {baseUrl}")),
            Timeout = TimeSpan.FromSeconds(300)
        };

        homeserver.FederationClient = await FederationClient.TryCreate(baseUrl, proxy);

        if (proxy is not null) homeserver.ClientHttpClient.DefaultRequestHeaders.Add("MXAE_UPSTREAM", baseUrl);

        return homeserver;
    }

    private Dictionary<string, object> _profileCache { get; set; } = new();
    public string BaseUrl { get; } = baseUrl;

    public MatrixHttpClient ClientHttpClient { get; set; } = null!;
    public FederationClient? FederationClient { get; set; }
    public HomeserverResolverService.WellKnownUris WellKnownUris { get; set; } = null!;

    public async Task<UserProfileResponse> GetProfileAsync(string mxid, bool useCache = false) {
        if (mxid is null) throw new ArgumentNullException(nameof(mxid));
        if (useCache && _profileCache.TryGetValue(mxid, out var value)) {
            if (value is SemaphoreSlim s) await s.WaitAsync();
            if (value is UserProfileResponse p) return p;
        }

        _profileCache[mxid] = new SemaphoreSlim(1);

        var resp = await ClientHttpClient.GetAsync($"/_matrix/client/v3/profile/{HttpUtility.UrlEncode(mxid)}");
        var data = await resp.Content.ReadFromJsonAsync<UserProfileResponse>();
        if (!resp.IsSuccessStatusCode) Console.WriteLine("Profile: " + data);
        _profileCache[mxid] = data;

        return data;
    }

    public async Task<ClientVersionsResponse> GetClientVersionsAsync() {
        var resp = await ClientHttpClient.GetAsync($"/_matrix/client/versions");
        var data = await resp.Content.ReadFromJsonAsync<ClientVersionsResponse>();
        if (!resp.IsSuccessStatusCode) Console.WriteLine("ClientVersions: " + data);
        return data;
    }

    public async Task<AliasResult> ResolveRoomAliasAsync(string alias) {
        var resp = await ClientHttpClient.GetAsync($"/_matrix/client/v3/directory/room/{alias.Replace("#", "%23")}");
        var data = await resp.Content.ReadFromJsonAsync<AliasResult>();
        //var text = await resp.Content.ReadAsStringAsync();
        if (!resp.IsSuccessStatusCode) Console.WriteLine("ResolveAlias: " + data.ToJson());
        return data;
    }

#region Authentication

    public async Task<LoginResponse> LoginAsync(string username, string password, string? deviceName = null) {
        var resp = await ClientHttpClient.PostAsJsonAsync("/_matrix/client/r0/login", new {
            type = "m.login.password",
            identifier = new {
                type = "m.id.user",
                user = username
            },
            password = password,
            initial_device_display_name = deviceName
        });
        var data = await resp.Content.ReadFromJsonAsync<LoginResponse>();
        if (!resp.IsSuccessStatusCode) Console.WriteLine("Login: " + data.ToJson());
        return data;
    }

    public async Task<LoginResponse> RegisterAsync(string username, string password, string? deviceName = null) {
        var resp = await ClientHttpClient.PostAsJsonAsync("/_matrix/client/r0/register", new {
            kind = "user",
            auth = new {
                type = "m.login.dummy"
            },
            username,
            password,
            initial_device_display_name = deviceName ?? "LibMatrix"
        }, new JsonSerializerOptions() {
            DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
        });
        var data = await resp.Content.ReadFromJsonAsync<LoginResponse>();
        if (!resp.IsSuccessStatusCode) Console.WriteLine("Register: " + data.ToJson());
        return data;
    }

#endregion

    public string? ResolveMediaUri(string? mxcUri) {
        if (mxcUri is null) return null;
        if (mxcUri.StartsWith("https://")) return mxcUri;
        return $"{ClientHttpClient.BaseAddress}/_matrix/media/v3/download/{mxcUri.Replace("mxc://", "")}".Replace("//_matrix", "/_matrix");
    }
}

public class AliasResult {
    [JsonPropertyName("room_id")]
    public string RoomId { get; set; } = null!;

    [JsonPropertyName("servers")]
    public List<string> Servers { get; set; } = null!;
}