From da96e0dce5fa398dab65b6085bc4d040001bf70a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 21 Jun 2026 15:44:03 +0000 Subject: Bump form-data in /src/web Bumps and [form-data](https://github.com/form-data/form-data). These dependencies needed to be updated together. Updates `form-data` from 4.0.5 to 4.0.6 - [Changelog](https://github.com/form-data/form-data/blob/master/CHANGELOG.md) - [Commits](https://github.com/form-data/form-data/compare/v4.0.5...v4.0.6) Updates `form-data` from 3.0.4 to 3.0.5 - [Changelog](https://github.com/form-data/form-data/blob/master/CHANGELOG.md) - [Commits](https://github.com/form-data/form-data/compare/v4.0.5...v4.0.6) --- updated-dependencies: - dependency-name: form-data dependency-version: 3.0.5 dependency-type: indirect - dependency-name: form-data dependency-version: 4.0.6 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'src/web') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 191d1cca..17e00d08 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -5998,16 +5998,16 @@ } }, "node_modules/axios/node_modules/form-data": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", - "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" + "hasown": "^2.0.4", + "mime-types": "^2.1.35" }, "engines": { "node": ">= 6" @@ -11051,16 +11051,16 @@ } }, "node_modules/form-data": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.4.tgz", - "integrity": "sha512-f0cRzm6dkyVYV3nPoooP8XlccPQukegwhAnpoLcXy+X+A8KfpGOoXwDr9FLZd3wzgLaBGQBE3lY93Zm/i1JvIQ==", + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.5.tgz", + "integrity": "sha512-j23EibVLnp4zNXGW7LjryXYa2X6U/M96yoOX+ybZxwkYajdxRNEqYY3zhh7y0i6kfISKS2jr+EJq1YTUDEv5+w==", "dev": true, "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", + "hasown": "^2.0.4", "mime-types": "^2.1.35" }, "engines": { @@ -11661,9 +11661,9 @@ } }, "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "license": "MIT", "dependencies": { "function-bind": "^1.1.2" -- cgit v1.2.3 From 651d94a28ddced7e65c005448dabce7075505625 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Jun 2026 14:11:56 -0500 Subject: stub dashboard --- src/web/src/components/Dashboard/Dashboard.jsx | 12 +++ src/web/src/components/Dashboard/SearchBar.jsx | 102 +++++++++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 src/web/src/components/Dashboard/Dashboard.jsx create mode 100644 src/web/src/components/Dashboard/SearchBar.jsx (limited to 'src/web') diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx new file mode 100644 index 00000000..01dd1aa0 --- /dev/null +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -0,0 +1,12 @@ +import SearchBar from './SearchBar'; +import React from 'react'; + +const Dashboard = ({ server } = {}) => { + return ( +
+ +
+ ); +}; + +export default Dashboard; diff --git a/src/web/src/components/Dashboard/SearchBar.jsx b/src/web/src/components/Dashboard/SearchBar.jsx new file mode 100644 index 00000000..e8c0b7e4 --- /dev/null +++ b/src/web/src/components/Dashboard/SearchBar.jsx @@ -0,0 +1,102 @@ +import '../Search/Search.css'; +import { urlBase } from '../../config'; +import * as library from '../../lib/searches'; +import React, { useRef, useState } from 'react'; +import { Link, useHistory } from 'react-router-dom'; +import { toast } from 'react-toastify'; +import { Button, Icon, Input, Segment } from 'semantic-ui-react'; +import { v4 as uuidv4 } from 'uuid'; + +const SearchBar = ({ server } = {}) => { + const [creating, setCreating] = useState(false); + + const inputRef = useRef(); + const history = useHistory(); + + const create = async ({ navigate = false } = {}) => { + const ref = inputRef?.current?.inputRef?.current; + const searchText = ref.value; + const id = uuidv4(); + + try { + setCreating(true); + await library.create({ id, searchText }); + + ref.value = ''; + ref.focus(); + + setCreating(false); + + if (navigate) { + history.push(`${urlBase}/searches/${id}`); + } else { + const label = + searchText.length > 30 ? `${searchText.slice(0, 15)}...` : searchText; + toast.info( + + Search for ‘{label}’ started.{' '} + View results + , + ); + } + } catch (createError) { + console.error(createError); + toast.error( + createError?.response?.data ?? createError?.message ?? createError, + ); + setCreating(false); + } + }; + + inputRef?.current?.inputRef?.current?.focus(); + + return ( + +
+ +
+ + + ))} + + + + + + + {formatBytesParts(sumBytes(summary.Download ?? {})).value} + + {formatBytesParts(sumBytes(summary.Download ?? {})).unit} + + + + Downloaded ·{' '} + {sumCounts(summary.Download ?? {}).toLocaleString()} files + + + + + + {formatBytesParts(sumBytes(summary.Upload ?? {})).value} + + {formatBytesParts(sumBytes(summary.Upload ?? {})).unit} + + + + Uploaded · {sumCounts(summary.Upload ?? {}).toLocaleString()}{' '} + files + + + + + + {shareRatio !== null ? shareRatio.toFixed(2) : '—'} + + Share ratio (↑/↓) + + + + + {( + (summary.Upload?.Succeeded?.distinctUsers ?? 0) + + (summary.Download?.Succeeded?.distinctUsers ?? 0) + ).toLocaleString()} + + Distinct peers + + +
+ +
+ + onTabChange(activeIndex)} + panes={historyPanes} + /> + + )} +
+ ); +}; + +export default HistoricalStatistics; diff --git a/src/web/src/components/Dashboard/Leaderboard.jsx b/src/web/src/components/Dashboard/Leaderboard.jsx new file mode 100644 index 00000000..b983dc5a --- /dev/null +++ b/src/web/src/components/Dashboard/Leaderboard.jsx @@ -0,0 +1,213 @@ +import * as reports from '../../lib/reports'; +import React, { useEffect, useState } from 'react'; +import { Divider, Grid, Header, Icon, Loader, Table } from 'semantic-ui-react'; + +const formatBytes = (bytes) => { + if (!bytes || bytes === 0) return '0 B'; + const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; + const index = Math.floor(Math.log(bytes) / Math.log(1_024)); + return `${(bytes / 1_024 ** index).toFixed(1)} ${units[index]}`; +}; + +const formatSpeed = (bytesPerSecond) => { + if (!bytesPerSecond || bytesPerSecond === 0) return '0 B/s'; + return `${formatBytes(bytesPerSecond)}/s`; +}; + +const SORT_FIELDS = [ + { label: 'Count', sort: 'Count' }, + { label: 'Total Size', sort: 'TotalBytes' }, + { label: 'Avg Speed', sort: 'AverageSpeed' }, +]; + +const sortHeaderStyle = { cursor: 'pointer', userSelect: 'none' }; + +const LeaderboardTable = ({ loading, onSort, rows, sortBy }) => ( + + + + + # + + Username + {SORT_FIELDS.map(({ label, sort }) => ( + onSort(sort)} + style={sortHeaderStyle} + textAlign="right" + > + {label} + {sortBy === sort && ( + + )} + + ))} + + + + {loading && ( + + + + + + )} + {!loading && (!rows || rows.length === 0) && ( + + + No data to display + + + )} + {!loading && + rows && + rows.map((row, index) => ( + + + {index + 1} + + {row.username} + + {row.count.toLocaleString()} + + + {formatBytes(row.totalBytes)} + + + {formatSpeed(row.averageSpeed)} + + + ))} + +
+); + +const initialState = { + sortBy: 'Count', + rows: { + upload: [], + download: [], + }, + loading: { + upload: false, + download: false, + }, +}; + +const Leaderboard = ({ downloads, end, start, uploads }) => { + const [state, setState] = useState(initialState); + + useEffect(() => { + setState((previous) => ({ + ...previous, + sortBy: 'Count', + rows: { upload: uploads, download: downloads }, + })); + }, [downloads, uploads]); + + const onSort = async (sort) => { + if (sort === state.sortBy) return; + + setState((previous) => ({ + ...previous, + sortBy: sort, + loading: { upload: true, download: true }, + })); + + const startDate = start ? new Date(start) : undefined; + const endDate = end ? new Date(end) : new Date(); + + const [newUploads, newDownloads] = await Promise.all([ + reports + .getLeaderboard({ + direction: 'Upload', + end: endDate, + sortBy: sort, + start: startDate, + }) + .catch((error) => { + console.error(error); + return state.rows.upload; + }), + reports + .getLeaderboard({ + direction: 'Download', + end: endDate, + sortBy: sort, + start: startDate, + }) + .catch((error) => { + console.error(error); + return state.rows.download; + }), + ]); + + setState((previous) => ({ + ...previous, + rows: { upload: newUploads, download: newDownloads }, + loading: { upload: false, download: false }, + })); + }; + + return ( + + +
+ Downloads +
+ +
+ + +
+ Uploads +
+ +
+
+ ); +}; + +export default Leaderboard; diff --git a/src/web/src/components/Dashboard/TopDirectories.jsx b/src/web/src/components/Dashboard/TopDirectories.jsx new file mode 100644 index 00000000..00eae5d9 --- /dev/null +++ b/src/web/src/components/Dashboard/TopDirectories.jsx @@ -0,0 +1,71 @@ +import React from 'react'; +import { Table } from 'semantic-ui-react'; + +const getLastTwoSegments = (path) => { + if (!path) { + return path; + } + + const parts = path.split(/[/\\]/u).filter((p) => p.length > 0); + + if (parts.length <= 2) { + return parts.join('/'); + } + + return parts.slice(-2).join('/'); +}; + +const TopDirectories = ({ rows }) => ( + + + + + # + + Directory + Downloads + Distinct Users + + + + {(!rows || rows.length === 0) && ( + + + No data to display. + + + )} + {rows && + rows.map((row, index) => ( + + + {index + 1} + + + {getLastTwoSegments(row.directory)} + + + {row.count.toLocaleString()} + + + {row.distinctUsers.toLocaleString()} + + + ))} + +
+); + +export default TopDirectories; diff --git a/src/web/src/components/Dashboard/TransferErrors.jsx b/src/web/src/components/Dashboard/TransferErrors.jsx new file mode 100644 index 00000000..c0b79cf1 --- /dev/null +++ b/src/web/src/components/Dashboard/TransferErrors.jsx @@ -0,0 +1,242 @@ +import { Graph, useDarkMode } from '../Shared'; +import React, { useMemo } from 'react'; +import { Divider, Header, Table } from 'semantic-ui-react'; + +const truncate = (text, maxLength) => { + if (!text) { + return ''; + } + + if (text.length <= maxLength) { + return text; + } + + return `${text.slice(0, maxLength)}…`; +}; + +const getFilename = (path) => { + if (!path) { + return ''; + } + + const parts = path.replaceAll('\\', '/').split('/'); + return parts[parts.length - 1] || path; +}; + +const formatDateTime = (isoString) => { + if (!isoString) { + return ''; + } + + return new Date(isoString).toLocaleString(); +}; + +const mergePareto = (uploadRows, downloadRows) => { + const combined = {}; + for (const row of [...(uploadRows || []), ...(downloadRows || [])]) { + const key = row.exception ?? ''; + combined[key] = combined[key] + ? { + exception: key, + count: combined[key].count + row.count, + distinctUsers: combined[key].distinctUsers + row.distinctUsers, + } + : { ...row }; + } + + return Object.values(combined) + .sort((a, b) => b.count - a.count) + .slice(0, 10); +}; + +const mergeRecent = (uploadRows, downloadRows) => + [ + ...(uploadRows || []).map((r) => ({ ...r, direction: 'Upload' })), + ...(downloadRows || []).map((r) => ({ ...r, direction: 'Download' })), + ] + .sort((a, b) => new Date(b.endedAt) - new Date(a.endedAt)) + .slice(0, 10); + +const ERRORS_SERIES = [ + { + color: '#db2828', + format: (v) => v.toLocaleString(), + key: 'uploadErrors', + name: 'Upload Errors', + }, + { + color: '#a333c8', + format: (v) => v.toLocaleString(), + key: 'downloadErrors', + name: 'Download Errors', + }, +]; + +const DEFAULT_ERRORS_SERIES = new Set(['uploadErrors', 'downloadErrors']); + +const TransferErrors = ({ + chartData, + download, + historyDays, + upload, +}) => { + const isDark = useDarkMode(); + + const paretoRows = useMemo( + () => mergePareto(upload.pareto, download.pareto), + [upload.pareto, download.pareto], + ); + const recentRows = useMemo( + () => mergeRecent(upload.recent, download.recent), + [upload.recent, download.recent], + ); + + const xFormatter = (timestamp) => { + if (historyDays === 1) { + return new Date(timestamp).toLocaleTimeString(undefined, { + hour: '2-digit', + minute: '2-digit', + }); + } + + return new Date(timestamp).toLocaleDateString(undefined, { + day: 'numeric', + month: 'short', + }); + }; + + const maxParetoCount = + paretoRows && paretoRows.length > 0 ? paretoRows[0].count : 1; + + return ( +
+
Error Count Over Time
+ v.toLocaleString()} + /> + +
+ Top Fault Types + + pareto + +
+ + + + Exception + + Count + + Distinct Users + + + + + {(!paretoRows || paretoRows.length === 0) && ( + + + No data to display. + + + )} + {paretoRows && + paretoRows.map((row) => ( + + + {truncate(row.exception, 80)} + + +
+
+
+ + + {row.count.toLocaleString()} + + + {row.distinctUsers.toLocaleString()} + + + ))} + +
+ +
Recent Errors
+ + + + Time + Direction + Username + Filename + Exception + + + + {(!recentRows || recentRows.length === 0) && ( + + + No data to display. + + + )} + {recentRows && + recentRows.map((row) => ( + + + {formatDateTime(row.endedAt)} + + {row.direction} + {row.username} + + {getFilename(row.filename)} + + + {truncate(row.exception, 80)} + + + ))} + +
+
+ ); +}; + +export default TransferErrors; -- cgit v1.2.3 From 7bdc1e5d5f64c5095cdd7659795a535697b403e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Jun 2026 18:43:17 -0500 Subject: initial swag at a shared graph component --- src/web/src/components/Dashboard/Dashboard.jsx | 1 - .../components/Dashboard/HistoricalStatistics.jsx | 30 +-- .../src/components/Dashboard/TransferErrors.jsx | 29 +-- src/web/src/components/Shared/Graph.jsx | 284 +++++++++++++++++++++ src/web/src/components/Shared/index.js | 1 + 5 files changed, 303 insertions(+), 42 deletions(-) create mode 100644 src/web/src/components/Shared/Graph.jsx (limited to 'src/web') diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx index 959df68b..a345f593 100644 --- a/src/web/src/components/Dashboard/Dashboard.jsx +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -149,7 +149,6 @@ const Dashboard = ({ server } = {}) => { directories={data.directories} exceptions={data.exceptions} histogram={data.histogram} - historyDays={historyParameters.days} historyEnd={historyParameters.end} historyLabel={historyLabel} historyRanges={HISTORY_RANGES} diff --git a/src/web/src/components/Dashboard/HistoricalStatistics.jsx b/src/web/src/components/Dashboard/HistoricalStatistics.jsx index 91af07ae..b0963082 100644 --- a/src/web/src/components/Dashboard/HistoricalStatistics.jsx +++ b/src/web/src/components/Dashboard/HistoricalStatistics.jsx @@ -85,72 +85,84 @@ const HISTORY_SERIES = [ format: formatBytes, key: 'uploadBytes', name: 'Upload Size', + unit: 'bytes', }, { color: '#2185d0', format: formatBytes, key: 'downloadBytes', name: 'Download Size', + unit: 'bytes', }, { color: '#6435c9', format: (v) => v.toLocaleString(), key: 'uploadCount', name: 'Upload Count', + unit: 'count', }, { color: '#e03997', format: (v) => v.toLocaleString(), key: 'downloadCount', name: 'Download Count', + unit: 'count', }, { color: '#f2711c', format: formatSpeed, key: 'uploadSpeed', name: 'Upload Speed', + unit: 'speed', }, { color: '#fbbd08', format: formatSpeed, key: 'downloadSpeed', name: 'Download Speed', + unit: 'speed', }, { color: '#db2828', format: (v) => v.toLocaleString(), key: 'uploadErrors', name: 'Upload Errors', + unit: 'count', }, { color: '#a333c8', format: (v) => v.toLocaleString(), key: 'downloadErrors', name: 'Download Errors', + unit: 'count', }, { color: '#d4500a', format: (v) => `${v.toFixed(1)}%`, key: 'uploadErrorRate', name: 'Upload Error Rate', + unit: 'rate', }, { color: '#1aa9b0', format: (v) => `${v.toFixed(1)}%`, key: 'downloadErrorRate', name: 'Download Error Rate', + unit: 'rate', }, { color: '#8e44ad', format: formatWait, key: 'uploadWait', name: 'Upload Queue Wait', + unit: 'seconds', }, { color: '#b5cc18', format: (v) => v.toFixed(2), key: 'shareRatio', name: 'Share Ratio', + unit: 'ratio', }, ]; @@ -161,7 +173,6 @@ const HistoricalStatistics = ({ directories, exceptions, histogram, - historyDays, historyEnd, historyLabel, historyRanges, @@ -186,20 +197,6 @@ const HistoricalStatistics = ({ ? 'yellow' : 'red'; - const histogramTickFormatter = (timestamp) => { - if (historyDays === 1) { - return new Date(timestamp).toLocaleTimeString(undefined, { - hour: '2-digit', - minute: '2-digit', - }); - } - - return new Date(timestamp).toLocaleDateString(undefined, { - day: 'numeric', - month: 'short', - }); - }; - const historyPanes = [ { menuItem: { content: 'Users', icon: 'users', key: 'users' }, @@ -229,7 +226,6 @@ const HistoricalStatistics = ({ @@ -338,8 +334,6 @@ const HistoricalStatistics = ({ data={chartData} defaultSeries={DEFAULT_HISTORY_SERIES} series={HISTORY_SERIES} - xFormatter={histogramTickFormatter} - yFormatter={formatBytes} /> diff --git a/src/web/src/components/Dashboard/TransferErrors.jsx b/src/web/src/components/Dashboard/TransferErrors.jsx index c0b79cf1..d4c9c25c 100644 --- a/src/web/src/components/Dashboard/TransferErrors.jsx +++ b/src/web/src/components/Dashboard/TransferErrors.jsx @@ -63,23 +63,20 @@ const ERRORS_SERIES = [ format: (v) => v.toLocaleString(), key: 'uploadErrors', name: 'Upload Errors', + unit: 'count', }, { color: '#a333c8', format: (v) => v.toLocaleString(), key: 'downloadErrors', name: 'Download Errors', + unit: 'count', }, ]; const DEFAULT_ERRORS_SERIES = new Set(['uploadErrors', 'downloadErrors']); -const TransferErrors = ({ - chartData, - download, - historyDays, - upload, -}) => { +const TransferErrors = ({ chartData, download, upload }) => { const isDark = useDarkMode(); const paretoRows = useMemo( @@ -91,20 +88,6 @@ const TransferErrors = ({ [upload.recent, download.recent], ); - const xFormatter = (timestamp) => { - if (historyDays === 1) { - return new Date(timestamp).toLocaleTimeString(undefined, { - hour: '2-digit', - minute: '2-digit', - }); - } - - return new Date(timestamp).toLocaleDateString(undefined, { - day: 'numeric', - month: 'short', - }); - }; - const maxParetoCount = paretoRows && paretoRows.length > 0 ? paretoRows[0].count : 1; @@ -115,8 +98,6 @@ const TransferErrors = ({ data={chartData ?? []} defaultSeries={DEFAULT_ERRORS_SERIES} series={ERRORS_SERIES} - xFormatter={xFormatter} - yFormatter={(v) => v.toLocaleString()} />
@@ -219,7 +200,9 @@ const TransferErrors = ({ )} {recentRows && recentRows.map((row) => ( - + {formatDateTime(row.endedAt)} diff --git a/src/web/src/components/Shared/Graph.jsx b/src/web/src/components/Shared/Graph.jsx new file mode 100644 index 00000000..d383345f --- /dev/null +++ b/src/web/src/components/Shared/Graph.jsx @@ -0,0 +1,284 @@ +import React, { useEffect, useMemo, useState } from 'react'; +import { + Area, + AreaChart, + CartesianGrid, + Legend, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from 'recharts'; + +export const useDarkMode = () => { + const [isDark, setIsDark] = useState(() => + document.documentElement.classList.contains('dark'), + ); + + useEffect(() => { + const observer = new MutationObserver(() => { + setIsDark(document.documentElement.classList.contains('dark')); + }); + observer.observe(document.documentElement, { attributeFilter: ['class'] }); + return () => observer.disconnect(); + }, []); + + return isDark; +}; + +const formatBytes = (bytes) => { + if (!bytes || bytes === 0) return '0 B'; + const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; + const index = Math.floor(Math.log(bytes) / Math.log(1_024)); + return `${(bytes / 1_024 ** index).toFixed(1)} ${units[index]}`; +}; + +const formatSpeed = (bytesPerSecond) => { + if (!bytesPerSecond || bytesPerSecond === 0) return '0 B/s'; + return `${formatBytes(bytesPerSecond)}/s`; +}; + +const formatWait = (seconds) => { + if (!seconds || seconds === 0) return '0s'; + if (seconds < 60) return `${Math.round(seconds)}s`; + return `${(seconds / 60).toFixed(1)}m`; +}; + +const UNIT_FORMATTERS = { + bytes: formatBytes, + count: (v) => v.toLocaleString(), + rate: (v) => `${v.toFixed(1)}%`, + ratio: (v) => v.toFixed(2), + seconds: formatWait, + speed: formatSpeed, +}; + +const mixedFormatter = (v) => { + if (v >= 1e9) return `${(v / 1e9).toFixed(1)}B`; + if (v >= 1e6) return `${(v / 1e6).toFixed(1)}M`; + if (v >= 1e3) return `${(v / 1e3).toFixed(1)}K`; + return v.toLocaleString(); +}; + +const X_TICK_COUNT = 11; +const ONE_DAY_MS = 86_400_000; + +// series: [{ key, name, color, unit?, format? }] +// key — the data key in each data point +// name — label shown in the legend and tooltip +// color — stroke / fill color +// unit — one of: 'bytes' | 'count' | 'rate' | 'ratio' | 'seconds' | 'speed' +// used to pick the Y axis formatter; omit for unitless/mixed +// format — (value) => string used in the tooltip; defaults to toLocaleString() +const Graph = ({ data = [], defaultSeries, height = 200, series = [] }) => { + const isDark = useDarkMode(); + + const [visible, setVisible] = useState( + () => defaultSeries ?? new Set(series.map((s) => s.key)), + ); + + const axisStyle = useMemo( + () => ({ + fill: isDark ? '#8b949e' : '#666', + fontSize: '0.8em', + }), + [isDark], + ); + + const xRange = useMemo(() => { + if (data.length < 2) return null; + const min = data[0].timestamp; + const max = data[data.length - 1].timestamp; + return { min, max }; + }, [data]); + + const xTicks = useMemo(() => { + if (!xRange) return []; + const { max, min } = xRange; + const step = (max - min) / (X_TICK_COUNT - 1); + return Array.from({ length: X_TICK_COUNT }, (_, index) => + Math.round(min + index * step), + ); + }, [xRange]); + + const xFormatter = useMemo(() => { + if (!xRange) return String; + const isIntraday = xRange.max - xRange.min <= ONE_DAY_MS; + if (isIntraday) { + return (timestamp) => + new Date(timestamp).toLocaleTimeString(undefined, { + hour: '2-digit', + minute: '2-digit', + }); + } + + return (timestamp) => + new Date(timestamp).toLocaleDateString(undefined, { + day: 'numeric', + month: 'short', + }); + }, [xRange]); + + const yFormatter = useMemo(() => { + const units = series + .filter((s) => visible.has(s.key) && s.unit) + .map((s) => s.unit); + const unique = [...new Set(units)]; + return unique.length === 1 + ? UNIT_FORMATTERS[unique[0]] ?? mixedFormatter + : mixedFormatter; + }, [series, visible]); + + const toggle = (key) => { + setVisible((previous) => { + const next = new Set(previous); + if (next.has(key)) { + next.delete(key); + } else { + next.add(key); + } + + return next; + }); + }; + + const renderTooltip = ({ active, label, payload }) => { + if (!active || !payload?.length) return null; + const bg = isDark ? '#161b22' : '#fff'; + const border = isDark ? '#30363d' : '#d0d0d0'; + const labelColor = isDark ? '#c9d1d9' : '#333'; + const valueColor = isDark ? '#8b949e' : '#666'; + return ( +
+
+ {xFormatter(label)} +
+ {payload.map((entry) => { + const s = series.find((item) => item.name === entry.name); + const formatted = s?.format + ? s.format(entry.value) + : entry.value.toLocaleString(); + return ( +
+ ▬ + {entry.name}: + {formatted} +
+ ); + })} +
+ ); + }; + + const renderLegend = ({ payload }) => ( +
+ {payload.map((entry) => ( + toggle(entry.dataKey)} + onKeyDown={(event) => { + if (event.key === 'Enter' || event.key === ' ') { + toggle(entry.dataKey); + } + }} + role="checkbox" + style={{ + alignItems: 'center', + cursor: 'pointer', + display: 'flex', + gap: '0.4em', + opacity: visible.has(entry.dataKey) ? 1 : 0.35, + }} + tabIndex={0} + > + + + + {entry.value} + + ))} +
+ ); + + return ( + + + + + + + + {series.map(({ color, key, name }) => ( + + ))} + + + ); +}; + +export default Graph; diff --git a/src/web/src/components/Shared/index.js b/src/web/src/components/Shared/index.js index 0e36bc48..6fbf167f 100644 --- a/src/web/src/components/Shared/index.js +++ b/src/web/src/components/Shared/index.js @@ -2,6 +2,7 @@ export { default as CodeEditor } from './CodeEditor'; export { default as Div } from './Div'; export { default as ErrorSegment } from './ErrorSegment'; export { default as FileList } from './FileList'; +export { default as Graph, useDarkMode } from './Graph'; export { default as LoaderSegment } from './LoaderSegment'; export { default as Nbsp } from './Nbsp'; export { default as PlaceholderSegment } from './PlaceholderSegment'; -- cgit v1.2.3 From f8537aefc2ca61716305e5f1cfefbbae896b11c5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Jun 2026 18:27:40 -0500 Subject: remove unused props --- src/web/src/components/App.jsx | 1 - src/web/src/components/Dashboard/Dashboard.jsx | 1 - 2 files changed, 2 deletions(-) (limited to 'src/web') diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx index fd017dfe..3fbaa468 100644 --- a/src/web/src/components/App.jsx +++ b/src/web/src/components/App.jsx @@ -587,7 +587,6 @@ class App extends Component {
, diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx index a345f593..8043ab0b 100644 --- a/src/web/src/components/Dashboard/Dashboard.jsx +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -45,7 +45,6 @@ const Dashboard = ({ server } = {}) => { HISTORY_RANGES.find((r) => r.label === historyLabel) ?? HISTORY_RANGES[2]; const now = new Date(); return { - days: range.days, end: now.toISOString(), interval: range.interval, start: -- cgit v1.2.3 From b0b1a6514f42b65003ab55d264f4c8c9eb593582 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Jun 2026 13:53:48 +0000 Subject: Bump js-yaml from 3.14.2 to 3.15.0 in /src/web Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 3.14.2 to 3.15.0. - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/3.14.2...3.15.0) --- updated-dependencies: - dependency-name: js-yaml dependency-version: 3.15.0 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) (limited to 'src/web') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 191d1cca..ce6c1070 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -3427,9 +3427,9 @@ } }, "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { - "version": "3.14.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", - "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "version": "3.15.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.0.tgz", + "integrity": "sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==", "dev": true, "license": "MIT", "dependencies": { @@ -14054,10 +14054,20 @@ } }, "node_modules/js-yaml": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", + "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "license": "MIT", "dependencies": { "argparse": "^2.0.1" @@ -19615,9 +19625,9 @@ } }, "node_modules/svgo/node_modules/js-yaml": { - "version": "3.14.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", - "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "version": "3.15.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.0.tgz", + "integrity": "sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==", "dev": true, "license": "MIT", "dependencies": { -- cgit v1.2.3 From ff2c651aeed76b070969a9ce55b0c170c1ec9fb8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jul 2026 19:04:22 -0500 Subject: couple tweaks --- src/slskd/Telemetry/ReportsService.cs | 4 ++-- src/web/src/components/Dashboard/Dashboard.jsx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src/web') diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index e0304d2a..adc2febf 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -181,8 +181,8 @@ public class ReportsService StateDescription, SUM(Size) AS TotalBytes, COUNT(*) AS Count, - COUNT(DISTINCT Username) AS Users, - AVG(AverageSpeed) AS AverageSpeed, + COUNT(DISTINCT Username) AS DistinctUsers, + CAST(SUM(Size) AS REAL) / NULLIF(SUM(strftime('%s', EndedAt) - strftime('%s', StartedAt)), 0) AS AverageSpeed, COALESCE(AVG(strftime('%s', StartedAt) - strftime('%s', EnqueuedAt)), 0.0) AS AverageWait, COALESCE(AVG(strftime('%s', EndedAt) - strftime('%s', StartedAt)), 0.0) AS AverageDuration FROM Transfers diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx index 8043ab0b..302e0f0a 100644 --- a/src/web/src/components/Dashboard/Dashboard.jsx +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -50,7 +50,7 @@ const Dashboard = ({ server } = {}) => { start: range.days != null ? new Date(now - range.days * 86_400_000).toISOString() - : null, + : new Date(0).toISOString(), }; }, [historyLabel]); -- cgit v1.2.3 From 0e41af9c1767b29a9a270e055155b338a7b46b4e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 20:35:34 -0500 Subject: remove periods --- src/web/src/components/Dashboard/TopDirectories.jsx | 2 +- src/web/src/components/Dashboard/TransferErrors.jsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src/web') diff --git a/src/web/src/components/Dashboard/TopDirectories.jsx b/src/web/src/components/Dashboard/TopDirectories.jsx index 00eae5d9..e9d4aba5 100644 --- a/src/web/src/components/Dashboard/TopDirectories.jsx +++ b/src/web/src/components/Dashboard/TopDirectories.jsx @@ -40,7 +40,7 @@ const TopDirectories = ({ rows }) => ( colSpan={4} style={{ opacity: 0.5, textAlign: 'center' }} > - No data to display. + No data to display
)} diff --git a/src/web/src/components/Dashboard/TransferErrors.jsx b/src/web/src/components/Dashboard/TransferErrors.jsx index d4c9c25c..5fa0408c 100644 --- a/src/web/src/components/Dashboard/TransferErrors.jsx +++ b/src/web/src/components/Dashboard/TransferErrors.jsx @@ -134,7 +134,7 @@ const TransferErrors = ({ chartData, download, upload }) => { colSpan={4} style={{ opacity: 0.5, textAlign: 'center' }} > - No data to display. + No data to display
)} @@ -194,7 +194,7 @@ const TransferErrors = ({ chartData, download, upload }) => { colSpan={5} style={{ opacity: 0.5, textAlign: 'center' }} > - No data to display. + No data to display )} -- cgit v1.2.3 From aa86e4c3e67a4b9ae591325b3e4d2a6d9c31f77b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 21:22:38 -0500 Subject: use buckets instead of intervals --- src/web/src/lib/reports.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/web') diff --git a/src/web/src/lib/reports.js b/src/web/src/lib/reports.js index 464c37e5..17c6d214 100644 --- a/src/web/src/lib/reports.js +++ b/src/web/src/lib/reports.js @@ -20,7 +20,7 @@ export const getSummary = async ({ export const getHistogram = async ({ start, end, - interval, + buckets, direction, username = null, } = {}) => { @@ -28,7 +28,7 @@ export const getHistogram = async ({ if (start) parameters.append('start', start.toISOString()); if (end) parameters.append('end', end.toISOString()); - if (interval) parameters.append('interval', interval); + if (buckets) parameters.append('buckets', buckets); if (direction) parameters.append('direction', direction); if (username) parameters.append('username', username); -- cgit v1.2.3 From c4d87a3c25a9b1376ed3252f09fbec83303057f1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 21:23:22 -0500 Subject: include year on date labels if the data set spans years --- src/web/src/components/Shared/Graph.jsx | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'src/web') diff --git a/src/web/src/components/Shared/Graph.jsx b/src/web/src/components/Shared/Graph.jsx index d383345f..386f9a46 100644 --- a/src/web/src/components/Shared/Graph.jsx +++ b/src/web/src/components/Shared/Graph.jsx @@ -112,11 +112,14 @@ const Graph = ({ data = [], defaultSeries, height = 200, series = [] }) => { }); } - return (timestamp) => - new Date(timestamp).toLocaleDateString(undefined, { - day: 'numeric', - month: 'short', - }); + const spansYears = + new Date(xRange.min).getFullYear() !== new Date(xRange.max).getFullYear(); + + return (timestamp) => { + const d = new Date(timestamp); + const date = d.toLocaleDateString(undefined, { day: 'numeric', month: 'short' }); + return spansYears ? `${date} '${String(d.getFullYear()).slice(2)}` : date; + }; }, [xRange]); const yFormatter = useMemo(() => { -- cgit v1.2.3 From 555da1c27697059fa5d96f9d062608772880c720 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 21:23:35 -0500 Subject: use buckets --- src/web/src/components/Dashboard/Dashboard.jsx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'src/web') diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx index 302e0f0a..4554d6d0 100644 --- a/src/web/src/components/Dashboard/Dashboard.jsx +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -5,13 +5,13 @@ import SearchBar from './SearchBar'; import React, { useEffect, useMemo, useState } from 'react'; const HISTORY_RANGES = [ - { label: '24h', days: 1, interval: 60 }, - { label: '7d', days: 7, interval: 360 }, - { label: '30d', days: 30, interval: 1_440 }, - { label: '90d', days: 90, interval: 1_440 }, - { label: '180d', days: 180, interval: 2_880 }, - { label: '1y', days: 365, interval: 10_080 }, - { label: 'All', days: null, interval: 43_200 }, + { label: '24h', days: 1, buckets: 24 }, + { label: '7d', days: 7, buckets: 84 }, + { label: '30d', days: 30, buckets: 60 }, + { label: '90d', days: 90, buckets: 90 }, + { label: '180d', days: 180, buckets: 90 }, + { label: '1y', days: 365, buckets: 100 }, + { label: 'All', days: null, buckets: 100 }, ]; const initialState = { @@ -45,8 +45,8 @@ const Dashboard = ({ server } = {}) => { HISTORY_RANGES.find((r) => r.label === historyLabel) ?? HISTORY_RANGES[2]; const now = new Date(); return { + buckets: range.buckets, end: now.toISOString(), - interval: range.interval, start: range.days != null ? new Date(now - range.days * 86_400_000).toISOString() @@ -76,7 +76,7 @@ const Dashboard = ({ server } = {}) => { return {}; }), reports - .getHistogram({ end, interval: parameters.interval, start }) + .getHistogram({ buckets: parameters.buckets, end, start }) .catch((error) => { console.error(error); return {}; -- cgit v1.2.3 From ac972c0c2578e6c532a22ec489672071be1cf02b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 22:04:04 -0500 Subject: tweaks --- src/slskd/Telemetry/API/ReportsController.cs | 2 +- src/slskd/Telemetry/ReportsService.cs | 4 ++-- src/web/src/lib/reports.js | 14 -------------- src/web/src/lib/reports.test.js | 8 ++++---- 4 files changed, 7 insertions(+), 21 deletions(-) (limited to 'src/web') diff --git a/src/slskd/Telemetry/API/ReportsController.cs b/src/slskd/Telemetry/API/ReportsController.cs index e2bf5963..6192a4bd 100644 --- a/src/slskd/Telemetry/API/ReportsController.cs +++ b/src/slskd/Telemetry/API/ReportsController.cs @@ -193,7 +193,7 @@ public class ReportsController : ControllerBase // and this will let the caller avoid a bunch of empty series on their histogram if (start < Program.GenesisDateTime) { - start = Transfers.Query(q => q.Min(t => t.RequestedAt)) ?? Program.GenesisDateTime; + start = Transfers.Query(q => q.Select(t => (DateTime?)t.RequestedAt).Min()) ?? Program.GenesisDateTime; } TransferDirection? transferDirection = null; diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index d7baa3f0..965b95d0 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -192,7 +192,7 @@ public class ReportsService if (buckets.HasValue && (buckets.Value > 1000 || buckets.Value < 1)) { - throw new ArgumentOutOfRangeException(nameof(buckets), buckets, "Buckets must be between 1 and 5000"); + throw new ArgumentOutOfRangeException(nameof(buckets), buckets, "Buckets must be between 1 and 1000"); } if (interval.HasValue && interval.Value <= TimeSpan.Zero) @@ -227,7 +227,7 @@ public class ReportsService SUM(Size) AS TotalBytes, COUNT(*) AS Count, COUNT(DISTINCT Username) AS DistinctUsers, - CAST(SUM(Size) AS REAL) / NULLIF(SUM(strftime('%s', EndedAt) - strftime('%s', StartedAt)), 0) AS AverageSpeed, + COALESCE(CAST(SUM(Size) AS REAL) / NULLIF(SUM(strftime('%s', EndedAt) - strftime('%s', StartedAt)), 0), 0.0) AS AverageSpeed, COALESCE(AVG(strftime('%s', StartedAt) - strftime('%s', EnqueuedAt)), 0.0) AS AverageWait, COALESCE(AVG(strftime('%s', EndedAt) - strftime('%s', StartedAt)), 0.0) AS AverageDuration FROM Transfers diff --git a/src/web/src/lib/reports.js b/src/web/src/lib/reports.js index 17c6d214..9815fa9c 100644 --- a/src/web/src/lib/reports.js +++ b/src/web/src/lib/reports.js @@ -131,17 +131,3 @@ export const getExceptionPareto = async ({ ) ).data; }; - -export const getUserDetails = async ({ - username, - start = null, - end = null, -} = {}) => { - const parameters = new URLSearchParams(); - - parameters.append('username', username); - parameters.append('start', start); - parameters.append('end', end); - - return (await api.get(`/telemetry/reports/transfers/users/${username}`)).data; -}; diff --git a/src/web/src/lib/reports.test.js b/src/web/src/lib/reports.test.js index d4b3dece..2b73fdca 100644 --- a/src/web/src/lib/reports.test.js +++ b/src/web/src/lib/reports.test.js @@ -74,9 +74,9 @@ describe('reports', () => { expect(paramsOf().get('end')).toBe(end.toISOString()); }); - it('appends interval when provided', async () => { - await reports.getHistogram({ interval: 360 }); - expect(paramsOf().get('interval')).toBe('360'); + it('appends buckets when provided', async () => { + await reports.getHistogram({ buckets: 50 }); + expect(paramsOf().get('buckets')).toBe('50'); }); it('appends direction when provided', async () => { @@ -94,7 +94,7 @@ describe('reports', () => { const p = paramsOf(); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); - expect(p.has('interval')).toBe(false); + expect(p.has('buckets')).toBe(false); expect(p.has('direction')).toBe(false); expect(p.has('username')).toBe(false); }); -- cgit v1.2.3 From ffd47b2287f8d8e8dbf47079e5f746f71671805a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 22:15:23 -0500 Subject: linting --- src/web/src/components/Shared/Graph.jsx | 7 +- src/web/src/lib/reports.test.js | 130 +++++++++++++++++++++----------- 2 files changed, 93 insertions(+), 44 deletions(-) (limited to 'src/web') diff --git a/src/web/src/components/Shared/Graph.jsx b/src/web/src/components/Shared/Graph.jsx index 386f9a46..4d672d3d 100644 --- a/src/web/src/components/Shared/Graph.jsx +++ b/src/web/src/components/Shared/Graph.jsx @@ -116,8 +116,11 @@ const Graph = ({ data = [], defaultSeries, height = 200, series = [] }) => { new Date(xRange.min).getFullYear() !== new Date(xRange.max).getFullYear(); return (timestamp) => { - const d = new Date(timestamp); - const date = d.toLocaleDateString(undefined, { day: 'numeric', month: 'short' }); + const d = new Date(timestamp); + const date = d.toLocaleDateString(undefined, { + day: 'numeric', + month: 'short', + }); return spansYears ? `${date} '${String(d.getFullYear()).slice(2)}` : date; }; }, [xRange]); diff --git a/src/web/src/lib/reports.test.js b/src/web/src/lib/reports.test.js index 2b73fdca..12bdfd0d 100644 --- a/src/web/src/lib/reports.test.js +++ b/src/web/src/lib/reports.test.js @@ -6,6 +6,9 @@ jest.mock('./api', () => ({ default: { get: jest.fn() }, })); +const urlOf = () => api.get.mock.calls[0][0]; +const parametersOf = () => new URLSearchParams(urlOf().split('?')[1] ?? ''); + describe('reports', () => { beforeEach(() => { api.get.mockResolvedValue({ data: {} }); @@ -15,40 +18,43 @@ describe('reports', () => { jest.clearAllMocks(); }); - const urlOf = () => api.get.mock.calls[0][0]; - const paramsOf = () => new URLSearchParams(urlOf().split('?')[1] ?? ''); - describe('getSummary', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getSummary(); expect(urlOf()).toContain('/telemetry/reports/transfers/summary'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getSummary({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getSummary({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('appends direction when provided', async () => { + expect.hasAssertions(); await reports.getSummary({ direction: 'Upload' }); - expect(paramsOf().get('direction')).toBe('Upload'); + expect(parametersOf().get('direction')).toBe('Upload'); }); it('appends username when provided', async () => { + expect.hasAssertions(); await reports.getSummary({ username: 'testuser' }); - expect(paramsOf().get('username')).toBe('testuser'); + expect(parametersOf().get('username')).toBe('testuser'); }); it('omits optional params when not provided', async () => { + expect.hasAssertions(); await reports.getSummary(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); expect(p.has('direction')).toBe(false); @@ -58,40 +64,47 @@ describe('reports', () => { describe('getHistogram', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getHistogram(); expect(urlOf()).toContain('/telemetry/reports/transfers/histogram'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getHistogram({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getHistogram({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('appends buckets when provided', async () => { + expect.hasAssertions(); await reports.getHistogram({ buckets: 50 }); - expect(paramsOf().get('buckets')).toBe('50'); + expect(parametersOf().get('buckets')).toBe('50'); }); it('appends direction when provided', async () => { + expect.hasAssertions(); await reports.getHistogram({ direction: 'Download' }); - expect(paramsOf().get('direction')).toBe('Download'); + expect(parametersOf().get('direction')).toBe('Download'); }); it('appends username when provided', async () => { + expect.hasAssertions(); await reports.getHistogram({ username: 'testuser' }); - expect(paramsOf().get('username')).toBe('testuser'); + expect(parametersOf().get('username')).toBe('testuser'); }); it('omits optional params when not provided', async () => { + expect.hasAssertions(); await reports.getHistogram(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); expect(p.has('buckets')).toBe(false); @@ -102,50 +115,59 @@ describe('reports', () => { describe('getLeaderboard', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getLeaderboard(); expect(urlOf()).toContain('/telemetry/reports/transfers/leaderboard'); }); it('appends direction when provided', async () => { + expect.hasAssertions(); await reports.getLeaderboard({ direction: 'Upload' }); - expect(paramsOf().get('direction')).toBe('Upload'); + expect(parametersOf().get('direction')).toBe('Upload'); }); it('defaults limit to 10', async () => { + expect.hasAssertions(); await reports.getLeaderboard(); - expect(paramsOf().get('limit')).toBe('10'); + expect(parametersOf().get('limit')).toBe('10'); }); it('appends the specified limit', async () => { + expect.hasAssertions(); await reports.getLeaderboard({ limit: 25 }); - expect(paramsOf().get('limit')).toBe('25'); + expect(parametersOf().get('limit')).toBe('25'); }); it('defaults sortBy to Count', async () => { + expect.hasAssertions(); await reports.getLeaderboard(); - expect(paramsOf().get('sortBy')).toBe('Count'); + expect(parametersOf().get('sortBy')).toBe('Count'); }); it('appends the specified sortBy', async () => { + expect.hasAssertions(); await reports.getLeaderboard({ sortBy: 'TotalBytes' }); - expect(paramsOf().get('sortBy')).toBe('TotalBytes'); + expect(parametersOf().get('sortBy')).toBe('TotalBytes'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getLeaderboard({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getLeaderboard({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('omits start and end when not provided', async () => { + expect.hasAssertions(); await reports.getLeaderboard(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); }); @@ -153,35 +175,41 @@ describe('reports', () => { describe('getTopDirectories', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getTopDirectories(); expect(urlOf()).toContain('/telemetry/reports/transfers/directories'); }); it('defaults limit to 10', async () => { + expect.hasAssertions(); await reports.getTopDirectories(); - expect(paramsOf().get('limit')).toBe('10'); + expect(parametersOf().get('limit')).toBe('10'); }); it('appends the specified limit', async () => { + expect.hasAssertions(); await reports.getTopDirectories({ limit: 20 }); - expect(paramsOf().get('limit')).toBe('20'); + expect(parametersOf().get('limit')).toBe('20'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getTopDirectories({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getTopDirectories({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('omits start and end when not provided', async () => { + expect.hasAssertions(); await reports.getTopDirectories(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); }); @@ -189,40 +217,49 @@ describe('reports', () => { describe('getExceptionPareto', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getExceptionPareto(); - expect(urlOf()).toContain('/telemetry/reports/transfers/exceptions/pareto'); + expect(urlOf()).toContain( + '/telemetry/reports/transfers/exceptions/pareto', + ); }); it('appends direction when provided', async () => { + expect.hasAssertions(); await reports.getExceptionPareto({ direction: 'Download' }); - expect(paramsOf().get('direction')).toBe('Download'); + expect(parametersOf().get('direction')).toBe('Download'); }); it('defaults limit to 10', async () => { + expect.hasAssertions(); await reports.getExceptionPareto(); - expect(paramsOf().get('limit')).toBe('10'); + expect(parametersOf().get('limit')).toBe('10'); }); it('appends the specified limit', async () => { + expect.hasAssertions(); await reports.getExceptionPareto({ limit: 20 }); - expect(paramsOf().get('limit')).toBe('20'); + expect(parametersOf().get('limit')).toBe('20'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getExceptionPareto({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getExceptionPareto({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('omits direction, start, and end when not provided', async () => { + expect.hasAssertions(); await reports.getExceptionPareto(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('direction')).toBe(false); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); @@ -231,51 +268,60 @@ describe('reports', () => { describe('getExceptions', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getExceptions(); expect(urlOf()).toContain('/telemetry/reports/transfers/exceptions'); expect(urlOf()).not.toContain('/exceptions/pareto'); }); it('appends direction when provided', async () => { + expect.hasAssertions(); await reports.getExceptions({ direction: 'Upload' }); - expect(paramsOf().get('direction')).toBe('Upload'); + expect(parametersOf().get('direction')).toBe('Upload'); }); it('defaults limit to 10', async () => { + expect.hasAssertions(); await reports.getExceptions(); - expect(paramsOf().get('limit')).toBe('10'); + expect(parametersOf().get('limit')).toBe('10'); }); it('appends the specified limit', async () => { + expect.hasAssertions(); await reports.getExceptions({ limit: 50 }); - expect(paramsOf().get('limit')).toBe('50'); + expect(parametersOf().get('limit')).toBe('50'); }); it('defaults sortOrder to DESC', async () => { + expect.hasAssertions(); await reports.getExceptions(); - expect(paramsOf().get('sortOrder')).toBe('DESC'); + expect(parametersOf().get('sortOrder')).toBe('DESC'); }); it('appends the specified sortOrder', async () => { + expect.hasAssertions(); await reports.getExceptions({ sortOrder: 'ASC' }); - expect(paramsOf().get('sortOrder')).toBe('ASC'); + expect(parametersOf().get('sortOrder')).toBe('ASC'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getExceptions({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getExceptions({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('omits direction, start, and end when not provided', async () => { + expect.hasAssertions(); await reports.getExceptions(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('direction')).toBe(false); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); -- cgit v1.2.3 From 0ff48cabb1464f171b246225c58d15e8ecdb1e57 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 6 Jul 2026 20:53:42 -0500 Subject: move utility functions to util --- .../components/Dashboard/HistoricalStatistics.jsx | 21 +++--------- src/web/src/components/Dashboard/Leaderboard.jsx | 13 +------- .../src/components/Dashboard/TransferErrors.jsx | 38 ++++------------------ src/web/src/lib/util.js | 11 +++++++ 4 files changed, 23 insertions(+), 60 deletions(-) (limited to 'src/web') diff --git a/src/web/src/components/Dashboard/HistoricalStatistics.jsx b/src/web/src/components/Dashboard/HistoricalStatistics.jsx index b0963082..c14649c4 100644 --- a/src/web/src/components/Dashboard/HistoricalStatistics.jsx +++ b/src/web/src/components/Dashboard/HistoricalStatistics.jsx @@ -1,3 +1,4 @@ +import { formatBytes, formatSpeed } from '../../lib/util'; import { Graph, LoaderSegment } from '../Shared'; import Leaderboard from './Leaderboard'; import TopDirectories from './TopDirectories'; @@ -6,7 +7,6 @@ import React, { useMemo } from 'react'; import { Button, ButtonGroup, - Divider, Header, Icon, Segment, @@ -14,18 +14,6 @@ import { Tab, } from 'semantic-ui-react'; -const formatBytes = (bytes) => { - if (!bytes || bytes === 0) return '0 B'; - const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; - const index = Math.floor(Math.log(bytes) / Math.log(1_024)); - return `${(bytes / 1_024 ** index).toFixed(1)} ${units[index]}`; -}; - -const formatSpeed = (bytesPerSecond) => { - if (!bytesPerSecond || bytesPerSecond === 0) return '0 B/s'; - return `${formatBytes(bytesPerSecond)}/s`; -}; - const formatBytesParts = (bytes) => { if (!bytes || bytes === 0) return { unit: 'B', value: '0' }; const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; @@ -82,14 +70,14 @@ const buildChartData = (histogram) => const HISTORY_SERIES = [ { color: '#21ba45', - format: formatBytes, + format: (v) => formatBytes(v, 1), key: 'uploadBytes', name: 'Upload Size', unit: 'bytes', }, { color: '#2185d0', - format: formatBytes, + format: (v) => formatBytes(v, 1), key: 'downloadBytes', name: 'Download Size', unit: 'bytes', @@ -226,6 +214,8 @@ const HistoricalStatistics = ({ @@ -336,7 +326,6 @@ const HistoricalStatistics = ({ series={HISTORY_SERIES} /> - onTabChange(activeIndex)} diff --git a/src/web/src/components/Dashboard/Leaderboard.jsx b/src/web/src/components/Dashboard/Leaderboard.jsx index b983dc5a..a7fa6662 100644 --- a/src/web/src/components/Dashboard/Leaderboard.jsx +++ b/src/web/src/components/Dashboard/Leaderboard.jsx @@ -1,19 +1,8 @@ import * as reports from '../../lib/reports'; +import { formatBytes, formatSpeed } from '../../lib/util'; import React, { useEffect, useState } from 'react'; import { Divider, Grid, Header, Icon, Loader, Table } from 'semantic-ui-react'; -const formatBytes = (bytes) => { - if (!bytes || bytes === 0) return '0 B'; - const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; - const index = Math.floor(Math.log(bytes) / Math.log(1_024)); - return `${(bytes / 1_024 ** index).toFixed(1)} ${units[index]}`; -}; - -const formatSpeed = (bytesPerSecond) => { - if (!bytesPerSecond || bytesPerSecond === 0) return '0 B/s'; - return `${formatBytes(bytesPerSecond)}/s`; -}; - const SORT_FIELDS = [ { label: 'Count', sort: 'Count' }, { label: 'Total Size', sort: 'TotalBytes' }, diff --git a/src/web/src/components/Dashboard/TransferErrors.jsx b/src/web/src/components/Dashboard/TransferErrors.jsx index 5fa0408c..54dc9a20 100644 --- a/src/web/src/components/Dashboard/TransferErrors.jsx +++ b/src/web/src/components/Dashboard/TransferErrors.jsx @@ -1,35 +1,9 @@ -import { Graph, useDarkMode } from '../Shared'; -import React, { useMemo } from 'react'; -import { Divider, Header, Table } from 'semantic-ui-react'; - -const truncate = (text, maxLength) => { - if (!text) { - return ''; - } - - if (text.length <= maxLength) { - return text; - } - - return `${text.slice(0, maxLength)}…`; -}; - -const getFilename = (path) => { - if (!path) { - return ''; - } - - const parts = path.replaceAll('\\', '/').split('/'); - return parts[parts.length - 1] || path; -}; - -const formatDateTime = (isoString) => { - if (!isoString) { - return ''; - } - - return new Date(isoString).toLocaleString(); -}; +import * as reports from '../../lib/reports'; +import { Graph } from '../Shared'; +import ExceptionList from './ExceptionList'; +import ExceptionPareto from './ExceptionPareto'; +import React, { useEffect, useMemo, useState } from 'react'; +import { Header, Icon } from 'semantic-ui-react'; const mergePareto = (uploadRows, downloadRows) => { const combined = {}; diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js index 091a8207..b499f81e 100644 --- a/src/web/src/lib/util.js +++ b/src/web/src/lib/util.js @@ -39,10 +39,21 @@ export const formatBytes = ( return padded + ' ' + sizes[index]; }; +export const formatSpeed = (bytesPerSecond, decimals = 1) => { + if (!bytesPerSecond || bytesPerSecond === 0) return '0 B/s'; + return `${formatBytes(bytesPerSecond, decimals)}/s`; +}; + export const formatDate = (date) => { return new Date(date).toLocaleString(); }; +export const truncate = (text, maxLength) => { + if (!text) return ''; + if (text.length <= maxLength) return text; + return `${text.slice(0, maxLength)}...`; +}; + export const getFileName = (fullPath) => { return fullPath.split('\\').pop().split('/').pop(); }; -- cgit v1.2.3 From e86882aa36e403e32f1789ed47dc698a51eba0d8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 6 Jul 2026 21:19:52 -0500 Subject: tweak componensts for consistency --- src/web/src/components/Dashboard/ExceptionList.jsx | 96 ++++++++ .../src/components/Dashboard/ExceptionPareto.jsx | 110 +++++++++ src/web/src/components/Dashboard/Leaderboard.jsx | 35 ++- .../src/components/Dashboard/TopDirectories.jsx | 93 ++++---- .../src/components/Dashboard/TransferErrors.jsx | 248 +++++++++------------ 5 files changed, 374 insertions(+), 208 deletions(-) create mode 100644 src/web/src/components/Dashboard/ExceptionList.jsx create mode 100644 src/web/src/components/Dashboard/ExceptionPareto.jsx (limited to 'src/web') diff --git a/src/web/src/components/Dashboard/ExceptionList.jsx b/src/web/src/components/Dashboard/ExceptionList.jsx new file mode 100644 index 00000000..d0412006 --- /dev/null +++ b/src/web/src/components/Dashboard/ExceptionList.jsx @@ -0,0 +1,96 @@ +import { formatDate, getFileName, truncate } from '../../lib/util'; +import React from 'react'; +import { + Button, + ButtonGroup, + Header, + Icon, + Loader, + Table, +} from 'semantic-ui-react'; + +const DIRECTIONS = ['Upload', 'Download', 'All']; + +const ExceptionList = ({ direction, loading, onDirectionChange, rows }) => ( + <> +
+ + Recent Errors + + {DIRECTIONS.map((d) => ( + + ))} + +
+ + + + Time + Direction + Username + Filename + Exception + + + + {loading && ( + + + + + + )} + {rows.length === 0 && !loading && ( + + + No data to display + + + )} + {!loading && + rows.map((row) => ( + + + {row.endedAt ? formatDate(row.endedAt) : ''} + + {row.direction} + {row.username} + + {row.filename ? getFileName(row.filename) : ''} + + + {truncate(row.exception, 80)} + + + ))} + +
+ +); + +export default ExceptionList; diff --git a/src/web/src/components/Dashboard/ExceptionPareto.jsx b/src/web/src/components/Dashboard/ExceptionPareto.jsx new file mode 100644 index 00000000..13fafb5a --- /dev/null +++ b/src/web/src/components/Dashboard/ExceptionPareto.jsx @@ -0,0 +1,110 @@ +import { truncate } from '../../lib/util'; +import React from 'react'; +import { + Button, + ButtonGroup, + Header, + Icon, + Loader, + Progress, + Table, +} from 'semantic-ui-react'; + +const DIRECTIONS = ['Upload', 'Download', 'All']; + +const ExceptionPareto = ({ direction, loading, onDirectionChange, rows }) => { + const maxCount = rows.length > 0 ? rows[0].count : 1; + + return ( + <> +
+ + Error Count By Type + + {DIRECTIONS.map((d) => ( + + ))} + +
+ + + + Direction + Exception + + Count + + Distinct Users + + + + + {loading && ( + + + + + + )} + {!loading && rows.length === 0 && ( + + + No data to display + + + )} + {!loading && + rows.map((row) => ( + + {row.direction} + + {truncate(row.exception, 80)} + + + + + + {row.count.toLocaleString()} + + + {row.distinctUsers.toLocaleString()} + + + ))} + +
+ + ); +}; + +export default ExceptionPareto; diff --git a/src/web/src/components/Dashboard/Leaderboard.jsx b/src/web/src/components/Dashboard/Leaderboard.jsx index a7fa6662..4a37870c 100644 --- a/src/web/src/components/Dashboard/Leaderboard.jsx +++ b/src/web/src/components/Dashboard/Leaderboard.jsx @@ -129,30 +129,27 @@ const Leaderboard = ({ downloads, end, start, uploads }) => { const startDate = start ? new Date(start) : undefined; const endDate = end ? new Date(end) : new Date(); - const [newUploads, newDownloads] = await Promise.all([ - reports - .getLeaderboard({ + let newUploads = state.rows.upload; + let newDownloads = state.rows.download; + + try { + [newUploads, newDownloads] = await Promise.all([ + reports.getLeaderboard({ direction: 'Upload', end: endDate, sortBy: sort, start: startDate, - }) - .catch((error) => { - console.error(error); - return state.rows.upload; }), - reports - .getLeaderboard({ + reports.getLeaderboard({ direction: 'Download', end: endDate, sortBy: sort, start: startDate, - }) - .catch((error) => { - console.error(error); - return state.rows.download; }), - ]); + ]); + } catch (error) { + console.error(error); + } setState((previous) => ({ ...previous, @@ -167,10 +164,7 @@ const Leaderboard = ({ downloads, end, start, uploads }) => { stackable > -
+
Downloads
{ -
+
Uploads
{ if (!path) { @@ -16,56 +16,61 @@ const getLastTwoSegments = (path) => { }; const TopDirectories = ({ rows }) => ( - - - - - # - - Directory - Downloads - Distinct Users - - - - {(!rows || rows.length === 0) && ( + <> +
+ Directories +
+
+ - - No data to display - + # + + Directory + Downloads + Distinct Users - )} - {rows && - rows.map((row, index) => ( - + + + {(!rows || rows.length === 0) && ( + - {index + 1} - - - {getLastTwoSegments(row.directory)} - - - {row.count.toLocaleString()} - - - {row.distinctUsers.toLocaleString()} + No data to display - ))} - -
+ )} + {rows && + rows.map((row, index) => ( + + + {index + 1} + + + {getLastTwoSegments(row.directory)} + + + {row.count.toLocaleString()} + + + {row.distinctUsers.toLocaleString()} + + + ))} + + + ); export default TopDirectories; diff --git a/src/web/src/components/Dashboard/TransferErrors.jsx b/src/web/src/components/Dashboard/TransferErrors.jsx index 54dc9a20..7def5ca6 100644 --- a/src/web/src/components/Dashboard/TransferErrors.jsx +++ b/src/web/src/components/Dashboard/TransferErrors.jsx @@ -5,23 +5,13 @@ import ExceptionPareto from './ExceptionPareto'; import React, { useEffect, useMemo, useState } from 'react'; import { Header, Icon } from 'semantic-ui-react'; -const mergePareto = (uploadRows, downloadRows) => { - const combined = {}; - for (const row of [...(uploadRows || []), ...(downloadRows || [])]) { - const key = row.exception ?? ''; - combined[key] = combined[key] - ? { - exception: key, - count: combined[key].count + row.count, - distinctUsers: combined[key].distinctUsers + row.distinctUsers, - } - : { ...row }; - } - - return Object.values(combined) +const buildParetoRows = (uploadRows, downloadRows) => + [ + ...(uploadRows || []).map((r) => ({ ...r, direction: 'Upload' })), + ...(downloadRows || []).map((r) => ({ ...r, direction: 'Download' })), + ] .sort((a, b) => b.count - a.count) .slice(0, 10); -}; const mergeRecent = (uploadRows, downloadRows) => [ @@ -50,148 +40,122 @@ const ERRORS_SERIES = [ const DEFAULT_ERRORS_SERIES = new Set(['uploadErrors', 'downloadErrors']); -const TransferErrors = ({ chartData, download, upload }) => { - const isDark = useDarkMode(); +const RECENT_PAGE_SIZE = 10; + +const TransferErrors = ({ chartData, download, end, start, upload }) => { + const [paretoDirection, setParetoDirection] = useState('All'); + const [paretoRows, setParetoRows] = useState(null); + const [paretoLoading, setParetoLoading] = useState(false); - const paretoRows = useMemo( - () => mergePareto(upload.pareto, download.pareto), + const [recentDirection, setRecentDirection] = useState('All'); + const [recentRows, setRecentRows] = useState(null); + const [recentLoading, setRecentLoading] = useState(false); + + useEffect(() => { + setParetoDirection('All'); + setParetoRows(null); + setRecentDirection('All'); + setRecentRows(null); + }, [end, start]); + + const initialParetoRows = useMemo( + () => buildParetoRows(upload.pareto, download.pareto), [upload.pareto, download.pareto], ); - const recentRows = useMemo( + + const initialRecentRows = useMemo( () => mergeRecent(upload.recent, download.recent), [upload.recent, download.recent], ); - const maxParetoCount = - paretoRows && paretoRows.length > 0 ? paretoRows[0].count : 1; + const displayedParetoRows = paretoRows ?? initialParetoRows; + const displayedRecentRows = recentRows ?? initialRecentRows; + + const fetchPareto = async (direction) => { + try { + return await reports.getExceptionPareto({ + direction, + end: new Date(end), + start: start ? new Date(start) : undefined, + }); + } catch (error) { + console.error(error); + return []; + } + }; + + const fetchRecent = async (direction) => { + try { + return await reports.getExceptions({ + direction, + end: new Date(end), + limit: RECENT_PAGE_SIZE, + start: start ? new Date(start) : undefined, + }); + } catch (error) { + console.error(error); + return []; + } + }; + + const onParetoDirectionChange = async (d) => { + setParetoDirection(d); + setParetoLoading(true); + + if (d === 'All') { + const [uploadRows, downloadRows] = await Promise.all([ + fetchPareto('Upload'), + fetchPareto('Download'), + ]); + setParetoRows(buildParetoRows(uploadRows, downloadRows)); + } else { + const rows = await fetchPareto(d); + setParetoRows(rows.map((r) => ({ ...r, direction: d }))); + } + + setParetoLoading(false); + }; + + const onRecentDirectionChange = async (d) => { + setRecentDirection(d); + setRecentLoading(true); + + if (d === 'All') { + const [uploadRows, downloadRows] = await Promise.all([ + fetchRecent('Upload'), + fetchRecent('Download'), + ]); + setRecentRows(mergeRecent(uploadRows, downloadRows)); + } else { + const rows = await fetchRecent(d); + setRecentRows(rows.map((r) => ({ ...r, direction: d }))); + } + + setRecentLoading(false); + }; return (
-
Error Count Over Time
+
+ Errors +
- -
- Top Fault Types - - pareto - -
- - - - Exception - - Count - - Distinct Users - - - - - {(!paretoRows || paretoRows.length === 0) && ( - - - No data to display - - - )} - {paretoRows && - paretoRows.map((row) => ( - - - {truncate(row.exception, 80)} - - -
-
-
- - - {row.count.toLocaleString()} - - - {row.distinctUsers.toLocaleString()} - - - ))} - -
- -
Recent Errors
- - - - Time - Direction - Username - Filename - Exception - - - - {(!recentRows || recentRows.length === 0) && ( - - - No data to display - - - )} - {recentRows && - recentRows.map((row) => ( - - - {formatDateTime(row.endedAt)} - - {row.direction} - {row.username} - - {getFilename(row.filename)} - - - {truncate(row.exception, 80)} - - - ))} - -
+ +
); }; -- cgit v1.2.3 From 5bc50e07cfb9d2bdbc0c8f90d6a6eda24158076e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 7 Jul 2026 10:26:58 -0500 Subject: remove StartOffset --- .../Telemetry/Types/TransferExceptionDetail.cs | 1 - .../components/Dashboard/HistoricalStatistics.jsx | 8 +- src/web/src/components/Dashboard/Leaderboard.jsx | 7 +- src/web/src/components/Dashboard/SearchBar.jsx | 6 +- .../src/components/Dashboard/TransferErrors.jsx | 48 +++++----- src/web/src/components/Shared/Graph.jsx | 19 +--- src/web/src/lib/util.js | 6 ++ .../Telemetry/ReportsServiceTests.cs | 104 +++++++++++++++++++++ 8 files changed, 148 insertions(+), 51 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Telemetry/ReportsServiceTests.cs (limited to 'src/web') diff --git a/src/slskd/Telemetry/Types/TransferExceptionDetail.cs b/src/slskd/Telemetry/Types/TransferExceptionDetail.cs index af20cc63..ea0b2a67 100644 --- a/src/slskd/Telemetry/Types/TransferExceptionDetail.cs +++ b/src/slskd/Telemetry/Types/TransferExceptionDetail.cs @@ -42,7 +42,6 @@ public record TransferExceptionDetail public TransferDirection Direction { get; init; } public string Filename { get; init; } public long Size { get; set; } - public long StartOffset { get; init; } public TransferStates State { get; set; } = TransferStates.None; public DateTime RequestedAt { get; set; } public DateTime? EnqueuedAt { get; set; } diff --git a/src/web/src/components/Dashboard/HistoricalStatistics.jsx b/src/web/src/components/Dashboard/HistoricalStatistics.jsx index c14649c4..a640fc1b 100644 --- a/src/web/src/components/Dashboard/HistoricalStatistics.jsx +++ b/src/web/src/components/Dashboard/HistoricalStatistics.jsx @@ -1,4 +1,4 @@ -import { formatBytes, formatSpeed } from '../../lib/util'; +import { formatBytes, formatSpeed, formatWait } from '../../lib/util'; import { Graph, LoaderSegment } from '../Shared'; import Leaderboard from './Leaderboard'; import TopDirectories from './TopDirectories'; @@ -32,12 +32,6 @@ const errorCount = (directionData = {}) => (directionData.Cancelled?.count ?? 0) + (directionData.TimedOut?.count ?? 0); -const formatWait = (seconds) => { - if (!seconds || seconds === 0) return '0s'; - if (seconds < 60) return `${Math.round(seconds)}s`; - return `${(seconds / 60).toFixed(1)}m`; -}; - const buildChartData = (histogram) => Object.entries(histogram) .sort(([a], [b]) => new Date(a) - new Date(b)) diff --git a/src/web/src/components/Dashboard/Leaderboard.jsx b/src/web/src/components/Dashboard/Leaderboard.jsx index 4a37870c..a3df7d2c 100644 --- a/src/web/src/components/Dashboard/Leaderboard.jsx +++ b/src/web/src/components/Dashboard/Leaderboard.jsx @@ -1,6 +1,6 @@ import * as reports from '../../lib/reports'; import { formatBytes, formatSpeed } from '../../lib/util'; -import React, { useEffect, useState } from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import { Divider, Grid, Header, Icon, Loader, Table } from 'semantic-ui-react'; const SORT_FIELDS = [ @@ -108,6 +108,7 @@ const initialState = { const Leaderboard = ({ downloads, end, start, uploads }) => { const [state, setState] = useState(initialState); + const sortRef = useRef(null); useEffect(() => { setState((previous) => ({ @@ -120,6 +121,8 @@ const Leaderboard = ({ downloads, end, start, uploads }) => { const onSort = async (sort) => { if (sort === state.sortBy) return; + sortRef.current = sort; + setState((previous) => ({ ...previous, sortBy: sort, @@ -151,6 +154,8 @@ const Leaderboard = ({ downloads, end, start, uploads }) => { console.error(error); } + if (sortRef.current !== sort) return; + setState((previous) => ({ ...previous, rows: { upload: newUploads, download: newDownloads }, diff --git a/src/web/src/components/Dashboard/SearchBar.jsx b/src/web/src/components/Dashboard/SearchBar.jsx index e8c0b7e4..43e7d18a 100644 --- a/src/web/src/components/Dashboard/SearchBar.jsx +++ b/src/web/src/components/Dashboard/SearchBar.jsx @@ -1,7 +1,7 @@ import '../Search/Search.css'; import { urlBase } from '../../config'; import * as library from '../../lib/searches'; -import React, { useRef, useState } from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import { Link, useHistory } from 'react-router-dom'; import { toast } from 'react-toastify'; import { Button, Icon, Input, Segment } from 'semantic-ui-react'; @@ -48,7 +48,9 @@ const SearchBar = ({ server } = {}) => { } }; - inputRef?.current?.inputRef?.current?.focus(); + useEffect(() => { + inputRef?.current?.inputRef?.current?.focus(); + }, []); return ( { setParetoDirection(d); setParetoLoading(true); - if (d === 'All') { - const [uploadRows, downloadRows] = await Promise.all([ - fetchPareto('Upload'), - fetchPareto('Download'), - ]); - setParetoRows(buildParetoRows(uploadRows, downloadRows)); - } else { - const rows = await fetchPareto(d); - setParetoRows(rows.map((r) => ({ ...r, direction: d }))); + try { + if (d === 'All') { + const [uploadRows, downloadRows] = await Promise.all([ + fetchPareto('Upload'), + fetchPareto('Download'), + ]); + setParetoRows(buildParetoRows(uploadRows, downloadRows)); + } else { + const rows = await fetchPareto(d); + setParetoRows(rows.map((r) => ({ ...r, direction: d }))); + } + } finally { + setParetoLoading(false); } - - setParetoLoading(false); }; const onRecentDirectionChange = async (d) => { setRecentDirection(d); setRecentLoading(true); - if (d === 'All') { - const [uploadRows, downloadRows] = await Promise.all([ - fetchRecent('Upload'), - fetchRecent('Download'), - ]); - setRecentRows(mergeRecent(uploadRows, downloadRows)); - } else { - const rows = await fetchRecent(d); - setRecentRows(rows.map((r) => ({ ...r, direction: d }))); + try { + if (d === 'All') { + const [uploadRows, downloadRows] = await Promise.all([ + fetchRecent('Upload'), + fetchRecent('Download'), + ]); + setRecentRows(mergeRecent(uploadRows, downloadRows)); + } else { + const rows = await fetchRecent(d); + setRecentRows(rows.map((r) => ({ ...r, direction: d }))); + } + } finally { + setRecentLoading(false); } - - setRecentLoading(false); }; return ( diff --git a/src/web/src/components/Shared/Graph.jsx b/src/web/src/components/Shared/Graph.jsx index 4d672d3d..0f753b72 100644 --- a/src/web/src/components/Shared/Graph.jsx +++ b/src/web/src/components/Shared/Graph.jsx @@ -1,3 +1,4 @@ +import { formatBytes, formatSpeed, formatWait } from '../../lib/util'; import React, { useEffect, useMemo, useState } from 'react'; import { Area, @@ -26,24 +27,6 @@ export const useDarkMode = () => { return isDark; }; -const formatBytes = (bytes) => { - if (!bytes || bytes === 0) return '0 B'; - const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; - const index = Math.floor(Math.log(bytes) / Math.log(1_024)); - return `${(bytes / 1_024 ** index).toFixed(1)} ${units[index]}`; -}; - -const formatSpeed = (bytesPerSecond) => { - if (!bytesPerSecond || bytesPerSecond === 0) return '0 B/s'; - return `${formatBytes(bytesPerSecond)}/s`; -}; - -const formatWait = (seconds) => { - if (!seconds || seconds === 0) return '0s'; - if (seconds < 60) return `${Math.round(seconds)}s`; - return `${(seconds / 60).toFixed(1)}m`; -}; - const UNIT_FORMATTERS = { bytes: formatBytes, count: (v) => v.toLocaleString(), diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js index b499f81e..854e625e 100644 --- a/src/web/src/lib/util.js +++ b/src/web/src/lib/util.js @@ -44,6 +44,12 @@ export const formatSpeed = (bytesPerSecond, decimals = 1) => { return `${formatBytes(bytesPerSecond, decimals)}/s`; }; +export const formatWait = (seconds) => { + if (!seconds || seconds === 0) return '0s'; + if (seconds < 60) return `${Math.round(seconds)}s`; + return `${(seconds / 60).toFixed(1)}m`; +}; + export const formatDate = (date) => { return new Date(date).toLocaleString(); }; diff --git a/tests/slskd.Tests.Unit/Telemetry/ReportsServiceTests.cs b/tests/slskd.Tests.Unit/Telemetry/ReportsServiceTests.cs new file mode 100644 index 00000000..9173b0e9 --- /dev/null +++ b/tests/slskd.Tests.Unit/Telemetry/ReportsServiceTests.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Dapper; +using Microsoft.Data.Sqlite; +using slskd.Telemetry; +using Soulseek; +using Xunit; + +namespace slskd.Tests.Unit.Telemetry; + +public class ReportsServiceTests : IDisposable +{ + private readonly SqliteConnection _anchor; + private readonly string _connectionString; + + public ReportsServiceTests() + { + var dbName = $"test_{Guid.NewGuid():N}"; + _connectionString = $"Data Source={dbName};Mode=Memory;Cache=Shared"; + + _anchor = new SqliteConnection(_connectionString); + _anchor.Open(); + + _anchor.Execute(@" + CREATE TABLE Transfers ( + Id TEXT PRIMARY KEY, + Username TEXT NOT NULL, + Direction TEXT NOT NULL, + Filename TEXT NOT NULL, + Size INTEGER NOT NULL DEFAULT 0, + State INTEGER NOT NULL DEFAULT 0, + StateDescription TEXT, + RequestedAt TEXT, + EnqueuedAt TEXT, + StartedAt TEXT, + EndedAt TEXT, + BytesTransferred INTEGER NOT NULL DEFAULT 0, + AverageSpeed REAL NOT NULL DEFAULT 0.0, + PlaceInQueue INTEGER, + Exception TEXT, + Removed INTEGER NOT NULL DEFAULT 0, + BatchId TEXT, + Attempts INTEGER NOT NULL DEFAULT 0, + NextAttemptAt TEXT + )"); + } + + public void Dispose() + { + _anchor.Dispose(); + } + + private ReportsService CreateService() => + new(new ConnectionStringDictionary( + new Dictionary { { Database.Transfers, _connectionString } })); + + [Fact] + public void GetTransferHistogram_DropsTransfersInFirstPartialBucket_WhenStartIsNotOnUnixBucketBoundary() + { + // start = 2026-01-04T00:00:00Z has Unix-epoch offset mod 6048 = 4320 seconds, + // so the first SQL bucket floor-snaps to 2026-01-03T22:33:36Z. The C# re-snap + // of that datetime gives 2026-01-03T21:07:12Z — a full 6048 s before the C# + // pre-fill first key (2026-01-03T22:48:00Z) — so TryGetValue misses and the + // transfer is silently dropped. + var state = TransferStates.Completed | TransferStates.Succeeded; + + _anchor.Execute(@" + INSERT INTO Transfers (Id, Username, Direction, Filename, Size, State, StateDescription, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, AverageSpeed) + VALUES (@Id, @Username, @Direction, @Filename, @Size, @State, @StateDescription, + @RequestedAt, @EnqueuedAt, @StartedAt, @EndedAt, @BytesTransferred, @AverageSpeed)", + new + { + Id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + Username = "testuser", + Direction = TransferDirection.Upload.ToString(), + Filename = "test.mp3", + Size = 1_048_576L, + State = (int)state, + StateDescription = state.ToString(), + RequestedAt = "2026-01-04 00:00:00", + EnqueuedAt = "2026-01-04 00:00:00", + StartedAt = "2026-01-04 00:01:00", + EndedAt = "2026-01-04 00:10:00", + BytesTransferred = 1_048_576L, + AverageSpeed = 1748.0, + }); + + var sut = CreateService(); + + var start = new DateTime(2026, 1, 4, 0, 0, 0, DateTimeKind.Utc); + var end = new DateTime(2026, 1, 11, 0, 0, 0, DateTimeKind.Utc); + + var histogram = sut.GetTransferHistogram(start: start, end: end, buckets: 100); + + var totalCount = histogram.Values + .SelectMany(directions => directions.Values) + .SelectMany(states => states.Values) + .Sum(summary => summary.Count); + + Assert.Equal(1, totalCount); + } +} -- cgit v1.2.3 From 1abc6ec12de826240cd0edfa478705241b2dabed Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 7 Jul 2026 14:21:49 -0500 Subject: fix bug preventing a user from initiating a chat --- src/web/src/components/Chat/Chat.jsx | 2 +- src/web/src/components/Chat/SendMessageModal.jsx | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) (limited to 'src/web') diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx index 39dd1a44..9224fb30 100644 --- a/src/web/src/components/Chat/Chat.jsx +++ b/src/web/src/components/Chat/Chat.jsx @@ -217,7 +217,7 @@ class Chat extends Component { }; initiateConversation = async (username, message) => { - await this.sendMessage(username, message); + await chat.send({ username, message }); await this.fetchConversations(); this.selectConversation(username); }; diff --git a/src/web/src/components/Chat/SendMessageModal.jsx b/src/web/src/components/Chat/SendMessageModal.jsx index 203b2d06..309f1759 100644 --- a/src/web/src/components/Chat/SendMessageModal.jsx +++ b/src/web/src/components/Chat/SendMessageModal.jsx @@ -1,10 +1,9 @@ import './Chat.css'; -import React, { useEffect } from 'react'; +import React, { useEffect, useRef } from 'react'; import { Button, Form, Header, Icon, Input, Modal } from 'semantic-ui-react'; -const usernameRef = React.createRef(); - const SendMessageModal = ({ initiateConversation, ...rest }) => { + const usernameRef = useRef(); const [open, setOpen] = React.useState(false); const [username, setUsername] = React.useState(''); const [message, setMessage] = React.useState(''); -- cgit v1.2.3 From a306f157a05da6fcb8798018d7be67c59a129be5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 9 Jul 2026 13:10:57 -0500 Subject: quiet noise --- src/web/.eslintrc.js | 1 + 1 file changed, 1 insertion(+) (limited to 'src/web') diff --git a/src/web/.eslintrc.js b/src/web/.eslintrc.js index 0b0f9fb6..a39caf8e 100644 --- a/src/web/.eslintrc.js +++ b/src/web/.eslintrc.js @@ -8,6 +8,7 @@ const overrides = { 'react/prop-types': 'off', // noisy 'canonical/sort-keys': 'off', // noisy 'unicorn/no-array-reduce': 'off', // noisy + 'unicorn/prevent-abbreviations': 'off', }; /** @type {import('eslint').Linter.Config} */ -- cgit v1.2.3 From 9584bc07cdc4ce5e94ec29273d07a1c67904fdda Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 10 Jul 2026 20:22:20 -0500 Subject: add enqueueBatch() --- src/web/src/lib/transfers.js | 61 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 50 insertions(+), 11 deletions(-) (limited to 'src/web') diff --git a/src/web/src/lib/transfers.js b/src/web/src/lib/transfers.js index 7fa58fc3..361926ae 100644 --- a/src/web/src/lib/transfers.js +++ b/src/web/src/lib/transfers.js @@ -20,6 +20,42 @@ export const download = ({ username, files = [] }) => { ); }; +/** + * Enqueues a batch of downloads. + * @param {object} params + * @param {string} params.username - The user to download from. + * @param {{ filename: string, size: number }[]} [params.files] - Files to enqueue. + * @param {string} [params.id] - Optional batch GUID. Generated server-side if omitted. + * @param {string} [params.searchId] - Optional GUID of an associated search. + * @param {{ destination?: string, externalId?: string }} [params.options] - `destination`: path relative to the configured download directory; `externalId`: optional external identifier for the batch. + * @returns {Promise} Resolves with the axios response. + * - 201: all files enqueued successfully + * - 200: batch created, but every file failed to enqueue — check `response.data.failures` + * - 207: partial — some enqueued, some failed — check `response.data.failures` + * @throws On error responses: + * - 400: validation failure (username/files required; duplicate filenames; id or searchId not a valid GUID) + * - 403: forbidden — running as relay agent + * - 404: user is offline + * - 409: a batch with the supplied id already exists + * - 429: a concurrent enqueue request is already in progress + * - 500: unexpected server error + */ +export const enqueueBatch = ({ + username, + files = [], + id, + searchId, + options = { destination: undefined, externalId: undefined }, +}) => { + return api.post('/transfers/downloads/batches', { + files, + id, + options, + searchId, + username, + }); +}; + export const cancel = ({ direction, username, id, remove = false }) => { return api.delete( `/transfers/${direction}s/${encodeURIComponent(username)}/${encodeURIComponent(id)}?remove=${remove}`, @@ -30,23 +66,26 @@ export const clearCompleted = ({ direction }) => { return api.delete(`/transfers/${direction}s/all/completed`); }; -// 'Requested' -// 'Queued, Remotely' -// 'Queued, Locally' -// 'Initializing' -// 'InProgress' -// 'Completed, Succeeded' -// 'Completed, Cancelled' -// 'Completed, TimedOut' -// 'Completed, Errored' -// 'Completed, Rejected' - export const getPlaceInQueue = ({ username, id }) => { return api.get( `/transfers/downloads/${encodeURIComponent(username)}/${encodeURIComponent(id)}/position`, ); }; +/* + states: + + 'Requested' + 'Queued, Remotely' + 'Queued, Locally' + 'Initializing' + 'InProgress' + 'Completed, Succeeded' + 'Completed, Cancelled' + 'Completed, TimedOut' + 'Completed, Errored' + 'Completed, Rejected' +*/ export const isStateRetryable = (state) => state.includes('Completed') && state !== 'Completed, Succeeded'; -- cgit v1.2.3 From 0f5fc71a0f956b4984c42d8d830f130bd32bf814 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 Jul 2026 13:30:09 -0500 Subject: replace Directory with Selection --- src/web/src/components/Browse/Directory.jsx | 136 ----------------- src/web/src/components/Browse/Selection.jsx | 221 ++++++++++++++++++++++++++++ 2 files changed, 221 insertions(+), 136 deletions(-) delete mode 100644 src/web/src/components/Browse/Directory.jsx create mode 100644 src/web/src/components/Browse/Selection.jsx (limited to 'src/web') diff --git a/src/web/src/components/Browse/Directory.jsx b/src/web/src/components/Browse/Directory.jsx deleted file mode 100644 index ed88f131..00000000 --- a/src/web/src/components/Browse/Directory.jsx +++ /dev/null @@ -1,136 +0,0 @@ -import * as transfers from '../../lib/transfers'; -import { formatBytes } from '../../lib/util'; -import FileList from '../Shared/FileList'; -import React, { Component } from 'react'; -import { Button, Card, Icon, Label } from 'semantic-ui-react'; - -const initialState = { - downloadError: '', - downloadRequest: undefined, -}; - -class Directory extends Component { - constructor(props) { - super(props); - - this.state = { - ...initialState, - files: this.props.files.map((f) => ({ selected: false, ...f })), - }; - } - - componentDidUpdate(previousProps) { - if (this.props.name !== previousProps.name) { - this.setState({ - files: this.props.files.map((f) => ({ selected: false, ...f })), - }); - } - } - - handleFileSelectionChange = (file, state) => { - file.selected = state; - this.setState((previousState) => ({ - downloadError: '', - downloadRequest: undefined, - tree: previousState.tree, - })); - }; - - download = (username, files) => { - this.setState({ downloadRequest: 'inProgress' }, async () => { - try { - const requests = (files || []).map(({ filename, size }) => ({ - filename, - size, - })); - await transfers.download({ files: requests, username }); - - this.setState({ downloadRequest: 'complete' }); - } catch (error) { - this.setState({ - downloadError: error.response, - downloadRequest: 'error', - }); - } - }); - }; - - render() { - const { locked, marginTop, name, onClose, username } = this.props; - const { downloadError, downloadRequest, files } = this.state; - - const selectedFiles = files.filter((f) => f.selected); - - const selectedSize = formatBytes( - selectedFiles.reduce((total, f) => total + f.size, 0), - ); - - return ( - - -
- -
-
- {selectedFiles.length > 0 && ( - - -