From 46ec9c72ff1904e917eb695bbb88241b001e681e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 Aug 2025 19:05:21 -0500 Subject: namespace tweaking --- src/slskd/Program.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 35ed87fc..bafab7f5 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -68,6 +68,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; @@ -626,8 +627,9 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From 78895ed39994ce66aa9e2847301da6a957044fff Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Nov 2025 12:19:06 -0600 Subject: remove unused import --- src/slskd/Program.cs | 2 -- 1 file changed, 2 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index abd39251..c5646df8 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -23,8 +23,6 @@ namespace slskd using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; - using System.Diagnostics; - using System.IO; using System.Linq; using System.Net; -- cgit v1.2.3 From 368cc845e147ed1badff14e76dd393449e4182e3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Nov 2025 14:20:13 -0600 Subject: make content negotiation work properly --- .../OpenAPI/ContentNegotiationOperationFilter.cs | 100 +++++++++++++++++++++ src/slskd/Program.cs | 3 + 2 files changed, 103 insertions(+) create mode 100644 src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs (limited to 'src/slskd/Program.cs') 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 (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/. +// + +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; + +/// +/// OpenAPI operation filter that properly handles content negotiation with different response schemas. +/// +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() + .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() + .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), + }; + } + } + } + } + + /// + /// Extracts the value of the _contentTypes field of . + /// + /// 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. + /// + /// The attribute from which to extract the _contentTypes field. + /// The value of the extracted field. + 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/Program.cs b/src/slskd/Program.cs index c5646df8..3af09a42 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -903,6 +903,9 @@ namespace slskd }, }); + // allow endpoints marked with multiple content types in [Produces] to generate properly + options.OperationFilter(); + if (IOFile.Exists(XmlDocumentationFile)) { options.IncludeXmlComments(XmlDocumentationFile); -- cgit v1.2.3 From 47b106fcd88200755c15eed8b9014761c48b2e24 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Nov 2025 18:45:50 -0600 Subject: add GenesisDateTime --- src/slskd/Program.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 3af09a42..e3656aaf 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -89,6 +89,11 @@ namespace slskd /// public static readonly string AppName = "slskd"; + /// + /// The DateTime of the 'genesis' of the application (the initial commit). + /// + public static readonly DateTime GenesisDateTime = new(2025, 12, 30, 6, 22, 0, DateTimeKind.Utc); + /// /// The name of the local share host. /// -- cgit v1.2.3 From d5f278bbf94f06ffb35c4db16602f74462f19bf6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Dec 2025 15:49:15 -0600 Subject: fix genesis date --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e3656aaf..b6713e15 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -92,7 +92,7 @@ namespace slskd /// /// The DateTime of the 'genesis' of the application (the initial commit). /// - public static readonly DateTime GenesisDateTime = new(2025, 12, 30, 6, 22, 0, DateTimeKind.Utc); + public static readonly DateTime GenesisDateTime = new(2020, 12, 30, 6, 22, 0, DateTimeKind.Utc); /// /// The name of the local share host. -- cgit v1.2.3 From 865fcbc4fed85e9eac58125092838f08dbd55430 Mon Sep 17 00:00:00 2001 From: xovi Date: Wed, 26 Nov 2025 15:23:43 +0100 Subject: Added configurable ip address for the Web GUI (useful for ipv6 only users) --- config/slskd.example.yml | 2 ++ src/slskd/Core/Options.cs | 22 +++++++++++++++++++++- src/slskd/Program.cs | 10 ++++++---- 3 files changed, 29 insertions(+), 5 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index a0ca4f3f..f923afbf 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -137,10 +137,12 @@ # - ^.{1,2}$ # web: # port: 5030 +# listen_ip_address: 0.0.0.0 # socket: ~ # https: # disabled: false # port: 5031 +# listen_ip_address: 0.0.0.0 # force: false # certificate: # pfx: ~ diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 254adcab..ab08be04 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1832,6 +1832,16 @@ namespace slskd [RequiresRestart] public int Port { get; init; } = 5030; + /// + /// Gets the IP address on which to listen for HTTP requests. + /// + [Argument(default, "http-listen-ip-address")] + [EnvironmentVariable("HTTP_LISTEN_IP_ADDRESS")] + [Description("IP address on which to listen for HTTP requests")] + [IPAddress] + [RequiresRestart] + public string ListenIpAddress { get; init; } = "0.0.0.0"; + /// /// Gets the HTTP listen unix domain socket (UDS) path. /// @@ -2032,7 +2042,17 @@ namespace slskd [Range(1, 65535)] [RequiresRestart] public int Port { get; init; } = 5031; - + + /// + /// Gets the IP address on which to listen for HTTPS requests. + /// + [Argument(default, "https-listen-ip-address")] + [EnvironmentVariable("HTTPS_LISTEN_IP_ADDRESS")] + [Description("IP address on which to listen for HTTPS requests")] + [IPAddress] + [RequiresRestart] + public string ListenIpAddress { get; init; } = "0.0.0.0"; + /// /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6b50aedb..e693db63 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -474,8 +474,9 @@ 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); + var httpIpAddress = IPAddress.Parse(OptionsAtStartup.Web.ListenIpAddress); + Log.Information($"Listening for HTTP requests at http://{httpIpAddress}:{OptionsAtStartup.Web.Port}/"); + options.Listen(httpIpAddress, OptionsAtStartup.Web.Port); if (OptionsAtStartup.Web.Socket != null) { @@ -485,8 +486,9 @@ namespace slskd if (!OptionsAtStartup.Web.Https.Disabled) { - Log.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/"); - options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions => + var httpsIpAddress = IPAddress.Parse(OptionsAtStartup.Web.Https.ListenIpAddress); + Log.Information($"Listening for HTTPS requests at https://{httpsIpAddress}:{OptionsAtStartup.Web.Https.Port}/"); + options.Listen(httpsIpAddress, OptionsAtStartup.Web.Https.Port, listenOptions => { var cert = OptionsAtStartup.Web.Https.Certificate; -- cgit v1.2.3 From f2460e95bfdcf7c800a2ef2b26af17dcf9210e65 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Dec 2025 16:08:34 -0600 Subject: Statistics -> Reports --- src/slskd/Program.cs | 2 +- src/slskd/Telemetry/API/ReportsController.cs | 557 ++++++++++++++++++++++++ src/slskd/Telemetry/API/StatisticsController.cs | 557 ------------------------ src/slskd/Telemetry/ReportsService.cs | 542 +++++++++++++++++++++++ src/slskd/Telemetry/StatisticsService.cs | 542 ----------------------- src/slskd/Telemetry/TelemetryService.cs | 6 +- 6 files changed, 1103 insertions(+), 1103 deletions(-) create mode 100644 src/slskd/Telemetry/API/ReportsController.cs delete mode 100644 src/slskd/Telemetry/API/StatisticsController.cs create mode 100644 src/slskd/Telemetry/ReportsService.cs delete mode 100644 src/slskd/Telemetry/StatisticsService.cs (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b6713e15..aa320961 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -644,7 +644,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); 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 (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/. +// + +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; + +/// +/// Reports. +/// +[Route("api/v{version:apiVersion}/telemetry/[controller]")] +[Tags("Telemetry")] +[ApiVersion("0")] +[ApiController] +[Produces("application/json")] +public class ReportsController : ControllerBase +{ + /// + /// Initializes a new instance of the class. + /// + public ReportsController(TelemetryService telemetryService) + { + Telemetry = telemetryService; + } + + private TelemetryService Telemetry { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Gets a summary of all transfer activity over the specified timeframe, grouped by direction and final state. + /// + /// The start time of the window (default: 7 days ago). + /// The end time of the window (default: now). + /// An optional direction (Upload, Download) by which to filter records. + /// An optional username by which to filter records. + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/summary")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Dictionary>), 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(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); + } + } + + /// + /// Gets a histogram of all transfer activity over the specified timeframe, aggregated into fixed size time intervals + /// and grouped by direction and final state. + /// + /// The start time of the window (default: 7 days ago). + /// The end time of the window (default: now). + /// The interval, in minutes (default: 60). + /// An optional direction (Upload, Download) by which to filter records. + /// An optional username by which to filter records. + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/histogram")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Dictionary>>), 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(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); + } + } + + /// + /// Gets the top N user summaries by count, total bytes, or average speed. + /// + /// The direction (Upload, Download). + /// The start time of the window (default: 12/30/2025). + /// The end time of the window (default: now). + /// The property by which to sort (Count, TotalBytes, AverageSpeed. Default: Count). + /// The sort order (ASC, DESC. Default: DESC). + /// The number of records to return (Default: 25). + /// The record offset (if paginating). + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/leaderboard")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(List), 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(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(sortBy, out var parsedSortBy)) + { + return BadRequest($"Invalid sortBy; expected one of: {string.Join(", ", Enum.GetNames(typeof(LeaderboardSortBy)))}"); + } + + if (!Enum.TryParse(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); + } + } + + /// + /// Gets detailed transfer activity for the specified user. + /// + /// The username of the user. + /// The start time of the summary window (default: 7 days ago). + /// The end time of the summary window (default: now). + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/users/{username}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Dictionary), 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 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(); + + 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); + } + } + + /// + /// Gets a list of transfer exceptions by direction. + /// + /// The direction. + /// The start time. + /// The end time. + /// An optional username by which to filter exceptions. + /// The sort order (ASC, DESC. Default: DESC). + /// The number of records to return (Default: 25). + /// The record offset (if paginating). + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/exceptions")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(List), 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(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, 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); + } + } + + /// + /// Gets the top N exceptions by total count and direction. + /// + /// The direction. + /// The start time. + /// The end time. + /// An optional username by which to filter exceptions. + /// The number of records to return (Default: 25). + /// The record offset (if paginating). + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/exceptions/pareto")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(List), 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(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); + } + } + + /// + /// Gets the top N most frequently downloaded directories by total count and distinct users. + /// + /// The start time of the window (default: 12/30/2025). + /// The end time of the window (default: now). + /// An optional username by which to filter records. + /// The number of records to return (Default: 25). + /// The record offset (if paginating). + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/directories")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(List), 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/API/StatisticsController.cs b/src/slskd/Telemetry/API/StatisticsController.cs deleted file mode 100644 index b535d31d..00000000 --- a/src/slskd/Telemetry/API/StatisticsController.cs +++ /dev/null @@ -1,557 +0,0 @@ -// -// 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/. -// - -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; - -/// -/// Statistics. -/// -[Route("api/v{version:apiVersion}/telemetry/[controller]")] -[Tags("Telemetry")] -[ApiVersion("0")] -[ApiController] -[Produces("application/json")] -public class StatisticsController : ControllerBase -{ - /// - /// Initializes a new instance of the class. - /// - public StatisticsController(TelemetryService telemetryService) - { - Telemetry = telemetryService; - } - - private TelemetryService Telemetry { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Gets a summary of all transfer activity over the specified timeframe, grouped by direction and final state. - /// - /// The start time of the window (default: 7 days ago). - /// The end time of the window (default: now). - /// An optional direction (Upload, Download) by which to filter records. - /// An optional username by which to filter records. - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/summary")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary>), 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(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.Statistics.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); - } - } - - /// - /// Gets a histogram of all transfer activity over the specified timeframe, aggregated into fixed size time intervals - /// and grouped by direction and final state. - /// - /// The start time of the window (default: 7 days ago). - /// The end time of the window (default: now). - /// The interval, in minutes (default: 60). - /// An optional direction (Upload, Download) by which to filter records. - /// An optional username by which to filter records. - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/histogram")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary>>), 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(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.Statistics.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); - } - } - - /// - /// Gets the top N user summaries by count, total bytes, or average speed. - /// - /// The direction (Upload, Download). - /// The start time of the window (default: 12/30/2025). - /// The end time of the window (default: now). - /// The property by which to sort (Count, TotalBytes, AverageSpeed. Default: Count). - /// The sort order (ASC, DESC. Default: DESC). - /// The number of records to return (Default: 25). - /// The record offset (if paginating). - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/leaderboard")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(List), 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(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(sortBy, out var parsedSortBy)) - { - return BadRequest($"Invalid sortBy; expected one of: {string.Join(", ", Enum.GetNames(typeof(LeaderboardSortBy)))}"); - } - - if (!Enum.TryParse(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.Statistics.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); - } - } - - /// - /// Gets detailed transfer activity for the specified user. - /// - /// The username of the user. - /// The start time of the summary window (default: 7 days ago). - /// The end time of the summary window (default: now). - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/users/{username}")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary), 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 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(); - - var summary = Telemetry.Statistics.GetTransferSummary(start, end, username: username); - - results.Add(TransferDirection.Upload, new UserDirectionTransferSummary - { - Summary = summary[TransferDirection.Upload], - Statistics = GetStatistics(summary[TransferDirection.Upload]), - Exceptions = Telemetry.Statistics.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.Statistics.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); - } - } - - /// - /// Gets a list of transfer exceptions by direction. - /// - /// The direction. - /// The start time. - /// The end time. - /// An optional username by which to filter exceptions. - /// The sort order (ASC, DESC. Default: DESC). - /// The number of records to return (Default: 25). - /// The record offset (if paginating). - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/exceptions")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(List), 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(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, 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.Statistics.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); - } - } - - /// - /// Gets the top N exceptions by total count and direction. - /// - /// The direction. - /// The start time. - /// The end time. - /// An optional username by which to filter exceptions. - /// The number of records to return (Default: 25). - /// The record offset (if paginating). - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/exceptions/pareto")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(List), 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(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.Statistics.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); - } - } - - /// - /// Gets the top N most frequently downloaded directories by total count and distinct users. - /// - /// The start time of the window (default: 12/30/2025). - /// The end time of the window (default: now). - /// An optional username by which to filter records. - /// The number of records to return (Default: 25). - /// The record offset (if paginating). - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/directories")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(List), 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.Statistics.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/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 (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/. +// + +namespace slskd.Telemetry; + +using System; +using System.Collections.Generic; +using System.Linq; +using Dapper; +using Microsoft.Data.Sqlite; +using Serilog; +using Soulseek; + +/// +/// Reports. +/// +public class ReportsService +{ + /// + /// Initializes a new instance of the class. + /// + public ReportsService(ConnectionStringDictionary connectionStringDictionary) + { + ConnectionStrings = connectionStringDictionary; + } + + private ConnectionStringDictionary ConnectionStrings { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Returns a summary of all transfer data grouped by direction and final transfer state. Includes only + /// completed transfers. + /// + /// The optional start time of the summary window. + /// The optional end time of the summary window. + /// The optional direction (Upload or Download) for the summary. + /// The optional username by which to filter results. + /// A nested dictionary keyed by direction and state and containing summary information. + /// Thrown if end time is not later than start time. + public Dictionary> 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.Download, new Dictionary() }, + { TransferDirection.Upload, new Dictionary() }, + }; + + 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(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; + } + + /// + /// 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. + /// + /// The start time of the histogram window. + /// The end time of the histogram window. + /// The interval for the histogram. + /// The optional direction (Upload or Download) by which to filter results. + /// The optional username by which to filter results. + /// A nested dictionary keyed by direction and state and containing summary information. + /// Thrown if end time is not later than start time. + public Dictionary>> 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>>(); + + // 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.Download, new Dictionary() }, + { TransferDirection.Upload, new Dictionary() }, + }; + 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(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; + } + + /// + /// Returns the top N users summaries by count, total bytes, or average speed. Only successful transfers are included in counts. + /// + /// The direction (Upload or Download). + /// The optional start time of the summary window. + /// The optional end time of the summary window. + /// The property by which to sort. + /// The sort order. + /// The number of records to return (default: 25). + /// The record offset (if paginating). + /// A dictionary keyed by username and containing summary information. + /// + /// Thrown if end time is not later than start time, or limit is not greater than zero. + /// + public List 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(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; + } + + /// + /// Returns a list of transfer exceptions. + /// + /// The direction (Upload or Download). + /// The optional start time of the summary window. + /// The optional end time of the summary window. + /// The optional username by which to filter results. + /// The sort order. + /// The number of records to return (default: 25). + /// The record offset (if paginating). + /// A list of exceptions. + /// + /// Thrown if end time is not later than start time, or limit is not greater than zero. + /// + public List 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(sql, param); + return results.ToList(); + } + + /// + /// Returns a summary of distinct transfer exceptions and the number of times they occurred. + /// + /// The direction (Upload or Download) for the summary. + /// The optional start time of the summary window. + /// The optional end time of the summary window. + /// The optional username by which to filter results. + /// The number of records to return (default: 25). + /// The record offset (if paginating). + /// A dictionary keyed by direction and containing a list of exceptions and the number of times they occurred. + /// + /// Thrown if end time is not later than start time, or limit is not greater than zero. + /// + public List 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(sql, param); + return results.ToList(); + } + + /// + /// Returns a list of directories and the frequency at which they have been downloaded. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Thrown if end time is not later than start time, or limit is not greater than zero. + /// + public List 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(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/StatisticsService.cs b/src/slskd/Telemetry/StatisticsService.cs deleted file mode 100644 index 53b543f4..00000000 --- a/src/slskd/Telemetry/StatisticsService.cs +++ /dev/null @@ -1,542 +0,0 @@ -// -// 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/. -// - -namespace slskd.Telemetry; - -using System; -using System.Collections.Generic; -using System.Linq; -using Dapper; -using Microsoft.Data.Sqlite; -using Serilog; -using Soulseek; - -/// -/// Statistics. -/// -public class StatisticsService -{ - /// - /// Initializes a new instance of the class. - /// - public StatisticsService(ConnectionStringDictionary connectionStringDictionary) - { - ConnectionStrings = connectionStringDictionary; - } - - private ConnectionStringDictionary ConnectionStrings { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Returns a summary of all transfer data grouped by direction and final transfer state. Includes only - /// completed transfers. - /// - /// The optional start time of the summary window. - /// The optional end time of the summary window. - /// The optional direction (Upload or Download) for the summary. - /// The optional username by which to filter results. - /// A nested dictionary keyed by direction and state and containing summary information. - /// Thrown if end time is not later than start time. - public Dictionary> 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.Download, new Dictionary() }, - { TransferDirection.Upload, new Dictionary() }, - }; - - 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(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; - } - - /// - /// 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. - /// - /// The start time of the histogram window. - /// The end time of the histogram window. - /// The interval for the histogram. - /// The optional direction (Upload or Download) by which to filter results. - /// The optional username by which to filter results. - /// A nested dictionary keyed by direction and state and containing summary information. - /// Thrown if end time is not later than start time. - public Dictionary>> 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>>(); - - // 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.Download, new Dictionary() }, - { TransferDirection.Upload, new Dictionary() }, - }; - 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(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; - } - - /// - /// Returns the top N users summaries by count, total bytes, or average speed. Only successful transfers are included in counts. - /// - /// The direction (Upload or Download). - /// The optional start time of the summary window. - /// The optional end time of the summary window. - /// The property by which to sort. - /// The sort order. - /// The number of records to return (default: 25). - /// The record offset (if paginating). - /// A dictionary keyed by username and containing summary information. - /// - /// Thrown if end time is not later than start time, or limit is not greater than zero. - /// - public List 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(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; - } - - /// - /// Returns a list of transfer exceptions. - /// - /// The direction (Upload or Download). - /// The optional start time of the summary window. - /// The optional end time of the summary window. - /// The optional username by which to filter results. - /// The sort order. - /// The number of records to return (default: 25). - /// The record offset (if paginating). - /// A list of exceptions. - /// - /// Thrown if end time is not later than start time, or limit is not greater than zero. - /// - public List 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(sql, param); - return results.ToList(); - } - - /// - /// Returns a summary of distinct transfer exceptions and the number of times they occurred. - /// - /// The direction (Upload or Download) for the summary. - /// The optional start time of the summary window. - /// The optional end time of the summary window. - /// The optional username by which to filter results. - /// The number of records to return (default: 25). - /// The record offset (if paginating). - /// A dictionary keyed by direction and containing a list of exceptions and the number of times they occurred. - /// - /// Thrown if end time is not later than start time, or limit is not greater than zero. - /// - public List 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(sql, param); - return results.ToList(); - } - - /// - /// Returns a list of directories and the frequency at which they have been downloaded. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// Thrown if end time is not later than start time, or limit is not greater than zero. - /// - public List 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(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 f0914fb8..e122cbe4 100644 --- a/src/slskd/Telemetry/TelemetryService.cs +++ b/src/slskd/Telemetry/TelemetryService.cs @@ -19,12 +19,12 @@ namespace slskd.Telemetry; public class TelemetryService { - public TelemetryService(PrometheusService prometheusService, StatisticsService statisticsService) + public TelemetryService(PrometheusService prometheusService, ReportsService reportsService) { Prometheus = prometheusService; - Statistics = statisticsService; + Reports = reportsService; } public PrometheusService Prometheus { get; } - public StatisticsService Statistics { get; } + public ReportsService Reports { get; } } \ No newline at end of file -- cgit v1.2.3 From cf6f43d9225a996d376ea1ae21b3f52e2a06a8fe Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 10 Dec 2025 19:06:14 -0600 Subject: add support for multiple IPs --- src/slskd/Program.cs | 49 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 7 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index a56c8afc..d5e593b3 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; @@ -478,21 +479,36 @@ namespace slskd .UseUrls() .UseKestrel(options => { - var httpIpAddress = IPAddress.Parse(OptionsAtStartup.Web.ListenIpAddress); - Log.Information($"Listening for HTTP requests at http://{httpIpAddress}:{OptionsAtStartup.Web.Port}/"); - options.Listen(httpIpAddress, 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 => 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 + void ListenHttps(KestrelServerOptions o, IPAddress ip) { - var httpsIpAddress = IPAddress.Parse(OptionsAtStartup.Web.Https.ListenIpAddress); - Log.Information($"Listening for HTTPS requests at https://{httpsIpAddress}:{OptionsAtStartup.Web.Https.Port}/"); - options.Listen(httpsIpAddress, OptionsAtStartup.Web.Https.Port, listenOptions => + o.Listen(ip, OptionsAtStartup.Web.Https.Port, listenOptions => { var cert = OptionsAtStartup.Web.Https.Certificate; @@ -508,6 +524,25 @@ 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 => 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 -- cgit v1.2.3 From 22e8ebec9534150f8d04309bd7855ef60644e030 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Dec 2025 09:03:59 -0600 Subject: trim ips --- src/slskd/Program.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index d5e593b3..288fa0e3 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -488,7 +488,10 @@ namespace slskd } else { - var httpIps = OptionsAtStartup.Web.IpAddress.Split(',').Select(ip => IPAddress.Parse(ip)); + var httpIps = OptionsAtStartup.Web.IpAddress + .Split(',') + .Select(ip => ip.Trim()) + .Select(ip => IPAddress.Parse(ip)); foreach (var ip in httpIps) { @@ -506,7 +509,7 @@ namespace slskd // 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 - void ListenHttps(KestrelServerOptions o, IPAddress ip) + static void ListenHttps(KestrelServerOptions o, IPAddress ip) { o.Listen(ip, OptionsAtStartup.Web.Https.Port, listenOptions => { @@ -534,7 +537,10 @@ namespace slskd } else { - var httpsIps = OptionsAtStartup.Web.Https.IpAddress.Split(',').Select(ip => IPAddress.Parse(ip)); + var httpsIps = OptionsAtStartup.Web.Https.IpAddress + .Split(',') + .Select(ip => ip.Trim()) + .Select(ip => IPAddress.Parse(ip)); foreach (var ip in httpsIps) { -- cgit v1.2.3 From 848262831fe6281d448afd3bdcf802bbc643fbd1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 14:19:52 -0600 Subject: remove ISecurityService interface, add logging to api key handler --- src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 9 ++++++--- src/slskd/Core/API/Controllers/SessionController.cs | 4 ++-- src/slskd/Program.cs | 4 ++-- 3 files changed, 10 insertions(+), 7 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index 1aaa4a4f..fb209478 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/. // +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; /// /// API key authentication. @@ -51,7 +52,7 @@ namespace slskd.Authentication /// A url encoder. public ApiKeyAuthenticationHandler( IOptionsMonitor 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(); + private SecurityService Security { get; } /// /// Authenticates via API key. @@ -86,6 +88,7 @@ namespace slskd.Authentication } catch (Exception ex) { + Log.Warning(ex, "Unauthorized: {Message}", ex.Message); return AuthenticateResult.Fail(ex); } } 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 optionsSnapshot, OptionsAtStartup optionsAtStartup) { @@ -47,7 +47,7 @@ namespace slskd.Core.API private IOptionsSnapshot OptionsSnapshot { get; set; } private OptionsAtStartup OptionsAtStartup { get; set; } - private ISecurityService Security { get; } + private SecurityService Security { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 288fa0e3..cb1961a2 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -768,7 +768,7 @@ namespace slskd var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key)); services.AddSingleton(jwtSigningKey); - services.AddSingleton(); + services.AddSingleton(); if (!OptionsAtStartup.Web.Authentication.Disabled) { @@ -835,7 +835,7 @@ namespace slskd try { // check to see if the provided value is a valid API key - var service = services.BuildServiceProvider().GetRequiredService(); + var service = services.BuildServiceProvider().GetRequiredService(); 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 -- cgit v1.2.3