about summary refs log tree commit diff
path: root/Utilities/LibMatrix.Utilities.Bot/Interfaces/RoomInviteContext.cs
blob: 380c1c71c3e7d7d0fc5448a6c7fbffbeeb82e4c5 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
using LibMatrix.EventTypes.Spec.State.RoomInfo;
using LibMatrix.Homeservers;
using LibMatrix.Responses;

namespace LibMatrix.Utilities.Bot.Interfaces;

public class RoomInviteContext {
    public required string RoomId { get; init; }
    public required AuthenticatedHomeserverGeneric Homeserver { get; init; }
    public required StateEventResponse MemberEvent { get; init; }
    public required SyncResponse.RoomsDataStructure.InvitedRoomDataStructure InviteData { get; init; }

    public async Task<string> TryGetInviterNameAsync() {
        var name = InviteData.InviteState?.Events?
            .FirstOrDefault(evt => evt is { Type: RoomMemberEventContent.EventId } && evt.StateKey == MemberEvent.Sender)?
            .ContentAs<RoomMemberEventContent>()?.DisplayName;

        if (!string.IsNullOrWhiteSpace(name))
            return name;

        try {
            await Homeserver.GetProfileAsync(MemberEvent.Sender!);
        }
        catch {
            //ignored
        }

        return MemberEvent.Sender!;
    }

    public async Task<string> TryGetRoomNameAsync() {
        // try to get room name from invite state
        var name = InviteData.InviteState?.Events?
            .FirstOrDefault(evt => evt is { Type: RoomNameEventContent.EventId, StateKey: "" })?
            .ContentAs<RoomNameEventContent>()?.Name;

        if (!string.IsNullOrWhiteSpace(name))
            return name;

        // try to get room alias
        var alias = InviteData.InviteState?.Events?
            .FirstOrDefault(evt => evt is { Type: RoomCanonicalAliasEventContent.EventId, StateKey: "" })?
            .ContentAs<RoomCanonicalAliasEventContent>()?.Alias;

        if (!string.IsNullOrWhiteSpace(alias))
            return alias;

        // try to get room name via public previews
        try {
            name = await Homeserver.GetRoom(RoomId).GetNameOrFallbackAsync();
            if (name != RoomId && !string.IsNullOrWhiteSpace(name))
                return name;
        }
        catch {
            //ignored
        }

        // fallback to room alias via public previews
        try {
            alias = (await Homeserver.GetRoom(RoomId).GetCanonicalAliasAsync())?.Alias;
            if (!string.IsNullOrWhiteSpace(alias))
                return alias;
        }
        catch {
            //ignored
        }

        // fall back to room ID
        return RoomId;
    }
}