about summary refs log tree commit diff
path: root/MatrixRoomUtils.Core/RemoteHomeServer.cs
blob: 3f50d2e218fb6a14e8543bf7122f308451386752 (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
using System.Net.Http.Json;
using System.Text.Json;
using MatrixRoomUtils.Core.Extensions;
using MatrixRoomUtils.Core.Interfaces;

namespace MatrixRoomUtils.Core;

public class RemoteHomeServer : IHomeServer {
    public RemoteHomeServer(string canonicalHomeServerDomain) {
        HomeServerDomain = canonicalHomeServerDomain;
        _httpClient = new MatrixHttpClient();
        _httpClient.Timeout = TimeSpan.FromSeconds(5);
    }

    public async Task<RemoteHomeServer> Configure() {
        FullHomeServerDomain = await ResolveHomeserverFromWellKnown(HomeServerDomain);
        _httpClient.Dispose();
        _httpClient = new MatrixHttpClient { BaseAddress = new Uri(FullHomeServerDomain) };
        _httpClient.Timeout = TimeSpan.FromSeconds(5);
        Console.WriteLine("[RHS] Finished setting up http client");

        return this;
    }

    public async Task<Room> GetRoom(string roomId) => new Room(_httpClient, roomId);

    public async Task<List<Room>> GetJoinedRooms() {
        var rooms = new List<Room>();
        var roomQuery = await _httpClient.GetAsync("/_matrix/client/v3/joined_rooms");
        if (!roomQuery.IsSuccessStatusCode) {
            Console.WriteLine($"Failed to get rooms: {await roomQuery.Content.ReadAsStringAsync()}");
            throw new InvalidDataException($"Failed to get rooms: {await roomQuery.Content.ReadAsStringAsync()}");
        }

        var roomsJson = await roomQuery.Content.ReadFromJsonAsync<JsonElement>();
        foreach (var room in roomsJson.GetProperty("joined_rooms").EnumerateArray()) rooms.Add(new Room(_httpClient, room.GetString()));

        return rooms;
    }
}