aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2025-12-13 17:15:33 -0600
committerGitHub <noreply@github.com>2025-12-13 17:15:33 -0600
commit0b939fe41b22e0151d2b0e106310520f19d0c670 (patch)
treefd7023550e6e65cddccedfe4e3073d686329e02c /src
parente08479ee8d91952fee13b009f861912a92a2dbae (diff)
parent8c842ff28f507e886ebf7ca6217e11ae2650dff9 (diff)
downloadslskd-0b939fe41b22e0151d2b0e106310520f19d0c670.tar.gz
Merge branch 'master' into copilot/gracefully-handle-mutex-creation
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs1
-rw-r--r--src/slskd/Common/Authentication/ApiKeyAuthentication.cs9
-rw-r--r--src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs100
-rw-r--r--src/slskd/Common/Validation/IPAddressAttribute.cs32
-rw-r--r--src/slskd/Core/API/Controllers/SessionController.cs4
-rw-r--r--src/slskd/Core/Data/Databases.cs2
-rw-r--r--src/slskd/Core/Options.cs112
-rw-r--r--src/slskd/Core/Security/SecurityService.cs171
-rw-r--r--src/slskd/Program.cs69
-rw-r--r--src/slskd/Telemetry/API/MetricsController.cs (renamed from src/slskd/Telemetry/API/TelemetryController.cs)80
-rw-r--r--src/slskd/Telemetry/API/ReportsController.cs557
-rw-r--r--src/slskd/Telemetry/Metrics.cs242
-rw-r--r--src/slskd/Telemetry/PrometheusService.cs27
-rw-r--r--src/slskd/Telemetry/ReportsService.cs542
-rw-r--r--src/slskd/Telemetry/TelemetryService.cs6
-rw-r--r--src/slskd/Telemetry/Types/DirectoryDetail.cs23
-rw-r--r--src/slskd/Telemetry/Types/LeaderboardSorting.cs25
-rw-r--r--src/slskd/Telemetry/Types/PrometheusMetric.cs2
-rw-r--r--src/slskd/Telemetry/Types/SortOrder.cs24
-rw-r--r--src/slskd/Telemetry/Types/TransferExceptionDetail.cs39
-rw-r--r--src/slskd/Telemetry/Types/TransferExceptionSummary.cs25
-rw-r--r--src/slskd/Telemetry/Types/TransferSummary.cs29
-rw-r--r--src/slskd/Telemetry/Types/UserDirectionTransferSummary.cs36
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs6
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs6
-rw-r--r--src/slskd/slskd.csproj5
-rw-r--r--src/web/package-lock.json38
-rw-r--r--src/web/src/components/System/Files/Explorer.jsx70
-rw-r--r--src/web/src/components/Transfers/TransferDetails.jsx107
-rw-r--r--src/web/src/components/Transfers/TransferList.jsx43
-rw-r--r--src/web/src/components/Transfers/Transfers.css5
31 files changed, 2163 insertions, 274 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index c1e09d42..1a18790f 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -47,6 +47,7 @@ namespace slskd
using slskd.Relay;
using slskd.Search;
using slskd.Shares;
+ using slskd.Telemetry;
using slskd.Transfers;
using slskd.Users;
using Soulseek;
diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
index 1aaa4a4f..e2733442 100644
--- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
+++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
@@ -15,6 +15,7 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace slskd.Authentication
@@ -24,7 +25,7 @@ namespace slskd.Authentication
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
- using Microsoft.Extensions.Logging;
+ using Serilog;
/// <summary>
/// API key authentication.
@@ -51,7 +52,7 @@ namespace slskd.Authentication
/// <param name="urlEncoder">A url encoder.</param>
public ApiKeyAuthenticationHandler(
IOptionsMonitor<ApiKeyAuthenticationOptions> apiKeyOptionsMonitor,
- ISecurityService securityService,
+ SecurityService securityService,
ILoggerFactory logger,
UrlEncoder urlEncoder)
: base(apiKeyOptionsMonitor, logger, urlEncoder)
@@ -59,7 +60,8 @@ namespace slskd.Authentication
Security = securityService;
}
- private ISecurityService Security { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<ApiKeyAuthenticationHandler>();
+ private SecurityService Security { get; }
/// <summary>
/// Authenticates via API key.
@@ -86,6 +88,7 @@ namespace slskd.Authentication
}
catch (Exception ex)
{
+ Log.Warning("Unauthorized request from IP address {IP}: {Message}", Request.HttpContext.Connection.RemoteIpAddress, ex.Message);
return AuthenticateResult.Fail(ex);
}
}
diff --git a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
new file mode 100644
index 00000000..db5c4baa
--- /dev/null
+++ b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
@@ -0,0 +1,100 @@
+// <copyright file="ContentNegotiationOperationFilter.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;
+
+using System.Linq;
+using System.Reflection;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Formatters;
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+
+/// <summary>
+/// OpenAPI operation filter that properly handles content negotiation with different response schemas.
+/// </summary>
+public class ContentNegotiationOperationFilter : IOperationFilter
+{
+ public void Apply(OpenApiOperation operation, OperationFilterContext context)
+ {
+ // check to see if the current operation is decorated with [Produces], which is what enables content negotiation
+ var producesAttribute = context.MethodInfo
+ .GetCustomAttributes(typeof(ProducesAttribute), false)
+ .Cast<ProducesAttribute>()
+ .FirstOrDefault();
+
+ if (producesAttribute == null || producesAttribute.ContentTypes.Count == 0)
+ {
+ return;
+ }
+
+ // next, get all of the [ProducesResponseType] attributes, if any
+ var producesResponseTypeAttributes = context.MethodInfo
+ .GetCustomAttributes(typeof(ProducesResponseTypeAttribute), false)
+ .Cast<ProducesResponseTypeAttribute>()
+ .ToList();
+
+ if (producesResponseTypeAttributes.Count == 0)
+ {
+ return;
+ }
+
+ // map over the list of status codes; we need to (attempt to) perform this mapping for each status code and each
+ // content type listed in [Produces]
+ foreach (var statusCodeGroup in producesResponseTypeAttributes.GroupBy(x => x.StatusCode))
+ {
+ foreach (var contentType in producesAttribute.ContentTypes)
+ {
+ // find the first [ProducesResponseType] that contains this content type in its list of content types
+ var attribute = statusCodeGroup.FirstOrDefault(x => GetContentTypes(x).Contains(contentType));
+
+ if (attribute is not null)
+ {
+ var response = operation.Responses[statusCodeGroup.Key.ToString()];
+ response.Content[contentType] = new OpenApiMediaType
+ {
+ Schema = context.SchemaGenerator.GenerateSchema(attribute.Type, context.SchemaRepository),
+ };
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Extracts the value of the _contentTypes field of <see cref="ProducesResponseTypeAttribute"/>.
+ ///
+ /// This is necessary because Microsoft didn't see fit to bless us with the ability to retrieve the content types
+ /// we specifify along with our [ProducesResponseType] attributes.
+ ///
+ /// It will most likely break at some point.
+ /// </summary>
+ /// <param name="attribute">The attribute from which to extract the _contentTypes field.</param>
+ /// <returns>The value of the extracted field.</returns>
+ private MediaTypeCollection GetContentTypes(ProducesResponseTypeAttribute attribute)
+ {
+ var contentTypesField = typeof(ProducesResponseTypeAttribute).GetField("_contentTypes", BindingFlags.NonPublic | BindingFlags.Instance);
+
+ MediaTypeCollection value = (MediaTypeCollection)contentTypesField.GetValue(attribute);
+
+ if (value is null)
+ {
+ return [];
+ }
+
+ return value;
+ }
+}
diff --git a/src/slskd/Common/Validation/IPAddressAttribute.cs b/src/slskd/Common/Validation/IPAddressAttribute.cs
index 6e53df57..b9075808 100644
--- a/src/slskd/Common/Validation/IPAddressAttribute.cs
+++ b/src/slskd/Common/Validation/IPAddressAttribute.cs
@@ -18,6 +18,7 @@
namespace slskd.Validation
{
using System.ComponentModel.DataAnnotations;
+ using System.Linq;
using System.Net;
/// <summary>
@@ -25,6 +26,13 @@ namespace slskd.Validation
/// </summary>
public class IPAddressAttribute : ValidationAttribute
{
+ public IPAddressAttribute(bool allowCommaSeparatedValues = false)
+ {
+ AllowCommaSeparatedValues = allowCommaSeparatedValues;
+ }
+
+ private bool AllowCommaSeparatedValues { get; set; }
+
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
@@ -36,9 +44,29 @@ namespace slskd.Validation
return fail;
}
- if (!IPAddress.TryParse(valueAsString, out _))
+ if (!valueAsString.Contains(','))
{
- return fail;
+ if (!IPAddress.TryParse(valueAsString, out _))
+ {
+ return fail;
+ }
+ }
+ else
+ {
+ if (!AllowCommaSeparatedValues)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field accepts a single value only (a comma separated list was specified)");
+ }
+
+ var values = valueAsString.Split(',').Select(v => v.Trim());
+
+ foreach (var currentValue in values)
+ {
+ if (!IPAddress.TryParse(currentValue, out _))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more invalid IPv4 or IPv6 IP addresses.");
+ }
+ }
}
}
diff --git a/src/slskd/Core/API/Controllers/SessionController.cs b/src/slskd/Core/API/Controllers/SessionController.cs
index 861fd468..cfcb3f23 100644
--- a/src/slskd/Core/API/Controllers/SessionController.cs
+++ b/src/slskd/Core/API/Controllers/SessionController.cs
@@ -36,7 +36,7 @@ namespace slskd.Core.API
public class SessionController : ControllerBase
{
public SessionController(
- ISecurityService securityService,
+ SecurityService securityService,
IOptionsSnapshot<Options> optionsSnapshot,
OptionsAtStartup optionsAtStartup)
{
@@ -47,7 +47,7 @@ namespace slskd.Core.API
private IOptionsSnapshot<Options> OptionsSnapshot { get; set; }
private OptionsAtStartup OptionsAtStartup { get; set; }
- private ISecurityService Security { get; }
+ private SecurityService Security { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<SessionController>();
/// <summary>
diff --git a/src/slskd/Core/Data/Databases.cs b/src/slskd/Core/Data/Databases.cs
index f118ad2a..a5d51ea6 100644
--- a/src/slskd/Core/Data/Databases.cs
+++ b/src/slskd/Core/Data/Databases.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+namespace slskd;
+
/// <summary>
/// A primitive type for Database names and a static value for each of them. And a list.
/// </summary>
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 254adcab..20b53f6c 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -115,7 +115,7 @@ namespace slskd
/// <summary>
/// Gets a value indicating whether to display a list of configuration environment variables.
/// </summary>
- [Argument('e', "envars")]
+ [Argument(default, "envars")]
[Description("display environment variables")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
@@ -125,7 +125,7 @@ namespace slskd
/// <summary>
/// Gets a value indicating whether to generate an X509 certificate and password.
/// </summary>
- [Argument('g', "generate-cert")]
+ [Argument(default, "generate-cert")]
[Description("generate X509 certificate and password for HTTPS")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
@@ -135,7 +135,7 @@ namespace slskd
/// <summary>
/// Gets a value indicating whether to generate a random secret.
/// </summary>
- [Argument('k', "generate-secret")]
+ [Argument(default, "generate-secret")]
[Description("generate random secret of the specified length")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
@@ -1252,6 +1252,12 @@ namespace slskd
return results;
}
+ if (string.IsNullOrWhiteSpace(File))
+ {
+ results.Add(new ValidationResult("The Enabled field is true, but no File has been specified."));
+ return results;
+ }
+
// loading/validating the entire list will be costly on low spec systems
// just make sure that we can detect a valid format and leave it at that
// if there's a problem with any of the entries, the load will fail and
@@ -1833,6 +1839,16 @@ namespace slskd
public int Port { get; init; } = 5030;
/// <summary>
+ /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTP requests.
+ /// </summary>
+ [Argument(default, "http-ip-address")]
+ [EnvironmentVariable("HTTP_IP_ADDRESS")]
+ [Description("IP addresses on which to listen for HTTP requests")]
+ [IPAddress(allowCommaSeparatedValues: true)]
+ [RequiresRestart]
+ public string IpAddress { get; init; }
+
+ /// <summary>
/// Gets the HTTP listen unix domain socket (UDS) path.
/// </summary>
[Argument(default, "http-socket")]
@@ -1887,7 +1903,7 @@ namespace slskd
/// <summary>
/// Authentication options.
/// </summary>
- public class WebAuthenticationOptions
+ public class WebAuthenticationOptions : IValidatableObject
{
/// <summary>
/// Gets a value indicating whether authentication should be disabled.
@@ -1925,11 +1941,89 @@ namespace slskd
public JwtOptions Jwt { get; init; } = new JwtOptions();
/// <summary>
+ /// Gets the primary API key. Defaults to 'Administrator' role and CIDR '0.0.0.0/0,::/0'.
+ /// role and CIDR can be supplied by prefixing the key with 'role=[role];cidr=[cidrs];[key]'.
+ /// </summary>
+ [Argument('k', "api-key")]
+ [EnvironmentVariable("API_KEY")]
+ [Description("primary API key value")]
+ [Secret]
+ [RequiresRestart]
+ public string ApiKey { get; init; }
+
+ /// <summary>
/// Gets API keys.
/// </summary>
[Validate]
public Dictionary<string, ApiKeyOptions> ApiKeys { get; init; } = new Dictionary<string, ApiKeyOptions>();
+ public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
+ {
+ var results = new List<ValidationResult>();
+
+ if (string.IsNullOrWhiteSpace(ApiKey))
+ {
+ return results;
+ }
+
+ var tuples = ApiKey.Split(';');
+
+ // if only one tuple is supplied, it's just the key, no role or list of CIDRs
+ if (tuples.Length == 1)
+ {
+ var key = tuples.FirstOrDefault();
+
+ if (key?.Length < 16 || key?.Length > 255)
+ {
+ results.Add(new ValidationResult("API key must be between 16 and 255 characters"));
+ }
+
+ return results;
+ }
+
+ /*
+ if multiple tuples are supplied, verify that:
+
+ * if a tuple starts with 'role=', it's defining a role and it must match one of the Role enum values
+ * if a tuple starts with 'cidr=', it's defining a list of CIDRs which need to be valid
+ * if a tuple doesn't start with a prefix, it's the API key itself and it must be between 16 and 255 characters
+ */
+ foreach (var tuple in tuples)
+ {
+ if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase))
+ {
+ var role = tuple.Split('=').LastOrDefault();
+
+ if (!Enum.TryParse(typeof(Role), value: role, ignoreCase: true, out _))
+ {
+ results.Add(new ValidationResult($"API key role must be one of: {string.Join(", ", Enum.GetNames(typeof(Role)))}"));
+ }
+ }
+ else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase))
+ {
+ var cidrs = tuple.Split('=').LastOrDefault();
+
+ foreach (var cidr in cidrs.Split(','))
+ {
+ try
+ {
+ _ = IPAddressRange.Parse(cidr);
+ }
+ catch (Exception ex)
+ {
+ results.Add(new ValidationResult($"API key CIDR {cidr} is invalid: {ex.Message}"));
+ }
+ }
+ }
+ else if (tuple?.Length < 16 || tuple?.Length > 255)
+ {
+ results.Add(new ValidationResult("API key must be between 16 and 255 characters"));
+ }
+ }
+
+ return results;
+ }
+
/// <summary>
/// JWT options.
/// </summary>
@@ -2034,6 +2128,16 @@ namespace slskd
public int Port { get; init; } = 5031;
/// <summary>
+ /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTPS requests.
+ /// </summary>
+ [Argument(default, "https-ip-address")]
+ [EnvironmentVariable("HTTPS_IP_ADDRESS")]
+ [Description("IP addresses on which to listen for HTTPS requests")]
+ [IPAddress(allowCommaSeparatedValues: true)]
+ [RequiresRestart]
+ public string IpAddress { get; init; }
+
+ /// <summary>
/// Gets a value indicating whether HTTP requests should be redirected to HTTPS.
/// </summary>
[Argument('f', "force-https")]
diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs
index 6da88571..254b3081 100644
--- a/src/slskd/Core/Security/SecurityService.cs
+++ b/src/slskd/Core/Security/SecurityService.cs
@@ -17,84 +17,133 @@
using Microsoft.Extensions.Options;
-namespace slskd
+namespace slskd;
+
+using System;
+using System.Collections.Generic;
+using System.IdentityModel.Tokens.Jwt;
+using System.Linq;
+using System.Net;
+using System.Security.Claims;
+using Microsoft.IdentityModel.Tokens;
+using NetTools;
+using slskd.Authentication;
+
+public class SecurityService
{
- using System;
- using System.Collections.Generic;
- using System.IdentityModel.Tokens.Jwt;
- using System.Linq;
- using System.Net;
- using System.Security.Claims;
- using Microsoft.IdentityModel.Tokens;
- using NetTools;
- using slskd.Authentication;
-
- public interface ISecurityService
+ public SecurityService(
+ SymmetricSecurityKey jwtSigningKey,
+ OptionsAtStartup optionsAtStartup,
+ IOptionsMonitor<Options> optionsMonitor)
{
- JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null);
- (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress);
- }
+ JwtSigningKey = jwtSigningKey;
+ OptionsAtStartup = optionsAtStartup;
+ OptionsMonitor = optionsMonitor;
- public class SecurityService : ISecurityService
- {
- public SecurityService(
- SymmetricSecurityKey jwtSigningKey,
- OptionsAtStartup optionsAtStartup,
- IOptionsMonitor<Options> optionsMonitor)
+ // parse the configured string into an instance of ApiKeyOptions and assign it to
+ // PrimaryApiKey, if a string is provided.
+ // this is kind of expensive in terms of allocations, so do it once at instantiation
+ // and mark the option with [RequiresRestart]
+ var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey;
+
+ if (!string.IsNullOrWhiteSpace(adminApiKeyString))
{
- JwtSigningKey = jwtSigningKey;
- OptionsAtStartup = optionsAtStartup;
- OptionsMonitor = optionsMonitor;
- }
+ if (!adminApiKeyString.Contains(';'))
+ {
+ PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions
+ {
+ Key = adminApiKeyString,
+ };
+ }
- private SymmetricSecurityKey JwtSigningKey { get; }
- private OptionsAtStartup OptionsAtStartup { get; }
- private IOptionsMonitor<Options> OptionsMonitor { get; }
+ var tuples = adminApiKeyString.Split(';');
- public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress)
- {
- var record = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys
- .FirstOrDefault(k => k.Value.Key == key);
+ string key = null;
+ string role = null;
+ string cidr = null;
- if (record.Key == null)
+ foreach (var tuple in tuples)
{
- throw new NotFoundException($"The provided API key does not match an existing key");
+ if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase))
+ {
+ role = tuple.Split('=').LastOrDefault();
+ }
+ else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase))
+ {
+ cidr = tuple.Split('=').LastOrDefault();
+ }
+ else
+ {
+ key = tuple;
+ }
}
- if (!record.Value.Cidr.Split(',')
- .Select(cidr => IPAddressRange.Parse(cidr))
- .Any(range => range.Contains(callerIpAddress)))
+ if (!string.IsNullOrEmpty(key))
{
- throw new OutOfRangeException("The remote IP address is not within the range specified for the key");
+ PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions
+ {
+ Key = key,
+ Role = string.IsNullOrWhiteSpace(role) ? Role.Administrator.ToString() : role,
+ Cidr = string.IsNullOrWhiteSpace(cidr) ? "0.0.0.0/0,::/0" : cidr,
+ };
}
+ }
+ }
+
+ private SymmetricSecurityKey JwtSigningKey { get; }
+ private OptionsAtStartup OptionsAtStartup { get; }
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions PrimaryApiKey { get; } = null;
+
+ public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress)
+ {
+ var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable();
- return (record.Key, record.Value.Role.ToEnum<Role>());
+ if (PrimaryApiKey is not null)
+ {
+ keys = keys.Prepend(new KeyValuePair<string, Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions>(nameof(PrimaryApiKey), PrimaryApiKey));
}
- public JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null)
+ var record = keys.FirstOrDefault(k => k.Value.Key == key);
+
+ if (record.Key == null)
{
- var issuedUtc = DateTime.UtcNow;
- var expiresUtc = DateTime.UtcNow.AddMilliseconds(ttl ?? OptionsAtStartup.Web.Authentication.Jwt.Ttl);
+ throw new NotFoundException($"Unknown API key beginning with: {key.Substring(0, 4)}");
+ }
- var claims = new List<Claim>()
- {
- new Claim(ClaimTypes.Name, username),
- new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
- new Claim(ClaimTypes.Role, role.ToString()),
- new Claim("name", username),
- new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()),
- };
-
- var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256);
-
- var token = new JwtSecurityToken(
- issuer: Program.AppName,
- claims: claims,
- notBefore: issuedUtc,
- expires: expiresUtc,
- signingCredentials: credentials);
-
- return token;
+ if (!record.Value.Cidr.Split(',')
+ .Select(cidr => IPAddressRange.Parse(cidr))
+ .Any(range => range.Contains(callerIpAddress)))
+ {
+ throw new OutOfRangeException($"IP address {callerIpAddress} not included in CIDR range(s) for API key {record.Key}; allowed: {record.Value.Cidr}");
}
+
+ return (record.Key, record.Value.Role.ToEnum<Role>());
+ }
+
+ public JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null)
+ {
+ var issuedUtc = DateTime.UtcNow;
+ var expiresUtc = DateTime.UtcNow.AddMilliseconds(ttl ?? OptionsAtStartup.Web.Authentication.Jwt.Ttl);
+
+ var claims = new List<Claim>()
+ {
+ new Claim(ClaimTypes.Name, username),
+ new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
+ new Claim(ClaimTypes.Role, role.ToString()),
+ new Claim("name", username),
+ new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()),
+ };
+
+ var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256);
+
+ var token = new JwtSecurityToken(
+ issuer: Program.AppName,
+ claims: claims,
+ notBefore: issuedUtc,
+ expires: expiresUtc,
+ signingCredentials: credentials);
+
+ return token;
}
}
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index db4f7c6c..770c6746 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -40,6 +40,7 @@ namespace slskd
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
+ using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -68,6 +69,7 @@ namespace slskd
using slskd.Search;
using slskd.Search.API;
using slskd.Shares;
+ using slskd.Telemetry;
using slskd.Transfers;
using slskd.Transfers.Downloads;
using slskd.Transfers.Uploads;
@@ -89,6 +91,11 @@ namespace slskd
public static readonly string AppName = "slskd";
/// <summary>
+ /// The DateTime of the 'genesis' of the application (the initial commit).
+ /// </summary>
+ public static readonly DateTime GenesisDateTime = new(2020, 12, 30, 6, 22, 0, DateTimeKind.Utc);
+
+ /// <summary>
/// The name of the local share host.
/// </summary>
public static readonly string LocalHostName = "local";
@@ -492,19 +499,39 @@ namespace slskd
.UseUrls()
.UseKestrel(options =>
{
- Log.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/");
- options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port);
+ // configure HTTP, either by listening at any IP or by each of the IPs provided in the
+ // config (note: they've already been validated at this point!)
+ if (string.IsNullOrWhiteSpace(OptionsAtStartup.Web.IpAddress))
+ {
+ Log.Information("Listening for HTTP requests at http://{IP}:{Port}/", IPAddress.IPv6Any, OptionsAtStartup.Web.Port);
+ options.Listen(IPAddress.IPv6Any, OptionsAtStartup.Web.Port); // [::]; any IPv4 or IPv6 address
+ }
+ else
+ {
+ var httpIps = OptionsAtStartup.Web.IpAddress
+ .Split(',')
+ .Select(ip => ip.Trim())
+ .Select(ip => IPAddress.Parse(ip));
+ foreach (var ip in httpIps)
+ {
+ Log.Information("Listening for HTTP requests at http://{IP}:{Port}/", ip, OptionsAtStartup.Web.Port);
+ options.Listen(ip, OptionsAtStartup.Web.Port);
+ }
+ }
+
+ // configure UDS, if supplied
if (OptionsAtStartup.Web.Socket != null)
{
Log.Information($"Listening for HTTP requests on unix domain socket (UDS) {OptionsAtStartup.Web.Socket}");
options.ListenUnixSocket(OptionsAtStartup.Web.Socket);
}
- if (!OptionsAtStartup.Web.Https.Disabled)
+ // configure HTTPS, again listening on any IP or on a list of supplied IPs
+ // use a local function because Microsoft can't get enough of the obtuse builder pattern
+ static void ListenHttps(KestrelServerOptions o, IPAddress ip)
{
- Log.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/");
- options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions =>
+ o.Listen(ip, OptionsAtStartup.Web.Https.Port, listenOptions =>
{
var cert = OptionsAtStartup.Web.Https.Certificate;
@@ -520,6 +547,28 @@ namespace slskd
}
});
}
+
+ if (!OptionsAtStartup.Web.Https.Disabled)
+ {
+ if (string.IsNullOrWhiteSpace(OptionsAtStartup.Web.Https.IpAddress))
+ {
+ Log.Information("Listening for HTTPS requests at https://{IP}:{Port}/", IPAddress.IPv6Any, OptionsAtStartup.Web.Https.Port);
+ ListenHttps(options, IPAddress.IPv6Any);
+ }
+ else
+ {
+ var httpsIps = OptionsAtStartup.Web.Https.IpAddress
+ .Split(',')
+ .Select(ip => ip.Trim())
+ .Select(ip => IPAddress.Parse(ip));
+
+ foreach (var ip in httpsIps)
+ {
+ Log.Information("Listening for HTTPS requests at https://{IP}:{Port}/", ip, OptionsAtStartup.Web.Https.Port);
+ ListenHttps(options, ip);
+ }
+ }
+ }
});
builder.Services
@@ -666,8 +715,9 @@ namespace slskd
services.AddSingleton<EventService>();
services.AddSingleton<EventBus>();
- services.AddSingleton<TelemetryService>();
services.AddSingleton<PrometheusService>();
+ services.AddSingleton<ReportsService>();
+ services.AddSingleton<TelemetryService>();
services.AddSingleton<ScriptService>();
services.AddSingleton<WebhookService>();
@@ -747,7 +797,7 @@ namespace slskd
var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key));
services.AddSingleton(jwtSigningKey);
- services.AddSingleton<ISecurityService, SecurityService>();
+ services.AddSingleton<SecurityService>();
if (!OptionsAtStartup.Web.Authentication.Disabled)
{
@@ -814,7 +864,7 @@ namespace slskd
try
{
// check to see if the provided value is a valid API key
- var service = services.BuildServiceProvider().GetRequiredService<ISecurityService>();
+ var service = services.BuildServiceProvider().GetRequiredService<SecurityService>();
var (name, role) = service.AuthenticateWithApiKey(token, callerIpAddress: context.HttpContext.Connection.RemoteIpAddress);
// the API key is valid. create a new, short lived jwt for the key name and role
@@ -930,6 +980,9 @@ namespace slskd
},
});
+ // allow endpoints marked with multiple content types in [Produces] to generate properly
+ options.OperationFilter<ContentNegotiationOperationFilter>();
+
if (IOFile.Exists(XmlDocumentationFile))
{
options.IncludeXmlComments(XmlDocumentationFile);
diff --git a/src/slskd/Telemetry/API/TelemetryController.cs b/src/slskd/Telemetry/API/MetricsController.cs
index d5c44c1a..3ed7c1e2 100644
--- a/src/slskd/Telemetry/API/TelemetryController.cs
+++ b/src/slskd/Telemetry/API/MetricsController.cs
@@ -1,4 +1,4 @@
-// <copyright file="TelemetryController.cs" company="slskd Team">
+// <copyright file="MetricsController.cs" company="slskd Team">
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
@@ -23,30 +23,33 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
+using Serilog;
/// <summary>
/// Telemetry.
/// </summary>
-[Route("api/v{version:apiVersion}/[controller]")]
+[Route("api/v{version:apiVersion}/telemetry/[controller]")]
+[Tags("Telemetry")]
[ApiVersion("0")]
[ApiController]
[Produces("application/json")]
-public class TelemetryController : ControllerBase
+public class MetricsController : ControllerBase
{
/// <summary>
- /// Initializes a new instance of the <see cref="TelemetryController"/> class.
+ /// Initializes a new instance of the <see cref="MetricsController"/> class.
/// </summary>
- /// <param name="telemetryService"></param>
- public TelemetryController(TelemetryService telemetryService)
+ public MetricsController(TelemetryService telemetryService)
{
Telemetry = telemetryService;
}
private TelemetryService Telemetry { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<MetricsController>();
/// <summary>
- /// KPIs for the app, based on the Prometheus dashboard
+ /// Gets KPIs for the app, based on the Prometheus dashboard
/// * process_Working_set_bytes = total memory used
/// * dotnet_total_memory_bytes = sum of all managed memory
/// * process_cpu_seconds_total = total cpu time spent (not a great measure)
@@ -59,8 +62,8 @@ public class TelemetryController : ControllerBase
/// Other
/// * process_start_time_seconds = unix timestamp of start time.
/// </summary>
- private List<Regex> KpiRegexes { get; } = new List<Regex>
- {
+ private List<Regex> KpiRegexes { get; } =
+ [
new Regex("slskd_.*", RegexOptions.Compiled),
new Regex("node_(?!cpu)", RegexOptions.Compiled),
new Regex("process_.*", RegexOptions.Compiled),
@@ -68,36 +71,65 @@ public class TelemetryController : ControllerBase
new Regex("system_runtime_[cpu_usage|working_set|alloc_total]", RegexOptions.Compiled),
new Regex("system_net_sockets.*", RegexOptions.Compiled),
new Regex("microsoft_aspnetcore_server_kestrel_[current|total]_connections", RegexOptions.Compiled),
- };
+ ];
/// <summary>
- /// Gets application metrics.
+ /// Gets all application metrics.
/// </summary>
- /// <returns></returns>
- [HttpGet("metrics")]
+ /// <remarks>
+ /// If the 'Accept' header is set to 'text/plain', the response is in Prometheus format. Otherwise if 'application/json' is set,
+ /// the metrics are formatted into a dictionary.
+ /// </remarks>
+ /// <returns>A flat Prometheus-formatted list of all metrics given text/plain, a dictionary keyed by metric name otherwise.</returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("")]
[Authorize(Policy = AuthPolicy.Any)]
[Produces("text/plain", "application/json")]
+ [ProducesResponseType(typeof(string), 200, "text/plain")]
+ [ProducesResponseType(typeof(Dictionary<string, PrometheusMetric>), 200, "application/json")]
+ [ProducesResponseType(typeof(string), 500)]
public async Task<IActionResult> Get()
{
- if (Request.Headers.Accept.ToString().Equals("application/json", StringComparison.OrdinalIgnoreCase))
+ try
{
- Dictionary<string, PrometheusMetric> dict = await Telemetry.Prometheus.GetMetricsAsObject();
- return Ok(dict);
- }
+ if (Request.Headers.Accept.ToString().Equals("application/json", StringComparison.OrdinalIgnoreCase))
+ {
+ Dictionary<string, PrometheusMetric> dict = await Telemetry.Prometheus.GetMetricsAsObject();
+ return Ok(dict);
+ }
- var response = await Telemetry.Prometheus.GetMetricsAsString();
- return Content(response, "text/plain");
+ var response = await Telemetry.Prometheus.GetMetricsAsString();
+ return Content(response, "text/plain");
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching metrics: {Message}", ex.Message);
+ return StatusCode(500, ex.Message);
+ }
}
/// <summary>
- /// Gets gets key performance indicators for the application.
+ /// Gets gets key performance indicators (KPIs) for the application.
/// </summary>
- /// <returns></returns>
- [HttpGet("metrics/kpi")]
+ /// <returns>A dictionary keyed by metric name.</returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("kpis")]
[Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(Dictionary<string, PrometheusMetric>), 200)]
+ [ProducesResponseType(typeof(string), 500)]
public async Task<IActionResult> GetKpis()
{
- Dictionary<string, PrometheusMetric> dict = await Telemetry.Prometheus.GetMetricsAsObject(include: KpiRegexes);
- return Ok(dict);
+ try
+ {
+ Dictionary<string, PrometheusMetric> dict = await Telemetry.Prometheus.GetMetricsAsObject(include: KpiRegexes);
+ return Ok(dict);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching KPIs: {Message}", ex.Message);
+ return StatusCode(500, ex.Message);
+ }
}
}
diff --git a/src/slskd/Telemetry/API/ReportsController.cs b/src/slskd/Telemetry/API/ReportsController.cs
new file mode 100644
index 00000000..da088800
--- /dev/null
+++ b/src/slskd/Telemetry/API/ReportsController.cs
@@ -0,0 +1,557 @@
+// <copyright file="ReportsController.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.Telemetry;
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Serilog;
+using Soulseek;
+
+/// <summary>
+/// Reports.
+/// </summary>
+[Route("api/v{version:apiVersion}/telemetry/[controller]")]
+[Tags("Telemetry")]
+[ApiVersion("0")]
+[ApiController]
+[Produces("application/json")]
+public class ReportsController : ControllerBase
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ReportsController"/> class.
+ /// </summary>
+ public ReportsController(TelemetryService telemetryService)
+ {
+ Telemetry = telemetryService;
+ }
+
+ private TelemetryService Telemetry { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<ReportsController>();
+
+ /// <summary>
+ /// Gets a summary of all transfer activity over the specified timeframe, grouped by direction and final state.
+ /// </summary>
+ /// <param name="start">The start time of the window (default: 7 days ago).</param>
+ /// <param name="end">The end time of the window (default: now).</param>
+ /// <param name="direction">An optional direction (Upload, Download) by which to filter records.</param>
+ /// <param name="username">An optional username by which to filter records.</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/summary")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferSummary(
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] string direction = null,
+ [FromQuery] string username = null)
+ {
+ var now = DateTime.UtcNow;
+
+ start ??= now.AddDays(-7);
+ end ??= now;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ TransferDirection? transferDirection = null;
+
+ if (!string.IsNullOrWhiteSpace(direction))
+ {
+ if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ {
+ return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}");
+ }
+
+ transferDirection = parsedDirection;
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferSummary(
+ start: start.Value,
+ end: end,
+ direction: transferDirection,
+ username: username));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer summary over {Start}-{End}: {Message}", start, end, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets a histogram of all transfer activity over the specified timeframe, aggregated into fixed size time intervals
+ /// and grouped by direction and final state.
+ /// </summary>
+ /// <param name="start">The start time of the window (default: 7 days ago).</param>
+ /// <param name="end">The end time of the window (default: now).</param>
+ /// <param name="interval">The interval, in minutes (default: 60).</param>
+ /// <param name="direction">An optional direction (Upload, Download) by which to filter records.</param>
+ /// <param name="username">An optional username by which to filter records.</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/histogram")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(Dictionary<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferHistogram(
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] int interval = 60,
+ [FromQuery] string direction = null,
+ [FromQuery] string username = null)
+ {
+ var now = DateTime.UtcNow;
+
+ start ??= now.AddDays(-7);
+ end ??= now;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ // clamp the start time to the earliest reasonable date to avoid returning a ton of empty intervals
+ // and introducing performance issues client side
+ if (start < Program.GenesisDateTime)
+ {
+ Log.Warning("A start time prior to the genesis date of the application was supplied; the start time has been adjusted to the genesis time {Genesis}", Program.GenesisDateTime);
+ start = Program.GenesisDateTime;
+ }
+
+ if (interval < 5)
+ {
+ return BadRequest("Interval must be greater than or equal to 5");
+ }
+
+ var intervalTimeSpan = TimeSpan.FromMinutes(interval);
+
+ TransferDirection? transferDirection = null;
+
+ if (!string.IsNullOrWhiteSpace(direction))
+ {
+ if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ {
+ return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}");
+ }
+
+ transferDirection = parsedDirection;
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferHistogram(
+ start: start.Value,
+ end: end.Value,
+ interval: intervalTimeSpan,
+ direction: transferDirection,
+ username: username));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer histogram over {Start}-{End}/{Interval}: {Message}", start, end, interval, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets the top N user summaries by count, total bytes, or average speed.
+ /// </summary>
+ /// <param name="direction">The direction (Upload, Download).</param>
+ /// <param name="start">The start time of the window (default: 12/30/2025).</param>
+ /// <param name="end">The end time of the window (default: now).</param>
+ /// <param name="sortBy">The property by which to sort (Count, TotalBytes, AverageSpeed. Default: Count).</param>
+ /// <param name="sortOrder">The sort order (ASC, DESC. Default: DESC).</param>
+ /// <param name="limit">The number of records to return (Default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/leaderboard")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(List<TransferSummary>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferLeaderboard(
+ [FromQuery] string direction,
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] string sortBy = "Count",
+ [FromQuery] string sortOrder = "DESC",
+ [FromQuery] int limit = 25,
+ [FromQuery] int offset = 0)
+ {
+ if (string.IsNullOrWhiteSpace(direction))
+ {
+ return BadRequest("Direction is required");
+ }
+
+ if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ {
+ return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}");
+ }
+
+ start ??= Program.GenesisDateTime;
+ end ??= DateTime.UtcNow;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ if (!Enum.TryParse<LeaderboardSortBy>(sortBy, out var parsedSortBy))
+ {
+ return BadRequest($"Invalid sortBy; expected one of: {string.Join(", ", Enum.GetNames(typeof(LeaderboardSortBy)))}");
+ }
+
+ if (!Enum.TryParse<SortOrder>(sortOrder, out var parsedSortOrder))
+ {
+ return BadRequest($"Invalid sortOrder; expected one of: {string.Join(", ", Enum.GetNames(typeof(SortOrder)))}");
+ }
+
+ if (limit <= 0)
+ {
+ return BadRequest("Limit must be greater than zero");
+ }
+
+ if (offset < 0)
+ {
+ return BadRequest("Offset must be greater than or equal to zero");
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferLeaderboard(
+ direction: parsedDirection,
+ start: start.Value,
+ end: end,
+ sortBy: parsedSortBy,
+ sortOrder: parsedSortOrder,
+ limit: limit,
+ offset: offset));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer leaderboard over {Start}-{End}: {Message}", start, end, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets detailed transfer activity for the specified user.
+ /// </summary>
+ /// <param name="username">The username of the user.</param>
+ /// <param name="start">The start time of the summary window (default: 7 days ago).</param>
+ /// <param name="end">The end time of the summary window (default: now).</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/users/{username}")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(Dictionary<TransferDirection, UserDirectionTransferSummary>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetUserDetails(
+ [FromRoute] string username,
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null)
+ {
+ if (string.IsNullOrWhiteSpace(username))
+ {
+ return BadRequest("Username is required");
+ }
+
+ start ??= Program.GenesisDateTime;
+ end ??= DateTime.UtcNow;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ static UserDirectionTransferStatistics GetStatistics(Dictionary<TransferStates, TransferSummary> summary)
+ {
+ var totalTransfers = summary.Values.Sum(x => x.Count);
+ var successful = summary.Where(x => x.Key == TransferStates.Succeeded).Sum(x => x.Value.Count);
+ var errored = summary.Where(x => new[] { TransferStates.Errored, TransferStates.TimedOut, TransferStates.Rejected, TransferStates.Aborted }.Contains(x.Key)).Sum(x => x.Value.Count);
+ var cancelled = summary.Where(x => x.Key == TransferStates.Cancelled).Sum(x => x.Value.Count);
+
+ return new UserDirectionTransferStatistics
+ {
+ Total = totalTransfers,
+ Successful = successful,
+ Errored = errored,
+ Cancelled = cancelled,
+ };
+ }
+
+ try
+ {
+ var results = new Dictionary<TransferDirection, UserDirectionTransferSummary>();
+
+ var summary = Telemetry.Reports.GetTransferSummary(start, end, username: username);
+
+ results.Add(TransferDirection.Upload, new UserDirectionTransferSummary
+ {
+ Summary = summary[TransferDirection.Upload],
+ Statistics = GetStatistics(summary[TransferDirection.Upload]),
+ Exceptions = Telemetry.Reports.GetTransferExceptionsPareto(TransferDirection.Upload, start, end, username: username, limit: 25, offset: 0),
+ });
+
+ results.Add(TransferDirection.Download, new UserDirectionTransferSummary
+ {
+ Summary = summary[TransferDirection.Download],
+ Statistics = GetStatistics(summary[TransferDirection.Download]),
+ Exceptions = Telemetry.Reports.GetTransferExceptionsPareto(TransferDirection.Download, start, end, username: username, limit: 25, offset: 0),
+ });
+
+ return Ok(results);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching user details for {Username}: {Message}", username, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets a list of transfer exceptions by direction.
+ /// </summary>
+ /// <param name="direction">The direction.</param>
+ /// <param name="start">The start time.</param>
+ /// <param name="end">The end time.</param>
+ /// <param name="username">An optional username by which to filter exceptions.</param>
+ /// <param name="sortOrder">The sort order (ASC, DESC. Default: DESC).</param>
+ /// <param name="limit">The number of records to return (Default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/exceptions")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(List<TransferExceptionDetail>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferExceptions(
+ [FromQuery] string direction = null,
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] string username = null,
+ [FromQuery] string sortOrder = "DESC",
+ [FromQuery] int limit = 25,
+ [FromQuery] int offset = 0)
+ {
+ if (string.IsNullOrWhiteSpace(direction))
+ {
+ return BadRequest("Direction is required");
+ }
+
+ if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ {
+ return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}");
+ }
+
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ if (!Enum.TryParse<SortOrder>(sortOrder, out var parsedSortOrder))
+ {
+ return BadRequest($"Invalid sortOrder; expected one of: {string.Join(", ", Enum.GetNames(typeof(SortOrder)))}");
+ }
+
+ if (limit <= 0)
+ {
+ return BadRequest("Limit must be greater than zero");
+ }
+
+ if (offset < 0)
+ {
+ return BadRequest("Offset must be greater than or equal to zero");
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferExceptions(
+ direction: parsedDirection,
+ start: start.Value,
+ end: end.Value,
+ username: username,
+ sortOrder: parsedSortOrder,
+ limit: limit,
+ offset: offset));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer exceptions over {Start}-{End}: {Message}", start, end, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets the top N exceptions by total count and direction.
+ /// </summary>
+ /// <param name="direction">The direction.</param>
+ /// <param name="start">The start time.</param>
+ /// <param name="end">The end time.</param>
+ /// <param name="username">An optional username by which to filter exceptions.</param>
+ /// <param name="limit">The number of records to return (Default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/exceptions/pareto")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(List<TransferExceptionSummary>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferExceptionsPareto(
+ [FromQuery] string direction,
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] string username = null,
+ [FromQuery] int limit = 25,
+ [FromQuery] int offset = 0)
+ {
+ if (string.IsNullOrWhiteSpace(direction))
+ {
+ return BadRequest("Direction is required");
+ }
+
+ if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ {
+ return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}");
+ }
+
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ return BadRequest("Limit must be greater than zero");
+ }
+
+ if (offset < 0)
+ {
+ return BadRequest("Offset must be greater than or equal to zero");
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferExceptionsPareto(
+ direction: parsedDirection,
+ start: start.Value,
+ end: end.Value,
+ limit: limit,
+ offset: offset,
+ username: username));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer exceptions over {Start}-{End}: {Message}", start, end, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets the top N most frequently downloaded directories by total count and distinct users.
+ /// </summary>
+ /// <param name="start">The start time of the window (default: 12/30/2025).</param>
+ /// <param name="end">The end time of the window (default: now).</param>
+ /// <param name="username">An optional username by which to filter records.</param>
+ /// <param name="limit">The number of records to return (Default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/directories")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(List<TransferDirectorySummary>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferDirectoryFrequency(
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] string username = null,
+ [FromQuery] int limit = 25,
+ [FromQuery] int offset = 0)
+ {
+ start ??= Program.GenesisDateTime;
+ end ??= DateTime.MaxValue;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ return BadRequest("Limit must be greater than zero");
+ }
+
+ if (offset < 0)
+ {
+ return BadRequest("Offset must be greater than or equal to zero");
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferDirectoryFrequency(
+ start: start,
+ end: end,
+ username: username,
+ limit: limit,
+ offset: offset));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer directories over {Start}-{End}: {Message}", start, end, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+}
diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs
index 0525a81a..7bc6fd25 100644
--- a/src/slskd/Telemetry/Metrics.cs
+++ b/src/slskd/Telemetry/Metrics.cs
@@ -15,126 +15,134 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
-namespace slskd
+namespace slskd.Telemetry;
+
+using System;
+using Prometheus;
+
+/// <summary>
+/// This class contains all of the custom Prometheus metrics for slskd. These represent a small subset of the metrics
+/// available, with the rest coming from the .NET and ASP.NET frameworks and the host system.
+/// </summary>
+/// <remarks>
+/// These metrics and their names are part of the public API contract; avoid renaming or removing them, and think
+/// carefully about naming when adding new metrics.
+/// </remarks>
+public static class Metrics
{
- using System;
- using Prometheus;
+ /// <summary>
+ /// Metrics related to search requests and responses.
+ /// </summary>
+ public static class Search
+ {
+ /// <summary>
+ /// Gets a histogram representing the time taken to resolve a response to an incoming search request, in milliseconds.
+ /// </summary>
+ public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram(
+ "slskd_search_response_latency",
+ "The time taken to resolve a response to an incoming search request, in milliseconds",
+ new HistogramConfiguration
+ {
+ Buckets = Histogram.ExponentialBuckets(0.1, 2, 11),
+ });
+
+ /// <summary>
+ /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds.
+ /// </summary>
+ public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value));
+
+ /// <summary>
+ /// Gets an automatically resetting counter of the number of search requests received.
+ /// </summary>
+ public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromSeconds(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count));
+
+ /// <summary>
+ /// Gets a counter representing the total number of search requests received.
+ /// </summary>
+ public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_requests_received", "Total number of search requests received");
+
+ /// <summary>
+ /// Gets a counter representing the total number of search responses sent.
+ /// </summary>
+ public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_responses_sent", "Total number of search responses sent");
+
+ private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve a response to an incoming search request, in milliseconds");
+ private static Gauge CurrentRequestReceiveRateGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_request_receive_rate_current", "Number of search requests received in the last second");
+ }
+
+ /// <summary>
+ /// Metrics related to browse requests and responses.
+ /// </summary>
+ public static class Browse
+ {
+ /// <summary>
+ /// Gets a histogram representing the time taken to resolve a response to an incoming browse request, in milliseconds.
+ /// </summary>
+ public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram(
+ "slskd_browse_response_latency",
+ "The time taken to resolve a response to an incoming browse request, in milliseconds",
+ new HistogramConfiguration
+ {
+ Buckets = Histogram.ExponentialBuckets(1, 2, 10),
+ });
+
+ /// <summary>
+ /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds.
+ /// </summary>
+ public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value));
+
+ /// <summary>
+ /// Gets a counter representing the total number of browse requests received.
+ /// </summary>
+ public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_browse_requests_received", "Total number of browse requests received");
+
+ /// <summary>
+ /// Gets a counter representing the total number of browse responses sent.
+ /// </summary>
+ public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_browse_responses_sent", "Total number of browse responses sent");
+
+ private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_browse_response_latency_current", "The average time taken to resolve a response to an incoming browse request, in milliseconds");
+ }
/// <summary>
- /// This class contains all of the custom Prometheus metrics for slskd. These represent a small subset of the metrics
- /// available, with the rest coming from the .NET and ASP.NET frameworks and the host system.
+ /// Metrics related to the distributed network.
/// </summary>
- /// <remarks>
- /// These metrics and their names are part of the public API contract; avoid renaming or removing them, and think
- /// carefully about naming when adding new metrics.
- /// </remarks>
- public static class Metrics
+ public static class DistributedNetwork
{
- public static class Search
- {
- /// <summary>
- /// Gets a histogram representing the time taken to resolve a response to an incoming search request, in milliseconds.
- /// </summary>
- public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram(
- "slskd_search_response_latency",
- "The time taken to resolve a response to an incoming search request, in milliseconds",
- new HistogramConfiguration
- {
- Buckets = Histogram.ExponentialBuckets(0.1, 2, 11),
- });
-
- /// <summary>
- /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds.
- /// </summary>
- public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value));
-
- /// <summary>
- /// Gets an automatically resetting counter of the number of search requests received.
- /// </summary>
- public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromSeconds(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count));
-
- /// <summary>
- /// Gets a counter representing the total number of search requests received.
- /// </summary>
- public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_requests_received", "Total number of search requests received");
-
- /// <summary>
- /// Gets a counter representing the total number of search responses sent.
- /// </summary>
- public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_responses_sent", "Total number of search responses sent");
-
- private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve a response to an incoming search request, in milliseconds");
- private static Gauge CurrentRequestReceiveRateGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_request_receive_rate_current", "Number of search requests received in the last second");
- }
-
- public static class Browse
- {
- /// <summary>
- /// Gets a histogram representing the time taken to resolve a response to an incoming browse request, in milliseconds.
- /// </summary>
- public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram(
- "slskd_browse_response_latency",
- "The time taken to resolve a response to an incoming browse request, in milliseconds",
- new HistogramConfiguration
- {
- Buckets = Histogram.ExponentialBuckets(1, 2, 10),
- });
-
- /// <summary>
- /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds.
- /// </summary>
- public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value));
-
- /// <summary>
- /// Gets a counter representing the total number of browse requests received.
- /// </summary>
- public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_browse_requests_received", "Total number of browse requests received");
-
- /// <summary>
- /// Gets a counter representing the total number of browse responses sent.
- /// </summary>
- public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_browse_responses_sent", "Total number of browse responses sent");
-
- private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_browse_response_latency_current", "The average time taken to resolve a response to an incoming browse request, in milliseconds");
- }
-
- public static class DistributedNetwork
- {
- /// <summary>
- /// Gets a gauge representing the current number of connected distributed children.
- /// </summary>
- public static Gauge Children { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_children", "Current number of connected distributed children");
-
- /// <summary>
- /// Gets a gauge representing the current distributed child limit.
- /// </summary>
- public static Gauge ChildLimit { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_child_limit", "Current distributed child limit");
-
- /// <summary>
- /// Gets a gauge indicating whether a distributed parent connection is established.
- /// </summary>
- public static Gauge HasParent { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_has_parent", "A value indicating whether a distributed parent connection is established");
-
- /// <summary>
- /// Gets a gauge representing the current distributed branch level.
- /// </summary>
- public static Gauge BranchLevel { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_branch_level", "Current distributed branch level");
-
- /// <summary>
- /// Gets a gauge representing the most recent average time taken to broadcast incoming search requests to connected children.
- /// </summary>
- public static Gauge CurrentBroadcastLatency { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_broadcast_latency_current", "The average time taken to broadcast incoming search requests to connected children");
-
- /// <summary>
- /// Gets a histogram representing the time taken to resolve a response to an incoming browse request, in milliseconds.
- /// </summary>
- public static Histogram BroadcastLatency { get; } = Prometheus.Metrics.CreateHistogram(
- "slskd_dnet_broadcast_latency",
- "The time taken to broadcast incoming search requests to connected children, in milliseconds",
- new HistogramConfiguration
- {
- Buckets = Histogram.ExponentialBuckets(0.1, 2, 11),
- });
- }
+ /// <summary>
+ /// Gets a gauge representing the current number of connected distributed children.
+ /// </summary>
+ public static Gauge Children { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_children", "Current number of connected distributed children");
+
+ /// <summary>
+ /// Gets a gauge representing the current distributed child limit.
+ /// </summary>
+ public static Gauge ChildLimit { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_child_limit", "Current distributed child limit");
+
+ /// <summary>
+ /// Gets a gauge indicating whether a distributed parent connection is established.
+ /// </summary>
+ public static Gauge HasParent { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_has_parent", "A value indicating whether a distributed parent connection is established");
+
+ /// <summary>
+ /// Gets a gauge representing the current distributed branch level.
+ /// </summary>
+ public static Gauge BranchLevel { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_branch_level", "Current distributed branch level");
+
+ /// <summary>
+ /// Gets a gauge representing the most recent average time taken to broadcast incoming search requests to connected children.
+ /// </summary>
+ public static Gauge CurrentBroadcastLatency { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_broadcast_latency_current", "The average time taken to broadcast incoming search requests to connected children");
+
+ /// <summary>
+ /// Gets a histogram representing the time taken to resolve a response to an incoming browse request, in milliseconds.
+ /// </summary>
+ public static Histogram BroadcastLatency { get; } = Prometheus.Metrics.CreateHistogram(
+ "slskd_dnet_broadcast_latency",
+ "The time taken to broadcast incoming search requests to connected children, in milliseconds",
+ new HistogramConfiguration
+ {
+ Buckets = Histogram.ExponentialBuckets(0.1, 2, 11),
+ });
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/PrometheusService.cs b/src/slskd/Telemetry/PrometheusService.cs
index 249319d5..06235981 100644
--- a/src/slskd/Telemetry/PrometheusService.cs
+++ b/src/slskd/Telemetry/PrometheusService.cs
@@ -15,7 +15,7 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
-namespace slskd;
+namespace slskd.Telemetry;
using System;
using System.Collections.Generic;
@@ -30,6 +30,25 @@ public class PrometheusService
private static Regex PrometheusLabelSplittingRegex { get; } = new Regex("([a-zA-Z_][a-zA-Z0-9_]*)\\s*=\\s*\"([^\"]*)\"", RegexOptions.Compiled);
/// <summary>
+ /// These metrics repeat many times with disambiguating labels, and this conflicts with the current approach
+ /// for building metrics in object format; dictionary entries (keyed by the names seen in this list) conflict,
+ /// and values are merged and potentially collide. This could be fixed by pulling disambiguating labels up into
+ /// the names, but these labels are things like HTTP route names, exception types, and server addresses. All of
+ /// which has very little value to an application that wants to display metrics to an end user (which is why this exists).
+ ///
+ /// The easy solution is to just ignore these classes of metrics, and that's what I'm going to do.
+ ///
+ /// This can be revisited if someone feels very strongly.
+ /// </summary>
+ private static Regex[] ExcludedMetrics { get; } = new[]
+ {
+ new Regex("^microsoft_aspnetcore_hosting_http_server_request_duration.*", RegexOptions.Compiled),
+ new Regex("^system_net_http_http_client_request_time_in_queue.*", RegexOptions.Compiled),
+ new Regex("^system_net_http_http_client_request_duration.*", RegexOptions.Compiled),
+ new Regex("^microsoft_aspnetcore_server_kestrel_kestrel_connection_duration.*", RegexOptions.Compiled),
+ };
+
+ /// <summary>
/// Get the current list of Prometheus metrics in Prometheus exposition format (text based).
/// </summary>
/// <returns></returns>
@@ -85,6 +104,12 @@ public class PrometheusService
continue;
}
+ // see the note above about excluded metrics and why this is necessary
+ if (ExcludedMetrics.Any(regex => regex.IsMatch(name)))
+ {
+ continue;
+ }
+
var type = lines[startIndex + 1].Substring(7).Split(' ', 2)[1];
var metric = new PrometheusMetric() { Name = name, Help = help, Type = type };
diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs
new file mode 100644
index 00000000..da325dc0
--- /dev/null
+++ b/src/slskd/Telemetry/ReportsService.cs
@@ -0,0 +1,542 @@
+// <copyright file="ReportsService.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.Telemetry;
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Dapper;
+using Microsoft.Data.Sqlite;
+using Serilog;
+using Soulseek;
+
+/// <summary>
+/// Reports.
+/// </summary>
+public class ReportsService
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ReportsService"/> class.
+ /// </summary>
+ public ReportsService(ConnectionStringDictionary connectionStringDictionary)
+ {
+ ConnectionStrings = connectionStringDictionary;
+ }
+
+ private ConnectionStringDictionary ConnectionStrings { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<ReportsService>();
+
+ /// <summary>
+ /// Returns a summary of all transfer data grouped by direction and final transfer state. Includes only
+ /// completed transfers.
+ /// </summary>
+ /// <param name="start">The optional start time of the summary window.</param>
+ /// <param name="end">The optional end time of the summary window.</param>
+ /// <param name="direction">The optional direction (Upload or Download) for the summary.</param>
+ /// <param name="username">The optional username by which to filter results.</param>
+ /// <returns>A nested dictionary keyed by direction and state and containing summary information.</returns>
+ /// <exception cref="ArgumentException">Thrown if end time is not later than start time.</exception>
+ public Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>> GetTransferSummary(
+ DateTime? start = null,
+ DateTime? end = null,
+ TransferDirection? direction = null,
+ string username = null)
+ {
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ var dict = new Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>()
+ {
+ { TransferDirection.Download, new Dictionary<TransferStates, TransferSummary>() },
+ { TransferDirection.Upload, new Dictionary<TransferStates, TransferSummary>() },
+ };
+
+ var sql = @$"
+ SELECT
+ Direction,
+ StateDescription,
+ SUM(Size) AS TotalBytes,
+ COUNT(*) AS Count,
+ COUNT(DISTINCT Username) AS DistinctUsers,
+ AVG(AverageSpeed) AS AverageSpeed,
+ AVG(strftime('%s', StartedAt) - strftime('%s', EnqueuedAt)) AS AverageWait,
+ AVG(strftime('%s', EndedAt) - strftime('%s', StartedAt)) AS AverageDuration
+ FROM Transfers
+ WHERE EndedAt IS NOT NULL
+ AND EndedAt BETWEEN @Start AND @End
+ {(direction is not null ? "AND Direction = @Direction" : string.Empty)}
+ {(username is not null ? "AND Username = @Username" : string.Empty)}
+ GROUP BY Direction, StateDescription
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Direction = direction?.ToString(),
+ Username = username,
+ Start = start,
+ End = end,
+ };
+
+ var results = connection.Query<TransferSummaryRow>(sql, param);
+
+ foreach (var result in results)
+ {
+ var record = new TransferSummary
+ {
+ TotalBytes = result.TotalBytes,
+ Count = result.Count,
+ DistinctUsers = result.DistinctUsers,
+ AverageSpeed = result.AverageSpeed,
+ AverageWait = result.AverageWait,
+ AverageDuration = result.AverageDuration,
+ };
+
+ dict[result.Direction].Add(result.StateDescription & ~TransferStates.Completed, record);
+ }
+
+ return dict;
+ }
+
+ /// <summary>
+ /// Returns a histogram of all transfer data, aggregated into fixed size time intervals and grouped by
+ /// direction and final transfer state. Includes only completed transfers.
+ /// </summary>
+ /// <param name="start">The start time of the histogram window.</param>
+ /// <param name="end">The end time of the histogram window.</param>
+ /// <param name="interval">The interval for the histogram.</param>
+ /// <param name="direction">The optional direction (Upload or Download) by which to filter results.</param>
+ /// <param name="username">The optional username by which to filter results.</param>
+ /// <returns>A nested dictionary keyed by direction and state and containing summary information.</returns>
+ /// <exception cref="ArgumentException">Thrown if end time is not later than start time.</exception>
+ public Dictionary<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>> GetTransferHistogram(
+ DateTime start,
+ DateTime end,
+ TimeSpan interval,
+ TransferDirection? direction = null,
+ string username = null)
+ {
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ var dict = new Dictionary<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>>();
+
+ // fill the dictionary with gapless intervals and empty dictionaries
+ var currentInterval = new DateTime(start.Ticks / interval.Ticks * interval.Ticks, DateTimeKind.Utc);
+
+ while (currentInterval < end)
+ {
+ dict[currentInterval] = new Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>()
+ {
+ { TransferDirection.Download, new Dictionary<TransferStates, TransferSummary>() },
+ { TransferDirection.Upload, new Dictionary<TransferStates, TransferSummary>() },
+ };
+ currentInterval = currentInterval.Add(interval);
+ }
+
+ var sql = @$"
+ SELECT
+ datetime(strftime('%s', EndedAt) / CAST(@Interval AS INTEGER) * CAST(@Interval AS INTEGER), 'unixepoch') AS Interval,
+ Direction,
+ StateDescription,
+ SUM(Size) AS TotalBytes,
+ COUNT(*) AS Count,
+ COUNT(DISTINCT Username) AS Users,
+ AVG(AverageSpeed) AS AverageSpeed,
+ COALESCE(AVG(strftime('%s', StartedAt) - strftime('%s', EnqueuedAt)), 0.0) AS AverageWait,
+ COALESCE(AVG(strftime('%s', EndedAt) - strftime('%s', StartedAt)), 0.0) AS AverageDuration
+ FROM Transfers
+ WHERE EndedAt IS NOT NULL
+ AND EndedAt BETWEEN @Start AND @End
+ {(direction is not null ? "AND Direction = @Direction" : string.Empty)}
+ {(username is not null ? "AND Username = @Username" : string.Empty)}
+ GROUP BY Interval, Direction, StateDescription
+ ORDER BY Interval, Direction, StateDescription;
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Direction = direction?.ToString(),
+ Username = username,
+ Start = start,
+ End = end,
+ Interval = (int)interval.TotalSeconds,
+ };
+
+ var results = connection.Query<TransferSummaryRow>(sql, param);
+
+ foreach (var result in results)
+ {
+ var record = new TransferSummary
+ {
+ TotalBytes = result.TotalBytes,
+ Count = result.Count,
+ DistinctUsers = result.DistinctUsers,
+ AverageSpeed = result.AverageSpeed,
+ AverageWait = result.AverageWait,
+ AverageDuration = result.AverageDuration,
+ };
+
+ if (result.Interval.HasValue)
+ {
+ // normalize the result interval to match the bucket interval
+ var bucketInterval = new DateTime(result.Interval.Value.Ticks / interval.Ticks * interval.Ticks, DateTimeKind.Utc);
+
+ if (dict.TryGetValue(bucketInterval, out var intervalDict))
+ {
+ intervalDict[result.Direction][result.StateDescription & ~TransferStates.Completed] = record;
+ }
+ }
+ }
+
+ return dict;
+ }
+
+ /// <summary>
+ /// Returns the top N users summaries by count, total bytes, or average speed. Only successful transfers are included in counts.
+ /// </summary>
+ /// <param name="direction">The direction (Upload or Download).</param>
+ /// <param name="start">The optional start time of the summary window.</param>
+ /// <param name="end">The optional end time of the summary window.</param>
+ /// <param name="sortBy">The property by which to sort.</param>
+ /// <param name="sortOrder">The sort order.</param>
+ /// <param name="limit">The number of records to return (default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns>A dictionary keyed by username and containing summary information.</returns>
+ /// <exception cref="ArgumentException">
+ /// Thrown if end time is not later than start time, or limit is not greater than zero.
+ /// </exception>
+ public List<TransferSummary> GetTransferLeaderboard(
+ TransferDirection direction,
+ DateTime? start = null,
+ DateTime? end = null,
+ LeaderboardSortBy sortBy = LeaderboardSortBy.Count,
+ SortOrder sortOrder = SortOrder.DESC,
+ int limit = 25,
+ int offset = 0)
+ {
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ throw new ArgumentOutOfRangeException("Limit must be greater than zero");
+ }
+
+ var sql = @$"
+ SELECT
+ Username,
+ Direction,
+ State,
+ SUM(Size) AS TotalBytes,
+ COUNT(*) AS Count,
+ AVG(AverageSpeed) AS AverageSpeed,
+ AVG(strftime('%s', StartedAt) - strftime('%s', EnqueuedAt)) AS AverageWait,
+ AVG(strftime('%s', EndedAt) - strftime('%s', StartedAt)) AS AverageDuration
+ FROM Transfers
+ WHERE Direction = @Direction
+ AND State = 48
+ AND EndedAt IS NOT NULL
+ AND EndedAt BETWEEN @Start AND @End
+ GROUP BY Username, Direction, StateDescription
+ ORDER BY {sortBy} {sortOrder}, Username DESC
+ LIMIT @Limit
+ OFFSET @Offset
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Direction = direction.ToString(),
+ Limit = limit,
+ Offset = offset,
+ Start = start,
+ End = end,
+ };
+
+ var results = connection.Query<TransferSummaryRow>(sql, param);
+
+ var list = results.Select(row => new TransferSummary
+ {
+ Username = row.Username,
+ TotalBytes = row.TotalBytes,
+ Count = row.Count,
+ AverageSpeed = row.AverageSpeed,
+ AverageWait = row.AverageWait,
+ AverageDuration = row.AverageDuration,
+ }).ToList();
+
+ return list;
+ }
+
+ /// <summary>
+ /// Returns a list of transfer exceptions.
+ /// </summary>
+ /// <param name="direction">The direction (Upload or Download).</param>
+ /// <param name="start">The optional start time of the summary window.</param>
+ /// <param name="end">The optional end time of the summary window.</param>
+ /// <param name="username">The optional username by which to filter results.</param>
+ /// <param name="sortOrder">The sort order.</param>
+ /// <param name="limit">The number of records to return (default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns>A list of exceptions.</returns>
+ /// <exception cref="ArgumentException">
+ /// Thrown if end time is not later than start time, or limit is not greater than zero.
+ /// </exception>
+ public List<TransferExceptionDetail> GetTransferExceptions(
+ TransferDirection direction,
+ DateTime? start = null,
+ DateTime? end = null,
+ string username = null,
+ SortOrder sortOrder = SortOrder.DESC,
+ int limit = 25,
+ int offset = 0)
+ {
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ throw new ArgumentOutOfRangeException("Limit must be greater than zero");
+ }
+
+ var sql = @$"
+ SELECT
+ Id,
+ Username,
+ Direction,
+ Filename,
+ Size,
+ StartOffset,
+ State,
+ RequestedAt
+ EnqueuedAt,
+ StartedAt,
+ EndedAt,
+ BytesTransferred,
+ AverageSpeed,
+ CASE
+ WHEN INSTR(Exception, ':') > 0
+ THEN SUBSTR(Exception, INSTR(Exception, ':') + 2)
+ ELSE Exception
+ END as Exception
+ FROM transfers
+ WHERE state & ~48
+ AND Direction = @Direction
+ {(username is not null ? "AND Username = @Username" : string.Empty)}
+ ORDER BY EndedAt {sortOrder}
+ LIMIT @Limit
+ OFFSET @Offset
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Direction = direction.ToString(),
+ Username = username,
+ Start = start,
+ End = end,
+ Limit = limit,
+ Offset = offset,
+ };
+
+ var results = connection.Query<TransferExceptionDetail>(sql, param);
+ return results.ToList();
+ }
+
+ /// <summary>
+ /// Returns a summary of distinct transfer exceptions and the number of times they occurred.
+ /// </summary>
+ /// <param name="direction">The direction (Upload or Download) for the summary.</param>
+ /// <param name="start">The optional start time of the summary window.</param>
+ /// <param name="end">The optional end time of the summary window.</param>
+ /// <param name="username">The optional username by which to filter results.</param>
+ /// <param name="limit">The number of records to return (default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns>A dictionary keyed by direction and containing a list of exceptions and the number of times they occurred.</returns>
+ /// <exception cref="ArgumentException">
+ /// Thrown if end time is not later than start time, or limit is not greater than zero.
+ /// </exception>
+ public List<TransferExceptionSummary> GetTransferExceptionsPareto(
+ TransferDirection direction,
+ DateTime? start = null,
+ DateTime? end = null,
+ string username = null,
+ int limit = 25,
+ int offset = 0)
+ {
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ throw new ArgumentOutOfRangeException("Limit must be greater than zero");
+ }
+
+ var sql = @$"
+ SELECT
+ CASE
+ WHEN INSTR(Exception, ':') > 0
+ THEN SUBSTR(Exception, INSTR(Exception, ':') + 2)
+ ELSE Exception
+ END as Exception,
+ COUNT(*) as Count,
+ COUNT(DISTINCT Username) as DistinctUsers
+ FROM transfers
+ WHERE state & ~48
+ AND Direction = @Direction
+ {(username is not null ? "AND Username = @Username" : string.Empty)}
+ GROUP BY Direction,
+ CASE
+ WHEN INSTR(Exception, ':') > 0
+ THEN SUBSTR(Exception, INSTR(Exception, ':') + 2)
+ ELSE Exception
+ END
+ ORDER BY Count DESC
+ LIMIT @Limit
+ OFFSET @Offset
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Direction = direction.ToString(),
+ Username = username,
+ Start = start,
+ End = end,
+ Limit = limit,
+ Offset = offset,
+ };
+
+ var results = connection.Query<TransferExceptionSummary>(sql, param);
+ return results.ToList();
+ }
+
+ /// <summary>
+ /// Returns a list of directories and the frequency at which they have been downloaded.
+ /// </summary>
+ /// <param name="start"></param>
+ /// <param name="end"></param>
+ /// <param name="username"></param>
+ /// <param name="sortOrder"></param>
+ /// <param name="limit"></param>
+ /// <param name="offset"></param>
+ /// <returns></returns>
+ /// <exception cref="ArgumentException">
+ /// Thrown if end time is not later than start time, or limit is not greater than zero.
+ /// </exception>
+ public List<TransferDirectorySummary> GetTransferDirectoryFrequency(
+ DateTime? start = null,
+ DateTime? end = null,
+ string username = null,
+ SortOrder sortOrder = SortOrder.DESC,
+ int limit = 25,
+ int offset = 0)
+ {
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ throw new ArgumentOutOfRangeException("Limit must be greater than zero");
+ }
+
+ var sql = @$"
+ WITH directories AS (
+ SELECT
+ RTRIM(
+ RTRIM(filename, REPLACE(REPLACE(filename, '/', ''), '\', '')), '/\'
+ ) AS Directory,
+ Username
+ FROM transfers
+ WHERE Direction = 'Upload'
+ AND State = 48
+ AND EndedAt IS NOT NULL
+ AND EndedAt BETWEEN @Start AND @End
+ {(username is not null ? "AND Username = @Username" : string.Empty)}
+ )
+ SELECT Directory, COUNT(*) AS Count, COUNT(DISTINCT Username) AS DistinctUsers
+ FROM directories
+ GROUP BY Directory
+ ORDER BY DistinctUsers DESC, Count DESC
+ LIMIT @Limit
+ OFFSET @Offset
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Start = start,
+ End = end,
+ Limit = limit,
+ Offset = offset,
+ Username = username,
+ };
+
+ var results = connection.Query<TransferDirectorySummary>(sql, param);
+ return results.ToList();
+ }
+
+ private record TransferSummaryRow
+ {
+ public DateTime? Interval { get; init; }
+ public string Username { get; init; }
+ public TransferDirection Direction { get; init; }
+ public TransferStates StateDescription { get; init; }
+ public long TotalBytes { get; init; }
+ public long Count { get; init; }
+ public long DistinctUsers { get; init; }
+ public double AverageSpeed { get; init; }
+ public double AverageWait { get; init; }
+ public double AverageDuration { get; init; }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/TelemetryService.cs b/src/slskd/Telemetry/TelemetryService.cs
index 1c124610..e122cbe4 100644
--- a/src/slskd/Telemetry/TelemetryService.cs
+++ b/src/slskd/Telemetry/TelemetryService.cs
@@ -15,14 +15,16 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
-namespace slskd;
+namespace slskd.Telemetry;
public class TelemetryService
{
- public TelemetryService(PrometheusService prometheusService)
+ public TelemetryService(PrometheusService prometheusService, ReportsService reportsService)
{
Prometheus = prometheusService;
+ Reports = reportsService;
}
public PrometheusService Prometheus { get; }
+ public ReportsService Reports { get; }
} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/DirectoryDetail.cs b/src/slskd/Telemetry/Types/DirectoryDetail.cs
new file mode 100644
index 00000000..54901507
--- /dev/null
+++ b/src/slskd/Telemetry/Types/DirectoryDetail.cs
@@ -0,0 +1,23 @@
+// <copyright file="DirectoryDetail.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>
+
+public record TransferDirectorySummary
+{
+ public string Directory { get; init; }
+ public long Count { get; init; }
+ public long DistinctUsers { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/LeaderboardSorting.cs b/src/slskd/Telemetry/Types/LeaderboardSorting.cs
new file mode 100644
index 00000000..e90a8c3d
--- /dev/null
+++ b/src/slskd/Telemetry/Types/LeaderboardSorting.cs
@@ -0,0 +1,25 @@
+// <copyright file="LeaderboardSorting.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.Telemetry;
+
+public enum LeaderboardSortBy
+{
+ Count,
+ TotalBytes,
+ AverageSpeed,
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/PrometheusMetric.cs b/src/slskd/Telemetry/Types/PrometheusMetric.cs
index 93ca6422..05e2446d 100644
--- a/src/slskd/Telemetry/Types/PrometheusMetric.cs
+++ b/src/slskd/Telemetry/Types/PrometheusMetric.cs
@@ -15,7 +15,7 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
-namespace slskd;
+namespace slskd.Telemetry;
using System.Collections.Generic;
diff --git a/src/slskd/Telemetry/Types/SortOrder.cs b/src/slskd/Telemetry/Types/SortOrder.cs
new file mode 100644
index 00000000..7f70fd21
--- /dev/null
+++ b/src/slskd/Telemetry/Types/SortOrder.cs
@@ -0,0 +1,24 @@
+// <copyright file="SortOrder.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.Telemetry;
+
+public enum SortOrder
+{
+ ASC,
+ DESC,
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/TransferExceptionDetail.cs b/src/slskd/Telemetry/Types/TransferExceptionDetail.cs
new file mode 100644
index 00000000..a749c6a5
--- /dev/null
+++ b/src/slskd/Telemetry/Types/TransferExceptionDetail.cs
@@ -0,0 +1,39 @@
+// <copyright file="TransferExceptionDetail.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.Telemetry;
+
+using System;
+using Soulseek;
+
+public record TransferExceptionDetail
+{
+ public string Id { get; init; }
+ public string Username { get; init; }
+ public TransferDirection Direction { get; init; }
+ public string Filename { get; init; }
+ public long Size { get; set; }
+ public long StartOffset { get; init; }
+ public TransferStates State { get; set; } = TransferStates.None;
+ public DateTime RequestedAt { get; set; }
+ public DateTime? EnqueuedAt { get; set; }
+ public DateTime? StartedAt { get; set; }
+ public DateTime? EndedAt { get; set; }
+ public long BytesTransferred { get; set; }
+ public double AverageSpeed { get; set; }
+ public string Exception { get; set; }
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/TransferExceptionSummary.cs b/src/slskd/Telemetry/Types/TransferExceptionSummary.cs
new file mode 100644
index 00000000..03b64df5
--- /dev/null
+++ b/src/slskd/Telemetry/Types/TransferExceptionSummary.cs
@@ -0,0 +1,25 @@
+// <copyright file="TransferExceptionSummary.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.Telemetry;
+
+public record TransferExceptionSummary
+{
+ public string Exception { get; init; }
+ public long Count { get; init; }
+ public long DistinctUsers { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/TransferSummary.cs b/src/slskd/Telemetry/Types/TransferSummary.cs
new file mode 100644
index 00000000..c25f81fc
--- /dev/null
+++ b/src/slskd/Telemetry/Types/TransferSummary.cs
@@ -0,0 +1,29 @@
+// <copyright file="TransferSummary.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.Telemetry;
+
+public record TransferSummary
+{
+ public string Username { get; init; }
+ public long TotalBytes { get; init; }
+ public long Count { get; init; }
+ public long DistinctUsers { get; init; }
+ public double AverageSpeed { get; init; }
+ public double AverageWait { get; init; }
+ public double AverageDuration { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/UserDirectionTransferSummary.cs b/src/slskd/Telemetry/Types/UserDirectionTransferSummary.cs
new file mode 100644
index 00000000..c6d30a04
--- /dev/null
+++ b/src/slskd/Telemetry/Types/UserDirectionTransferSummary.cs
@@ -0,0 +1,36 @@
+// <copyright file="UserDirectionTransferSummary.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.Telemetry;
+
+using System.Collections.Generic;
+using Soulseek;
+
+public record UserDirectionTransferSummary
+{
+ public Dictionary<TransferStates, TransferSummary> Summary { get; init; }
+ public UserDirectionTransferStatistics Statistics { get; init; }
+ public List<TransferExceptionSummary> Exceptions { get; init; }
+}
+
+public record UserDirectionTransferStatistics
+{
+ public long Total { get; init; }
+ public long Successful { get; init; }
+ public long Errored { get; init; }
+ public long Cancelled { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index d906688a..9bc25373 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -805,7 +805,11 @@ namespace slskd.Transfers.Downloads
}
t.EndedAt ??= DateTime.UtcNow;
- t.Exception ??= exception.Message;
+
+ // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking
+ // exceptions in a database. when we encounter one of these, drop the first segment.
+ var m = exception.Message;
+ t.Exception ??= m.Contains(':') ? m.Substring(m.IndexOf(':') + 1).Trim() : m;
if (!t.State.HasFlag(TransferStates.Completed))
{
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index c541d4f0..c96d1131 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -923,7 +923,11 @@ namespace slskd.Transfers.Uploads
}
t.EndedAt ??= DateTime.UtcNow;
- t.Exception ??= exception;
+
+ // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking
+ // exceptions in a database. when we encounter one of these, drop the first segment.
+ var m = exception;
+ t.Exception ??= m.Contains(':') ? m.Substring(m.IndexOf(':') + 1).Trim() : m;
if (!t.State.HasFlag(TransferStates.Completed))
{
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index 63dd6937..ce5a7d54 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -17,11 +17,11 @@
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
- <NoWarn>1701;1702;1591;S1133;S2094;S1135;S3925;S125</NoWarn>
+ <NoWarn>1701;1702;1591;S1133;S2094;S1135;S3925;S125;IDE0290;IDE0130</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
- <NoWarn>1591;S1133;S2094;S1135;S3925;S125</NoWarn>
+ <NoWarn>1591;S1133;S2094;S1135;S3925;S125;IDE0290;IDE0130</NoWarn>
</PropertyGroup>
<ItemGroup>
@@ -44,6 +44,7 @@
<ItemGroup>
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.0" />
+ <PackageReference Include="Dapper" Version="2.1.66" />
<PackageReference Include="FluentFTP" Version="49.0.2" />
<PackageReference Include="IPAddressRange" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.6" />
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index 5d0ae3d2..0fdcae0d 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -180,7 +180,6 @@
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.9.tgz",
"integrity": "sha512-5q0175NOjddqpvvzU+kDiSOAk4PfdO6FvwCWoQ6RO7rTzEe8vlo+4HVfcnAREhD4npMs0e9uZypjTwzZPCf/cw==",
"dev": true,
- "peer": true,
"dependencies": {
"@ampproject/remapping": "^2.2.0",
"@babel/code-frame": "^7.23.5",
@@ -226,7 +225,6 @@
"resolved": "https://registry.npmjs.org/@babel/eslint-parser/-/eslint-parser-7.23.10.tgz",
"integrity": "sha512-3wSYDPZVnhseRnxRJH6ZVTNknBz76AEnyC+AYYhasjP3Yy23qz0ERR7Fcd2SHmYuSFJ2kY9gaaDd3vyqU09eSw==",
"dev": true,
- "peer": true,
"dependencies": {
"@nicolo-ribaudo/eslint-scope-5-internals": "5.1.1-v1",
"eslint-visitor-keys": "^2.1.0",
@@ -1005,7 +1003,6 @@
"resolved": "https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.22.5.tgz",
"integrity": "sha512-9RdCl0i+q0QExayk2nOS7853w08yLucnnPML6EN9S8fgMPVtdLDCdx/cOQ/i44Lb9UeQX9A35yaqBBOMMZxPxQ==",
"dev": true,
- "peer": true,
"dependencies": {
"@babel/helper-plugin-utils": "^7.22.5"
},
@@ -1880,7 +1877,6 @@
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.22.5.tgz",
"integrity": "sha512-rog5gZaVbUip5iWDMTYbVM15XQq+RkUKhET/IHR6oizR+JEoN6CAfTTuHcK4vwUyzca30qqHqEpzBOnaRMWYMA==",
"dev": true,
- "peer": true,
"dependencies": {
"@babel/helper-annotate-as-pure": "^7.22.5",
"@babel/helper-module-imports": "^7.22.5",
@@ -2509,7 +2505,6 @@
"version": "6.13.0",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.13.0.tgz",
"integrity": "sha512-oXTfJzHJ5Tl7f6T8ZO0HKf981zubxgKohjddLobbntbNZHlOZGMRL+pPZGtclDWFaFJWtGBYRGyNdjQ6Xsx5yA==",
- "peer": true,
"dependencies": {
"@codemirror/state": "^6.1.4",
"style-mod": "^4.0.0",
@@ -2521,7 +2516,6 @@
"resolved": "https://registry.npmjs.org/@craco/craco/-/craco-7.1.0.tgz",
"integrity": "sha512-oRAcPIKYrfPXp9rSzlsDNeOaVtDiKhoyqSXUoqiK24jCkHr4T8m/a2f74yXIzCbIheoUWDOIfWZyRgFgT+cpqA==",
"dev": true,
- "peer": true,
"dependencies": {
"autoprefixer": "^10.4.12",
"cosmiconfig": "^7.0.1",
@@ -4138,7 +4132,6 @@
"version": "2.11.8",
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
"integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==",
- "peer": true,
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
@@ -4663,7 +4656,6 @@
"resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.40.1.tgz",
"integrity": "sha512-vRb792M4mF1FBT+eoLecmkpLXwxsBHvWWRGJjzbYANBM6DtiJc6yETyv4rqDA6QNjF1pkj1U7LMA6dGb3VYlHw==",
"dev": true,
- "peer": true,
"dependencies": {
"@types/estree": "*",
"@types/json-schema": "*"
@@ -4907,7 +4899,6 @@
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.59.9.tgz",
"integrity": "sha512-4uQIBq1ffXd2YvF7MAvehWKW3zVv/w+mSfRAu+8cKbfj3nwzyqJLNcZJpQ/WZ1HLbJDiowwmQ6NO+63nCA+fqA==",
"dev": true,
- "peer": true,
"dependencies": {
"@eslint-community/regexpp": "^4.4.0",
"@typescript-eslint/scope-manager": "5.59.9",
@@ -4961,7 +4952,6 @@
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.59.9.tgz",
"integrity": "sha512-FsPkRvBtcLQ/eVK1ivDiNYBjn3TGJdXy2fhXX+rc7czWl4ARwnpArwbihSOHI2Peg9WbtGHrbThfBUkZZGTtvQ==",
"dev": true,
- "peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "5.59.9",
"@typescript-eslint/types": "5.59.9",
@@ -5409,7 +5399,6 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz",
"integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==",
"dev": true,
- "peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -5505,7 +5494,6 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
"dev": true,
- "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0",
@@ -6440,7 +6428,6 @@
"url": "https://github.com/sponsors/ai"
}
],
- "peer": true,
"dependencies": {
"caniuse-lite": "^1.0.30001646",
"electron-to-chromium": "^1.5.4",
@@ -7378,7 +7365,6 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
- "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -8521,7 +8507,6 @@
"resolved": "https://registry.npmjs.org/eslint/-/eslint-8.56.0.tgz",
"integrity": "sha512-Go19xM6T9puCOWntie1/P997aXxFsOi37JIHRWI514Hc6ZnaHGKY9xFhrU65RT6CcBEzZoGG1e6Nq+DT04ZtZQ==",
"dev": true,
- "peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.6.1",
@@ -8719,7 +8704,6 @@
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.21.0.tgz",
"integrity": "sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ==",
"dev": true,
- "peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "6.21.0",
"@typescript-eslint/types": "6.21.0",
@@ -8969,7 +8953,6 @@
"resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz",
"integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==",
"dev": true,
- "peer": true,
"bin": {
"eslint-config-prettier": "bin/cli.js"
},
@@ -9382,7 +9365,6 @@
"resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.27.5.tgz",
"integrity": "sha512-LmEt3GVofgiGuiE+ORpnvP+kAm3h6MLZJ4Q5HCyHADofsb4VzXFsRiWj3c0OFiV+3DWFh0qg3v9gcPlfc3zRow==",
"dev": true,
- "peer": true,
"dependencies": {
"array-includes": "^3.1.6",
"array.prototype.flat": "^1.3.1",
@@ -10143,7 +10125,6 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
- "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -12785,7 +12766,6 @@
"resolved": "https://registry.npmjs.org/jest/-/jest-27.5.1.tgz",
"integrity": "sha512-Yn0mADZB89zTtjkPJEXwrac3LHudkQMR+Paqa8uxJHCBr9agxztUifWCyiYrjhMPBoUVBjyny0I7XH6ozDr7QQ==",
"dev": true,
- "peer": true,
"dependencies": {
"@jest/core": "^27.5.1",
"import-local": "^3.0.2",
@@ -14230,7 +14210,6 @@
"resolved": "https://registry.npmjs.org/less/-/less-4.1.3.tgz",
"integrity": "sha512-w16Xk/Ta9Hhyei0Gpz9m7VS8F28nieJaL/VyShID7cYvP6IL5oHeL6p4TXSDJqZE/lNv0oJ2pGVjJsRkfwm5FA==",
"dev": true,
- "peer": true,
"dependencies": {
"copy-anything": "^2.0.1",
"parse-node-version": "^1.0.1",
@@ -14770,7 +14749,6 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
- "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -15721,7 +15699,6 @@
"url": "https://github.com/sponsors/ai"
}
],
- "peer": true,
"dependencies": {
"nanoid": "^3.3.6",
"picocolors": "^1.0.0",
@@ -16856,7 +16833,6 @@
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.13.tgz",
"integrity": "sha512-EaV1Gl4mUEV4ddhDnv/xtj7sxwrwxdetHdWUGnT4VJQf+4d05v6lHYZr8N573k5Z0BViss7BDhfWtKS3+sfAqQ==",
"dev": true,
- "peer": true,
"dependencies": {
"cssesc": "^3.0.0",
"util-deprecate": "^1.0.2"
@@ -16981,7 +16957,6 @@
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz",
"integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==",
"dev": true,
- "peer": true,
"bin": {
"prettier": "bin/prettier.cjs"
},
@@ -17295,7 +17270,6 @@
"version": "16.14.0",
"resolved": "https://registry.npmjs.org/react/-/react-16.14.0.tgz",
"integrity": "sha512-0X2CImDkJGApiAlcf0ODKIneSwBPhqJawOa5wCtKbu7ZECrmS26NvtSILynQ66cgkT/RJ4LidJOc3bUESwmU8g==",
- "peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
@@ -17386,7 +17360,6 @@
"version": "16.14.0",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.14.0.tgz",
"integrity": "sha512-1gCeQXDLoIqMgqD3IO2Ah9bnf0w9kzhwN5q4FGnHZ67hBm9yePzB5JJAIQCc8x3pFnNlwFq4RidZggNAAkzWWw==",
- "peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
@@ -17432,7 +17405,6 @@
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
"integrity": "sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A==",
"dev": true,
- "peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -17495,7 +17467,6 @@
"resolved": "https://registry.npmjs.org/react-scripts/-/react-scripts-5.0.1.tgz",
"integrity": "sha512-8VAmEm/ZAwQzJ+GOMLbBsTdDKOpuZh7RPs0UymvBR2vRk4iZWCskjbFnxqjrzoIvlNNRZ3QJFx6/qDSi6zSnaQ==",
"dev": true,
- "peer": true,
"dependencies": {
"@babel/core": "^7.16.0",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.3",
@@ -18158,7 +18129,6 @@
"resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.2.tgz",
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
"dev": true,
- "peer": true,
"bin": {
"rollup": "dist/bin/rollup"
},
@@ -19982,7 +19952,6 @@
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz",
"integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==",
"dev": true,
- "peer": true,
"engines": {
"node": ">=10"
},
@@ -20082,6 +20051,7 @@
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
"dev": true,
+ "peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -20500,7 +20470,6 @@
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.94.0.tgz",
"integrity": "sha512-KcsGn50VT+06JH/iunZJedYGUJS5FGjow8wb9c0v5n1Om8O1g4L6LjtfxwlXIATopoQu+vOXXa7gYisWxCoPyg==",
"dev": true,
- "peer": true,
"dependencies": {
"@types/estree": "^1.0.5",
"@webassemblyjs/ast": "^1.12.1",
@@ -20570,7 +20539,6 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
- "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -20624,7 +20592,6 @@
"resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-4.15.1.tgz",
"integrity": "sha512-5hbAst3h3C3L8w6W4P96L5vaV0PxSmJhxZvWKYIdgxOQm8pNZ5dEOmmSLBVpP85ReeyRt6AS1QJNyo/oFFPeVA==",
"dev": true,
- "peer": true,
"dependencies": {
"@types/bonjour": "^3.5.9",
"@types/connect-history-api-fallback": "^1.3.5",
@@ -20684,7 +20651,6 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
- "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -21099,7 +21065,6 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
- "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -21364,7 +21329,6 @@
"resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz",
"integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=8.3.0"
},
diff --git a/src/web/src/components/System/Files/Explorer.jsx b/src/web/src/components/System/Files/Explorer.jsx
index e577b31c..ca0bdba1 100644
--- a/src/web/src/components/System/Files/Explorer.jsx
+++ b/src/web/src/components/System/Files/Explorer.jsx
@@ -126,6 +126,8 @@ const Explorer = ({ remoteFileManagement, root }) => {
const [directory, setDirectory] = useState({ directories: [], files: [] });
const [subdirectory, setSubdirectory] = useState([]);
const [loading, setLoading] = useState(false);
+ const [sortColumn, setSortColumn] = useState('name');
+ const [sortDirection, setSortDirection] = useState('ascending');
const fetch = async () => {
setLoading(true);
@@ -155,11 +157,45 @@ const Explorer = ({ remoteFileManagement, root }) => {
setSubdirectory(copy);
};
+ const handleSort = (column) => {
+ if (sortColumn === column) {
+ setSortDirection(
+ sortDirection === 'ascending' ? 'descending' : 'ascending',
+ );
+ } else {
+ setSortColumn(column);
+ setSortDirection('ascending');
+ }
+ };
+
+ const sortItems = (items) => {
+ if (!items || items.length === 0) return items;
+
+ return [...items].sort((a, b) => {
+ let compareValue = 0;
+
+ if (sortColumn === 'name') {
+ compareValue = a.name.localeCompare(b.name, undefined, {
+ numeric: true,
+ sensitivity: 'base',
+ });
+ } else if (sortColumn === 'date') {
+ const dateA = a.modifiedAt ? new Date(a.modifiedAt) : new Date(0);
+ const dateB = b.modifiedAt ? new Date(b.modifiedAt) : new Date(0);
+ compareValue = dateA - dateB;
+ }
+
+ return sortDirection === 'ascending' ? compareValue : -compareValue;
+ });
+ };
+
if (loading) {
return <LoaderSegment />;
}
const total = directory?.directories?.length + directory?.files?.length ?? 0;
+ const sortedDirectories = sortItems(directory?.directories);
+ const sortedFiles = sortItems(directory?.files);
return (
<>
@@ -176,11 +212,37 @@ const Explorer = ({ remoteFileManagement, root }) => {
>
<Table.Header>
<Table.Row>
- <Table.HeaderCell className="explorer-list-name">
+ <Table.HeaderCell
+ className="explorer-list-name"
+ onClick={() => handleSort('name')}
+ style={{ cursor: 'pointer' }}
+ >
Name
+ {sortColumn === 'name' && (
+ <Icon
+ name={
+ sortDirection === 'ascending'
+ ? 'chevron up'
+ : 'chevron down'
+ }
+ />
+ )}
</Table.HeaderCell>
- <Table.HeaderCell className="explorer-list-date">
+ <Table.HeaderCell
+ className="explorer-list-date"
+ onClick={() => handleSort('date')}
+ style={{ cursor: 'pointer' }}
+ >
Date Modified
+ {sortColumn === 'date' && (
+ <Icon
+ name={
+ sortDirection === 'ascending'
+ ? 'chevron up'
+ : 'chevron down'
+ }
+ />
+ )}
</Table.HeaderCell>
<Table.HeaderCell className="explorer-list-size">
Size
@@ -215,7 +277,7 @@ const Explorer = ({ remoteFileManagement, root }) => {
subdirectory={subdirectory}
/>
)}
- {directory?.directories?.map((d) => (
+ {sortedDirectories?.map((d) => (
<DirectoryRow
key={d.name}
onClick={() => select({ path: d.name })}
@@ -225,7 +287,7 @@ const Explorer = ({ remoteFileManagement, root }) => {
{...d}
/>
))}
- {directory?.files?.map((f) => (
+ {sortedFiles?.map((f) => (
<FileRow
key={f.name}
remoteFileManagement={remoteFileManagement}
diff --git a/src/web/src/components/Transfers/TransferDetails.jsx b/src/web/src/components/Transfers/TransferDetails.jsx
new file mode 100644
index 00000000..256ddcac
--- /dev/null
+++ b/src/web/src/components/Transfers/TransferDetails.jsx
@@ -0,0 +1,107 @@
+import { formatBytes, formatDate } from '../../lib/util';
+import { Table } from 'semantic-ui-react';
+
+// Regex patterns for field name formatting
+const UPPERCASE_PATTERN = /([A-Z])/gu;
+const FIRST_CHAR_PATTERN = /^./u;
+const DURATION_PATTERN = /^\d{2}:\d{2}:\d{2}/u;
+
+// Convert camelCase to Title Case with spaces
+const formatFieldName = (fieldName) => {
+ return fieldName
+ .replaceAll(UPPERCASE_PATTERN, ' $1')
+ .replace(FIRST_CHAR_PATTERN, (string) => string.toUpperCase())
+ .trim();
+};
+
+// Format value based on field type
+const formatValue = (key, value) => {
+ if (value === null || value === undefined) {
+ return 'N/A';
+ }
+
+ const lowerKey = key.toLowerCase();
+
+ // Format datetime fields
+ if (
+ (lowerKey.includes('at') || lowerKey.includes('time')) &&
+ typeof value === 'string' &&
+ value.includes(':')
+ ) {
+ // Check if it's a duration (HH:MM:SS format)
+ if (DURATION_PATTERN.test(value)) {
+ return value;
+ }
+
+ // Otherwise it's a datetime
+ return formatDate(value);
+ }
+
+ // Format byte-related fields
+ if (lowerKey.includes('bytes') || key === 'size') {
+ return formatBytes(value);
+ }
+
+ // Format speed
+ if (lowerKey.includes('speed')) {
+ return `${formatBytes(value)}/s`;
+ }
+
+ // Format percentage
+ if (lowerKey.includes('percent')) {
+ if (typeof value === 'number') {
+ return `${value.toFixed(2)}%`;
+ }
+
+ return String(value);
+ }
+
+ return String(value);
+};
+
+const TransferDetails = ({ file }) => {
+ // Fields to display in the popup
+ const fields = [
+ 'id',
+ 'username',
+ 'direction',
+ 'filename',
+ 'size',
+ 'startOffset',
+ 'state',
+ 'requestedAt',
+ 'enqueuedAt',
+ 'startedAt',
+ 'endedAt',
+ 'bytesTransferred',
+ 'averageSpeed',
+ 'bytesRemaining',
+ 'elapsedTime',
+ 'percentComplete',
+ 'remainingTime',
+ ];
+
+ return (
+ <Table
+ basic="very"
+ compact
+ size="small"
+ >
+ <Table.Body>
+ {fields.map((field) => {
+ const value = file[field];
+ return (
+ <Table.Row key={field}>
+ <Table.Cell style={{ fontWeight: 'bold', paddingRight: '1em' }}>
+ {formatFieldName(field)}
+ </Table.Cell>
+ <Table.Cell>{formatValue(field, value)}</Table.Cell>
+ </Table.Row>
+ );
+ })}
+ </Table.Body>
+ </Table>
+ );
+};
+
+export default TransferDetails;
diff --git a/src/web/src/components/Transfers/TransferList.jsx b/src/web/src/components/Transfers/TransferList.jsx
index b81049ec..4bd1e14e 100644
--- a/src/web/src/components/Transfers/TransferList.jsx
+++ b/src/web/src/components/Transfers/TransferList.jsx
@@ -1,4 +1,5 @@
import { formatBytes, formatBytesAsUnit, getFileName } from '../../lib/util';
+import TransferDetails from './TransferDetails';
import React, { Component } from 'react';
import {
Button,
@@ -6,6 +7,7 @@ import {
Header,
Icon,
List,
+ Popup,
Progress,
Table,
} from 'semantic-ui-react';
@@ -114,6 +116,12 @@ class TransferList extends Component {
<Table.HeaderCell className="transferlist-size">
Size
</Table.HeaderCell>
+ <Table.HeaderCell className="transferlist-detail">
+ <Icon
+ name="info circle"
+ size="small"
+ />
+ </Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
@@ -172,10 +180,37 @@ class TransferList extends Component {
)}
</Table.Cell>
<Table.Cell className="transferlist-size">
- {formatBytesTransferred({
- size: f.size,
- transferred: f.bytesTransferred,
- })}
+ <div
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ justifyContent: 'space-between',
+ }}
+ >
+ <span>
+ {formatBytesTransferred({
+ size: f.size,
+ transferred: f.bytesTransferred,
+ })}
+ </span>
+ </div>
+ </Table.Cell>
+ <Table.Cell className="transferlist-detail">
+ <Popup
+ content={<TransferDetails file={f} />}
+ on="click"
+ position="left center"
+ style={{ maxWidth: '600px' }}
+ trigger={
+ <Icon
+ color="grey"
+ link
+ name="info circle"
+ size="small"
+ />
+ }
+ wide="very"
+ />
</Table.Cell>
</Table.Row>
))}
diff --git a/src/web/src/components/Transfers/Transfers.css b/src/web/src/components/Transfers/Transfers.css
index 0b787f5f..2b16d32f 100644
--- a/src/web/src/components/Transfers/Transfers.css
+++ b/src/web/src/components/Transfers/Transfers.css
@@ -43,6 +43,11 @@
min-width: 150px;
}
+.transferlist-detail {
+ width: 5px;
+ min-width: 5px;
+}
+
.transferlist-filename {
word-wrap: break-word !important;
}