about summary refs log tree commit diff
path: root/ModerationClient/Services/MatrixAuthenticationService.cs
blob: 7e9ce70ff2b7bfbc839ab6f4f7fd1f2336977ae6 (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
using System;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using ArcaneLibs;
using ArcaneLibs.Extensions;
using Avalonia.Controls.Diagnostics;
using LibMatrix;
using LibMatrix.Homeservers;
using LibMatrix.Responses;
using LibMatrix.Services;
using MatrixUtils.Desktop;
using Microsoft.Extensions.Logging;

namespace ModerationClient.Services;

public class MatrixAuthenticationService(ILogger<MatrixAuthenticationService> logger, HomeserverProviderService hsProvider, CommandLineConfiguration cfg) : NotifyPropertyChanged {
    private bool _isLoggedIn = false;
    public string Profile => cfg.Profile;
    public AuthenticatedHomeserverGeneric? Homeserver { get; private set; }

    public bool IsLoggedIn {
        get => _isLoggedIn;
        private set => SetField(ref _isLoggedIn, value);
    }

    public async Task LoadProfileAsync() {
        if (!File.Exists(Util.ExpandPath($"{cfg.ProfileDirectory}/login.json")!)) return;
        var loginJson = await File.ReadAllTextAsync(Util.ExpandPath($"{cfg.ProfileDirectory}/login.json")!);
        var login = JsonSerializer.Deserialize<LoginResponse>(loginJson);
        if (login is null) return;
        try {
            Homeserver = await hsProvider.GetAuthenticatedWithToken(login.Homeserver, login.AccessToken);
            IsLoggedIn = true;
        }
        catch (MatrixException e) {
            if (e is not { Error: MatrixException.ErrorCodes.M_UNKNOWN_TOKEN }) throw;
        }
    }

    public async Task LoginAsync(string username, string password) {
        Directory.CreateDirectory(Util.ExpandPath($"{cfg.ProfileDirectory}")!);
        var mxidParts = username.Split(':', 2);
        var res = await hsProvider.Login(mxidParts[1], username, password);
        await File.WriteAllTextAsync(Path.Combine(cfg.ProfileDirectory, "login.json"), res.ToJson());

        await LoadProfileAsync();
        // Console.WriteLine("Login result: " + res.ToJson());
    }

    public async Task LogoutAsync() {
        Directory.Delete(Util.ExpandPath($"{cfg.ProfileDirectory}")!, true);
        IsLoggedIn = false;
    }
}