summary refs log tree commit diff
path: root/MxApiExtensions/Services/UserContextService.cs
blob: 7c9699049ec793de8537ab182c666d02474b3df3 (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
using System.Collections.Concurrent;
using System.Text.Json.Serialization;
using ArcaneLibs.Extensions;
using LibMatrix;
using LibMatrix.Homeservers;
using MxApiExtensions.Classes;

namespace MxApiExtensions.Services;

public class UserContextService(MxApiExtensionsConfiguration config, AuthenticatedHomeserverProviderService hsProvider) {
    internal static ConcurrentDictionary<string, UserContext> UserContextStore { get; set; } = new();
    public readonly int SessionCount = UserContextStore.Count;

    public class UserContext {
        public SyncState? SyncState { get; set; }
        [JsonIgnore]
        public AuthenticatedHomeserverGeneric Homeserver { get; set; }
        public MxApiExtensionsUserConfiguration UserConfiguration { get; set; }
    }

    private readonly SemaphoreSlim _getUserContextSemaphore = new SemaphoreSlim(1, 1);
    public async Task<UserContext> GetCurrentUserContext() {
        var hs = await hsProvider.GetHomeserver();
        // await _getUserContextSemaphore.WaitAsync();
        var ucs = await UserContextStore.GetOrCreateAsync($"{hs.WhoAmI.UserId}/{hs.WhoAmI.DeviceId}/{hs.ServerName}:{hs.AccessToken}", async x => {
            var userContext = new UserContext() {
                Homeserver = hs
            };
            try {
                userContext.UserConfiguration = await hs.GetAccountDataAsync<MxApiExtensionsUserConfiguration>(MxApiExtensionsUserConfiguration.EventId);
            }
            catch (MatrixException e) {
                if (e is not { ErrorCode: "M_NOT_FOUND" }) throw;
                userContext.UserConfiguration = config.DefaultUserConfiguration;
            }

            await hs.SetAccountDataAsync(MxApiExtensionsUserConfiguration.EventId, userContext.UserConfiguration);

            return userContext;
        }, _getUserContextSemaphore);
        // _getUserContextSemaphore.Release();
        return ucs;
    }
}