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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
|
@page "/"
@inject ILogger<Index> logger
@using LibMatrix.Responses
@using LibMatrix
@using ArcaneLibs
@using System.Diagnostics
<PageTitle>Index</PageTitle>
<h3>Rory&::MatrixUtils</h3>
Small collection of tools to do not-so-everyday things.
<br/><br/>
<h5>@totalSessions signed in sessions - <a href="/Login">Add new account</a></h5>
@if (scannedSessions != totalSessions) {
<span>
<span>@scannedSessions/@totalSessions</span>
<progress max="@totalSessions" value="@scannedSessions"></progress>
</span>
}
<hr/>
<form>
<table>
@foreach (var session in _sessions.OrderByDescending(x => x.UserInfo.RoomCount)) {
var auth = session.UserAuth;
<tr class="user-entry">
<td>
@if (!string.IsNullOrWhiteSpace(@session.UserInfo.AvatarUrl)) {
<MxcAvatar Homeserver="session.Homeserver" MxcUri="@session.UserInfo.AvatarUrl" Circular="true" Size="4" SizeUnit="em"/>
}
else {
<img class="avatar" src="@_identiconGenerator.GenerateAsDataUri(session.Homeserver.WhoAmI.UserId)"/>
}
@* <img class="avatar" src="@session.UserInfo.AvatarUrl" crossorigin="anonymous"/> *@
</td>
<td class="user-info">
<p>
<input type="radio" name="csa" checked="@(_currentSession.AccessToken == auth.AccessToken)" @onclick="@(() => SwitchSession(auth))" style="text-decoration-line: unset;"/>
<b>@session.UserInfo.DisplayName</b> on <b>@auth.Homeserver</b><br/>
</p>
<span style="display: inline-block; width: 128px;">@session.UserInfo.RoomCount rooms</span>
<a style="color: #888888" href="@("/ServerInfo/" + session.Homeserver?.ServerName + "/")">@session.ServerVersion?.Server.Name @session.ServerVersion?.Server.Version</a>
@if (auth.Proxy != null) {
<span class="badge badge-info"> (proxied via @auth.Proxy)</span>
}
else {
<p>Not proxied</p>
}
@if (_debug) {
<p>T=@session.Homeserver.GetType().FullName</p>
<p>D=@session.Homeserver.WhoAmI.DeviceId</p>
<p>U=@session.Homeserver.WhoAmI.UserId</p>
}
</td>
<td>
<p>
<LinkButton OnClick="@(() => ManageUser(auth))">Manage</LinkButton>
<LinkButton OnClick="@(() => RemoveUser(auth))">Remove</LinkButton>
<LinkButton OnClick="@(() => RemoveUser(auth, true))">Log out</LinkButton>
</p>
</td>
</tr>
}
</table>
</form>
@if (_offlineSessions.Count > 0) {
<br/>
<br/>
<h5>Sessions on unreachable servers</h5>
<hr/>
<form>
<table>
@foreach (var session in _offlineSessions) {
<tr class="user-entry">
<td>
<p>
@{
string[] parts = session.UserId.Split(':');
}
<span>@parts[0][1..]</span> on <span>@parts[1]</span>
@if (!string.IsNullOrWhiteSpace(session.Proxy)) {
<span class="badge badge-info"> (proxied via @session.Proxy)</span>
}
</p>
</td>
<td>
<LinkButton OnClick="@(() => RemoveUser(session))">Remove</LinkButton>
</td>
</tr>
}
</table>
</form>
}
@if (_invalidSessions.Count > 0) {
<br/>
<br/>
<h5>Invalid sessions</h5>
<hr/>
<form>
<table>
@foreach (var session in _invalidSessions) {
<tr class="user-entry">
<td>
<p>
@{
string[] parts = session.UserId.Split(':');
}
<span>@parts[0][1..]</span> on <span>@parts[1]</span>
@if (!string.IsNullOrWhiteSpace(session.Proxy)) {
<span class="badge badge-info"> (proxied via @session.Proxy)</span>
}
</p>
</td>
<td>
<LinkButton OnClick="@(() => Task.Run(()=>NavigationManager.NavigateTo($"/InvalidSession?ctx={session.AccessToken}")))">Re-login</LinkButton>
</td>
<td>
<LinkButton OnClick="@(() => RemoveUser(session))">Remove</LinkButton>
</td>
</tr>
}
</table>
</form>
}
@code
{
#if DEBUG
private const bool _debug = true;
#else
private const bool _debug = false;
#endif
private class AuthInfo {
public UserAuth? UserAuth { get; set; }
public UserInfo? UserInfo { get; set; }
public ServerVersionResponse? ServerVersion { get; set; }
public AuthenticatedHomeserverGeneric? Homeserver { get; set; }
}
private readonly List<AuthInfo> _sessions = [];
private readonly List<UserAuth> _offlineSessions = [];
private readonly List<UserAuth> _invalidSessions = [];
private LoginResponse? _currentSession;
int scannedSessions = 0, totalSessions = 1;
private SvgIdenticonGenerator _identiconGenerator = new();
protected override async Task OnInitializedAsync() {
Console.WriteLine("Index.OnInitializedAsync");
logger.LogDebug("Initialising index page");
_currentSession = await RMUStorage.GetCurrentToken();
_sessions.Clear();
_offlineSessions.Clear();
var tokens = await RMUStorage.GetAllTokens();
scannedSessions = 0;
totalSessions = tokens.Count;
logger.LogDebug("Found {0} tokens", totalSessions);
if (tokens is not { Count: > 0 }) {
Console.WriteLine("No tokens found, trying migration from MRU...");
await RMUStorage.MigrateFromMRU();
tokens = await RMUStorage.GetAllTokens();
if (tokens is not { Count: > 0 }) {
Console.WriteLine("No tokens found");
return;
}
}
List<string> offlineServers = [];
var sema = new SemaphoreSlim(8, 8);
var updateSw = Stopwatch.StartNew();
var tasks = tokens.Select(async token => {
await sema.WaitAsync();
AuthenticatedHomeserverGeneric hs;
try {
hs = await hsProvider.GetAuthenticatedWithToken(token.Homeserver, token.AccessToken, token.Proxy);
var joinedRoomsTask = hs.GetJoinedRooms();
var profileTask = hs.GetProfileAsync(hs.WhoAmI.UserId);
var serverVersionTask = hs.FederationClient?.GetServerVersionAsync();
_sessions.Add(new() {
UserInfo = new() {
AvatarUrl = (await profileTask).AvatarUrl,
RoomCount = (await joinedRoomsTask).Count,
DisplayName = (await profileTask).DisplayName ?? hs.WhoAmI.UserId
},
UserAuth = token,
ServerVersion = await (serverVersionTask ?? Task.FromResult<ServerVersionResponse?>(null)!),
Homeserver = hs
});
if (updateSw.ElapsedMilliseconds > 25) {
updateSw.Restart();
StateHasChanged();
}
}
catch (MatrixException e) {
if (e is { ErrorCode: "M_UNKNOWN_TOKEN" }) {
logger.LogWarning("Got unknown token error for {0} via {1}", token.UserId, token.Homeserver);
_invalidSessions.Add(token);
}
else {
logger.LogError("Failed to get info for {0} via {1}: {2}", token.UserId, token.Homeserver, e);
throw;
}
}
catch (Exception e) {
logger.LogError("Failed to get info for {0} via {1}: {2}", token.UserId, token.Homeserver, e);
if (!string.IsNullOrWhiteSpace(token.Proxy)) {
offlineServers.Add(token.Proxy);
sema.Release();
return;
}
offlineServers.Add(token.Homeserver);
}
scannedSessions++;
sema.Release();
}).ToList();
await Task.WhenAll(tasks);
scannedSessions = totalSessions;
await base.OnInitializedAsync();
}
private class UserInfo {
internal string? AvatarUrl { get; set; }
internal string DisplayName { get; set; }
internal int RoomCount { get; set; }
}
private async Task RemoveUser(UserAuth auth, bool logout = false) {
try {
if (logout) {
await (await hsProvider.GetAuthenticatedWithToken(auth.Homeserver, auth.AccessToken, auth.Proxy)).Logout();
}
}
catch (Exception e) {
if (e is MatrixException { ErrorCode: "M_UNKNOWN_TOKEN" }) {
//todo: handle this
return;
}
Console.WriteLine(e);
}
await RMUStorage.RemoveToken(auth);
if ((await RMUStorage.GetCurrentToken())?.AccessToken == auth.AccessToken)
await RMUStorage.SetCurrentToken((await RMUStorage.GetAllTokens() ?? throw new InvalidOperationException()).FirstOrDefault());
StateHasChanged();
}
private async Task SwitchSession(UserAuth auth) {
Console.WriteLine($"Switching to {auth.Homeserver} {auth.UserId} via {auth.Proxy}");
await RMUStorage.SetCurrentToken(auth);
_currentSession = auth;
StateHasChanged();
}
private async Task ManageUser(UserAuth auth) {
await SwitchSession(auth);
NavigationManager.NavigateTo("/User/Profile");
}
}
|