1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
|
// <copyright file="ReportsController.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ 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, version 3.
// │
// │ 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/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </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, UrlEncoded] 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);
}
}
}
|