blob: 5f7ab10723825ad46c515af31907a259140b0d9e (
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
|
using ArcaneLibs.Collections;
using LibMatrix;
using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Homeservers;
namespace MatrixContentFilter.Services;
public class InfoCacheService(AuthenticatedHomeserverGeneric hs) {
private static readonly ExpiringSemaphoreCache<string> DisplayNameCache = new();
public static readonly ExpiringSemaphoreCache<string> RoomNameCache = new();
public async Task<string> GetDisplayNameAsync(string roomId, string userId) =>
await DisplayNameCache.GetOrAdd($"{roomId}\t{userId}", async () => {
var room = hs.GetRoom(roomId);
try {
var userState = await room.GetStateOrNullAsync<RoomMemberEventContent>(RoomMemberEventContent.EventId, userId);
if (!string.IsNullOrWhiteSpace(userState?.DisplayName)) return userState.DisplayName;
}
catch (MatrixException e) {
if (e is not { ErrorCode: MatrixException.ErrorCodes.M_NOT_FOUND or MatrixException.ErrorCodes.M_FORBIDDEN })
throw;
}
var user = await hs.GetProfileAsync(userId);
if (!string.IsNullOrWhiteSpace(user?.DisplayName)) return user.DisplayName;
return userId;
}, TimeSpan.FromMinutes(5));
public async Task<string> GetRoomNameAsync(string roomId) =>
await RoomNameCache.GetOrAdd(roomId, async () => {
var room = hs.GetRoom(roomId);
var name = await room.GetNameOrFallbackAsync();
return name;
}, TimeSpan.FromMinutes(30));
}
|