From aa3401f33bb0a6e55324f1f0b67c9946a2df86db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:18:11 -0500 Subject: whitelist log directory --- src/slskd/Files/FileService.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 62d17f20..6ab2328a 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -61,6 +61,7 @@ namespace slskd.Files { Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), + Path.GetFullPath(Program.LogDirectory), }; private ILogger Log { get; } = Serilog.Log.ForContext(); -- cgit v1.2.3 From 96420adbda382a91406c71ecfdddd5878bfb8f9d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:18:43 -0500 Subject: rename method for clarity --- src/slskd/Files/API/FilesController.cs | 2 +- src/slskd/Files/FileService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index 8a96d83f..5f30f325 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -200,7 +200,7 @@ namespace slskd.Files.API try { - var response = await Files.ListContentsAsync( + var response = await Files.ListDirectoryContentsAsync( directory: requestedDir, enumerationOptions: new EnumerationOptions { diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 6ab2328a..f348e658 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -301,7 +301,7 @@ namespace slskd.Files /// Thrown if the specified directory has a relative path. /// Thrown if the specified directory does not exist. /// Thrown if the specified root directory is restricted. - public virtual async Task ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) + public virtual async Task ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); -- cgit v1.2.3 From 514911ad65d3bdad6c05eedeef1d0aa3213803ca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:18:57 -0500 Subject: warnings --- src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs | 2 +- src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs | 2 +- src/slskd/Transfers/Uploads/UploadService.cs | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs index 7af36fcb..3e2c138f 100644 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs @@ -1,4 +1,4 @@ -// +// // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs index 3d066fe9..924611eb 100644 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs @@ -1,4 +1,4 @@ -// +// // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 5f98afac..1c2b85b5 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -413,7 +413,6 @@ namespace slskd.Transfers.Uploads lastReportedAverageSpeed = now; } - } finally { -- cgit v1.2.3 From 1f6c6b1bf962dd03c66f55098704530bb5c4620a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:19:09 -0500 Subject: stub function to return file contents --- src/slskd/Files/FileService.cs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index f348e658..a78d4dd4 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -365,6 +365,39 @@ namespace slskd.Files }); } + public virtual Stream GetFileContents(string filename) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to read a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename); + throw new ArgumentException("Filenames containing traversal segments are not allowed"); + } + + // important! we must fully expand the path with GetFullPath() to resolve a given relative directory, like '..' + if (!AllowedDirectories.Any(allowed => filename.StartsWith(allowed + Path.DirectorySeparatorChar))) + { + throw new UnauthorizedException($"Only application-controlled directories can be listed"); + } + + var info = ResolveFileInfo(filename); + + if (!info.Exists) + { + throw new NotFoundException(); + } + + try + { + return new FileStream(filename, FileMode.Open, FileAccess.Read); + } + catch (Exception ex) + { + throw new IOException($"Failed to open file {Path.GetFileName(filename)} for reading: {ex.Message}", ex); + } + } + /// /// Creates a new file with the specified fully qualified and the optional , /// returning a with which the contents of the file can be written. -- cgit v1.2.3 From 91ad4826bbd0d89f69276ea0789e1498f2a92801 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:19:36 -0500 Subject: stub endpoints to list and read log files --- src/slskd/Core/API/Controllers/LogsController.cs | 59 +++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 8055c696..a12d9187 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -32,9 +32,14 @@ namespace slskd.Core.API { + using System; + using System.IO; + using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Serilog; + using slskd.Files; /// /// Logs. @@ -46,15 +51,67 @@ namespace slskd.Core.API [Consumes("application/json")] public class LogsController : ControllerBase { + public LogsController( + FileService fileService, + OptionsAtStartup optionsAtStartup) + { + Files = fileService; + OptionsAtStartup = optionsAtStartup; + } + + private FileService Files { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + /// /// Gets the last few application logs. /// /// - [HttpGet] + [HttpGet("buffer")] [Authorize(Policy = AuthPolicy.Any)] public IActionResult Logs() { return Ok(Program.LogBuffer); } + + [HttpGet] + [Authorize(Policy = AuthPolicy.Any)] + public async Task List() + { + var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions + { + AttributesToSkip = FileAttributes.System, + RecurseSubdirectories = false, + }); + + return Ok(directory.Files); + } + + [HttpGet("{filename}")] + [Authorize(Policy = AuthPolicy.Any)] + public async Task Get(string filename, [FromQuery] bool download = false) + { + filename = FileSafety.GetFileNameSafely(filename); + + try + { + var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, filename)); + + if (download) + { + return File(stream, "text/plain", filename); + } + + return File(stream, "text/plain"); + } + catch (UnauthorizedException) + { + return NotFound(); + } + catch (NotFoundException) + { + return NotFound(); + } + } } } -- cgit v1.2.3 From 8133ee872bfe07e859fc09bf6ea7062c08249ecb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 18:08:06 -0500 Subject: docs for GetFileContents --- src/slskd/Files/FileService.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index a78d4dd4..c100c7e9 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -365,6 +365,16 @@ namespace slskd.Files }); } + /// + /// Retrieves the contents of the specified as a stream. + /// + /// The file for which contents are to be retrieved. + /// A Stream containing the contents of the file. + /// Thrown if the specified filename is null or contains only whitespace. + /// Thrown if the specified filename contains path traversal segments. + /// Thrown if the specified file is not within an allowed directory. + /// Thrown if the specified file does not exist. + /// Thrown if the file can't be opened for some reason. public virtual Stream GetFileContents(string filename) { ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); -- cgit v1.2.3 From 2c719dd8f5f330de61caf850c9087b5b989c1611 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 18:10:29 -0500 Subject: docs, change routes, lock endpoints down to administrators only --- src/slskd/Core/API/Controllers/LogsController.cs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index a12d9187..465993c1 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -67,15 +67,19 @@ namespace slskd.Core.API /// Gets the last few application logs. /// /// - [HttpGet("buffer")] - [Authorize(Policy = AuthPolicy.Any)] + [HttpGet("live")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public IActionResult Logs() { return Ok(Program.LogBuffer); } - [HttpGet] - [Authorize(Policy = AuthPolicy.Any)] + /// + /// Lists the log files currently on disk. + /// + /// + [HttpGet("files")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task List() { var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions @@ -87,8 +91,14 @@ namespace slskd.Core.API return Ok(directory.Files); } - [HttpGet("{filename}")] - [Authorize(Policy = AuthPolicy.Any)] + /// + /// Retrieves the requested log file from disk. + /// + /// + /// + /// + [HttpGet("files/{filename}")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task Get(string filename, [FromQuery] bool download = false) { filename = FileSafety.GetFileNameSafely(filename); -- cgit v1.2.3 From f76b210689cf1d0bc8b3f0d971194263eb66b3d7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 18:25:11 -0500 Subject: remove uneccessary import --- src/slskd/Core/API/Controllers/LogsController.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 465993c1..590ee6b7 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -52,15 +52,12 @@ namespace slskd.Core.API public class LogsController : ControllerBase { public LogsController( - FileService fileService, - OptionsAtStartup optionsAtStartup) + FileService fileService) { Files = fileService; - OptionsAtStartup = optionsAtStartup; } private FileService Files { get; } - private OptionsAtStartup OptionsAtStartup { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); /// -- cgit v1.2.3 From bb25e7accb1e47bfea4ddbb998106ad7365a88a6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 19:08:47 -0500 Subject: add log file fetch and download --- src/slskd/Core/API/Controllers/LogsController.cs | 92 ++++++++++++++++++++++-- 1 file changed, 88 insertions(+), 4 deletions(-) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 590ee6b7..43300e63 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -98,27 +98,111 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task Get(string filename, [FromQuery] bool download = false) { - filename = FileSafety.GetFileNameSafely(filename); + if (string.IsNullOrWhiteSpace(filename)) + { + return BadRequest("Filename is required"); + } + + if (filename.ContainsAny('/', '\\')) + { + return BadRequest("Filename must not contain a path"); + } + + var sanitizedFilename = FileSafety.GetFileNameSafely(filename, sanitize: true); + + if (!sanitizedFilename.Equals(filename, StringComparison.OrdinalIgnoreCase)) + { + Log.Warning("Input filename {Filename} sanitized to {Sanitized}", filename, sanitizedFilename); + return BadRequest("Filename contains one or more invalid characters"); + } try { - var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, filename)); + var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); if (download) { return File(stream, "text/plain", filename); } - return File(stream, "text/plain"); + var logs = await ParseLogEntriesAsync(stream); + + return Ok(logs); } catch (UnauthorizedException) { - return NotFound(); + return Unauthorized(); } catch (NotFoundException) { return NotFound(); } } + + private async Task> ParseLogEntriesAsync(Stream stream) + { + Dictionary levels = new() + { + ["VRB"] = nameof(Serilog.Events.LogEventLevel.Verbose), + ["DBG"] = nameof(Serilog.Events.LogEventLevel.Debug), + ["INF"] = nameof(Serilog.Events.LogEventLevel.Information), + ["WRN"] = nameof(Serilog.Events.LogEventLevel.Warning), + ["ERR"] = nameof(Serilog.Events.LogEventLevel.Error), + ["FTL"] = nameof(Serilog.Events.LogEventLevel.Fatal), + }; + + var list = new List(); + + var reader = new StreamReader(stream); + string line; + + while ((line = await reader.ReadLineAsync()) is not null) + { + if (line.Length == 0) + { + continue; + } + + try + { + // if the line isn't a log, append it to the previous message + if (!line.StartsWith('[')) + { + var lastIndex = list.Count - 1; + + if (lastIndex >= 0) + { + var old = list[lastIndex]; + + list[lastIndex] = new LogRecord + { + Timestamp = old.Timestamp, + Level = old.Level, + Message = old.Message + '\n' + line, + }; + } + + continue; + } + + var parts = line.TrimStart('[').Split(']', count: 2); + var meta = parts[0].Split(' '); + + list.Add(new LogRecord + { + Timestamp = DateTime.Parse(meta[0]), + Level = levels[meta[1]], + Message = parts[1].TrimStart(), + }); + } + catch (Exception ex) + { + Log.Warning(ex, "Error parsing log message: {Message}", ex.Message); + continue; + } + } + + return list; + } } } -- cgit v1.2.3 From 3b2d0c62f410a4db800055b831bf37c1e512c1b7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 19:10:36 -0500 Subject: wip of log zip --- src/slskd/Core/API/Controllers/LogsController.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 43300e63..569848b2 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -33,7 +33,10 @@ namespace slskd.Core.API { using System; + using System.Collections.Generic; using System.IO; + using System.IO.Compression; + using System.Threading; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -77,7 +80,7 @@ namespace slskd.Core.API /// [HttpGet("files")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task List() + public async Task List(CancellationToken cancellationToken, [FromQuery] bool download = false) { var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { @@ -85,6 +88,16 @@ namespace slskd.Core.API RecurseSubdirectories = false, }); + if (download) + { + var stream = new MemoryStream(); + await ZipFile.CreateFromDirectoryAsync(Program.LogDirectory, stream, cancellationToken: cancellationToken); + + var now = DateTime.UtcNow; + + return File(stream, "application/zip", $"logs-{now:yyyyMMdd}-{new DateTimeOffset(now).ToUnixTimeMilliseconds}.zip"); + } + return Ok(directory.Files); } -- cgit v1.2.3 From e5a8ae30b640212386cbb4e1fffd2ae937234793 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 08:55:24 -0500 Subject: forget about downloading a zip --- src/slskd/Core/API/Controllers/LogsController.cs | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 569848b2..a35c6097 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -35,7 +35,6 @@ namespace slskd.Core.API using System; using System.Collections.Generic; using System.IO; - using System.IO.Compression; using System.Threading; using System.Threading.Tasks; using Asp.Versioning; @@ -88,16 +87,6 @@ namespace slskd.Core.API RecurseSubdirectories = false, }); - if (download) - { - var stream = new MemoryStream(); - await ZipFile.CreateFromDirectoryAsync(Program.LogDirectory, stream, cancellationToken: cancellationToken); - - var now = DateTime.UtcNow; - - return File(stream, "application/zip", $"logs-{now:yyyyMMdd}-{new DateTimeOffset(now).ToUnixTimeMilliseconds}.zip"); - } - return Ok(directory.Files); } -- cgit v1.2.3 From e427bc851f09fbda5768ef427de83286ee1b4822 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 17:56:57 -0500 Subject: use r/w fileshare --- src/slskd/Files/FileService.cs | 2 +- src/web/src/components/System/Logs/Live.jsx | 98 ++++++++++++++++++++++++++++ src/web/src/components/System/Logs/index.jsx | 98 ---------------------------- 3 files changed, 99 insertions(+), 99 deletions(-) create mode 100644 src/web/src/components/System/Logs/Live.jsx delete mode 100644 src/web/src/components/System/Logs/index.jsx diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index c100c7e9..e3479210 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -400,7 +400,7 @@ namespace slskd.Files try { - return new FileStream(filename, FileMode.Open, FileAccess.Read); + return new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } catch (Exception ex) { diff --git a/src/web/src/components/System/Logs/Live.jsx b/src/web/src/components/System/Logs/Live.jsx new file mode 100644 index 00000000..f36258ec --- /dev/null +++ b/src/web/src/components/System/Logs/Live.jsx @@ -0,0 +1,98 @@ +import '../System.css'; +import { createLogsHubConnection } from '../../../lib/hubFactory'; +import { LoaderSegment } from '../../Shared'; +import React, { Component } from 'react'; +import { Table } from 'semantic-ui-react'; + +const initialState = { + connected: false, + logs: [], +}; + +const levels = { + Debug: 'DBG', + Error: 'ERR', + Information: 'INF', + Warning: 'WRN', +}; + +const maxLogs = 500; + +class Logs extends Component { + constructor(props) { + super(props); + + this.state = initialState; + } + + componentDidMount() { + const logsHub = createLogsHubConnection(); + + logsHub.on('buffer', (buffer) => { + this.setState({ + connected: true, + logs: buffer.reverse().slice(0, maxLogs), + }); + }); + + logsHub.on('log', (log) => { + this.setState((previousState) => ({ + connected: true, + logs: [log].concat(previousState.logs).slice(0, maxLogs), + })); + }); + + logsHub.onreconnecting(() => this.setState({ connected: false })); + logsHub.onclose(() => this.setState({ connected: false })); + logsHub.onreconnected(() => this.setState({ connected: true })); + + logsHub.start(); + } + + formatTimestamp = (timestamp) => { + const date = new Date(timestamp); + return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len + }; + + render() { + const { connected, logs } = this.state; + + return ( +
+ {!connected && } + {connected && ( + + + + Timestamp + Level + Message + + + + {logs.map((log) => ( + + {this.formatTimestamp(log.timestamp)} + {levels[log.level] || log.level} + + {log.message} + + + ))} + +
+ )} +
+ ); + } +} + +export default Logs; diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx deleted file mode 100644 index f36258ec..00000000 --- a/src/web/src/components/System/Logs/index.jsx +++ /dev/null @@ -1,98 +0,0 @@ -import '../System.css'; -import { createLogsHubConnection } from '../../../lib/hubFactory'; -import { LoaderSegment } from '../../Shared'; -import React, { Component } from 'react'; -import { Table } from 'semantic-ui-react'; - -const initialState = { - connected: false, - logs: [], -}; - -const levels = { - Debug: 'DBG', - Error: 'ERR', - Information: 'INF', - Warning: 'WRN', -}; - -const maxLogs = 500; - -class Logs extends Component { - constructor(props) { - super(props); - - this.state = initialState; - } - - componentDidMount() { - const logsHub = createLogsHubConnection(); - - logsHub.on('buffer', (buffer) => { - this.setState({ - connected: true, - logs: buffer.reverse().slice(0, maxLogs), - }); - }); - - logsHub.on('log', (log) => { - this.setState((previousState) => ({ - connected: true, - logs: [log].concat(previousState.logs).slice(0, maxLogs), - })); - }); - - logsHub.onreconnecting(() => this.setState({ connected: false })); - logsHub.onclose(() => this.setState({ connected: false })); - logsHub.onreconnected(() => this.setState({ connected: true })); - - logsHub.start(); - } - - formatTimestamp = (timestamp) => { - const date = new Date(timestamp); - return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len - }; - - render() { - const { connected, logs } = this.state; - - return ( -
- {!connected && } - {connected && ( - - - - Timestamp - Level - Message - - - - {logs.map((log) => ( - - {this.formatTimestamp(log.timestamp)} - {levels[log.level] || log.level} - - {log.message} - - - ))} - -
- )} -
- ); - } -} - -export default Logs; -- cgit v1.2.3 From f3dca154f98a9f37c9323b2e276e4f6d5540850c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 18:01:56 -0500 Subject: share logs --- src/slskd/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 5260760f..778502a2 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1247,7 +1247,8 @@ namespace slskd Path.Combine(LogDirectory, $"{AppName}-.log"), outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day, - retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs)))) + retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs), + shared: true))) // allow log file to be read concurrently .WriteTo.Conditional( e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), config => -- cgit v1.2.3 From 556b588197f31ed98c0e3dec7a9ceeddf8eb10e3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 18:04:46 -0500 Subject: enable disk logging by default --- config/slskd.example.yml | 2 +- src/slskd/Core/Options.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index af2871e2..442d0ce3 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -195,7 +195,7 @@ # circuit_breaker: 500 # maximum number of pending search requests # response_file_limit: 500 # maximum number of files to return in a single search response # logger: -# disk: false +# disk: true # no_color: false # loki: ~ # metrics: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index d1062a2c..84dafe29 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1458,11 +1458,11 @@ namespace slskd /// /// Gets a value indicating whether to write logs to disk. /// - [Argument(default, "disk-logger")] - [EnvironmentVariable("DISK_LOGGER")] - [Description("enable logging to disk")] + [Argument(default, "no-disk-logger")] + [EnvironmentVariable("NO_DISK_LOGGER")] + [Description("disable logging to disk")] [RequiresRestart] - public bool Disk { get; init; } = false; + public bool Disk { get; init; } = true; /// /// Gets a value indicating whether to suppress colorization of console logs. -- cgit v1.2.3 From 42e69540d07af2819b74735c1aea194eb344ac46 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 18:05:56 -0500 Subject: reduce default log retention to 30 days, increase minimum to 7 --- src/slskd/Core/Options.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 84dafe29..3499e564 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1500,8 +1500,8 @@ namespace slskd /// /// Gets the time to retain logs, in days. /// - [Range(1, maximum: int.MaxValue)] - public int Logs { get; init; } = 180; + [Range(7, maximum: int.MaxValue)] + public int Logs { get; init; } = 30; /// /// Transfer retention options. -- cgit v1.2.3 From cd4f42166d1dfcad952799a8dfe76aaf5ad271df Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 18:06:34 -0500 Subject: update logger docs --- docs/config.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/config.md b/docs/config.md index 0202d89b..2c21d12b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -1342,7 +1342,7 @@ Console colors can be disabled via typical application configuration described b | Command Line | Environment Variable | Description | | ------------------ | ------------------------------ | ---------------------------------- | -| `--disk-logger` | `SLSKD_DISK_LOGGER` | Enable logging to disk | +| `--no-disk-logger` | `SLSKD_NO_DISK_LOGGER` | Disable logging to disk | | `--no-color` | `SLSKD_NO_COLOR` or `NO_COLOR` | Disable console log colors | Logs can optionally be forwarded to external services, and the targets can be expanded to any service supported by a [Serilog Sink](https://github.com/serilog/serilog/wiki/Provided-Sinks). Support for targets is added on an as-needed basis and within reason. -- cgit v1.2.3 From 216c8ab2bcf84c2e11b8fa6fa640a9fdaa37f472 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:11:14 -0500 Subject: add date and milliseconds to disk logs --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 778502a2..def4c2aa 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1245,7 +1245,7 @@ namespace slskd e => OptionsAtStartup.Logger.Disk, config => config.File( Path.Combine(LogDirectory, $"{AppName}-.log"), - outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:yyyy-MM-ddTHH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day, retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs), shared: true))) // allow log file to be read concurrently -- cgit v1.2.3 From ec02691a206451e9e9c11a2f305ab928c6f9676b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:11:38 -0500 Subject: add regex for parsing log lines --- src/slskd/Core/API/Controllers/LogsController.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index a35c6097..fff5e843 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -35,6 +35,7 @@ namespace slskd.Core.API using System; using System.Collections.Generic; using System.IO; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Asp.Versioning; @@ -61,6 +62,7 @@ namespace slskd.Core.API private FileService Files { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private Regex LogLineParseRegex { get; } = new Regex(@"^(\[?([a-zA-Z\.]*)\]?\s)?(\[((\d{4}-\d{2}-\d{2})T)?(\d{2}:\d{2}:\d{2}(?:.\d{3})?)\s([A-Z]+)\]\s)?(.*)", RegexOptions.Compiled); /// /// Gets the last few application logs. -- cgit v1.2.3 From 5b063c478b5d5f8e694a5cdea76af0d8eada3150 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:11:53 -0500 Subject: leave note about streaming optimization --- src/slskd/Core/API/Controllers/LogsController.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index fff5e843..13f8ab95 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -129,6 +129,10 @@ namespace slskd.Core.API return File(stream, "text/plain", filename); } + // future optimization: use IAsyncEnumerable to 'stream' the log records instead of beating up + // memory to build a list. save each log in memory and then emit it when the next log + // (starting with '[') is read, which indicates that it's not multi-line. in other words, a 1-log buffer + // that is flushed when the next log is read, or the file is complete var logs = await ParseLogEntriesAsync(stream); return Ok(logs); -- cgit v1.2.3 From ea4ca200cd6dda759917dcd76d47d2bddfa5d2f5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:12:23 -0500 Subject: break if the file is being appended to avoid an endless loop --- src/slskd/Core/API/Controllers/LogsController.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 13f8ab95..d7e011eb 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -161,6 +161,8 @@ namespace slskd.Core.API var list = new List(); + var currentLength = stream.Length; + var reader = new StreamReader(stream); string line; @@ -171,6 +173,15 @@ namespace slskd.Core.API continue; } + if (stream.Position > currentLength) + { + // if we're reading the latest file, Serilog can append it while we're inside of this loop, + // or worse, a problem inside this loop appends lines. if this happens the position will grow + // beyond the length at the start + Log.Information("Parsing of log file {Filename} stopped before end of file; log was appended during the read"); + break; + } + try { // if the line isn't a log, append it to the previous message -- cgit v1.2.3 From e2bc14a1572c4a3d035ac7a4ffe47cff35fd2e16 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:12:39 -0500 Subject: parse logs with the regex --- src/slskd/Core/API/Controllers/LogsController.cs | 48 +++++++++++++++++++++--- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index d7e011eb..1c1f057b 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -204,14 +204,52 @@ namespace slskd.Core.API continue; } - var parts = line.TrimStart('[').Split(']', count: 2); - var meta = parts[0].Split(' '); + /* + there should be 3 possible line types: + + debug: + [Some.Context] [2000-1-1T11:11:11 WRN] foo bar + + info: + [2000-1-1T11:11:11 WRN] foo bar + + line wrap/newline: + foo bar + + additionally, date was added to disk log files around 9/1/26, so we need to gracefully handle + cases where the timestamp contains only hh:mm:ss, and substitute the unix epoch for the date + + the regex includes 8 matching groups (hopefully this comment and the regex don't diverge!) + using the debug log as an example, the groups are: + + 0. [Some.Context] [2026-08-29T11:11:11 WRN] foo bar + 1. [Some.Context] + 2. Some.Context + 3. [2000-01-01T11:11:11 WRN] + 4. 2000-01-01T + 5. 2000-01-01 + 6. 11:11:11 + 7. WRN + 8. foo bar + + the final group in the regex is simply `.*`, so we're guaranteed to get a match for every line + */ + match = LogLineParseRegex.Match(line); + + var grp = match.Groups; + + var date = grp[5].Success ? DateOnly.Parse(grp[5].Value) : DateOnly.FromDateTime(DateTime.UnixEpoch); + var time = grp[6].Success ? TimeOnly.Parse(grp[6].Value) : TimeOnly.FromDateTime(DateTime.UnixEpoch); + var dateTime = date.ToDateTime(time); + + var level = levels.ContainsKey(grp[7].Value) ? levels[grp[7].Value] : null; list.Add(new LogRecord { - Timestamp = DateTime.Parse(meta[0]), - Level = levels[meta[1]], - Message = parts[1].TrimStart(), + Context = grp[2].Value, + Timestamp = dateTime, + Level = level, + Message = grp[8].Value, }); } catch (Exception ex) -- cgit v1.2.3 From 0ef9cd71e115642cce876372c76fd3a1d8de6a4b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:13:02 -0500 Subject: wip --- src/slskd/Core/API/Controllers/LogsController.cs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 1c1f057b..1a3e027f 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -165,6 +165,7 @@ namespace slskd.Core.API var reader = new StreamReader(stream); string line; + Match match = default; while ((line = await reader.ReadLineAsync()) is not null) { @@ -251,14 +252,31 @@ namespace slskd.Core.API Level = level, Message = grp[8].Value, }); + + Log.Information("Added: {Text}", grp[8].Value); } catch (Exception ex) { - Log.Warning(ex, "Error parsing log message: {Message}", ex.Message); - continue; + Log.Debug("Error parsing log message: {Message}. Line: {Line}", ex.Message, line); + + Log.Warning("Got {GroupCount} groups", match.Groups.Count); + + foreach (var key in match.Groups.Keys) + { + Log.Warning("Key: {Key}, Success: {Success}, Value: {Value}", key, match.Groups[key].Success, match.Groups[key].Value); + } + + break; + + list.Add(new LogRecord + { + Message = line, + }); } } + Log.Information("Returned {Lines}", list.Count); + return list; } } -- cgit v1.2.3 From ca02e5352f17ed89142c456c27b70d7e8f1a50ad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 5 Sep 2026 18:45:38 -0500 Subject: wip --- src/web/src/components/System/Logs/Controls.jsx | 83 ++++++++ .../src/components/System/Logs/FileNavigator.jsx | 64 ++++++ src/web/src/components/System/Logs/History.jsx | 216 +++++++++++++++++++++ src/web/src/components/System/Logs/Live.jsx | 61 ++---- src/web/src/components/System/Logs/LogTable.jsx | 90 +++++++++ src/web/src/components/System/Logs/Logs.css | 49 +++++ src/web/src/components/System/Logs/index.jsx | 35 ++++ src/web/src/lib/logs.js | 29 +++ 8 files changed, 581 insertions(+), 46 deletions(-) create mode 100644 src/web/src/components/System/Logs/Controls.jsx create mode 100644 src/web/src/components/System/Logs/FileNavigator.jsx create mode 100644 src/web/src/components/System/Logs/History.jsx create mode 100644 src/web/src/components/System/Logs/LogTable.jsx create mode 100644 src/web/src/components/System/Logs/Logs.css create mode 100644 src/web/src/components/System/Logs/index.jsx create mode 100644 src/web/src/lib/logs.js diff --git a/src/web/src/components/System/Logs/Controls.jsx b/src/web/src/components/System/Logs/Controls.jsx new file mode 100644 index 00000000..f5d7a030 --- /dev/null +++ b/src/web/src/components/System/Logs/Controls.jsx @@ -0,0 +1,83 @@ +import './Logs.css'; +import React from 'react'; +import { Dropdown, Input, Segment } from 'semantic-ui-react'; + +/** + * Serilog's levels, ordered least to most severe. Selecting a level displays + * that level and everything below it in this list. + */ +export const levels = [ + 'Verbose', + 'Debug', + 'Information', + 'Warning', + 'Error', + 'Fatal', +]; + +const levelOptions = levels.map((level, index) => ({ + key: level, + text: index === 0 ? `${level} (all)` : `${level} and above`, + value: level, +})); + +export const perPageOptions = [50, 100, 200, 500, 1_000].map((count) => ({ + key: count, + text: `${count} per page`, + value: count, +})); + +export const defaultPerPage = 200; + +const Controls = ({ + filter, + level, + onFilterChange, + onLevelChange, + onPerPageChange, + perPage, +}) => { + return ( + + onLevelChange(value)} + options={levelOptions} + text={levelOptions.find((o) => o.value === level)?.text} + /> + onPerPageChange(value)} + options={perPageOptions} + text={perPageOptions.find((o) => o.value === perPage)?.text} + /> + onFilterChange(''), + } + } + className="logs-filter" + label={{ content: 'Filter', icon: 'filter' }} + onChange={(_event, data) => onFilterChange(data.value)} + placeholder="Show only lines matching this text" + value={filter} + /> + + ); +}; + +export default Controls; diff --git a/src/web/src/components/System/Logs/FileNavigator.jsx b/src/web/src/components/System/Logs/FileNavigator.jsx new file mode 100644 index 00000000..81c0e77c --- /dev/null +++ b/src/web/src/components/System/Logs/FileNavigator.jsx @@ -0,0 +1,64 @@ +import './Logs.css'; +import { formatBytes, formatDate } from '../../../lib/util'; +import React from 'react'; +import { Button, Dropdown } from 'semantic-ui-react'; + +/** + * Sits just above the log display. The dropdown selects a file directly; the + * arrow buttons step through the newest-to-oldest sorted file list one at a + * time, left toward newer files and right toward older ones. + */ +const FileNavigator = ({ file, files, onChange }) => { + const index = files.findIndex((f) => f.name === file); + + const options = files.map((f) => ({ + description: `${formatBytes(f.length)} · ${formatDate(f.modifiedAt)}`, + key: f.name, + text: f.name, + value: f.name, + })); + + const goNewer = () => { + if (index > 0) { + onChange(files[index - 1].name); + } + }; + + const goOlder = () => { + if (index !== -1 && index < files.length - 1) { + onChange(files[index + 1].name); + } + }; + + return ( +
+
+ ); +}; + +export default FileNavigator; diff --git a/src/web/src/components/System/Logs/History.jsx b/src/web/src/components/System/Logs/History.jsx new file mode 100644 index 00000000..1bf4976c --- /dev/null +++ b/src/web/src/components/System/Logs/History.jsx @@ -0,0 +1,216 @@ +import './Logs.css'; +import '../System.css'; +import { getLogFile, getLogFiles } from '../../../lib/logs'; +import { ErrorSegment, LoaderSegment } from '../../Shared'; +import Controls, { defaultPerPage, levels } from './Controls'; +import FileNavigator from './FileNavigator'; +import LogTable from './LogTable'; +import React, { useEffect, useMemo, useState } from 'react'; +import { Pagination } from 'semantic-ui-react'; + +/** + * Sorts log files newest first, so that the most recent is selected by default + * and sits at the top of the file dropdown. + */ +const newestFirst = (files) => + [...files].sort((a, b) => { + const dateA = a.modifiedAt ? new Date(a.modifiedAt) : new Date(0); + const dateB = b.modifiedAt ? new Date(b.modifiedAt) : new Date(0); + + return dateB - dateA; + }); + +const History = () => { + const [files, setFiles] = useState([]); + const [file, setFile] = useState(undefined); + const [logs, setLogs] = useState([]); + const [loadingFiles, setLoadingFiles] = useState(true); + const [loadingLogs, setLoadingLogs] = useState(false); + const [error, setError] = useState(undefined); + + const [level, setLevel] = useState(levels[0]); + const [filter, setFilter] = useState(''); + const [sortDirection, setSortDirection] = useState('descending'); + const [page, setPage] = useState(1); + const [perPage, setPerPage] = useState(defaultPerPage); + + // fetch the list of files on mount, and select the most recent + useEffect(() => { + const fetch = async () => { + setLoadingFiles(true); + + try { + const sorted = newestFirst(await getLogFiles()); + + setFiles(sorted); + setFile(sorted[0]?.name); + } catch (fetchError) { + setError(fetchError); + } finally { + setLoadingFiles(false); + } + }; + + fetch(); + }, []); + + // load the contents of the selected file whenever the selection changes + useEffect(() => { + if (!file) { + return; + } + + const fetch = async () => { + setLoadingLogs(true); + setError(undefined); + + try { + const records = await getLogFile({ filename: file }); + + setLogs(records); + } catch (fetchError) { + setError(fetchError); + setLogs([]); + } finally { + setLoadingLogs(false); + } + }; + + fetch(); + }, [file]); + + // apply the level filter, text filter, and sort. log files can be large, so + // memoize this to keep typing in the filter responsive + const filteredLogs = useMemo(() => { + const minimumSeverity = levels.indexOf(level); + const text = filter.trim().toLowerCase(); + + return logs + .filter((log) => levels.indexOf(log.level) >= minimumSeverity) + .filter( + (log) => + !text || + log.message?.toLowerCase().includes(text) || + log.level?.toLowerCase().includes(text), + ) + .sort((a, b) => { + // timestamps are only second precision, so fall back to position in the + // file to keep lines logged within the same second in the right order + const compareValue = + new Date(a.timestamp) - new Date(b.timestamp) || a.id - b.id; + + return sortDirection === 'ascending' ? compareValue : -compareValue; + }); + }, [filter, level, logs, sortDirection]); + + const totalPages = Math.ceil(filteredLogs.length / perPage); + + // anything that changes the shape of the result set resets pagination, so a + // user is never left looking at a page that no longer exists + const currentPage = Math.min(page, Math.max(totalPages, 1)); + + const pagedLogs = useMemo( + () => + filteredLogs.slice((currentPage - 1) * perPage, currentPage * perPage), + [currentPage, filteredLogs, perPage], + ); + + const changeFile = (value) => { + setFile(value); + setPage(1); + }; + + const changeLevel = (value) => { + setLevel(value); + setPage(1); + }; + + const changeFilter = (value) => { + setFilter(value); + setPage(1); + }; + + const changePerPage = (value) => { + setPerPage(value); + setPage(1); + }; + + const toggleSort = () => { + setSortDirection( + sortDirection === 'ascending' ? 'descending' : 'ascending', + ); + setPage(1); + }; + + const paginationChanged = ({ activePage }) => { + if (activePage >= 1) { + setPage(activePage); + } + }; + + if (loadingFiles) { + return ; + } + + const hiddenCount = logs.length - filteredLogs.length; + const firstOnPage = (currentPage - 1) * perPage + 1; + const lastOnPage = firstOnPage + pagedLogs.length - 1; + + return ( +
+ + + {error ? ( + + ) : loadingLogs ? ( + + ) : ( + <> + {totalPages > 1 && ( +
+ paginationChanged({ ...data })} + siblingRange={1} + totalPages={totalPages} + /> +
+ )} + + {filteredLogs.length > 0 && ( +
+ {`Showing ${firstOnPage}-${lastOnPage} of ${filteredLogs.length} lines` + + (hiddenCount > 0 + ? ` (${hiddenCount} of ${logs.length} hidden by filter(s))` + : '')} +
+ )} + + )} +
+ ); +}; + +export default History; diff --git a/src/web/src/components/System/Logs/Live.jsx b/src/web/src/components/System/Logs/Live.jsx index f36258ec..2c4b42db 100644 --- a/src/web/src/components/System/Logs/Live.jsx +++ b/src/web/src/components/System/Logs/Live.jsx @@ -1,24 +1,17 @@ import '../System.css'; import { createLogsHubConnection } from '../../../lib/hubFactory'; import { LoaderSegment } from '../../Shared'; +import LogTable from './LogTable'; import React, { Component } from 'react'; -import { Table } from 'semantic-ui-react'; const initialState = { connected: false, logs: [], }; -const levels = { - Debug: 'DBG', - Error: 'ERR', - Information: 'INF', - Warning: 'WRN', -}; - const maxLogs = 500; -class Logs extends Component { +class Live extends Component { constructor(props) { super(props); @@ -31,14 +24,16 @@ class Logs extends Component { logsHub.on('buffer', (buffer) => { this.setState({ connected: true, - logs: buffer.reverse().slice(0, maxLogs), + logs: buffer.reverse().slice(0, maxLogs).map(this.withId), }); }); logsHub.on('log', (log) => { + const record = this.withId(log); + this.setState((previousState) => ({ connected: true, - logs: [log].concat(previousState.logs).slice(0, maxLogs), + logs: [record].concat(previousState.logs).slice(0, maxLogs), })); }); @@ -49,10 +44,13 @@ class Logs extends Component { logsHub.start(); } - formatTimestamp = (timestamp) => { - const date = new Date(timestamp); - return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len - }; + // log records carry nothing unique; timestamps are second precision and the + // same line can repeat within a second. tag each record as it arrives so the + // table has a stable, unique key. never reset, so records from a replayed + // buffer can't collide with those already rendered. + nextId = 0; + + withId = (log) => ({ ...log, id: this.nextId++ }); render() { const { connected, logs } = this.state; @@ -60,39 +58,10 @@ class Logs extends Component { return (
{!connected && } - {connected && ( - - - - Timestamp - Level - Message - - - - {logs.map((log) => ( - - {this.formatTimestamp(log.timestamp)} - {levels[log.level] || log.level} - - {log.message} - - - ))} - -
- )} + {connected && }
); } } -export default Logs; +export default Live; diff --git a/src/web/src/components/System/Logs/LogTable.jsx b/src/web/src/components/System/Logs/LogTable.jsx new file mode 100644 index 00000000..468187b8 --- /dev/null +++ b/src/web/src/components/System/Logs/LogTable.jsx @@ -0,0 +1,90 @@ +import '../System.css'; +import React from 'react'; +import { Icon, Table } from 'semantic-ui-react'; + +const abbreviations = { + Debug: 'DBG', + Error: 'ERR', + Fatal: 'FTL', + Information: 'INF', + Verbose: 'VRB', + Warning: 'WRN', +}; + +export const formatTimestamp = (timestamp) => { + const date = new Date(timestamp); + return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len +}; + +/** + * Renders log records. Shared by the Live and History views; both consume the + * same record shape ({ timestamp, level, message }), the former from the logs + * hub and the latter from the logs API. + * + * Passing onSortChange makes the Timestamp column sortable; omitting it (as the + * Live view does) renders a static header. + */ +const LogTable = ({ + emptyMessage = 'No logs', + logs, + onSortChange, + sortDirection, +}) => ( + + + + onSortChange() : undefined} + style={onSortChange ? { cursor: 'pointer' } : undefined} + > + Timestamp + {Boolean(onSortChange) && ( + + )} + + Level + Message + + + + {logs?.length === 0 ? ( + + + {emptyMessage} + + + ) : ( + logs.map((log) => ( + + {formatTimestamp(log.timestamp)} + {abbreviations[log.level] || log.level} + + {log.message} + + + )) + )} + +
+); + +export default LogTable; diff --git a/src/web/src/components/System/Logs/Logs.css b/src/web/src/components/System/Logs/Logs.css new file mode 100644 index 00000000..8e97e592 --- /dev/null +++ b/src/web/src/components/System/Logs/Logs.css @@ -0,0 +1,49 @@ +.logs-file-navigator { + display: flex; + align-items: center; + gap: 0.5rem; + margin-bottom: 1rem; +} + +.logs-file-navigator-dropdown { + flex: 1 1 auto; +} + +.logs-options { + margin-top: 0px !important; +} + +.logs-filter { + width: 100%; + margin-top: 1rem; +} + +.logs-options-per-page { + margin-left: 1rem !important; +} + +.logs-pagination { + margin-top: 14px; + text-align: right; +} + +.logs-count { + margin-top: 1rem; + font-size: smaller; + opacity: 0.5; +} + +@media only screen and (max-width: 684px) { + .logs-pagination .ui.pagination.menu { + font-size: smaller; + } + + .logs-options-level, .logs-options-per-page { + width: 100%; + margin-left: 0px !important; + } + + .logs-options-per-page { + margin-top: 1rem !important; + } +} diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx new file mode 100644 index 00000000..ca3938c0 --- /dev/null +++ b/src/web/src/components/System/Logs/index.jsx @@ -0,0 +1,35 @@ +import History from './History'; +import Live from './Live'; +import React from 'react'; +import { Tab } from 'semantic-ui-react'; + +const Logs = () => { + const panes = [ + { + menuItem: 'Live', + render: () => ( + + + + ), + route: 'live', + }, + { + menuItem: 'History', + render: () => ( + + + + ), + route: 'history', + }, + ]; + + return ( +
+ +
+ ); +}; + +export default Logs; diff --git a/src/web/src/lib/logs.js b/src/web/src/lib/logs.js new file mode 100644 index 00000000..8616ce8c --- /dev/null +++ b/src/web/src/lib/logs.js @@ -0,0 +1,29 @@ +import api from './api'; + +export const getLogFiles = async () => { + const response = (await api.get('/logs/files')).data; + + return response; +}; + +export const getLogFile = async ({ filename }) => { + const response = ( + await api.get(`/logs/files/${encodeURIComponent(filename)}`) + ).data; + + // log records carry nothing unique; timestamps are second precision and the + // same line can repeat within a second. tag each with its position in the + // file so the UI has a stable, unique key to render and sort with. + return response.map((record, index) => ({ ...record, id: index })); +}; + +export const downloadLogFile = async ({ filename }) => { + const response = ( + await api.get(`/logs/files/${encodeURIComponent(filename)}`, { + params: { download: true }, + responseType: 'blob', + }) + ).data; + + return response; +}; -- cgit v1.2.3 From a6b6e1e0d7f61e284d2f455dbfb32887f1f9b352 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 10 Sep 2026 03:48:12 +0000 Subject: Bump js-yaml from 3.15.1 to 3.15.2 in /src/web Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 3.15.1 to 3.15.2. - [Changelog](https://github.com/nodeca/js-yaml/blob/3.15.2/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/3.15.1...3.15.2) --- updated-dependencies: - dependency-name: js-yaml dependency-version: 3.15.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 217e5132..11dafd7a 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -3429,9 +3429,9 @@ } }, "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { - "version": "3.15.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.1.tgz", - "integrity": "sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==", + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", "dev": true, "license": "MIT", "dependencies": { @@ -14313,9 +14313,9 @@ } }, "node_modules/js-yaml": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz", - "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "dev": true, "funding": [ { @@ -19967,9 +19967,9 @@ } }, "node_modules/svgo/node_modules/js-yaml": { - "version": "3.15.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.1.tgz", - "integrity": "sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==", + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", "dev": true, "license": "MIT", "dependencies": { -- cgit v1.2.3 From 58a289bcdcf4d649d94ee6058c40ee7197d95209 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 25 Sep 2026 09:29:34 -0500 Subject: strip out complicated parsing --- src/slskd/Core/API/Controllers/LogsController.cs | 176 +++-------------------- 1 file changed, 21 insertions(+), 155 deletions(-) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 1a3e027f..6ef4a7b6 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -33,10 +33,8 @@ namespace slskd.Core.API { using System; - using System.Collections.Generic; using System.IO; - using System.Text.RegularExpressions; - using System.Threading; + using System.Linq; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -54,15 +52,13 @@ namespace slskd.Core.API [Consumes("application/json")] public class LogsController : ControllerBase { - public LogsController( - FileService fileService) + public LogsController(FileService fileService) { Files = fileService; } private FileService Files { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private Regex LogLineParseRegex { get; } = new Regex(@"^(\[?([a-zA-Z\.]*)\]?\s)?(\[((\d{4}-\d{2}-\d{2})T)?(\d{2}:\d{2}:\d{2}(?:.\d{3})?)\s([A-Z]+)\]\s)?(.*)", RegexOptions.Compiled); /// /// Gets the last few application logs. @@ -81,26 +77,29 @@ namespace slskd.Core.API /// [HttpGet("files")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task List(CancellationToken cancellationToken, [FromQuery] bool download = false) + public async Task List() { - var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions + var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { - AttributesToSkip = FileAttributes.System, + IgnoreInaccessible = true, + AttributesToSkip = FileAttributes.System | FileAttributes.Hidden | FileAttributes.ReparsePoint, RecurseSubdirectories = false, }); - return Ok(directory.Files); + var logs = directory.Files.Where(f => f.Name.EndsWith(".log", StringComparison.OrdinalIgnoreCase)); + + return Ok(logs); } /// - /// Retrieves the requested log file from disk. + /// Retrieves the requested log file from disk as plain text. /// - /// - /// + /// The name of the log file. + /// A value indicating whether the file should be sent as an attachment. /// [HttpGet("files/{filename}")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task Get(string filename, [FromQuery] bool download = false) + public IActionResult Get(string filename, [FromQuery] bool download = false) { if (string.IsNullOrWhiteSpace(filename)) { @@ -120,22 +119,22 @@ namespace slskd.Core.API return BadRequest("Filename contains one or more invalid characters"); } + if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase)) + { + return BadRequest("Only .log files may be retrieved"); + } + try { var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); + const string contentType = "text/plain; charset=utf-8"; if (download) { - return File(stream, "text/plain", filename); + return File(stream, contentType, filename); } - // future optimization: use IAsyncEnumerable to 'stream' the log records instead of beating up - // memory to build a list. save each log in memory and then emit it when the next log - // (starting with '[') is read, which indicates that it's not multi-line. in other words, a 1-log buffer - // that is flushed when the next log is read, or the file is complete - var logs = await ParseLogEntriesAsync(stream); - - return Ok(logs); + return File(stream, contentType); } catch (UnauthorizedException) { @@ -146,138 +145,5 @@ namespace slskd.Core.API return NotFound(); } } - - private async Task> ParseLogEntriesAsync(Stream stream) - { - Dictionary levels = new() - { - ["VRB"] = nameof(Serilog.Events.LogEventLevel.Verbose), - ["DBG"] = nameof(Serilog.Events.LogEventLevel.Debug), - ["INF"] = nameof(Serilog.Events.LogEventLevel.Information), - ["WRN"] = nameof(Serilog.Events.LogEventLevel.Warning), - ["ERR"] = nameof(Serilog.Events.LogEventLevel.Error), - ["FTL"] = nameof(Serilog.Events.LogEventLevel.Fatal), - }; - - var list = new List(); - - var currentLength = stream.Length; - - var reader = new StreamReader(stream); - string line; - Match match = default; - - while ((line = await reader.ReadLineAsync()) is not null) - { - if (line.Length == 0) - { - continue; - } - - if (stream.Position > currentLength) - { - // if we're reading the latest file, Serilog can append it while we're inside of this loop, - // or worse, a problem inside this loop appends lines. if this happens the position will grow - // beyond the length at the start - Log.Information("Parsing of log file {Filename} stopped before end of file; log was appended during the read"); - break; - } - - try - { - // if the line isn't a log, append it to the previous message - if (!line.StartsWith('[')) - { - var lastIndex = list.Count - 1; - - if (lastIndex >= 0) - { - var old = list[lastIndex]; - - list[lastIndex] = new LogRecord - { - Timestamp = old.Timestamp, - Level = old.Level, - Message = old.Message + '\n' + line, - }; - } - - continue; - } - - /* - there should be 3 possible line types: - - debug: - [Some.Context] [2000-1-1T11:11:11 WRN] foo bar - - info: - [2000-1-1T11:11:11 WRN] foo bar - - line wrap/newline: - foo bar - - additionally, date was added to disk log files around 9/1/26, so we need to gracefully handle - cases where the timestamp contains only hh:mm:ss, and substitute the unix epoch for the date - - the regex includes 8 matching groups (hopefully this comment and the regex don't diverge!) - using the debug log as an example, the groups are: - - 0. [Some.Context] [2026-08-29T11:11:11 WRN] foo bar - 1. [Some.Context] - 2. Some.Context - 3. [2000-01-01T11:11:11 WRN] - 4. 2000-01-01T - 5. 2000-01-01 - 6. 11:11:11 - 7. WRN - 8. foo bar - - the final group in the regex is simply `.*`, so we're guaranteed to get a match for every line - */ - match = LogLineParseRegex.Match(line); - - var grp = match.Groups; - - var date = grp[5].Success ? DateOnly.Parse(grp[5].Value) : DateOnly.FromDateTime(DateTime.UnixEpoch); - var time = grp[6].Success ? TimeOnly.Parse(grp[6].Value) : TimeOnly.FromDateTime(DateTime.UnixEpoch); - var dateTime = date.ToDateTime(time); - - var level = levels.ContainsKey(grp[7].Value) ? levels[grp[7].Value] : null; - - list.Add(new LogRecord - { - Context = grp[2].Value, - Timestamp = dateTime, - Level = level, - Message = grp[8].Value, - }); - - Log.Information("Added: {Text}", grp[8].Value); - } - catch (Exception ex) - { - Log.Debug("Error parsing log message: {Message}. Line: {Line}", ex.Message, line); - - Log.Warning("Got {GroupCount} groups", match.Groups.Count); - - foreach (var key in match.Groups.Keys) - { - Log.Warning("Key: {Key}, Success: {Success}, Value: {Value}", key, match.Groups[key].Success, match.Groups[key].Value); - } - - break; - - list.Add(new LogRecord - { - Message = line, - }); - } - } - - Log.Information("Returned {Lines}", list.Count); - - return list; - } } } -- cgit v1.2.3 From edf1ee43c596a7986700cd14db17c9b8fe7d19ca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Sep 2026 15:11:56 -0500 Subject: add logs lib --- src/web/src/lib/logs.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/web/src/lib/logs.js diff --git a/src/web/src/lib/logs.js b/src/web/src/lib/logs.js new file mode 100644 index 00000000..9b742c2d --- /dev/null +++ b/src/web/src/lib/logs.js @@ -0,0 +1,27 @@ +import api from './api'; + +export const list = async () => { + const response = (await api.get('/logs/files')).data; + + return response; +}; + +export const getFile = async ({ filename }) => { + const response = ( + await api.get(`/logs/files/${encodeURIComponent(filename)}`, { + responseType: 'text', + }) + ).data; + + return response; +}; + +export const getFileBlob = async ({ filename }) => { + const response = ( + await api.get(`/logs/files/${encodeURIComponent(filename)}`, { + responseType: 'blob', + }) + ).data; + + return response; +}; -- cgit v1.2.3 From 7ce8b280b9d0f82e326ca0fe536716b657b2e68a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Sep 2026 15:12:15 -0500 Subject: make text-returning function more obvious --- src/web/src/lib/logs.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web/src/lib/logs.js b/src/web/src/lib/logs.js index 9b742c2d..35ae5d84 100644 --- a/src/web/src/lib/logs.js +++ b/src/web/src/lib/logs.js @@ -6,7 +6,7 @@ export const list = async () => { return response; }; -export const getFile = async ({ filename }) => { +export const getFileText = async ({ filename }) => { const response = ( await api.get(`/logs/files/${encodeURIComponent(filename)}`, { responseType: 'text', -- cgit v1.2.3 From 897cf768b18ed95a394b84ad172edabf20c6a92d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Sep 2026 15:17:06 -0500 Subject: add a LogTable component for live logs --- src/web/src/components/System/Logs/LogTable.jsx | 64 +++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/web/src/components/System/Logs/LogTable.jsx diff --git a/src/web/src/components/System/Logs/LogTable.jsx b/src/web/src/components/System/Logs/LogTable.jsx new file mode 100644 index 00000000..68bf6244 --- /dev/null +++ b/src/web/src/components/System/Logs/LogTable.jsx @@ -0,0 +1,64 @@ +import '../System.css'; +import { Table } from 'semantic-ui-react'; + +const abbreviations = { + Debug: 'DBG', + Error: 'ERR', + Fatal: 'FTL', + Information: 'INF', + Verbose: 'VRB', + Warning: 'WRN', +}; + +export const formatTimestamp = (timestamp) => { + const date = new Date(timestamp); + return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len +}; + +const LogTable = ({ emptyMessage = 'No logs', logs }) => ( + + + + Timestamp + Level + Message + + + + {logs?.length === 0 ? ( + + + {emptyMessage} + + + ) : ( + logs.map((log) => ( + + {formatTimestamp(log.timestamp)} + {abbreviations[log.level] || log.level} + + {log.message} + + + )) + )} + +
+); + +export default LogTable; -- cgit v1.2.3 From 0ff0c4eb7d795ee27f97c0abf5973ba5baa31f82 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Sep 2026 16:17:45 -0500 Subject: reuse the explorer from /files --- src/web/src/components/System/Logs/Explorer.jsx | 202 ++++++++++++++++++++++++ src/web/src/components/System/Logs/Live.jsx | 59 ++----- src/web/src/components/System/Logs/index.jsx | 35 ++++ 3 files changed, 249 insertions(+), 47 deletions(-) create mode 100644 src/web/src/components/System/Logs/Explorer.jsx create mode 100644 src/web/src/components/System/Logs/index.jsx diff --git a/src/web/src/components/System/Logs/Explorer.jsx b/src/web/src/components/System/Logs/Explorer.jsx new file mode 100644 index 00000000..ac6d982f --- /dev/null +++ b/src/web/src/components/System/Logs/Explorer.jsx @@ -0,0 +1,202 @@ +import '../Files/Files.css'; +import { getFileBlob, list } from '../../../lib/logs'; +import { downloadFile, formatBytes, formatDate } from '../../../lib/util'; +import { LoaderSegment } from '../../Shared'; +import React, { useEffect, useState } from 'react'; +import { toast } from 'react-toastify'; +import { Header, Icon, Table } from 'semantic-ui-react'; + +const view = async (filename) => { + const tab = window.open('', '_blank'); + + try { + const blob = await getFileBlob({ filename }); + + // hack: we can't pass a JWT in a plain link, so we have to fetch the blob + // and then shove it into the window rather than just displaying it + tab.location.href = window.URL.createObjectURL( + new Blob([blob], { type: 'text/plain; charset=utf-8' }), + ); + } catch (error) { + tab.close(); + toast.error(error?.message ?? error); + } +}; + +const download = async (filename) => { + try { + const blob = await getFileBlob({ filename }); + + downloadFile(blob, filename, 'text/plain'); + } catch (error) { + toast.error(error?.message ?? error); + } +}; + +const FileRow = ({ length, modifiedAt, name }) => ( + + + + {name} + + {modifiedAt ? formatDate(modifiedAt) : ''} + {length ? formatBytes(length) : ''} + + view(name)} + style={{ cursor: 'pointer', marginRight: '0.5em' }} + title={`View ${name} in a new window`} + /> + download(name)} + style={{ cursor: 'pointer' }} + title={`Download ${name}`} + /> + + +); + +const Explorer = () => { + const [files, setFiles] = useState([]); + const [loading, setLoading] = useState(false); + const [sortColumn, setSortColumn] = useState('date'); + const [sortDirection, setSortDirection] = useState('descending'); + + const fetch = async () => { + setLoading(true); + + try { + setFiles(await list()); + } catch (error) { + toast.error(error?.message ?? error); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetch(); + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + const handleSort = (column) => { + if (sortColumn === column) { + setSortDirection( + sortDirection === 'ascending' ? 'descending' : 'ascending', + ); + } else { + setSortColumn(column); + setSortDirection('ascending'); + } + }; + + const sortItems = (items) => { + if (!items || items.length === 0) return items; + + return [...items].sort((a, b) => { + let compareValue = 0; + + if (sortColumn === 'name') { + compareValue = a.name.localeCompare(b.name, undefined, { + numeric: true, + sensitivity: 'base', + }); + } else if (sortColumn === 'date') { + const dateA = a.modifiedAt ? new Date(a.modifiedAt) : new Date(0); + const dateB = b.modifiedAt ? new Date(b.modifiedAt) : new Date(0); + compareValue = dateA - dateB; + } + + return sortDirection === 'ascending' ? compareValue : -compareValue; + }); + }; + + if (loading) { + return ; + } + + const sortedFiles = sortItems(files); + + return ( + <> +
+ + /logs +
+ + + + handleSort('name')} + style={{ cursor: 'pointer' }} + > + Name + {sortColumn === 'name' && ( + + )} + + handleSort('date')} + style={{ cursor: 'pointer' }} + > + Date Modified + {sortColumn === 'date' && ( + + )} + + + Size + + + + + + {files.length === 0 ? ( + + + No log files + + + ) : ( + sortedFiles.map((f) => ( + + )) + )} + +
+ + ); +}; + +export default Explorer; diff --git a/src/web/src/components/System/Logs/Live.jsx b/src/web/src/components/System/Logs/Live.jsx index f36258ec..2699a2e3 100644 --- a/src/web/src/components/System/Logs/Live.jsx +++ b/src/web/src/components/System/Logs/Live.jsx @@ -1,24 +1,17 @@ import '../System.css'; import { createLogsHubConnection } from '../../../lib/hubFactory'; import { LoaderSegment } from '../../Shared'; -import React, { Component } from 'react'; -import { Table } from 'semantic-ui-react'; +import LogTable from './LogTable'; +import { Component } from 'react'; const initialState = { connected: false, logs: [], }; -const levels = { - Debug: 'DBG', - Error: 'ERR', - Information: 'INF', - Warning: 'WRN', -}; - const maxLogs = 500; -class Logs extends Component { +class Live extends Component { constructor(props) { super(props); @@ -31,14 +24,16 @@ class Logs extends Component { logsHub.on('buffer', (buffer) => { this.setState({ connected: true, - logs: buffer.reverse().slice(0, maxLogs), + logs: buffer.reverse().slice(0, maxLogs).map(this.withId), }); }); logsHub.on('log', (log) => { + const record = this.withId(log); + this.setState((previousState) => ({ connected: true, - logs: [log].concat(previousState.logs).slice(0, maxLogs), + logs: [record].concat(previousState.logs).slice(0, maxLogs), })); }); @@ -49,10 +44,9 @@ class Logs extends Component { logsHub.start(); } - formatTimestamp = (timestamp) => { - const date = new Date(timestamp); - return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len - }; + nextId = 0; + + withId = (log) => ({ ...log, id: this.nextId++ }); render() { const { connected, logs } = this.state; @@ -60,39 +54,10 @@ class Logs extends Component { return (
{!connected && } - {connected && ( - - - - Timestamp - Level - Message - - - - {logs.map((log) => ( - - {this.formatTimestamp(log.timestamp)} - {levels[log.level] || log.level} - - {log.message} - - - ))} - -
- )} + {connected && }
); } } -export default Logs; +export default Live; diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx new file mode 100644 index 00000000..f0fa4a58 --- /dev/null +++ b/src/web/src/components/System/Logs/index.jsx @@ -0,0 +1,35 @@ +import Explorer from './Explorer'; +import Live from './Live'; +import React from 'react'; +import { Tab } from 'semantic-ui-react'; + +const Logs = () => { + const panes = [ + { + menuItem: 'Live', + render: () => ( + + + + ), + route: 'live', + }, + { + menuItem: 'History', + render: () => ( + + + + ), + route: 'history', + }, + ]; + + return ( +
+ +
+ ); +}; + +export default Logs; -- cgit v1.2.3 From a4b82eb80f672095d0d699c5ce3ea8352c66fd28 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Sep 2026 16:25:24 -0500 Subject: remove stale files --- src/web/src/components/System/Logs/Controls.jsx | 83 -------- .../src/components/System/Logs/FileNavigator.jsx | 64 ------ src/web/src/components/System/Logs/History.jsx | 216 --------------------- src/web/src/components/System/Logs/Logs.css | 49 ----- 4 files changed, 412 deletions(-) delete mode 100644 src/web/src/components/System/Logs/Controls.jsx delete mode 100644 src/web/src/components/System/Logs/FileNavigator.jsx delete mode 100644 src/web/src/components/System/Logs/History.jsx delete mode 100644 src/web/src/components/System/Logs/Logs.css diff --git a/src/web/src/components/System/Logs/Controls.jsx b/src/web/src/components/System/Logs/Controls.jsx deleted file mode 100644 index f5d7a030..00000000 --- a/src/web/src/components/System/Logs/Controls.jsx +++ /dev/null @@ -1,83 +0,0 @@ -import './Logs.css'; -import React from 'react'; -import { Dropdown, Input, Segment } from 'semantic-ui-react'; - -/** - * Serilog's levels, ordered least to most severe. Selecting a level displays - * that level and everything below it in this list. - */ -export const levels = [ - 'Verbose', - 'Debug', - 'Information', - 'Warning', - 'Error', - 'Fatal', -]; - -const levelOptions = levels.map((level, index) => ({ - key: level, - text: index === 0 ? `${level} (all)` : `${level} and above`, - value: level, -})); - -export const perPageOptions = [50, 100, 200, 500, 1_000].map((count) => ({ - key: count, - text: `${count} per page`, - value: count, -})); - -export const defaultPerPage = 200; - -const Controls = ({ - filter, - level, - onFilterChange, - onLevelChange, - onPerPageChange, - perPage, -}) => { - return ( - - onLevelChange(value)} - options={levelOptions} - text={levelOptions.find((o) => o.value === level)?.text} - /> - onPerPageChange(value)} - options={perPageOptions} - text={perPageOptions.find((o) => o.value === perPage)?.text} - /> - onFilterChange(''), - } - } - className="logs-filter" - label={{ content: 'Filter', icon: 'filter' }} - onChange={(_event, data) => onFilterChange(data.value)} - placeholder="Show only lines matching this text" - value={filter} - /> - - ); -}; - -export default Controls; diff --git a/src/web/src/components/System/Logs/FileNavigator.jsx b/src/web/src/components/System/Logs/FileNavigator.jsx deleted file mode 100644 index 81c0e77c..00000000 --- a/src/web/src/components/System/Logs/FileNavigator.jsx +++ /dev/null @@ -1,64 +0,0 @@ -import './Logs.css'; -import { formatBytes, formatDate } from '../../../lib/util'; -import React from 'react'; -import { Button, Dropdown } from 'semantic-ui-react'; - -/** - * Sits just above the log display. The dropdown selects a file directly; the - * arrow buttons step through the newest-to-oldest sorted file list one at a - * time, left toward newer files and right toward older ones. - */ -const FileNavigator = ({ file, files, onChange }) => { - const index = files.findIndex((f) => f.name === file); - - const options = files.map((f) => ({ - description: `${formatBytes(f.length)} · ${formatDate(f.modifiedAt)}`, - key: f.name, - text: f.name, - value: f.name, - })); - - const goNewer = () => { - if (index > 0) { - onChange(files[index - 1].name); - } - }; - - const goOlder = () => { - if (index !== -1 && index < files.length - 1) { - onChange(files[index + 1].name); - } - }; - - return ( -
-
- ); -}; - -export default FileNavigator; diff --git a/src/web/src/components/System/Logs/History.jsx b/src/web/src/components/System/Logs/History.jsx deleted file mode 100644 index 1bf4976c..00000000 --- a/src/web/src/components/System/Logs/History.jsx +++ /dev/null @@ -1,216 +0,0 @@ -import './Logs.css'; -import '../System.css'; -import { getLogFile, getLogFiles } from '../../../lib/logs'; -import { ErrorSegment, LoaderSegment } from '../../Shared'; -import Controls, { defaultPerPage, levels } from './Controls'; -import FileNavigator from './FileNavigator'; -import LogTable from './LogTable'; -import React, { useEffect, useMemo, useState } from 'react'; -import { Pagination } from 'semantic-ui-react'; - -/** - * Sorts log files newest first, so that the most recent is selected by default - * and sits at the top of the file dropdown. - */ -const newestFirst = (files) => - [...files].sort((a, b) => { - const dateA = a.modifiedAt ? new Date(a.modifiedAt) : new Date(0); - const dateB = b.modifiedAt ? new Date(b.modifiedAt) : new Date(0); - - return dateB - dateA; - }); - -const History = () => { - const [files, setFiles] = useState([]); - const [file, setFile] = useState(undefined); - const [logs, setLogs] = useState([]); - const [loadingFiles, setLoadingFiles] = useState(true); - const [loadingLogs, setLoadingLogs] = useState(false); - const [error, setError] = useState(undefined); - - const [level, setLevel] = useState(levels[0]); - const [filter, setFilter] = useState(''); - const [sortDirection, setSortDirection] = useState('descending'); - const [page, setPage] = useState(1); - const [perPage, setPerPage] = useState(defaultPerPage); - - // fetch the list of files on mount, and select the most recent - useEffect(() => { - const fetch = async () => { - setLoadingFiles(true); - - try { - const sorted = newestFirst(await getLogFiles()); - - setFiles(sorted); - setFile(sorted[0]?.name); - } catch (fetchError) { - setError(fetchError); - } finally { - setLoadingFiles(false); - } - }; - - fetch(); - }, []); - - // load the contents of the selected file whenever the selection changes - useEffect(() => { - if (!file) { - return; - } - - const fetch = async () => { - setLoadingLogs(true); - setError(undefined); - - try { - const records = await getLogFile({ filename: file }); - - setLogs(records); - } catch (fetchError) { - setError(fetchError); - setLogs([]); - } finally { - setLoadingLogs(false); - } - }; - - fetch(); - }, [file]); - - // apply the level filter, text filter, and sort. log files can be large, so - // memoize this to keep typing in the filter responsive - const filteredLogs = useMemo(() => { - const minimumSeverity = levels.indexOf(level); - const text = filter.trim().toLowerCase(); - - return logs - .filter((log) => levels.indexOf(log.level) >= minimumSeverity) - .filter( - (log) => - !text || - log.message?.toLowerCase().includes(text) || - log.level?.toLowerCase().includes(text), - ) - .sort((a, b) => { - // timestamps are only second precision, so fall back to position in the - // file to keep lines logged within the same second in the right order - const compareValue = - new Date(a.timestamp) - new Date(b.timestamp) || a.id - b.id; - - return sortDirection === 'ascending' ? compareValue : -compareValue; - }); - }, [filter, level, logs, sortDirection]); - - const totalPages = Math.ceil(filteredLogs.length / perPage); - - // anything that changes the shape of the result set resets pagination, so a - // user is never left looking at a page that no longer exists - const currentPage = Math.min(page, Math.max(totalPages, 1)); - - const pagedLogs = useMemo( - () => - filteredLogs.slice((currentPage - 1) * perPage, currentPage * perPage), - [currentPage, filteredLogs, perPage], - ); - - const changeFile = (value) => { - setFile(value); - setPage(1); - }; - - const changeLevel = (value) => { - setLevel(value); - setPage(1); - }; - - const changeFilter = (value) => { - setFilter(value); - setPage(1); - }; - - const changePerPage = (value) => { - setPerPage(value); - setPage(1); - }; - - const toggleSort = () => { - setSortDirection( - sortDirection === 'ascending' ? 'descending' : 'ascending', - ); - setPage(1); - }; - - const paginationChanged = ({ activePage }) => { - if (activePage >= 1) { - setPage(activePage); - } - }; - - if (loadingFiles) { - return ; - } - - const hiddenCount = logs.length - filteredLogs.length; - const firstOnPage = (currentPage - 1) * perPage + 1; - const lastOnPage = firstOnPage + pagedLogs.length - 1; - - return ( -
- - - {error ? ( - - ) : loadingLogs ? ( - - ) : ( - <> - {totalPages > 1 && ( -
- paginationChanged({ ...data })} - siblingRange={1} - totalPages={totalPages} - /> -
- )} - - {filteredLogs.length > 0 && ( -
- {`Showing ${firstOnPage}-${lastOnPage} of ${filteredLogs.length} lines` + - (hiddenCount > 0 - ? ` (${hiddenCount} of ${logs.length} hidden by filter(s))` - : '')} -
- )} - - )} -
- ); -}; - -export default History; diff --git a/src/web/src/components/System/Logs/Logs.css b/src/web/src/components/System/Logs/Logs.css deleted file mode 100644 index 8e97e592..00000000 --- a/src/web/src/components/System/Logs/Logs.css +++ /dev/null @@ -1,49 +0,0 @@ -.logs-file-navigator { - display: flex; - align-items: center; - gap: 0.5rem; - margin-bottom: 1rem; -} - -.logs-file-navigator-dropdown { - flex: 1 1 auto; -} - -.logs-options { - margin-top: 0px !important; -} - -.logs-filter { - width: 100%; - margin-top: 1rem; -} - -.logs-options-per-page { - margin-left: 1rem !important; -} - -.logs-pagination { - margin-top: 14px; - text-align: right; -} - -.logs-count { - margin-top: 1rem; - font-size: smaller; - opacity: 0.5; -} - -@media only screen and (max-width: 684px) { - .logs-pagination .ui.pagination.menu { - font-size: smaller; - } - - .logs-options-level, .logs-options-per-page { - width: 100%; - margin-left: 0px !important; - } - - .logs-options-per-page { - margin-top: 1rem !important; - } -} -- cgit v1.2.3 From f950cfdb6145b7a251f3c12f3eee14b295a4b374 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 30 Sep 2026 08:34:12 -0500 Subject: remove version arg from web layer --- Dockerfile | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index de081302..daf0bef7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,14 +4,13 @@ # build static web content # note: pin this to amd64 to speed it up, it is prohibitively slow under QEMU FROM --platform=$BUILDPLATFORM node:22-alpine AS web -ARG VERSION=0.0.1.65534-local WORKDIR /slskd COPY bin bin/. COPY src/web src/web/. -RUN sh ./bin/build --web-only --version $VERSION +RUN sh ./bin/build --web-only # build, test, and publish application binaries # note: this needs to be pinned to an amd64 image in order to publish armv7 binaries -- cgit v1.2.3 From 76beb29f6e42b55a5f29a207fbca87237c40c3df Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 30 Sep 2026 19:02:27 -0500 Subject: fail loudly if git isn't installed and we need it --- bin/build | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/bin/build b/bin/build index 8283bf25..9a15ca66 100755 --- a/bin/build +++ b/bin/build @@ -39,7 +39,12 @@ while test $# -gt 0; do esac done -if [ -z "$version" ]; then +if [ -z "$version" ]; then + if ! command -v git >/dev/null 2>&1; then + echo "💥 error: git is required to compose the version, but the executable couldn't be found" + exit 1 + fi + tag=$(git describe --tags --abbrev=0) sha=$(git rev-parse --short HEAD) version=$tag+$sha -- cgit v1.2.3 From 65336e052d9e912ec623a60ea540ea206824ea7e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 30 Sep 2026 19:03:34 -0500 Subject: use a bogus version for web build --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index daf0bef7..f4c392dc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ WORKDIR /slskd COPY bin bin/. COPY src/web src/web/. -RUN sh ./bin/build --web-only +RUN sh ./bin/build --web-only --version 0.0.1.65534-local # build, test, and publish application binaries # note: this needs to be pinned to an amd64 image in order to publish armv7 binaries -- cgit v1.2.3 From 4426b0db00827663a5a58a64f39a0c41cc403af5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Oct 2026 09:48:02 -0500 Subject: move final stage args to improve cache hits --- Dockerfile | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index f4c392dc..d1063802 100644 --- a/Dockerfile +++ b/Dockerfile @@ -36,10 +36,6 @@ RUN bash ./bin/publish --no-prebuild --platform $TARGETPLATFORM --version $VERSI # application FROM mcr.microsoft.com/dotnet/runtime-deps:10.0-noble AS slskd ARG TARGETPLATFORM -ARG TAG=0.0.1 -ARG VERSION=0.0.1.65534-local -ARG REVISION=0 -ARG BUILD_DATE RUN apt-get update && apt-get install --no-install-recommends -y \ jq \ @@ -61,6 +57,11 @@ RUN bash -c 'mkdir -p /.net \ HEALTHCHECK --interval=60s --timeout=3s --start-period=60m --retries=3 CMD wget -q -O - http://localhost:${SLSKD_HTTP_PORT}/health +ARG TAG=0.0.1 +ARG VERSION=0.0.1.65534-local +ARG REVISION=0 +ARG BUILD_DATE + ENV SHELL=/usr/bin/bash \ DOTNET_EnableDiagnostics=0 \ DOTNET_BUNDLE_EXTRACT_BASE_DIR=/.net \ -- cgit v1.2.3 From 93e7bfa63a802563067757696bbed803d2cd5774 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Oct 2026 09:52:54 -0500 Subject: update authors --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index d1063802..aad3bd2a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -81,7 +81,7 @@ ENV SHELL=/usr/bin/bash \ LABEL org.opencontainers.image.title=slskd \ org.opencontainers.image.description="A modern client-server application for the Soulseek file sharing network" \ - org.opencontainers.image.authors="JP Dillingham, slskd Contributors" \ + org.opencontainers.image.authors="JP Dillingham" \ org.opencontainers.image.vendor="slskd Project" \ org.opencontainers.image.licenses=AGPL-3.0 \ org.opencontainers.image.url=https://slskd.org \ -- cgit v1.2.3 From f32f73b402e9bfd5aca47cb94a245fccbd21482f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Oct 2026 18:40:32 -0500 Subject: tweak controller --- src/slskd/Core/API/Controllers/LogsController.cs | 33 ++++++++++++------------ 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 6ef4a7b6..a83e608c 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -38,6 +38,7 @@ namespace slskd.Core.API using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; using slskd.Files; @@ -58,7 +59,7 @@ namespace slskd.Core.API } private FileService Files { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Gets the last few application logs. @@ -79,6 +80,11 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task List() { + if (!Directory.Exists(Path.GetFullPath(Program.LogDirectory))) + { + return NotFound(); + } + var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { IgnoreInaccessible = true, @@ -95,11 +101,12 @@ namespace slskd.Core.API /// Retrieves the requested log file from disk as plain text. /// /// The name of the log file. - /// A value indicating whether the file should be sent as an attachment. /// [HttpGet("files/{filename}")] + [Produces("text/plain")] + [ProducesResponseType(typeof(string), StatusCodes.Status200OK, contentType: "text/plain")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public IActionResult Get(string filename, [FromQuery] bool download = false) + public IActionResult Get([FromRoute] string filename) { if (string.IsNullOrWhiteSpace(filename)) { @@ -121,29 +128,23 @@ namespace slskd.Core.API if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase)) { - return BadRequest("Only .log files may be retrieved"); + return StatusCode(StatusCodes.Status403Forbidden, "Only .log files may be retrieved"); } try { var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); - const string contentType = "text/plain; charset=utf-8"; - - if (download) - { - return File(stream, contentType, filename); - } - - return File(stream, contentType); - } - catch (UnauthorizedException) - { - return Unauthorized(); + return File(stream, "text/plain; charset=utf-8", enableRangeProcessing: true); } catch (NotFoundException) { return NotFound(); } + catch (Exception ex) + { + Log.Error(ex, "Failed to retrieve log file {Filename}: {Message}", filename, ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } } } } -- cgit v1.2.3 From ffd4a8c60476fe75d3c37d8323b51b4367fb7492 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Oct 2026 18:42:06 -0500 Subject: show errors, toast if popup blocked --- src/web/src/components/System/Logs/Explorer.jsx | 150 +++++++++++++----------- 1 file changed, 82 insertions(+), 68 deletions(-) diff --git a/src/web/src/components/System/Logs/Explorer.jsx b/src/web/src/components/System/Logs/Explorer.jsx index ac6d982f..b1391da2 100644 --- a/src/web/src/components/System/Logs/Explorer.jsx +++ b/src/web/src/components/System/Logs/Explorer.jsx @@ -1,7 +1,12 @@ import '../Files/Files.css'; import { getFileBlob, list } from '../../../lib/logs'; import { downloadFile, formatBytes, formatDate } from '../../../lib/util'; -import { LoaderSegment } from '../../Shared'; +import { + ErrorSegment, + LoaderSegment, + PlaceholderSegment, + Switch, +} from '../../Shared'; import React, { useEffect, useState } from 'react'; import { toast } from 'react-toastify'; import { Header, Icon, Table } from 'semantic-ui-react'; @@ -9,6 +14,13 @@ import { Header, Icon, Table } from 'semantic-ui-react'; const view = async (filename) => { const tab = window.open('', '_blank'); + if (!tab) { + toast.error( + 'Unable to open a new window; allow pop-ups for this site to view logs', + ); + return; + } + try { const blob = await getFileBlob({ filename }); @@ -60,17 +72,23 @@ const FileRow = ({ length, modifiedAt, name }) => ( const Explorer = () => { const [files, setFiles] = useState([]); - const [loading, setLoading] = useState(false); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(undefined); const [sortColumn, setSortColumn] = useState('date'); const [sortDirection, setSortDirection] = useState('descending'); const fetch = async () => { setLoading(true); + setError(undefined); try { setFiles(await list()); - } catch (error) { - toast.error(error?.message ?? error); + } catch (fetchError) { + if (fetchError?.response?.status === 404) { + setFiles([]); + } else { + setError(fetchError?.message ?? fetchError); + } } finally { setLoading(false); } @@ -112,10 +130,6 @@ const Explorer = () => { }); }; - if (loading) { - return ; - } - const sortedFiles = sortItems(files); return ( @@ -127,74 +141,74 @@ const Explorer = () => { /logs - + ) + } + error={error && } + loading={loading && } > - - - handleSort('name')} - style={{ cursor: 'pointer' }} - > - Name - {sortColumn === 'name' && ( - - )} - - handleSort('date')} - style={{ cursor: 'pointer' }} - > - Date Modified - {sortColumn === 'date' && ( - - )} - - - Size - - - - - - {files.length === 0 ? ( +
+ - handleSort('name')} + style={{ cursor: 'pointer' }} + > + Name + {sortColumn === 'name' && ( + + )} + + handleSort('date')} + style={{ cursor: 'pointer' }} > - No log files - + Date Modified + {sortColumn === 'date' && ( + + )} + + + Size + + - ) : ( - sortedFiles.map((f) => ( + + + {sortedFiles.map((f) => ( - )) - )} - -
+ ))} + + + ); }; -- cgit v1.2.3 From 400108c9a4a88edb6738309e0b83c9299ca36072 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Oct 2026 19:04:22 -0500 Subject: make enumeration options default as intended --- src/slskd/Files/FileService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 665fe919..584aab08 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -320,7 +320,7 @@ namespace slskd.Files /// Thrown if the specified directory has a relative path. /// Thrown if the specified directory does not exist. /// Thrown if the specified root directory is restricted. - public virtual async Task ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions) + public virtual async Task ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); @@ -352,7 +352,7 @@ namespace slskd.Files try { - var contents = dir.GetFileSystemInfos("*", enumerationOptions); + var contents = dir.GetFileSystemInfos("*", enumerationOptions ?? new EnumerationOptions()); var files = contents .OfType() -- cgit v1.2.3 From a172390967d21b2f95cbb4ceb88de410b1f044c5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Oct 2026 19:04:26 -0500 Subject: fix tests --- tests/slskd.Tests.Unit/Files/FileServiceTests.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs index d6c30316..05f967da 100644 --- a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs +++ b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs @@ -34,7 +34,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task ListContentsAsync_Throws_ArgumentException_Given_Relative_Path() { - var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: "../")); + var ex = await Record.ExceptionAsync(() => FileService.ListDirectoryContentsAsync(directory: "../")); Assert.NotNull(ex); Assert.IsType(ex); @@ -53,7 +53,7 @@ namespace slskd.Tests.Unit.Files } }); - var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: Path.Combine(Temp, "foo"))); + var ex = await Record.ExceptionAsync(() => FileService.ListDirectoryContentsAsync(directory: Path.Combine(Temp, "foo"))); Assert.NotNull(ex); Assert.IsType(ex); @@ -71,7 +71,7 @@ namespace slskd.Tests.Unit.Files } }); - var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: Path.Combine(Temp, "downloads", "foo"))); + var ex = await Record.ExceptionAsync(() => FileService.ListDirectoryContentsAsync(directory: Path.Combine(Temp, "downloads", "foo"))); Assert.NotNull(ex); Assert.IsType(ex); -- cgit v1.2.3 From c2a9302741e79165978fa91da040b6f7e689cc48 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 13:51:32 -0500 Subject: compensate for late-populated LogDirectory --- src/slskd/Files/FileService.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 584aab08..70bfc293 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -59,10 +59,11 @@ namespace slskd.Files private IEnumerable AllowedDirectories => new[] { - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), - Path.GetFullPath(Program.LogDirectory), - }; + OptionsMonitor.CurrentValue.Directories.Downloads, + OptionsMonitor.CurrentValue.Directories.Incomplete, + Program.LogDirectory, + }.Where(x => !string.IsNullOrWhiteSpace(x)) + .Select(x => Path.GetFullPath(x)); private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } -- cgit v1.2.3