diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-10-03 23:28:23 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-10-03 23:28:23 -0500 |
| commit | fc11d5d691ac008e1507f25ebb5ce3ac7a5cfc60 (patch) | |
| tree | 3de54f5e8b4001253db53bd20dc153ebe49b271c | |
| parent | 1915a370c1bd11aee8849574e116b353a0b7153f (diff) | |
| parent | a97a425c7121f19c1613106c0bab7a1dcf616f92 (diff) | |
| download | slskd-fc11d5d691ac008e1507f25ebb5ce3ac7a5cfc60.tar.gz | |
Merge branch 'master' into upload-queue-fixes
| -rw-r--r-- | Dockerfile | 14 | ||||
| -rwxr-xr-x | bin/build | 7 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/LogsController.cs | 94 | ||||
| -rw-r--r-- | src/slskd/Files/API/FilesController.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Files/FileService.cs | 55 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 5 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadService.cs | 1 | ||||
| -rw-r--r-- | src/web/package-lock.json | 18 | ||||
| -rw-r--r-- | src/web/src/components/System/Logs/Explorer.jsx | 216 | ||||
| -rw-r--r-- | src/web/src/components/System/Logs/Live.jsx | 63 | ||||
| -rw-r--r-- | src/web/src/components/System/Logs/LogTable.jsx | 64 | ||||
| -rw-r--r-- | src/web/src/components/System/Logs/index.jsx | 127 | ||||
| -rw-r--r-- | src/web/src/lib/logs.js | 27 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Files/FileServiceTests.cs | 6 |
16 files changed, 575 insertions, 128 deletions
@@ -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 --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 @@ -37,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 \ @@ -62,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 \ @@ -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 \ @@ -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 diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 8055c696..a83e608c 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -32,9 +32,16 @@ namespace slskd.Core.API { + using System; + using System.IO; + using System.Linq; + using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; + using Serilog; + using slskd.Files; /// <summary> /// Logs. @@ -46,15 +53,98 @@ namespace slskd.Core.API [Consumes("application/json")] public class LogsController : ControllerBase { + public LogsController(FileService fileService) + { + Files = fileService; + } + + private FileService Files { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<LogsController>(); + /// <summary> /// Gets the last few application logs. /// </summary> /// <returns></returns> - [HttpGet] - [Authorize(Policy = AuthPolicy.Any)] + [HttpGet("live")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public IActionResult Logs() { return Ok(Program.LogBuffer); } + + /// <summary> + /// Lists the log files currently on disk. + /// </summary> + /// <returns></returns> + [HttpGet("files")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] + public async Task<IActionResult> List() + { + if (!Directory.Exists(Path.GetFullPath(Program.LogDirectory))) + { + return NotFound(); + } + + var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions + { + IgnoreInaccessible = true, + AttributesToSkip = FileAttributes.System | FileAttributes.Hidden | FileAttributes.ReparsePoint, + RecurseSubdirectories = false, + }); + + var logs = directory.Files.Where(f => f.Name.EndsWith(".log", StringComparison.OrdinalIgnoreCase)); + + return Ok(logs); + } + + /// <summary> + /// Retrieves the requested log file from disk as plain text. + /// </summary> + /// <param name="filename">The name of the log file.</param> + /// <returns></returns> + [HttpGet("files/{filename}")] + [Produces("text/plain")] + [ProducesResponseType(typeof(string), StatusCodes.Status200OK, contentType: "text/plain")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] + public IActionResult Get([FromRoute] string 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"); + } + + if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase)) + { + return StatusCode(StatusCodes.Status403Forbidden, "Only .log files may be retrieved"); + } + + try + { + var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); + 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); + } + } } } 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 8450ba48..70bfc293 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -59,9 +59,11 @@ namespace slskd.Files private IEnumerable<string> AllowedDirectories => new[] { - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), - }; + 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<FileService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } @@ -319,7 +321,7 @@ namespace slskd.Files /// <exception cref="ArgumentException">Thrown if the specified directory has a relative path.</exception> /// <exception cref="NotFoundException">Thrown if the specified directory does not exist.</exception> /// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception> - public virtual async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) + public virtual async Task<FilesystemDirectory> ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); @@ -351,7 +353,7 @@ namespace slskd.Files try { - var contents = dir.GetFileSystemInfos("*", enumerationOptions); + var contents = dir.GetFileSystemInfos("*", enumerationOptions ?? new EnumerationOptions()); var files = contents .OfType<FileInfo>() @@ -384,6 +386,49 @@ namespace slskd.Files } /// <summary> + /// Retrieves the contents of the specified <paramref name="filename"/> as a stream. + /// </summary> + /// <param name="filename">The file for which contents are to be retrieved.</param> + /// <returns>A Stream containing the contents of the file.</returns> + /// <exception cref="ArgumentNullException">Thrown if the specified filename is null or contains only whitespace.</exception> + /// <exception cref="ArgumentException">Thrown if the specified filename contains path traversal segments.</exception> + /// <exception cref="UnauthorizedException">Thrown if the specified file is not within an allowed directory.</exception> + /// <exception cref="NotFoundException">Thrown if the specified file does not exist.</exception> + /// <exception cref="IOException">Thrown if the file can't be opened for some reason.</exception> + 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, FileShare.ReadWrite); + } + catch (Exception ex) + { + throw new IOException($"Failed to open file {Path.GetFileName(filename)} for reading: {ex.Message}", ex); + } + } + + /// <summary> /// Creates a new file with the specified fully qualified <paramref name="filename"/> and the optional <paramref name="options"/>, /// returning a <see cref="Stream"/> with which the contents of the file can be written. /// </summary> diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b1f57ce4..cfe8bcba 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1250,9 +1250,10 @@ namespace slskd e => !OptionsAtStartup.Logger.NoDisk, 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)))) + retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs), + shared: true))) // allow log file to be read concurrently .WriteTo.Conditional( e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), config => 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 @@ -// <copyright file="QueueDownloadBatchRequest.cs" company="JP Dillingham"> +// <copyright file="EnqueueDownloadBatchRequest.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ 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 @@ -// <copyright file="QueueDownloadBatchResponse.cs" company="JP Dillingham"> +// <copyright file="EnqueueDownloadBatchResponse.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 7bc889ba..b480e764 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 { 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": { 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..b1391da2 --- /dev/null +++ b/src/web/src/components/System/Logs/Explorer.jsx @@ -0,0 +1,216 @@ +import '../Files/Files.css'; +import { getFileBlob, list } from '../../../lib/logs'; +import { downloadFile, formatBytes, formatDate } from '../../../lib/util'; +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'; + +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 }); + + // 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 }) => ( + <Table.Row key={name}> + <Table.Cell> + <Icon name="file alternate outline" /> + {name} + </Table.Cell> + <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell> + <Table.Cell>{length ? formatBytes(length) : ''}</Table.Cell> + <Table.Cell style={{ whiteSpace: 'nowrap' }}> + <Icon + name="external alternate" + onClick={() => view(name)} + style={{ cursor: 'pointer', marginRight: '0.5em' }} + title={`View ${name} in a new window`} + /> + <Icon + name="download" + onClick={() => download(name)} + style={{ cursor: 'pointer' }} + title={`Download ${name}`} + /> + </Table.Cell> + </Table.Row> +); + +const Explorer = () => { + const [files, setFiles] = useState([]); + 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 (fetchError) { + if (fetchError?.response?.status === 404) { + setFiles([]); + } else { + setError(fetchError?.message ?? fetchError); + } + } 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; + }); + }; + + const sortedFiles = sortItems(files); + + return ( + <> + <Header + className="explorer-working-directory" + size="small" + > + <Icon name="folder open" /> + /logs + </Header> + <Switch + empty={ + !loading && + !error && + files.length === 0 && ( + <PlaceholderSegment + caption="No log files" + icon="file alternate outline" + /> + ) + } + error={error && <ErrorSegment caption={error} />} + loading={loading && <LoaderSegment />} + > + <Table + className="unstackable" + size="large" + > + <Table.Header> + <Table.Row> + <Table.HeaderCell + className="explorer-list-name" + onClick={() => handleSort('name')} + style={{ cursor: 'pointer' }} + > + Name + {sortColumn === 'name' && ( + <Icon + name={ + sortDirection === 'ascending' + ? 'chevron up' + : 'chevron down' + } + /> + )} + </Table.HeaderCell> + <Table.HeaderCell + className="explorer-list-date" + onClick={() => handleSort('date')} + style={{ cursor: 'pointer' }} + > + Date Modified + {sortColumn === 'date' && ( + <Icon + name={ + sortDirection === 'ascending' + ? 'chevron up' + : 'chevron down' + } + /> + )} + </Table.HeaderCell> + <Table.HeaderCell className="explorer-list-size"> + Size + </Table.HeaderCell> + <Table.HeaderCell className="explorer-list-action" /> + </Table.Row> + </Table.Header> + <Table.Body> + {sortedFiles.map((f) => ( + <FileRow + key={f.name} + {...f} + /> + ))} + </Table.Body> + </Table> + </Switch> + </> + ); +}; + +export default Explorer; 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..2699a2e3 --- /dev/null +++ b/src/web/src/components/System/Logs/Live.jsx @@ -0,0 +1,63 @@ +import '../System.css'; +import { createLogsHubConnection } from '../../../lib/hubFactory'; +import { LoaderSegment } from '../../Shared'; +import LogTable from './LogTable'; +import { Component } from 'react'; + +const initialState = { + connected: false, + logs: [], +}; + +const maxLogs = 500; + +class Live 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).map(this.withId), + }); + }); + + logsHub.on('log', (log) => { + const record = this.withId(log); + + this.setState((previousState) => ({ + connected: true, + logs: [record].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(); + } + + nextId = 0; + + withId = (log) => ({ ...log, id: this.nextId++ }); + + render() { + const { connected, logs } = this.state; + + return ( + <div className="logs"> + {!connected && <LoaderSegment />} + {connected && <LogTable logs={logs} />} + </div> + ); + } +} + +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..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 }) => ( + <Table + className="logs-table" + compact="very" + > + <Table.Header> + <Table.Row> + <Table.HeaderCell>Timestamp</Table.HeaderCell> + <Table.HeaderCell>Level</Table.HeaderCell> + <Table.HeaderCell>Message</Table.HeaderCell> + </Table.Row> + </Table.Header> + <Table.Body className="logs-table-body"> + {logs?.length === 0 ? ( + <Table.Row> + <Table.Cell + colSpan={99} + style={{ + opacity: 0.5, + padding: '10px !important', + textAlign: 'center', + }} + > + {emptyMessage} + </Table.Cell> + </Table.Row> + ) : ( + logs.map((log) => ( + <Table.Row + disabled={log.level === 'Debug' || log.level === 'Verbose'} + key={log.id} + negative={log.level === 'Error' || log.level === 'Fatal'} + warning={log.level === 'Warning'} + > + <Table.Cell>{formatTimestamp(log.timestamp)}</Table.Cell> + <Table.Cell>{abbreviations[log.level] || log.level}</Table.Cell> + <Table.Cell className="logs-table-message"> + {log.message} + </Table.Cell> + </Table.Row> + )) + )} + </Table.Body> + </Table> +); + +export default LogTable; diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx index f36258ec..f0fa4a58 100644 --- a/src/web/src/components/System/Logs/index.jsx +++ b/src/web/src/components/System/Logs/index.jsx @@ -1,98 +1,35 @@ -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', +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: () => ( + <Tab.Pane> + <Live /> + </Tab.Pane> + ), + route: 'live', + }, + { + menuItem: 'History', + render: () => ( + <Tab.Pane> + <Explorer /> + </Tab.Pane> + ), + route: 'history', + }, + ]; + + return ( + <div> + <Tab panes={panes} /> + </div> + ); }; -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 ( - <div className="logs"> - {!connected && <LoaderSegment />} - {connected && ( - <Table - className="logs-table" - compact="very" - > - <Table.Header> - <Table.Row> - <Table.HeaderCell>Timestamp</Table.HeaderCell> - <Table.HeaderCell>Level</Table.HeaderCell> - <Table.HeaderCell>Message</Table.HeaderCell> - </Table.Row> - </Table.Header> - <Table.Body className="logs-table-body"> - {logs.map((log) => ( - <Table.Row - disabled={log.level === 'Debug'} - key={log.timestamp} - negative={log.level === 'Error'} - warning={log.level === 'Warning'} - > - <Table.Cell>{this.formatTimestamp(log.timestamp)}</Table.Cell> - <Table.Cell>{levels[log.level] || log.level}</Table.Cell> - <Table.Cell className="logs-table-message"> - {log.message} - </Table.Cell> - </Table.Row> - ))} - </Table.Body> - </Table> - )} - </div> - ); - } -} - 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..35ae5d84 --- /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 getFileText = 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; +}; 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<ArgumentException>(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<UnauthorizedException>(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<NotFoundException>(ex); |
