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 | |
| 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')
| -rw-r--r-- | src/slskd/Application.cs | 17 | ||||
| -rw-r--r-- | src/slskd/Options.cs | 4 | ||||
| -rw-r--r-- | src/slskd/State.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadGovernor.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadQueue.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Users/Domain/Statistics.cs | 42 | ||||
| -rw-r--r-- | src/slskd/Users/Domain/Status.cs | 21 | ||||
| -rw-r--r-- | src/slskd/Users/Domain/User.cs | 42 | ||||
| -rw-r--r-- | src/slskd/Users/Extensions.cs | 51 | ||||
| -rw-r--r-- | src/slskd/Users/IUserService.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Users/UserService.cs | 173 |
11 files changed, 343 insertions, 37 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index b03f1abd..56d17808 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -60,9 +60,9 @@ namespace slskd public static readonly string DefaultGroup = "default"; /// <summary> - /// The name of the priviledged user group. + /// The name of the privileged user group. /// </summary> - public static readonly string PriviledgedGroup = "priviledged"; + public static readonly string PrivilegedGroup = "privileged"; /// <summary> /// The name of the leecher user group. @@ -82,6 +82,7 @@ namespace slskd IConversationTracker conversationTracker, IRoomTracker roomTracker, IRoomService roomService, + IUserService userService, ISharedFileCache sharedFileCache, IPushbulletService pushbulletService, IHubContext<ApplicationHub> applicationHub, @@ -107,6 +108,7 @@ namespace slskd Pushbullet = pushbulletService; RoomService = roomService; + Users = userService; ApplicationHub = applicationHub; LogHub = logHub; @@ -157,6 +159,7 @@ namespace slskd private ITransferService Transfers { get; init; } private IHubContext<ApplicationHub> ApplicationHub { get; set; } private IHubContext<LogsHub> LogHub { get; set; } + private IUserService Users { get; set; } public void CollectGarbage() { @@ -587,6 +590,14 @@ namespace slskd // uploads would be handled separately. Task.Run(async () => { + // users with uploads must be watched so that we can keep informed of their + // online status, privileges, and statistics. this is so that we can accurately + // determine their effective group. + if (!Users.IsWatched(username)) + { + await Users.WatchAsync(username); + } + using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); }).ContinueWith(t => @@ -846,7 +857,7 @@ namespace slskd private void State_OnChange((State Previous, State Current) state) { - Log.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); + //Log.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); _ = ApplicationHub.BroadcastStateAsync(state.Current); } diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 2313ce69..5bebeb68 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -467,7 +467,7 @@ namespace slskd /// Gets options for the default user group. /// </summary> /// <remarks> - /// These options apply to users that are not priviledged, have not been identified as leechers, + /// These options apply to users that are not privileged, have not been identified as leechers, /// and have not been added as a member of any group. /// </remarks> [Validate] @@ -495,7 +495,7 @@ namespace slskd /// <returns></returns> public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { - var builtInGroups = new[] { Application.PriviledgedGroup, Application.DefaultGroup, Application.LeecherGroup }; + var builtInGroups = new[] { Application.PrivilegedGroup, Application.DefaultGroup, Application.LeecherGroup }; var intersection = UserDefined.Keys.Intersect(builtInGroups); return intersection.Select(group => new ValidationResult($"User defined group '{group}' collides with a built in group. Choose a different name.")); diff --git a/src/slskd/State.cs b/src/slskd/State.cs index 4c3deff8..bd82f8d7 100644 --- a/src/slskd/State.cs +++ b/src/slskd/State.cs @@ -20,6 +20,7 @@ namespace slskd using System; using System.Net; using System.Text.Json.Serialization; + using slskd.Users; using Soulseek; /// <summary> @@ -34,6 +35,7 @@ namespace slskd public ServerState Server { get; init; } = new ServerState(); public SharedFileCacheState SharedFileCache { get; init; } = new SharedFileCacheState(); public string[] Rooms { get; init; } = Array.Empty<string>(); + public User[] Users { get; init; } = Array.Empty<User>(); } public record VersionState diff --git a/src/slskd/Transfers/Uploads/UploadGovernor.cs b/src/slskd/Transfers/Uploads/UploadGovernor.cs index 9221d686..a806815f 100644 --- a/src/slskd/Transfers/Uploads/UploadGovernor.cs +++ b/src/slskd/Transfers/Uploads/UploadGovernor.cs @@ -150,7 +150,7 @@ namespace slskd.Transfers // also, so transfers in progress will briefly exceed the intended speeds. var tokenBuckets = new Dictionary<string, ITokenBucket>() { - { Application.PriviledgedGroup, CreateBucket(options.Global.Upload.SpeedLimit) }, + { Application.PrivilegedGroup, CreateBucket(options.Global.Upload.SpeedLimit) }, { Application.DefaultGroup, CreateBucket(options.Groups.Default.Upload.SpeedLimit) }, { Application.LeecherGroup, CreateBucket(options.Groups.Leechers.Upload.SpeedLimit) }, }; diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 44aa8af4..e5b8c5f5 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -296,15 +296,15 @@ namespace slskd.Transfers { // the priority group is hard-coded with priority 0, slot count equivalent to the overall max, // and a FIFO strategy. all other groups have a minimum priority of 1 (enforced by options validation) - // to ensure that priviledged users always take priority, regardless of user configuration. - // the strategy is fixed to FIFO because that gives priviledged users the closest experience + // to ensure that privileged users always take priority, regardless of user configuration. + // the strategy is fixed to FIFO because that gives privileged users the closest experience // to the official client, as well as the appearance of fairness once the first upload begins. new Group() { - Name = Application.PriviledgedGroup, + Name = Application.PrivilegedGroup, Priority = 0, Slots = MaxSlots, - UsedSlots = GetExistingUsedSlotsOrDefault(Application.PriviledgedGroup), + UsedSlots = GetExistingUsedSlotsOrDefault(Application.PrivilegedGroup), Strategy = QueueStrategy.FirstInFirstOut, }, new Group() diff --git a/src/slskd/Users/Domain/Statistics.cs b/src/slskd/Users/Domain/Statistics.cs new file mode 100644 index 00000000..a415d3d5 --- /dev/null +++ b/src/slskd/Users/Domain/Statistics.cs @@ -0,0 +1,42 @@ +// <copyright file="Statistics.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Users +{ + public record Statistics + { + /// <summary> + /// Gets the average upload speed of the user. + /// </summary> + public int AverageSpeed { get; init; } + + /// <summary> + /// Gets the number of directories shared by the user. + /// </summary> + public int DirectoryCount { get; init; } + + /// <summary> + /// Gets the number of files shared by the user. + /// </summary> + public int FileCount { get; init; } + + /// <summary> + /// Gets the number of uploads tracked by the server for this user. + /// </summary> + public long UploadCount { get; init; } + } +} diff --git a/src/slskd/Users/Domain/Status.cs b/src/slskd/Users/Domain/Status.cs index 41452e66..890afb74 100644 --- a/src/slskd/Users/Domain/Status.cs +++ b/src/slskd/Users/Domain/Status.cs @@ -19,18 +19,19 @@ namespace slskd.Users { using Soulseek; - public class Status + /// <summary> + /// User status. + /// </summary> + public record Status { + /// <summary> + /// Gets a value indicating whether the user is privileged. + /// </summary> public bool IsPrivileged { get; init; } - public UserPresence Presence { get; init; } - public static Status FromSoulseekUserStatus(UserStatus status) - { - return new Status() - { - IsPrivileged = status.IsPrivileged, - Presence = status.Presence, - }; - } + /// <summary> + /// Gets the user's presence. + /// </summary> + public UserPresence Presence { get; init; } } } diff --git a/src/slskd/Users/Domain/User.cs b/src/slskd/Users/Domain/User.cs new file mode 100644 index 00000000..2913620c --- /dev/null +++ b/src/slskd/Users/Domain/User.cs @@ -0,0 +1,42 @@ +// <copyright file="User.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Users +{ + public record User + { + /// <summary> + /// Gets the username of the user. + /// </summary> + public string Username { get; init; } + + /// <summary> + /// Gets the user's configured group. + /// </summary> + public string Group { get; init; } + + /// <summary> + /// Gets the user's statistics. + /// </summary> + public Statistics Statistics { get; init; } + + /// <summary> + /// Gets the user's status. + /// </summary> + public Status Status { get; init; } + } +} diff --git a/src/slskd/Users/Extensions.cs b/src/slskd/Users/Extensions.cs new file mode 100644 index 00000000..846fd125 --- /dev/null +++ b/src/slskd/Users/Extensions.cs @@ -0,0 +1,51 @@ +// <copyright file="Extensions.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Users +{ + using Soulseek; + + /// <summary> + /// Users extensions. + /// </summary> + public static class Extensions + { + /// <summary> + /// Converts <see cref="Soulseek.UserStatistics"/> to <see cref="Statistics"/>. + /// </summary> + /// <param name="u">The UserStatistics instance to convert.</param> + /// <returns>The converted instance.</returns> + public static Statistics ToStatistics(this UserStatistics u) => new() + { + AverageSpeed = u.AverageSpeed, + DirectoryCount = u.DirectoryCount, + FileCount = u.FileCount, + UploadCount = u.UploadCount, + }; + + /// <summary> + /// Converts <see cref="Soulseek.UserStatus"/> to <see cref="Status"/>. + /// </summary> + /// <param name="s">The UserStatus instance to convert.</param> + /// <returns>The converted instance.</returns> + public static Status ToStatus(this UserStatus s) => new() + { + IsPrivileged = s.IsPrivileged, + Presence = s.Presence, + }; + } +} diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index ad368c65..e78b1b1c 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -17,6 +17,7 @@ namespace slskd.Users { + using System.Collections.Generic; using System.Net; using System.Threading.Tasks; @@ -26,6 +27,16 @@ namespace slskd.Users public interface IUserService { /// <summary> + /// Gets the list of tracked users. + /// </summary> + IReadOnlyList<User> Users { get; } + + /// <summary> + /// Gets the list of watched usernames. + /// </summary> + IReadOnlyList<string> WatchedUsernames { get; } + + /// <summary> /// Gets the name of the group for the specified <paramref name="username"/>. /// </summary> /// <param name="username">The username of the peer.</param> @@ -70,6 +81,13 @@ namespace slskd.Users Task<bool> IsPrivilegedAsync(string username); /// <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> + bool IsWatched(string username); + + /// <summary> /// Adds the specified username to the server-side user list. /// </summary> /// <param name="username">The username of the peer.</param> 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 |
