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

namespace MatrixRoomUtils.Core;

public class Room
{
    private static SemaphoreSlim _semaphore = new SemaphoreSlim(16, 16);

    private readonly HttpClient _httpClient;
    public string RoomId { get; set; }

    public Room(HttpClient httpClient, string roomId)
    {
        _httpClient = httpClient;
        RoomId = roomId;
    }

    public async Task<JsonElement?> GetStateAsync(string type, string state_key = "", bool logOnFailure = false)
    {
        await _semaphore.WaitAsync();
        var url = $"/_matrix/client/v3/rooms/{RoomId}/state";
        if (!string.IsNullOrEmpty(state_key)) url += $"/{type}/{state_key}";
        else if (!string.IsNullOrEmpty(type)) url += $"/{type}";
        var cache_key = "room_states:" + type;
        if (!RuntimeCache.GenericResponseCache.ContainsKey(cache_key))
        {
            Console.WriteLine($"[!!] No cache for {cache_key}, creating...");
            RuntimeCache.GenericResponseCache.Add(cache_key, new ObjectCache<object?>());
        }

        RuntimeCache.GenericResponseCache[cache_key].DefaultExpiry = type switch
        {
            "m.room.name" => TimeSpan.FromMinutes(30),
            "org.matrix.mjolnir.shortcode" => TimeSpan.FromHours(4),
            "" => TimeSpan.FromSeconds(0),
            _ => TimeSpan.FromMinutes(15)
        };

        if (RuntimeCache.GenericResponseCache[cache_key].Cache.ContainsKey(url) && RuntimeCache.GenericResponseCache[cache_key][url] != null)
        {
            if (RuntimeCache.GenericResponseCache[cache_key][url].ExpiryTime > DateTime.Now)
            {
                // Console.WriteLine($"[:3] Found cached state: {RuntimeCache.GenericResponseCache[cache_key][url].Result}");
                _semaphore.Release();
                return (JsonElement?)RuntimeCache.GenericResponseCache[cache_key][url].Result;
            }
            else
            {
                Console.WriteLine($"[!!] Cached state expired at {RuntimeCache.GenericResponseCache[cache_key][url].ExpiryTime}: {RuntimeCache.GenericResponseCache[cache_key][url].Result}");
            }
        }
        // else
        // {
        //     Console.WriteLine($"[!!] No cached state for {url}");
        // }

        var res = await _httpClient.GetAsync(url);
        if (!res.IsSuccessStatusCode)
        {
            if (logOnFailure) Console.WriteLine($"{RoomId}/{state_key}/{type} - got status: {res.StatusCode}");
            _semaphore.Release();
            return null;
        }

        var result = await res.Content.ReadFromJsonAsync<JsonElement>();

        if (!RuntimeCache.GenericResponseCache.ContainsKey(cache_key) && type != "")
        {
            Console.WriteLine($"[!!] No cache for {cache_key}, creating...");
            RuntimeCache.GenericResponseCache.Add(cache_key, new ObjectCache<object?>());
        }

        RuntimeCache.GenericResponseCache[cache_key][url] = new GenericResult<object>()
        {
            Result = result
        };
        _semaphore.Release();
        return result;
    }

    public async Task<string> GetNameAsync()
    {
        var res = await GetStateAsync("m.room.name");
        if (!res.HasValue)
        {
            Console.WriteLine($"Room {RoomId} has no name!");
            return RoomId;
        }

        var resn = res?.TryGetProperty("name", out var name) ?? false ? name.GetString() ?? RoomId : RoomId;
        //Console.WriteLine($"Got name: {resn}");
        return resn;
    }

    public async Task JoinAsync(string[]? homeservers = null)
    {
        string join_url = $"/_matrix/client/r0/join/{HttpUtility.UrlEncode(RoomId)}";
        Console.WriteLine($"Calling {join_url} with {(homeservers == null ? 0 : homeservers.Length)} via's...");
        if(homeservers == null || homeservers.Length == 0) homeservers = new[] { RoomId.Split(':')[1] };
        var full_join_url = $"{join_url}?server_name=" + string.Join("&server_name=", homeservers);
        var res = await _httpClient.PostAsync(full_join_url, null);
    }
}