about summary refs log tree commit diff
path: root/MatrixUtils.Web/Shared/MxcAvatar.razor
blob: 09ea790339daaee44bb52ce15f4aa916c83a6b4b (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
@using System.Security
@using System.Security.Cryptography
@using Blazored.SessionStorage.JsonConverters
<StreamedImage Stream="@_stream" style="@StyleString"/>

@code {
    private string _mxcUri;
    private string _style;
    private Stream _stream;
    
    [Parameter]
    public string MxcUri {
        get => _mxcUri ?? "";
        set {
            if(_mxcUri == value) return;
            _mxcUri = value;
            UriHasChanged(value);
        }
    }

    [Parameter]
    public bool Circular { get; set; }

    [Parameter]
    public int Size { get; set; } = 48;

    [Parameter]
    public string SizeUnit { get; set; } = "px";

    [Parameter]
    public AuthenticatedHomeserverGeneric? Homeserver { get; set; }
    
    private string StyleString => $"{(Circular ? "border-radius: 50%;" : "")} width: {Size}{SizeUnit}; height: {Size}{SizeUnit}; object-fit: cover;";

    private static readonly string Prefix = "mxc://";
    private static readonly int PrefixLength = Prefix.Length;

    private async Task UriHasChanged(string value) {
        if (!value.StartsWith(Prefix)) {
            // Console.WriteLine($"UriHasChanged: {value} does not start with {Prefix}, passing as resolved URI!!!");
            // ResolvedUri = value;
            return;
        }

        if (Homeserver is null) {
            Console.WriteLine("Homeserver is required for MxcAvatar");
            return;
        }

        var uri = value[PrefixLength..].Split('/');
        // Console.WriteLine($"UriHasChanged: {value} {uri[0]}");
        var url = $"/_matrix/media/v3/download/{uri[0]}/{uri[1]}";
        Console.WriteLine($"ResolvedUri: {url}");
        _stream = await Homeserver.ClientHttpClient.GetStreamAsync(url);
        StateHasChanged();
    }

}