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.IO;
using System.Text.Json;
using System.Threading.Tasks;
using ArcaneLibs;
using ArcaneLibs.Extensions;
using LibMatrix;
using LibMatrix.Homeservers;
using LibMatrix.Responses;
using LibMatrix.Services;
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);
await Homeserver.UpdateProfilePropertyAsync("meow", "h");
IsLoggedIn = true;
}
catch (MatrixException e) {
if (e is not { Error: MatrixException.ErrorCodes.M_UNKNOWN_TOKEN }) throw;
}
}
public async Task LoginAsync(string username, string password, string? homeserver = null) {
Directory.CreateDirectory(Util.ExpandPath($"{cfg.ProfileDirectory}")!);
if (string.IsNullOrWhiteSpace(homeserver)) {
var mxidParts = username.Split(':', 2);
homeserver = mxidParts[1];
}
var res = await hsProvider.Login(homeserver, 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;
}
}
|