diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2022-02-25 09:47:06 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-02-25 09:47:06 -0600 |
| commit | 8c7861a0dfc2fd25379e03e1f23b4ae561206fc3 (patch) | |
| tree | 6a3ae3d3cb2cc7d68f81a4cdd82d76f31516d0af /src/slskd/Users/UserService.cs | |
| parent | da7589fb77be63657b69209386743a008b2ae3d3 (diff) | |
| parent | 38bb2f3a021120963be657cf2b363b25bfaa4043 (diff) | |
| download | slskd-8c7861a0dfc2fd25379e03e1f23b4ae561206fc3.tar.gz | |
Merge pull request #364 from slskd/privileges
Identify privileged users
Diffstat (limited to 'src/slskd/Users/UserService.cs')
| -rw-r--r-- | src/slskd/Users/UserService.cs | 173 |
1 files changed, 156 insertions, 17 deletions
diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index cb56e6dd..5adc7c71 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -40,28 +40,60 @@ namespace slskd.Users /// Initializes a new instance of the <see cref="UserService"/> class. /// </summary> /// <param name="soulseekClient"></param> + /// <param name="stateMutator"></param> /// <param name="contextFactory">The database context to use.</param> /// <param name="optionsMonitor"></param> public UserService( ISoulseekClient soulseekClient, + IStateMutator<State> stateMutator, IDbContextFactory<UserDbContext> contextFactory, IOptionsMonitor<Options> optionsMonitor) { Client = soulseekClient; + + StateMutator = stateMutator; + ContextFactory = contextFactory; OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(Configure); + OptionsMonitor.OnChange(options => Configure(options)); + + // updates may be sent unsolicited from the server, so update when we get them. + // binding these events will cause multiple redundant round trips when initially watching a user + // or when explicitly requesting via GetStatus/GetStatistics. this is wasteful, but there's no functional side effect. + Client.UserStatisticsChanged += (_, userStatistics) => UpdateStatistics(userStatistics.Username, userStatistics.ToStatistics()); + Client.UserStatusChanged += (_, userStatus) => + { + UpdateStatus(userStatus.Username, userStatus.ToStatus()); + + // the server doesn't send statistics events by itself, so when a user status changes, fetch stats at the same time. + _ = GetStatisticsAsync(userStatus.Username); + }; + + Client.LoggedIn += (_, _) => Configure(OptionsMonitor.CurrentValue, force: true); + Client.Disconnected += (_, _) => Reset(); Configure(OptionsMonitor.CurrentValue); } + /// <summary> + /// Gets the list of tracked users. + /// </summary> + public IReadOnlyList<User> Users => UserDictionary.Values.ToList().AsReadOnly(); + + /// <summary> + /// Gets the list of watched usernames. + /// </summary> + public IReadOnlyList<string> WatchedUsernames => WatchedUsernamesDictionary.Keys.ToList().AsReadOnly(); + private ISoulseekClient Client { get; } private IDbContextFactory<UserDbContext> ContextFactory { get; } private string LastOptionsHash { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext<UserService>(); - private ConcurrentDictionary<string, string> Map { get; set; } = new ConcurrentDictionary<string, string>(); private IOptionsMonitor<Options> OptionsMonitor { get; } + private IStateMutator<State> StateMutator { get; } + private ConcurrentDictionary<string, User> UserDictionary { get; set; } = new ConcurrentDictionary<string, User>(); + private ConcurrentDictionary<string, bool> WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary<string, bool>(); /// <summary> /// Gets the name of the group for the specified <paramref name="username"/>. @@ -70,7 +102,18 @@ namespace slskd.Users /// <returns>The group for the specified username.</returns> public string GetGroup(string username) { - return Map.GetValueOrDefault(username ?? string.Empty, Application.DefaultGroup); + // note: this is an extremely hot path; keep the work done to an absolute minimum. + if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) + { + if (user.Status?.IsPrivileged ?? false) + { + return Application.PrivilegedGroup; + } + + return user.Group ?? Application.DefaultGroup; + } + + return Application.DefaultGroup; } /// <summary> @@ -119,6 +162,21 @@ namespace slskd.Users } /// <summary> + /// Retrieves the current <see cref="Statistics"/> of a peer. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>The retrieved statistics.</returns> + public async Task<Statistics> GetStatisticsAsync(string username) + { + var soulseekStatistics = await Client.GetUserStatisticsAsync(username); + var statistics = soulseekStatistics.ToStatistics(); + + UpdateStatistics(username, statistics); + + return statistics; + } + + /// <summary> /// Retrieves the current <see cref="Status"/> of a peer. /// </summary> /// <param name="username">The username of the peer.</param> @@ -126,8 +184,11 @@ namespace slskd.Users public async Task<Status> GetStatusAsync(string username) { var soulseekStatus = await Client.GetUserStatusAsync(username); + var status = soulseekStatus.ToStatus(); - return Status.FromSoulseekUserStatus(soulseekStatus); + UpdateStatus(username, status); + + return status; } /// <summary> @@ -144,8 +205,18 @@ namespace slskd.Users /// </summary> /// <param name="username">The username of the peer.</param> /// <returns>A value indicating whether the specified peer is privileged.</returns> - public Task<bool> IsPrivilegedAsync(string username) - => Client.GetUserPrivilegedAsync(username); + public async Task<bool> IsPrivilegedAsync(string username) + { + var status = await GetStatusAsync(username); + return status.IsPrivileged; + } + + /// <summary> + /// Gets a value indicating whether the specified <paramref name="username"/> is watched. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>A value indicating whether the username is watched.</returns> + public bool IsWatched(string username) => WatchedUsernamesDictionary.ContainsKey(username); /// <summary> /// Adds the specified username to the server-side user list. @@ -154,33 +225,101 @@ namespace slskd.Users /// <returns>The operation context.</returns> public async Task WatchAsync(string username) { - await Client.AddUserAsync(username); + // note that this isn't strictly synchronized, and this may be executed more than once per user. this is acceptable, + // and has no side effects other than increased round trips to the server. + if (!WatchedUsernamesDictionary.ContainsKey(username)) + { + await Client.AddUserAsync(username); + WatchedUsernamesDictionary.TryAdd(username, true); + + Log.Information("Added user {Username} to watch list", username); + + // the server does not automatically send status and statistics information + // when watching a user initially. explicitly fetch both, so that the user has been + // watched and all information populated when this method returns. + await GetStatusAsync(username); + await GetStatisticsAsync(username); + } + } + + private void UpdateStatistics(string username, Statistics statistics) + { + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Statistics = statistics }, + updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics }); + + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + } + + private void UpdateStatus(string username, Status status) + { + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Status = status }, + updateValueFactory: (key, user) => user with { Username = username, Status = status }); + + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + } + + private void Reset() + { + WatchedUsernamesDictionary.Clear(); + UserDictionary.Clear(); + + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); } - private void Configure(Options options) + private void Configure(Options options, bool force = false) { var optionsHash = Compute.Sha1Hash(options.Groups.UserDefined.ToJson()); - if (optionsHash == LastOptionsHash) + if (optionsHash == LastOptionsHash && !force) { return; } - var map = new ConcurrentDictionary<string, string>(); + var usernamesBeforeUpdate = UserDictionary.Keys.ToList(); + var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members); + var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate); + + foreach (var username in usernamesRemoved) + { + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Username = username }, + updateValueFactory: (key, user) => user with { Username = username, Group = null }); + } - // sort by priority, ascending - foreach (var group in options.Groups.UserDefined.OrderBy(kvp => kvp.Value.Upload.Priority)) + // sort by priority, descending. this will cause the highest priority group for the user to be persisted when the + // operation is complete. + foreach (var group in options.Groups.UserDefined.OrderByDescending(kvp => kvp.Value.Upload.Priority)) { - foreach (var user in group.Value.Members) + foreach (var username in group.Value.Members) { - // if the key already exists, leave the existing entry. if a user appears in more than one group, the higher - // priority (lower numbered) group is their effective group. - map.TryAdd(user, group.Key); + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Username = username, Group = group.Key }, + updateValueFactory: (key, user) => user with { Username = username, Group = group.Key }); } } - Map = map; + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + + WatchAllUsers(); + LastOptionsHash = optionsHash; } + + private void WatchAllUsers() + { + if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn)) + { + foreach (var username in UserDictionary.Keys.ToList()) + { + _ = WatchAsync(username); + } + } + } } }
\ No newline at end of file |
