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

namespace MatrixRoomUtils.Core;

public class AuthenticatedHomeServer : IHomeServer
{
    public string UserId { get; set; }
    public string AccessToken { get; set; }
    public readonly HomeserverAdminApi Admin;

    public AuthenticatedHomeServer(string userId, string accessToken, string canonicalHomeServerDomain)
    {
        UserId = userId;
        AccessToken = accessToken;
        HomeServerDomain = canonicalHomeServerDomain;
        Admin = new HomeserverAdminApi(this);
        _httpClient = new HttpClient();
    }

    public async Task<AuthenticatedHomeServer> Configure()
    {
        FullHomeServerDomain = await ResolveHomeserverFromWellKnown(HomeServerDomain);
        _httpClient.Dispose();
        _httpClient = new HttpClient { BaseAddress = new Uri(FullHomeServerDomain) };
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
        Console.WriteLine("[AHS] Finished setting up http client");

        return this;
    }
    

    public async Task<Room> GetRoom(string roomId)
    {
        return 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()));
        }
        
        Console.WriteLine($"Fetched {rooms.Count} rooms");

        return rooms;
    }
    
    
    
    
    
    public class HomeserverAdminApi
    {
        private readonly AuthenticatedHomeServer _authenticatedHomeServer;

        public HomeserverAdminApi(AuthenticatedHomeServer authenticatedHomeServer)
        {
            _authenticatedHomeServer = authenticatedHomeServer;
        }
    
    
        
        
        
        
        
    }
}