aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-05-22 15:40:36 -0500
committerGitHub <noreply@github.com>2022-05-22 15:40:36 -0500
commitc9968c85dcbaab05d50dbbb1f0cdd4d9bd1b6d65 (patch)
tree89affaef890b667c8162e9fe0990da6f79108e5d
parent451b9df55a1ec073b5b8f5a74e41c1053e47f2c8 (diff)
parent044c4c5bb2be3b0a310154cdaf14feb0ea66c55a (diff)
downloadslskd-c9968c85dcbaab05d50dbbb1f0cdd4d9bd1b6d65.tar.gz
Merge pull request #482 from slskd/lint
Add ESLint and fix linting errors
-rw-r--r--src/web/.eslintrc30
-rw-r--r--src/web/package-lock.json129
-rw-r--r--src/web/package.json22
-rw-r--r--src/web/src/components/App.js39
-rw-r--r--src/web/src/components/Browse/Browse.js78
-rw-r--r--src/web/src/components/Browse/Directory.js18
-rw-r--r--src/web/src/components/Browse/DirectoryTree.js52
-rw-r--r--src/web/src/components/Chat/Chat.js127
-rw-r--r--src/web/src/components/Chat/ChatMenu.js2
-rw-r--r--src/web/src/components/Chat/SendMessageModal.js12
-rw-r--r--src/web/src/components/LoginForm.js6
-rw-r--r--src/web/src/components/Rooms/RoomJoinModal.js92
-rw-r--r--src/web/src/components/Rooms/RoomMenu.js2
-rw-r--r--src/web/src/components/Rooms/RoomUserList.js2
-rw-r--r--src/web/src/components/Rooms/Rooms.js141
-rw-r--r--src/web/src/components/Search/Detail/SearchDetail.js24
-rw-r--r--src/web/src/components/Search/Detail/SearchDetailHeader.js13
-rw-r--r--src/web/src/components/Search/List/SearchList.js56
-rw-r--r--src/web/src/components/Search/List/SearchListRow.js2
-rw-r--r--src/web/src/components/Search/Response.js242
-rw-r--r--src/web/src/components/Search/SearchStatusIcon.js30
-rw-r--r--src/web/src/components/Search/Searches.js18
-rw-r--r--src/web/src/components/Shared/ErrorSegment.js10
-rw-r--r--src/web/src/components/Shared/FileList.js28
-rw-r--r--src/web/src/components/Shared/PlaceholderSegment.js10
-rw-r--r--src/web/src/components/System/Logs.js12
-rw-r--r--src/web/src/components/System/Options/Edit.js3
-rw-r--r--src/web/src/components/System/System.js7
-rw-r--r--src/web/src/components/Transfers/TransferGroup.js258
-rw-r--r--src/web/src/components/Transfers/TransferList.js237
-rw-r--r--src/web/src/components/Transfers/Transfers.js14
-rw-r--r--src/web/src/components/Users/User.js63
-rw-r--r--src/web/src/components/Users/Users.js13
-rw-r--r--src/web/src/config.js18
-rw-r--r--src/web/src/index.js9
-rw-r--r--src/web/src/lib/api.js16
-rw-r--r--src/web/src/lib/hubFactory.js6
-rw-r--r--src/web/src/lib/searches.js22
-rw-r--r--src/web/src/lib/searches.test.js108
-rw-r--r--src/web/src/lib/util.js118
40 files changed, 1106 insertions, 983 deletions
diff --git a/src/web/.eslintrc b/src/web/.eslintrc
new file mode 100644
index 00000000..8b047235
--- /dev/null
+++ b/src/web/.eslintrc
@@ -0,0 +1,30 @@
+{
+ "env": {
+ "browser": true,
+ "jest": true,
+ "es6": true
+ },
+ "plugins": ["import"],
+ "extends": ["eslint:recommended", "react-app"],
+ "parserOptions": {
+ "ecmaVersion": "latest"
+ },
+ "rules": {
+ "max-len": ["warn", 120],
+ "quotes": ["warn", "single"],
+ "indent": ["warn", 2],
+ "comma-dangle": ["warn", {
+ "arrays": "always-multiline",
+ "objects": "always-multiline",
+ "imports": "always-multiline",
+ "exports": "always-multiline",
+ "functions": "never"
+ }],
+ "camelcase": "warn",
+ "import/first": "warn",
+ "prefer-destructuring": ["warn"],
+ "no-await-in-loop": "error",
+ "require-atomic-updates": "error",
+ "curly": ["warn", "multi-line"]
+ }
+} \ No newline at end of file
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index 86bb72af..0e1481c9 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -5,7 +5,6 @@
"requires": true,
"packages": {
"": {
- "name": "web",
"version": "0.1.0",
"hasInstallScript": true,
"dependencies": {
@@ -31,6 +30,7 @@
},
"devDependencies": {
"@semantic-ui-react/css-patch": "^1.0.0",
+ "eslint": "^8.16.0",
"react-scripts": "^5.0.0"
}
},
@@ -2353,19 +2353,19 @@
}
},
"node_modules/@eslint/eslintrc": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.1.0.tgz",
- "integrity": "sha512-C1DfL7XX4nPqGd6jcP01W9pVM1HYCuUkFk1432D7F0v3JSlUIeOYn9oCoi3eoLZ+iwBSb29BMFxxny0YrrEZqg==",
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.3.0.tgz",
+ "integrity": "sha512-UWW0TMTmk2d7hLcWD1/e2g5HDM/HQ3csaLSqXCfqwh4uNDuNqlaKWXmEsL4Cs41Z0KnILNvwbHAah3C2yt06kw==",
"dev": true,
"dependencies": {
"ajv": "^6.12.4",
"debug": "^4.3.2",
- "espree": "^9.3.1",
- "globals": "^13.9.0",
- "ignore": "^4.0.6",
+ "espree": "^9.3.2",
+ "globals": "^13.15.0",
+ "ignore": "^5.2.0",
"import-fresh": "^3.2.1",
"js-yaml": "^4.1.0",
- "minimatch": "^3.0.4",
+ "minimatch": "^3.1.2",
"strip-json-comments": "^3.1.1"
},
"engines": {
@@ -2379,9 +2379,9 @@
"dev": true
},
"node_modules/@eslint/eslintrc/node_modules/globals": {
- "version": "13.12.1",
- "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.1.tgz",
- "integrity": "sha512-317dFlgY2pdJZ9rspXDks7073GpDmXdfbM3vYYp0HAMKGDh1FfWPleI2ljVNLQX5M5lXcAslTcPTrOrMEFOjyw==",
+ "version": "13.15.0",
+ "resolved": "https://registry.npmjs.org/globals/-/globals-13.15.0.tgz",
+ "integrity": "sha512-bpzcOlgDhMG070Av0Vy5Owklpv1I6+j96GhUI7Rh7IzDCKLzboflLrrfqMu8NquDbiR4EOQk7XzJwqVJxicxog==",
"dev": true,
"dependencies": {
"type-fest": "^0.20.2"
@@ -2393,15 +2393,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/@eslint/eslintrc/node_modules/ignore": {
- "version": "4.0.6",
- "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz",
- "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==",
- "dev": true,
- "engines": {
- "node": ">= 4"
- }
- },
"node_modules/@eslint/eslintrc/node_modules/js-yaml": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
@@ -4388,9 +4379,9 @@
}
},
"node_modules/acorn": {
- "version": "8.7.0",
- "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.0.tgz",
- "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==",
+ "version": "8.7.1",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.1.tgz",
+ "integrity": "sha512-Xx54uLJQZ19lKygFXOWsscKUbsBZW0CPykPhVQdhIeIwrbPmJzqeASDInc8nKBnp/JT6igTs82qPXz069H8I/A==",
"dev": true,
"bin": {
"acorn": "bin/acorn"
@@ -7565,12 +7556,12 @@
}
},
"node_modules/eslint": {
- "version": "8.9.0",
- "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.9.0.tgz",
- "integrity": "sha512-PB09IGwv4F4b0/atrbcMFboF/giawbBLVC7fyDamk5Wtey4Jh2K+rYaBhCAbUyEI4QzB1ly09Uglc9iCtFaG2Q==",
+ "version": "8.16.0",
+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.16.0.tgz",
+ "integrity": "sha512-MBndsoXY/PeVTDJeWsYj7kLZ5hQpJOfMYLsF6LicLHQWbRDG19lK5jOix4DPl8yY4SUFcE3txy86OzFLWT+yoA==",
"dev": true,
"dependencies": {
- "@eslint/eslintrc": "^1.1.0",
+ "@eslint/eslintrc": "^1.3.0",
"@humanwhocodes/config-array": "^0.9.2",
"ajv": "^6.10.0",
"chalk": "^4.0.0",
@@ -7581,14 +7572,14 @@
"eslint-scope": "^7.1.1",
"eslint-utils": "^3.0.0",
"eslint-visitor-keys": "^3.3.0",
- "espree": "^9.3.1",
+ "espree": "^9.3.2",
"esquery": "^1.4.0",
"esutils": "^2.0.2",
"fast-deep-equal": "^3.1.3",
"file-entry-cache": "^6.0.1",
"functional-red-black-tree": "^1.0.1",
"glob-parent": "^6.0.1",
- "globals": "^13.6.0",
+ "globals": "^13.15.0",
"ignore": "^5.2.0",
"import-fresh": "^3.0.0",
"imurmurhash": "^0.1.4",
@@ -7597,7 +7588,7 @@
"json-stable-stringify-without-jsonify": "^1.0.1",
"levn": "^0.4.1",
"lodash.merge": "^4.6.2",
- "minimatch": "^3.0.4",
+ "minimatch": "^3.1.2",
"natural-compare": "^1.4.0",
"optionator": "^0.9.1",
"regexpp": "^3.2.0",
@@ -8047,9 +8038,9 @@
}
},
"node_modules/eslint/node_modules/globals": {
- "version": "13.12.1",
- "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.1.tgz",
- "integrity": "sha512-317dFlgY2pdJZ9rspXDks7073GpDmXdfbM3vYYp0HAMKGDh1FfWPleI2ljVNLQX5M5lXcAslTcPTrOrMEFOjyw==",
+ "version": "13.15.0",
+ "resolved": "https://registry.npmjs.org/globals/-/globals-13.15.0.tgz",
+ "integrity": "sha512-bpzcOlgDhMG070Av0Vy5Owklpv1I6+j96GhUI7Rh7IzDCKLzboflLrrfqMu8NquDbiR4EOQk7XzJwqVJxicxog==",
"dev": true,
"dependencies": {
"type-fest": "^0.20.2"
@@ -8098,13 +8089,13 @@
}
},
"node_modules/espree": {
- "version": "9.3.1",
- "resolved": "https://registry.npmjs.org/espree/-/espree-9.3.1.tgz",
- "integrity": "sha512-bvdyLmJMfwkV3NCRl5ZhJf22zBFo1y8bYh3VYb+bfzqNB4Je68P2sSuXyuFquzWLebHpNd2/d5uv7yoP9ISnGQ==",
+ "version": "9.3.2",
+ "resolved": "https://registry.npmjs.org/espree/-/espree-9.3.2.tgz",
+ "integrity": "sha512-D211tC7ZwouTIuY5x9XnS0E9sWNChB7IYKX/Xp5eQj3nFXhqmiUDB9q27y76oFl8jTg3pXcQx/bpxMfs3CIZbA==",
"dev": true,
"dependencies": {
- "acorn": "^8.7.0",
- "acorn-jsx": "^5.3.1",
+ "acorn": "^8.7.1",
+ "acorn-jsx": "^5.3.2",
"eslint-visitor-keys": "^3.3.0"
},
"engines": {
@@ -21202,19 +21193,19 @@
}
},
"@eslint/eslintrc": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.1.0.tgz",
- "integrity": "sha512-C1DfL7XX4nPqGd6jcP01W9pVM1HYCuUkFk1432D7F0v3JSlUIeOYn9oCoi3eoLZ+iwBSb29BMFxxny0YrrEZqg==",
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.3.0.tgz",
+ "integrity": "sha512-UWW0TMTmk2d7hLcWD1/e2g5HDM/HQ3csaLSqXCfqwh4uNDuNqlaKWXmEsL4Cs41Z0KnILNvwbHAah3C2yt06kw==",
"dev": true,
"requires": {
"ajv": "^6.12.4",
"debug": "^4.3.2",
- "espree": "^9.3.1",
- "globals": "^13.9.0",
- "ignore": "^4.0.6",
+ "espree": "^9.3.2",
+ "globals": "^13.15.0",
+ "ignore": "^5.2.0",
"import-fresh": "^3.2.1",
"js-yaml": "^4.1.0",
- "minimatch": "^3.0.4",
+ "minimatch": "^3.1.2",
"strip-json-comments": "^3.1.1"
},
"dependencies": {
@@ -21225,20 +21216,14 @@
"dev": true
},
"globals": {
- "version": "13.12.1",
- "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.1.tgz",
- "integrity": "sha512-317dFlgY2pdJZ9rspXDks7073GpDmXdfbM3vYYp0HAMKGDh1FfWPleI2ljVNLQX5M5lXcAslTcPTrOrMEFOjyw==",
+ "version": "13.15.0",
+ "resolved": "https://registry.npmjs.org/globals/-/globals-13.15.0.tgz",
+ "integrity": "sha512-bpzcOlgDhMG070Av0Vy5Owklpv1I6+j96GhUI7Rh7IzDCKLzboflLrrfqMu8NquDbiR4EOQk7XzJwqVJxicxog==",
"dev": true,
"requires": {
"type-fest": "^0.20.2"
}
},
- "ignore": {
- "version": "4.0.6",
- "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz",
- "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==",
- "dev": true
- },
"js-yaml": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
@@ -22752,9 +22737,9 @@
}
},
"acorn": {
- "version": "8.7.0",
- "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.0.tgz",
- "integrity": "sha512-V/LGr1APy+PXIwKebEWrkZPwoeoF+w1jiOBUmuxuiUIaOHtob8Qc9BTrYo7VuI5fR8tqsy+buA2WFooR5olqvQ==",
+ "version": "8.7.1",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.7.1.tgz",
+ "integrity": "sha512-Xx54uLJQZ19lKygFXOWsscKUbsBZW0CPykPhVQdhIeIwrbPmJzqeASDInc8nKBnp/JT6igTs82qPXz069H8I/A==",
"dev": true
},
"acorn-globals": {
@@ -25200,12 +25185,12 @@
}
},
"eslint": {
- "version": "8.9.0",
- "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.9.0.tgz",
- "integrity": "sha512-PB09IGwv4F4b0/atrbcMFboF/giawbBLVC7fyDamk5Wtey4Jh2K+rYaBhCAbUyEI4QzB1ly09Uglc9iCtFaG2Q==",
+ "version": "8.16.0",
+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.16.0.tgz",
+ "integrity": "sha512-MBndsoXY/PeVTDJeWsYj7kLZ5hQpJOfMYLsF6LicLHQWbRDG19lK5jOix4DPl8yY4SUFcE3txy86OzFLWT+yoA==",
"dev": true,
"requires": {
- "@eslint/eslintrc": "^1.1.0",
+ "@eslint/eslintrc": "^1.3.0",
"@humanwhocodes/config-array": "^0.9.2",
"ajv": "^6.10.0",
"chalk": "^4.0.0",
@@ -25216,14 +25201,14 @@
"eslint-scope": "^7.1.1",
"eslint-utils": "^3.0.0",
"eslint-visitor-keys": "^3.3.0",
- "espree": "^9.3.1",
+ "espree": "^9.3.2",
"esquery": "^1.4.0",
"esutils": "^2.0.2",
"fast-deep-equal": "^3.1.3",
"file-entry-cache": "^6.0.1",
"functional-red-black-tree": "^1.0.1",
"glob-parent": "^6.0.1",
- "globals": "^13.6.0",
+ "globals": "^13.15.0",
"ignore": "^5.2.0",
"import-fresh": "^3.0.0",
"imurmurhash": "^0.1.4",
@@ -25232,7 +25217,7 @@
"json-stable-stringify-without-jsonify": "^1.0.1",
"levn": "^0.4.1",
"lodash.merge": "^4.6.2",
- "minimatch": "^3.0.4",
+ "minimatch": "^3.1.2",
"natural-compare": "^1.4.0",
"optionator": "^0.9.1",
"regexpp": "^3.2.0",
@@ -25255,9 +25240,9 @@
"dev": true
},
"globals": {
- "version": "13.12.1",
- "resolved": "https://registry.npmjs.org/globals/-/globals-13.12.1.tgz",
- "integrity": "sha512-317dFlgY2pdJZ9rspXDks7073GpDmXdfbM3vYYp0HAMKGDh1FfWPleI2ljVNLQX5M5lXcAslTcPTrOrMEFOjyw==",
+ "version": "13.15.0",
+ "resolved": "https://registry.npmjs.org/globals/-/globals-13.15.0.tgz",
+ "integrity": "sha512-bpzcOlgDhMG070Av0Vy5Owklpv1I6+j96GhUI7Rh7IzDCKLzboflLrrfqMu8NquDbiR4EOQk7XzJwqVJxicxog==",
"dev": true,
"requires": {
"type-fest": "^0.20.2"
@@ -25591,13 +25576,13 @@
}
},
"espree": {
- "version": "9.3.1",
- "resolved": "https://registry.npmjs.org/espree/-/espree-9.3.1.tgz",
- "integrity": "sha512-bvdyLmJMfwkV3NCRl5ZhJf22zBFo1y8bYh3VYb+bfzqNB4Je68P2sSuXyuFquzWLebHpNd2/d5uv7yoP9ISnGQ==",
+ "version": "9.3.2",
+ "resolved": "https://registry.npmjs.org/espree/-/espree-9.3.2.tgz",
+ "integrity": "sha512-D211tC7ZwouTIuY5x9XnS0E9sWNChB7IYKX/Xp5eQj3nFXhqmiUDB9q27y76oFl8jTg3pXcQx/bpxMfs3CIZbA==",
"dev": true,
"requires": {
- "acorn": "^8.7.0",
- "acorn-jsx": "^5.3.1",
+ "acorn": "^8.7.1",
+ "acorn-jsx": "^5.3.2",
"eslint-visitor-keys": "^3.3.0"
}
},
diff --git a/src/web/package.json b/src/web/package.json
index 6603a2e5..2049e07a 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -3,6 +3,16 @@
"version": "0.1.0",
"private": true,
"homepage": ".",
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test",
+ "test-unattended": "react-scripts test --watchAll false --passWithNoTests",
+ "eject": "react-scripts eject",
+ "postinstall": "semantic-ui-css-patch",
+ "lint": "eslint .",
+ "lint:fix": "eslint --fix ."
+ },
"dependencies": {
"@codemirror/highlight": "^0.19.7",
"@codemirror/legacy-modes": "^0.19.0",
@@ -26,19 +36,9 @@
},
"devDependencies": {
"@semantic-ui-react/css-patch": "^1.0.0",
+ "eslint": "^8.16.0",
"react-scripts": "^5.0.0"
},
- "scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
- "test-unattended": "react-scripts test --watchAll false --passWithNoTests",
- "eject": "react-scripts eject",
- "postinstall": "semantic-ui-css-patch"
- },
- "eslintConfig": {
- "extends": "react-app"
- },
"browserslist": {
"production": [
">0.3%",
diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js
index 5e5ed10f..1078935a 100644
--- a/src/web/src/components/App.js
+++ b/src/web/src/components/App.js
@@ -1,5 +1,5 @@
import React, { Component } from 'react';
-import { Route, Link, Switch, Redirect } from "react-router-dom";
+import { Route, Link, Switch, Redirect } from 'react-router-dom';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
@@ -29,7 +29,7 @@ import {
Modal,
Header,
Button,
- Loader
+ Loader,
} from 'semantic-ui-react';
import Rooms from './Rooms/Rooms';
import ErrorSegment from './Shared/ErrorSegment';
@@ -37,7 +37,7 @@ import ErrorSegment from './Shared/ErrorSegment';
const initialState = {
login: {
pending: false,
- error: undefined
+ error: undefined,
},
applicationState: {},
applicationOptions: {},
@@ -125,9 +125,15 @@ class App extends Component {
if (error) {
return <ErrorSegment
- suppressPrefix
- icon='attention'
- caption={<><span>Lost connection to slskd</span><br/><span>{(retriesExhausted ? 'Refresh to reconnect' : 'Retrying...')}</span></>}/>;
+ suppressPrefix
+ icon='attention'
+ caption={
+ <>
+ <span>
+ Lost connection to slskd</span><br /><span>{(retriesExhausted ? 'Refresh to reconnect' : 'Retrying...')}
+ </span>
+ </>
+ }/>;
}
if (!session.isLoggedIn() && !session.isPassthroughEnabled()) {
@@ -218,7 +224,10 @@ class App extends Component {
>
<Modal.Header>New Version!</Modal.Header>
<Modal.Content>
- <p>You are currently running version <strong>{current}</strong> while version <strong>{latest}</strong> is available.</p>
+ <p>
+ You are currently running version <strong>{current}</strong>
+ while version <strong>{latest}</strong> is available.
+ </p>
</Modal.Content>
<Modal.Actions>
<Button
@@ -262,9 +271,17 @@ class App extends Component {
<Route path={`${urlBase}/users`} render={(props) => this.withTokenCheck(<Users {...props}/>)}/>
<Route path={`${urlBase}/chat`} render={(props) => this.withTokenCheck(<Chat {...props}/>)}/>
<Route path={`${urlBase}/rooms`} render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/>
- <Route path={`${urlBase}/uploads`} render={(props) => this.withTokenCheck(<Transfers {...props} direction='upload'/>)}/>
- <Route path={`${urlBase}/downloads`} render={(props) => this.withTokenCheck(<Transfers {...props} direction='download'/>)}/>
- <Route path={`${urlBase}/system/:tab?`} render={(props) => this.withTokenCheck(<System {...props} state={applicationState} options={applicationOptions}/>)}/>
+ <Route path={`${urlBase}/uploads`} render={
+ (props) => this.withTokenCheck(<Transfers {...props} direction='upload' />)
+ }/>
+ <Route path={`${urlBase}/downloads`} render={
+ (props) => this.withTokenCheck(<Transfers {...props} direction='download' />)
+ }/>
+ <Route path={`${urlBase}/system/:tab?`} render={
+ (props) => this.withTokenCheck(
+ <System {...props} state={applicationState} options={applicationOptions} />
+ )
+ }/>
<Redirect from='*' to={`${urlBase}/searches`}/>
</Switch>
</AppContext.Provider>
@@ -284,6 +301,6 @@ class App extends Component {
</>
)
};
-};
+}
export default App; \ No newline at end of file
diff --git a/src/web/src/components/Browse/Browse.js b/src/web/src/components/Browse/Browse.js
index 3a590d83..bca73c97 100644
--- a/src/web/src/components/Browse/Browse.js
+++ b/src/web/src/components/Browse/Browse.js
@@ -30,8 +30,8 @@ const initialState = {
directories: 0,
files: 0,
lockedDirectories: 0,
- lockedFiles: 0
- }
+ lockedFiles: 0,
+ },
};
class Browse extends Component {
@@ -59,8 +59,8 @@ class Browse extends Component {
directories: directoryCount,
files: fileCount,
lockedDirectories: lockedDirectoryCount,
- lockedFiles: lockedFileCount
- }
+ lockedFiles: lockedFileCount,
+ },
});
})
.then(() => this.setState({ browseState: 'complete', browseError: undefined }, () => {
@@ -95,23 +95,24 @@ class Browse extends Component {
}
loadState = () => {
- this.setState(JSON.parse(lzString.decompress(localStorage.getItem('soulseek-example-browse-state') || '')) || initialState);
+ this.setState(
+ JSON.parse(lzString.decompress(localStorage.getItem('soulseek-example-browse-state') || '')) || initialState);
}
componentDidMount = () => {
this.fetchStatus();
this.loadState();
this.setState({
- interval: window.setInterval(this.fetchStatus, 500)
+ interval: window.setInterval(this.fetchStatus, 500),
}, () => this.saveState());
- document.addEventListener("keyup", this.keyUp, false);
+ document.addEventListener('keyup', this.keyUp, false);
}
componentWillUnmount = () => {
clearInterval(this.state.interval);
this.setState({ interval: undefined });
- document.removeEventListener("keyup", this.keyUp, false);
+ document.removeEventListener('keyup', this.keyUp, false);
}
fetchStatus = () => {
@@ -119,7 +120,7 @@ class Browse extends Component {
if (browseState === 'pending') {
users.getBrowseStatus({ username })
.then(response => this.setState({
- browseStatus: response.data
+ browseStatus: response.data,
}));
}
}
@@ -164,7 +165,8 @@ class Browse extends Component {
const emptyTree = !(tree && tree.length > 0);
- const files = (selectedDirectory.files || []).map(f => ({ ...f, filename: `${name}${this.sep(name)}${f.filename}`}));
+ const files = (selectedDirectory.files || [])
+ .map(f => ({ ...f, filename: `${name}${this.sep(name)}${f.filename}` }));
return (
<div className='search-container'>
@@ -177,7 +179,9 @@ class Browse extends Component {
disabled={pending}
className='search-input'
placeholder="Username"
- action={!pending && (browseState === 'idle' ? { icon: 'search', onClick: this.browse } : { icon: 'x', color: 'red', onClick: this.clear })}
+ action={!pending && (browseState === 'idle'
+ ? { icon: 'search', onClick: this.browse }
+ : { icon: 'x', color: 'red', onClick: this.clear })}
onKeyUp={(e) => e.key === 'Enter' ? this.browse() : ''}
/>
</Segment>
@@ -190,42 +194,44 @@ class Browse extends Component {
>
Downloaded {Math.round(browseStatus.percentComplete || 0)}% of Response
</Loader>
- :
+ :
<div>
{browseError ?
<span className='browse-error'>Failed to browse {username}</span> :
<div className='browse-container'>
{emptyTree ?
- <PlaceholderSegment icon='folder open'/> :
- <Card className='browse-tree-card' raised>
- <Card.Content>
- <Card.Header>
+ <PlaceholderSegment icon='folder open'/> :
+ <Card className='browse-tree-card' raised>
+ <Card.Content>
+ <Card.Header>
<Icon name='circle' color='green'/>
{username}
- </Card.Header>
- <Card.Meta className='browse-meta'>
- <span>{`${info.files + info.lockedFiles} files in ${info.directories + info.lockedDirectories} directories (including ${info.lockedFiles} files in ${info.lockedDirectories} locked directories)`}</span>
- </Card.Meta>
- <Segment className='browse-folderlist'>
- <DirectoryTree
- tree={tree}
- selectedDirectoryName={name}
- onSelect={(_, value) => this.selectDirectory(value)}
- />
- </Segment>
- </Card.Content>
- </Card>}
+ </Card.Header>
+ <Card.Meta className='browse-meta'>
+ <span>
+ {`${info.files + info.lockedFiles} files in ${info.directories + info.lockedDirectories} directories (including ${info.lockedFiles} files in ${info.lockedDirectories} locked directories)`} {/* eslint-disable-line max-len */}
+ </span>
+ </Card.Meta>
+ <Segment className='browse-folderlist'>
+ <DirectoryTree
+ tree={tree}
+ selectedDirectoryName={name}
+ onSelect={(_, value) => this.selectDirectory(value)}
+ />
+ </Segment>
+ </Card.Content>
+ </Card>}
{name && <Directory
- marginTop={-20}
- name={name}
- locked={locked}
- files={files}
- username={username}
- onClose={this.deselectDirectory}
+ marginTop={-20}
+ name={name}
+ locked={locked}
+ files={files}
+ username={username}
+ onClose={this.deselectDirectory}
/>}
</div>
}
- </div>}
+ </div>}
</div>
)
}
diff --git a/src/web/src/components/Browse/Directory.js b/src/web/src/components/Browse/Directory.js
index 179af0ee..2ba53b3e 100644
--- a/src/web/src/components/Browse/Directory.js
+++ b/src/web/src/components/Browse/Directory.js
@@ -9,18 +9,18 @@ import {
Button,
Card,
Icon,
- Label
+ Label,
} from 'semantic-ui-react';
const initialState = {
downloadRequest: undefined,
- downloadError: ''
+ downloadError: '',
}
class Directory extends Component {
state = {
...initialState,
- files: this.props.files.map(f => ({ selected: false, ...f }))
+ files: this.props.files.map(f => ({ selected: false, ...f })),
}
onFileSelectionChange = (file, state) => {
@@ -31,14 +31,14 @@ class Directory extends Component {
download = (username, files) => {
this.setState({ downloadRequest: 'inProgress' }, async () => {
try {
- const requests = (files || []).map(({ filename, size }) => ({ filename, size }))
- await transfers.download({ username, files: requests })
+ const requests = (files || []).map(({ filename, size }) => ({ filename, size }))
+ await transfers.download({ username, files: requests })
- this.setState({ downloadRequest: 'complete' })
+ this.setState({ downloadRequest: 'complete' })
} catch (err) {
- this.setState({ downloadRequest: 'error', downloadError: err.response })
+ this.setState({ downloadRequest: 'error', downloadError: err.response })
}
- });
+ });
}
componentDidUpdate = (prevProps) => {
@@ -79,7 +79,7 @@ class Directory extends Component {
label={{
as: 'a',
basic: false,
- content: `${selectedFiles.length} file${selectedFiles.length === 1 ? '' : 's'}, ${selectedSize}`
+ content: `${selectedFiles.length} file${selectedFiles.length === 1 ? '' : 's'}, ${selectedSize}`,
}}
labelPosition='right'
onClick={() => this.download(username, selectedFiles)}
diff --git a/src/web/src/components/Browse/DirectoryTree.js b/src/web/src/components/Browse/DirectoryTree.js
index 0fc52327..0e9843b6 100644
--- a/src/web/src/components/Browse/DirectoryTree.js
+++ b/src/web/src/components/Browse/DirectoryTree.js
@@ -1,38 +1,38 @@
import React from 'react';
import {
- List
+ List,
} from 'semantic-ui-react';
const subtree = (root, selectedDirectoryName, onSelect) => {
return (root || []).map((d, index) => {
- const selected = d.name === selectedDirectoryName;
- const dimIfLocked = { opacity: d.locked ? 0.5 : 1 };
+ const selected = d.name === selectedDirectoryName;
+ const dimIfLocked = { opacity: d.locked ? 0.5 : 1 };
- return (
- <List key={index} className='browse-folderlist-list'>
- <List.Item>
- <List.Icon
- className='browse-folderlist-icon'
- name={d.locked === true ? 'lock' : selected ? 'folder open' : 'folder'}
- color={selected ? 'blue' : 'black'}
- style={dimIfLocked}
- />
- <List.Content>
- <List.Header
- className='browse-folderlist-header'
- onClick={(event) => onSelect(event, d)}
- style={{ color: selected ? '#0E6EB8' : 'black', fontWeight: selected ? 700 : 400, ...dimIfLocked }}
- >
- {d.name.split('\\').pop().split('/').pop()}
- </List.Header>
- <List.List>
- {subtree(d.children, selectedDirectoryName, onSelect)}
- </List.List>
- </List.Content>
- </List.Item>
+ return (
+ <List key={index} className='browse-folderlist-list'>
+ <List.Item>
+ <List.Icon
+ className='browse-folderlist-icon'
+ name={d.locked === true ? 'lock' : selected ? 'folder open' : 'folder'}
+ color={selected ? 'blue' : 'black'}
+ style={dimIfLocked}
+ />
+ <List.Content>
+ <List.Header
+ className='browse-folderlist-header'
+ onClick={(event) => onSelect(event, d)}
+ style={{ color: selected ? '#0E6EB8' : 'black', fontWeight: selected ? 700 : 400, ...dimIfLocked }}
+ >
+ {d.name.split('\\').pop().split('/').pop()}
+ </List.Header>
+ <List.List>
+ {subtree(d.children, selectedDirectoryName, onSelect)}
+ </List.List>
+ </List.Content>
+ </List.Item>
</List>)
- })
+ })
}
const DirectoryTree = ({ tree, selectedDirectoryName, onSelect }) => subtree(tree, selectedDirectoryName, onSelect);
diff --git a/src/web/src/components/Chat/Chat.js b/src/web/src/components/Chat/Chat.js
index 53651cde..81d02461 100644
--- a/src/web/src/components/Chat/Chat.js
+++ b/src/web/src/components/Chat/Chat.js
@@ -4,7 +4,7 @@ import * as chat from '../../lib/chat';
import './Chat.css';
import {
Segment,
- List, Input, Card, Icon, Ref, Dimmer, Loader
+ List, Input, Card, Icon, Ref, Dimmer, Loader,
} from 'semantic-ui-react';
import ChatMenu from './ChatMenu';
@@ -14,7 +14,7 @@ const initialState = {
active: '',
conversations: {},
interval: undefined,
- loading: false
+ loading: false,
};
class Chat extends Component {
@@ -25,7 +25,7 @@ class Chat extends Component {
componentDidMount = async () => {
this.setState({
interval: window.setInterval(this.fetchConversations, 5000),
- active: sessionStorage.getItem(activeChatKey) || ''
+ active: sessionStorage.getItem(activeChatKey) || '',
}, async () => {
await this.fetchConversations();
this.selectConversation(this.state.active || this.getFirstConversation());
@@ -53,9 +53,9 @@ class Chat extends Component {
await this.acknowledgeMessages(active, { force: true });
conversations = {
...conversations,
- [active]: conversations[active].map(message => ({...message, acknowledged: true }))
+ [active]: conversations[active].map(message => ({...message, acknowledged: true })),
};
- };
+ }
this.setState({ conversations }, () => {
if (!this.state.conversations[this.state.active]) {
@@ -93,7 +93,9 @@ class Chat extends Component {
this.messageRef.current.value = '';
}
- validInput = () => (this.state.active || '').length > 0 && ((this.messageRef && this.messageRef.current && this.messageRef.current.value) || '').length > 0;
+ validInput = () =>
+ (this.state.active || '').length > 0
+ && ((this.messageRef && this.messageRef.current && this.messageRef.current.value) || '').length > 0;
focusInput = () => {
this.messageRef.current.focus();
@@ -105,7 +107,7 @@ class Chat extends Component {
month: 'numeric',
day: 'numeric',
hour: 'numeric',
- minute: '2-digit'
+ minute: '2-digit',
});
return dtfUS.format(date);
@@ -114,7 +116,7 @@ class Chat extends Component {
selectConversation = (username) => {
this.setState({
active: username,
- loading: true
+ loading: true,
}, async () => {
const { active } = this.state;
@@ -123,7 +125,9 @@ class Chat extends Component {
this.setState({ loading: false }, () => {
try {
this.listRef.current.lastChild.scrollIntoView();
- } catch {}
+ } catch {
+ // no-op
+ }
});
});
}
@@ -155,58 +159,59 @@ class Chat extends Component {
/>
</Segment>
{!active ?
- <PlaceholderSegment icon='comment'/> :
- <Card className='chat-active-card' raised>
- <Card.Content onClick={() => this.focusInput()}>
- <Card.Header>
- <Icon name='circle' color='green'/>
- {active}
- <Icon
- className='close-button'
- name='close'
- color='red'
- link
- onClick={() => this.deleteConversation(active)}
- />
- </Card.Header>
- <div className='chat'>
- {loading ? <Dimmer active inverted><Loader inverted/></Dimmer> :
- <Segment.Group>
- <Segment className='chat-history'>
- <Ref innerRef={this.listRef}>
- <List>
- {messages.map((message, index) =>
- <List.Content
- key={index}
- className={`chat-message ${message.username !== active ? 'chat-message-self' : ''}`}
- >
- <span className='chat-message-time'>{this.formatTimestamp(message.timestamp)}</span>
- <span className='chat-message-name'>{message.username}: </span>
- <span className='chat-message-message'>{message.message}</span>
- </List.Content>
- )}
- <List.Content id='chat-history-scroll-anchor'/>
- </List>
- </Ref>
- </Segment>
- <Segment className='chat-input'>
- <Input
- fluid
- transparent
- input={<input id='chat-message-input' type="text" data-lpignore="true" autoComplete="off"></input>}
- ref={input => this.messageRef = input && input.inputRef}
- action={{
- icon: <Icon name='send' color='green'/>,
- className: 'chat-message-button', onClick: this.sendMessage,
- disabled: !this.validInput()
- }}
- onKeyUp={(e) => e.key === 'Enter' ? this.sendReply() : ''}
- />
- </Segment>
- </Segment.Group>}
- </div>
- </Card.Content>
- </Card>}
+ <PlaceholderSegment icon='comment'/> :
+ <Card className='chat-active-card' raised>
+ <Card.Content onClick={() => this.focusInput()}>
+ <Card.Header>
+ <Icon name='circle' color='green'/>
+ {active}
+ <Icon
+ className='close-button'
+ name='close'
+ color='red'
+ link
+ onClick={() => this.deleteConversation(active)}
+ />
+ </Card.Header>
+ <div className='chat'>
+ {loading ? <Dimmer active inverted><Loader inverted/></Dimmer> :
+ <Segment.Group>
+ <Segment className='chat-history'>
+ <Ref innerRef={this.listRef}>
+ <List>
+ {messages.map((message, index) =>
+ <List.Content
+ key={index}
+ className={`chat-message ${message.username !== active ? 'chat-message-self' : ''}`}
+ >
+ <span className='chat-message-time'>{this.formatTimestamp(message.timestamp)}</span>
+ <span className='chat-message-name'>{message.username}: </span>
+ <span className='chat-message-message'>{message.message}</span>
+ </List.Content>
+ )}
+ <List.Content id='chat-history-scroll-anchor'/>
+ </List>
+ </Ref>
+ </Segment>
+ <Segment className='chat-input'>
+ <Input
+ fluid
+ transparent
+ input={
+ <input id='chat-message-input' type="text" data-lpignore="true" autoComplete="off"></input>}
+ ref={input => this.messageRef = input && input.inputRef}
+ action={{
+ icon: <Icon name='send' color='green'/>,
+ className: 'chat-message-button', onClick: this.sendMessage,
+ disabled: !this.validInput(),
+ }}
+ onKeyUp={(e) => e.key === 'Enter' ? this.sendReply() : ''}
+ />
+ </Segment>
+ </Segment.Group>}
+ </div>
+ </Card.Content>
+ </Card>}
</div>
)
}
diff --git a/src/web/src/components/Chat/ChatMenu.js b/src/web/src/components/Chat/ChatMenu.js
index d8312148..75580ec0 100644
--- a/src/web/src/components/Chat/ChatMenu.js
+++ b/src/web/src/components/Chat/ChatMenu.js
@@ -2,7 +2,7 @@ import React from 'react';
import './Chat.css';
import {
- Icon, Button, Label, Menu
+ Icon, Button, Label, Menu,
} from 'semantic-ui-react';
import SendMessageModal from './SendMessageModal';
diff --git a/src/web/src/components/Chat/SendMessageModal.js b/src/web/src/components/Chat/SendMessageModal.js
index 3c91d570..6c817ae7 100644
--- a/src/web/src/components/Chat/SendMessageModal.js
+++ b/src/web/src/components/Chat/SendMessageModal.js
@@ -2,7 +2,7 @@ import React, { useEffect } from 'react';
import './Chat.css';
import {
- Icon, Button, Modal, Form, Header, Input
+ Icon, Button, Modal, Form, Header, Input,
} from 'semantic-ui-react';
const usernameRef = React.createRef();
@@ -46,11 +46,11 @@ const SendMessageModal = ({ initiateConversation, ...rest }) => {
<Modal.Content>
<Form>
<Form.Field>
- <Input
- ref={usernameRef}
- placeholder='Username'
- onChange={(e, data) => setUsername(data.value)}
- />
+ <Input
+ ref={usernameRef}
+ placeholder='Username'
+ onChange={(e, data) => setUsername(data.value)}
+ />
</Form.Field>
<Form.Field>
<Input
diff --git a/src/web/src/components/LoginForm.js b/src/web/src/components/LoginForm.js
index 88e6c465..fea82175 100644
--- a/src/web/src/components/LoginForm.js
+++ b/src/web/src/components/LoginForm.js
@@ -6,7 +6,7 @@ import Logos from './Shared/Logo';
const initialState = {
username: '',
password: '',
- rememberMe: true
+ rememberMe: true,
}
const LoginForm = ({ onLoginAttempt, loading, error }) => {
@@ -40,9 +40,9 @@ const LoginForm = ({ onLoginAttempt, loading, error }) => {
fontFamily: 'monospace',
lineHeight: 1.1,
fontSize: 'inherit',
- letterSpacing: -1
+ letterSpacing: -1,
}}>
- {logo}
+ {logo}
</Header>
<Form size='large'>
<Segment raised>
diff --git a/src/web/src/components/Rooms/RoomJoinModal.js b/src/web/src/components/Rooms/RoomJoinModal.js
index 4dffe840..134d9339 100644
--- a/src/web/src/components/Rooms/RoomJoinModal.js
+++ b/src/web/src/components/Rooms/RoomJoinModal.js
@@ -3,7 +3,7 @@ import * as rooms from '../../lib/rooms';
import './Rooms.css';
import {
- Icon, Button, Modal, Table, Header, Input, Loader, Dimmer
+ Icon, Button, Modal, Table, Header, Input, Loader, Dimmer,
} from 'semantic-ui-react';
const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => {
@@ -78,54 +78,54 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => {
</Header>
<Modal.Content scrolling>
{loading ? <Dimmer active inverted><Loader inverted content='Loading Room List' /></Dimmer> :
- <>
- <Input
- fluid
- onChange={(_, e) => setFilter(e.value)}
- placeholder='Room Filter'
- icon='filter'
- />
- <Table celled selectable>
- <Table.Header>
- <Table.Row>
- <Table.HeaderCell onClick={() => setSortBy('name')}>
+ <>
+ <Input
+ fluid
+ onChange={(_, e) => setFilter(e.value)}
+ placeholder='Room Filter'
+ icon='filter'
+ />
+ <Table celled selectable>
+ <Table.Header>
+ <Table.Row>
+ <Table.HeaderCell onClick={() => setSortBy('name')}>
Name
- <Icon
- link={sortBy === 'name'}
- name={sortBy === 'name' && (sortOrder === 'asc' ? 'chevron up' : 'chevron down')}
- onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
- />
- </Table.HeaderCell>
- <Table.HeaderCell onClick={() => setSortBy('userCount')}>
+ <Icon
+ link={sortBy === 'name'}
+ name={sortBy === 'name' && (sortOrder === 'asc' ? 'chevron up' : 'chevron down')}
+ onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
+ />
+ </Table.HeaderCell>
+ <Table.HeaderCell onClick={() => setSortBy('userCount')}>
Users
- <Icon
- link={sortBy === 'userCount'}
- name={sortBy === 'userCount' && (sortOrder === 'asc' ? 'chevron up' : 'chevron down')}
- onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
- />
- </Table.HeaderCell>
- </Table.Row>
- </Table.Header>
- <Table.Body>
- {sortedAvailable.map((room, index) =>
- <Table.Row
- key={index}
- style={isSelected(room) ? {fontWeight: 'bold'} : {}}
- onClick={() => setSelected(room.name)}
- >
- <Table.Cell>
- {isSelected(room) && <Icon name='check' color='green'/>}
- {room.isPrivate && <Icon name='lock'/>}
- {room.isOwned && <Icon name='chess queen'/>}
- {room.isModerated && <Icon name='gavel'/>}
- {room.name}
- </Table.Cell>
- <Table.Cell>{room.userCount}</Table.Cell>
+ <Icon
+ link={sortBy === 'userCount'}
+ name={sortBy === 'userCount' && (sortOrder === 'asc' ? 'chevron up' : 'chevron down')}
+ onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
+ />
+ </Table.HeaderCell>
</Table.Row>
- )}
- </Table.Body>
- </Table>
- </>}
+ </Table.Header>
+ <Table.Body>
+ {sortedAvailable.map((room, index) =>
+ <Table.Row
+ key={index}
+ style={isSelected(room) ? {fontWeight: 'bold'} : {}}
+ onClick={() => setSelected(room.name)}
+ >
+ <Table.Cell>
+ {isSelected(room) && <Icon name='check' color='green'/>}
+ {room.isPrivate && <Icon name='lock'/>}
+ {room.isOwned && <Icon name='chess queen'/>}
+ {room.isModerated && <Icon name='gavel'/>}
+ {room.name}
+ </Table.Cell>
+ <Table.Cell>{room.userCount}</Table.Cell>
+ </Table.Row>
+ )}
+ </Table.Body>
+ </Table>
+ </>}
</Modal.Content>
<Modal.Actions>
<Button onClick={() => setOpen(false)}>Cancel</Button>
diff --git a/src/web/src/components/Rooms/RoomMenu.js b/src/web/src/components/Rooms/RoomMenu.js
index c77dd8fb..485646d6 100644
--- a/src/web/src/components/Rooms/RoomMenu.js
+++ b/src/web/src/components/Rooms/RoomMenu.js
@@ -2,7 +2,7 @@ import React from 'react';
import './Rooms.css';
import {
- Icon, Button, Menu
+ Icon, Button, Menu,
} from 'semantic-ui-react';
import RoomJoinModal from './RoomJoinModal';
diff --git a/src/web/src/components/Rooms/RoomUserList.js b/src/web/src/components/Rooms/RoomUserList.js
index c719e5f1..0a891e88 100644
--- a/src/web/src/components/Rooms/RoomUserList.js
+++ b/src/web/src/components/Rooms/RoomUserList.js
@@ -2,7 +2,7 @@ import React, { useMemo } from 'react';
import './Rooms.css';
import {
- Icon, Flag, List, Popup
+ Icon, Flag, List, Popup,
} from 'semantic-ui-react';
const RoomUserList = ({ users }) => {
diff --git a/src/web/src/components/Rooms/Rooms.js b/src/web/src/components/Rooms/Rooms.js
index 524aeee9..e19face3 100644
--- a/src/web/src/components/Rooms/Rooms.js
+++ b/src/web/src/components/Rooms/Rooms.js
@@ -13,13 +13,13 @@ const initialState = {
joined: [],
room: {
messages: [],
- users: []
+ users: [],
},
intervals: {
rooms: undefined,
- messages: undefined
+ messages: undefined,
},
- loading: false
+ loading: false,
}
class Rooms extends Component {
@@ -31,9 +31,9 @@ class Rooms extends Component {
this.setState({
intervals: {
rooms: window.setInterval(this.fetchJoinedRooms, 500),
- messages: window.setInterval(this.fetchActiveRoom, 1000)
+ messages: window.setInterval(this.fetchActiveRoom, 1000),
},
- active: sessionStorage.getItem(activeRoomKey) || ''
+ active: sessionStorage.getItem(activeRoomKey) || '',
}, async () => {
await this.fetchJoinedRooms();
this.selectRoom(this.state.active || this.getFirstRoom())
@@ -54,9 +54,9 @@ class Rooms extends Component {
}
fetchJoinedRooms = async () => {
- const joined = await rooms.getJoined();;
+ const joined = await rooms.getJoined();
this.setState({
- joined
+ joined,
}, () => {
if (!this.state.joined.includes(this.state.active)) {
this.selectRoom(this.getFirstRoom());
@@ -75,8 +75,8 @@ class Rooms extends Component {
this.setState({
room: {
users,
- messages
- }
+ messages,
+ },
});
};
@@ -84,7 +84,7 @@ class Rooms extends Component {
this.setState({
active: roomName,
room: initialState.room,
- loading: true
+ loading: true,
}, async () => {
const { active } = this.state;
@@ -94,7 +94,9 @@ class Rooms extends Component {
this.setState({ loading: false }, () => {
try {
this.listRef.current.lastChild.scrollIntoView();
- } catch {}
+ } catch {
+ // no-op
+ }
});
});
};
@@ -111,7 +113,9 @@ class Rooms extends Component {
this.selectRoom(this.getFirstRoom());
};
- validInput = () => (this.state.active || '').length > 0 && ((this.messageRef && this.messageRef.current && this.messageRef.current.value) || '').length > 0;
+ validInput = () =>
+ (this.state.active || '').length > 0
+ && ((this.messageRef && this.messageRef.current && this.messageRef.current.value) || '').length > 0;
focusInput = () => {
this.messageRef.current.focus();
@@ -120,10 +124,10 @@ class Rooms extends Component {
formatTimestamp = (timestamp) => {
const date = new Date(timestamp);
const dtfUS = new Intl.DateTimeFormat('en', {
- month: 'numeric',
- day: 'numeric',
- hour: 'numeric',
- minute: '2-digit'
+ month: 'numeric',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
});
return dtfUS.format(date);
@@ -155,65 +159,66 @@ class Rooms extends Component {
/>
</Segment>
{!active ?
- <PlaceholderSegment icon='comments'/> :
- <Card className='room-active-card' raised>
- <Card.Content onClick={() => this.focusInput()}>
- <Card.Header>
- <Icon name='circle' color='green'/>
- {active}
- <Icon
+ <PlaceholderSegment icon='comments'/> :
+ <Card className='room-active-card' raised>
+ <Card.Content onClick={() => this.focusInput()}>
+ <Card.Header>
+ <Icon name='circle' color='green'/>
+ {active}
+ <Icon
className='close-button'
name='close'
color='red'
link
onClick={() => this.leaveRoom(active)}
- />
- </Card.Header>
- <div className='room'>
- {loading ? <Dimmer active inverted><Loader inverted/></Dimmer> : <>
- <Segment.Group>
- <Segment className='room-history'>
- <Ref innerRef={this.listRef}>
- <List>
- {room.messages.map((message, index) =>
- <List.Content
- key={index}
- className={`room-message ${!!message.self ? 'room-message-self' : ''}`}
- >
- <span className='room-message-time'>{this.formatTimestamp(message.timestamp)}</span>
- <span className='room-message-name'>{message.username}: </span>
- <span className='room-message-message'>{message.message}</span>
- </List.Content>
- )}
- <List.Content id='room-history-scroll-anchor'/>
- </List>
- </Ref>
- </Segment>
- <Segment className='room-input'>
- <Input
- fluid
- transparent
- input={<input id='room-message-input' type="text" data-lpignore="true" autoComplete="off"></input>}
- ref={input => this.messageRef = input && input.inputRef}
- action={{
- icon: <Icon name='send' color='green'/>,
- className: 'room-message-button', onClick: this.sendMessage,
- disabled: !this.validInput()
- }}
- onKeyUp={(e) => e.key === 'Enter' ? this.sendMessage() : ''}
- />
- </Segment>
- </Segment.Group>
- <Segment className='room-users'>
- <RoomUserList users={room.users}/>
- </Segment>
- </>}
- </div>
- </Card.Content>
- </Card>}
+ />
+ </Card.Header>
+ <div className='room'>
+ {loading ? <Dimmer active inverted><Loader inverted/></Dimmer> : <>
+ <Segment.Group>
+ <Segment className='room-history'>
+ <Ref innerRef={this.listRef}>
+ <List>
+ {room.messages.map((message, index) =>
+ <List.Content
+ key={index}
+ className={`room-message ${message.self ? 'room-message-self' : ''}`}
+ >
+ <span className='room-message-time'>{this.formatTimestamp(message.timestamp)}</span>
+ <span className='room-message-name'>{message.username}: </span>
+ <span className='room-message-message'>{message.message}</span>
+ </List.Content>
+ )}
+ <List.Content id='room-history-scroll-anchor'/>
+ </List>
+ </Ref>
+ </Segment>
+ <Segment className='room-input'>
+ <Input
+ fluid
+ transparent
+ input={
+ <input id='room-message-input' type="text" data-lpignore="true" autoComplete="off"></input>}
+ ref={input => this.messageRef = input && input.inputRef}
+ action={{
+ icon: <Icon name='send' color='green'/>,
+ className: 'room-message-button', onClick: this.sendMessage,
+ disabled: !this.validInput(),
+ }}
+ onKeyUp={(e) => e.key === 'Enter' ? this.sendMessage() : ''}
+ />
+ </Segment>
+ </Segment.Group>
+ <Segment className='room-users'>
+ <RoomUserList users={room.users}/>
+ </Segment>
+ </>}
+ </div>
+ </Card.Content>
+ </Card>}
</div>
)
};
-};
+}
export default Rooms; \ No newline at end of file
diff --git a/src/web/src/components/Search/Detail/SearchDetail.js b/src/web/src/components/Search/Detail/SearchDetail.js
index 9c66d4e0..be64aabd 100644
--- a/src/web/src/components/Search/Detail/SearchDetail.js
+++ b/src/web/src/components/Search/Detail/SearchDetail.js
@@ -18,7 +18,7 @@ import SearchDetailHeader from './SearchDetailHeader';
const sortDropdownOptions = [
{ key: 'uploadSpeed', text: 'Upload Speed (Fastest to Slowest)', value: 'uploadSpeed' },
- { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' }
+ { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' },
];
const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate, onStop, onRemove }) => {
@@ -68,7 +68,7 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate
const sortedAndFilteredResults = useMemo(() => {
const sortOptions = {
uploadSpeed: { field: 'uploadSpeed', order: 'desc' },
- queueLength: { field: 'queueLength', order: 'asc' }
+ queueLength: { field: 'queueLength', order: 'asc' },
}
const { field, order } = sortOptions[resultSort];
@@ -141,8 +141,11 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate
<Switch
searching={!isComplete &&
<LoaderSegment>
- {state === 'InProgress' ? `Found ${fileCount} files ${lockedFileCount > 0 ? `(plus ${lockedFileCount} locked) ` : ''}from ${responseCount} users`
- : 'Loading results...'}
+ {state === 'InProgress'
+ ? `Found ${fileCount} files ${lockedFileCount > 0
+ ? `(plus ${lockedFileCount} locked) `
+ : ''}from ${responseCount} users`
+ : 'Loading results...'}
</LoaderSegment>
}
loading={loading && <LoaderSegment/>}
@@ -184,7 +187,10 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate
</div>
<Input
className='search-filter'
- placeholder='lackluster container -bothersome iscbr|isvbr islossless|islossy minbitrate:320 minfilesize:10 minfilesinfolder:8 minlength:5000'
+ placeholder='
+ lackluster container -bothersome iscbr|isvbr islossless|islossy
+ minbitrate:320 minfilesize:10 minfilesinfolder:8 minlength:5000
+ '
label={{ icon: 'filter', content: 'Filter' }}
value={resultFilters}
onChange={(e, data) => setResultFilters(data.value)}
@@ -204,10 +210,14 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate
{loaded && (remainingCount > 0 ?
<Button className='showmore-button' size='large' fluid primary
onClick={() => setDisplayCount(displayCount + 5)}>
- Show {remainingCount > 5 ? 5 : remainingCount} More Results {`(${remainingCount} remaining, ${filteredCount} hidden by filter(s))`}
+ Show {remainingCount > 5
+ ? 5
+ : remainingCount} More Results {`(${remainingCount} remaining, ${filteredCount} hidden by filter(s))`}
</Button>
: filteredCount > 0 ?
- <Button className='showmore-button' size='large' fluid disabled>{`All results shown. ${filteredCount} results hidden by filter(s)`}</Button> : '')}
+ <Button className='showmore-button' size='large' fluid disabled>{
+ `All results shown. ${filteredCount} results hidden by filter(s)`
+ }</Button> : '')}
</Switch>
</>
)
diff --git a/src/web/src/components/Search/Detail/SearchDetailHeader.js b/src/web/src/components/Search/Detail/SearchDetailHeader.js
index 8eaf111c..9e04ba6d 100644
--- a/src/web/src/components/Search/Detail/SearchDetailHeader.js
+++ b/src/web/src/components/Search/Detail/SearchDetailHeader.js
@@ -9,7 +9,18 @@ import {
} from 'semantic-ui-react';
import SearchStatusIcon from '../SearchStatusIcon';
-const SearchDetailHeader = ({ search, loading, loaded, creating, removing, stopping, disabled, onCreate, onStop, onRemove }) => {
+const SearchDetailHeader = ({
+ search,
+ loading,
+ loaded,
+ creating,
+ removing,
+ stopping,
+ disabled,
+ onCreate,
+ onStop,
+ onRemove,
+}) => {
const isSmallScreen = useMediaQuery({ query: '(max-width: 899px)' });
const isTinyScreen = useMediaQuery({ query: '(max-width: 684px)'});
diff --git a/src/web/src/components/Search/List/SearchList.js b/src/web/src/components/Search/List/SearchList.js
index c65c949d..b6e001a6 100644
--- a/src/web/src/components/Search/List/SearchList.js
+++ b/src/web/src/components/Search/List/SearchList.js
@@ -11,10 +11,16 @@ import {
Loader,
Segment,
Header,
- List
+ List,
} from 'semantic-ui-react';
-const SearchList = ({ connecting = false, error = undefined, searches = {}, onRemove = () => {}, onStop = () => {} }) => {
+const SearchList = ({
+ connecting = false,
+ error = undefined,
+ searches = {},
+ onRemove = () => { },
+ onStop = () => { },
+}) => {
const searchCount = useMemo(() => {
return Object.values(searches).length
}, [searches])
@@ -40,29 +46,29 @@ const SearchList = ({ connecting = false, error = undefined, searches = {}, onRe
<Segment basic style={{opacity: .5}} textAlign='center'>No searches to display</Segment>
}
>
- <Table size='large'>
- <Table.Header>
- <Table.Row>
- <Table.HeaderCell className="search-list-action"><Icon name="info circle"/></Table.HeaderCell>
- <Table.HeaderCell className="search-list-phrase">Search</Table.HeaderCell>
- <Table.HeaderCell className="search-list-files">Files</Table.HeaderCell>
- <Table.HeaderCell className="search-list-locked">Locked</Table.HeaderCell>
- <Table.HeaderCell className="search-list-responses">Responses</Table.HeaderCell>
- <Table.HeaderCell className="search-list-started">Ended</Table.HeaderCell>
- <Table.HeaderCell className="search-list-action"></Table.HeaderCell>
- </Table.Row>
- </Table.Header>
- <Table.Body>
- {Object.values(searches)
- .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt)))
- .map((search, index) => <SearchListRow
- search={search}
- key={index}
- onRemove={onRemove}
- onStop={onStop}
- />)}
- </Table.Body>
- </Table>
+ <Table size='large'>
+ <Table.Header>
+ <Table.Row>
+ <Table.HeaderCell className="search-list-action"><Icon name="info circle"/></Table.HeaderCell>
+ <Table.HeaderCell className="search-list-phrase">Search</Table.HeaderCell>
+ <Table.HeaderCell className="search-list-files">Files</Table.HeaderCell>
+ <Table.HeaderCell className="search-list-locked">Locked</Table.HeaderCell>
+ <Table.HeaderCell className="search-list-responses">Responses</Table.HeaderCell>
+ <Table.HeaderCell className="search-list-started">Ended</Table.HeaderCell>
+ <Table.HeaderCell className="search-list-action"></Table.HeaderCell>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {Object.values(searches)
+ .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt)))
+ .map((search, index) => <SearchListRow
+ search={search}
+ key={index}
+ onRemove={onRemove}
+ onStop={onStop}
+ />)}
+ </Table.Body>
+ </Table>
</Switch>
</List.Item>
</List>
diff --git a/src/web/src/components/Search/List/SearchListRow.js b/src/web/src/components/Search/List/SearchListRow.js
index c2552892..fd762069 100644
--- a/src/web/src/components/Search/List/SearchListRow.js
+++ b/src/web/src/components/Search/List/SearchListRow.js
@@ -3,7 +3,7 @@ import React, { useState } from 'react';
import {
Link,
useRouteMatch,
-} from "react-router-dom";
+} from 'react-router-dom';
import {
Table,
diff --git a/src/web/src/components/Search/Response.js b/src/web/src/components/Search/Response.js
index 4e389288..05d5544c 100644
--- a/src/web/src/components/Search/Response.js
+++ b/src/web/src/components/Search/Response.js
@@ -6,134 +6,136 @@ import { formatBytes, getDirectoryName } from '../../lib/util';
import FileList from '../Shared/FileList'
import {
- Button,
- Card,
- Icon,
- Label
+ Button,
+ Card,
+ Icon,
+ Label,
} from 'semantic-ui-react';
const buildTree = (response) => {
- let { files = [], lockedFiles = [] } = response;
- files = files.concat(lockedFiles.map(file => ({ ...file, locked: true })));
-
- return files.reduce((dict, file) => {
- let dir = getDirectoryName(file.filename);
- let selectable = { selected: false, ...file };
- dict[dir] = dict[dir] === undefined ? [ selectable ] : dict[dir].concat(selectable);
- return dict;
- }, {});
+ let { files = [], lockedFiles = [] } = response;
+ files = files.concat(lockedFiles.map(file => ({ ...file, locked: true })));
+
+ return files.reduce((dict, file) => {
+ let dir = getDirectoryName(file.filename);
+ let selectable = { selected: false, ...file };
+ dict[dir] = dict[dir] === undefined ? [ selectable ] : dict[dir].concat(selectable);
+ return dict;
+ }, {});
}
class Response extends Component {
- state = {
- tree: buildTree(this.props.response),
- downloadRequest: undefined,
- downloadError: '',
- isFolded: this.props.isInitiallyFolded,
+ state = {
+ tree: buildTree(this.props.response),
+ downloadRequest: undefined,
+ downloadError: '',
+ isFolded: this.props.isInitiallyFolded,
+ }
+
+ componentDidUpdate = (prevProps) => {
+ if (JSON.stringify(this.props.response) !== JSON.stringify(prevProps.response)) {
+ this.setState({ tree: buildTree(this.props.response) });
}
-
- componentDidUpdate = (prevProps) => {
- if (JSON.stringify(this.props.response) !== JSON.stringify(prevProps.response)) {
- this.setState({ tree: buildTree(this.props.response) });
- }
- if (this.props.isInitiallyFolded !== prevProps.isInitiallyFolded) {
- this.setState({ isFolded: this.props.isInitiallyFolded });
- }
- }
-
- onFileSelectionChange = (file, state) => {
- file.selected = state;
- this.setState({ tree: this.state.tree, downloadRequest: undefined, downloadError: '' })
- }
-
- download = (username, files) => {
- this.setState({ downloadRequest: 'inProgress' }, async () => {
- try {
- const requests = (files || []).map(({ filename, size }) => ({ filename, size }))
- await transfers.download({ username, files: requests })
-
- this.setState({ downloadRequest: 'complete' })
- } catch (err) {
- this.setState({ downloadRequest: 'error', downloadError: err.response })
- }
- });
- }
-
- toggleFolded = () => {
- this.setState({ isFolded: !this.state.isFolded });
- }
-
- render = () => {
- let response = this.props.response;
- let free = response.freeUploadSlots > 0;
-
- let { tree, downloadRequest, downloadError, isFolded } = this.state;
-
- let selectedFiles = Object.keys(tree)
- .reduce((list, dict) => list.concat(tree[dict]), [])
- .filter(f => f.selected);
-
- let selectedSize = formatBytes(selectedFiles.reduce((total, f) => total + f.size, 0));
-
- return (
- <Card className='result-card' raised>
- <Card.Content>
- <Card.Header>
- <Icon
- link
- name={isFolded ? 'chevron right' : 'chevron down'}
- onClick={this.toggleFolded}
- />
- <Icon name='circle' color={free ? 'green' : 'yellow'}/>
- {response.username}
- <Icon
- className='close-button'
- name='close'
- color='red'
- link
- onClick={() => this.props.onHide()}
- />
- </Card.Header>
- <Card.Meta className='result-meta'>
- <span>Upload Speed: {formatBytes(response.uploadSpeed)}/s, Free Upload Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength}</span>
- </Card.Meta>
- {((!isFolded && Object.keys(tree)) || []).map((dir, i) =>
- <FileList
- key={i}
- directoryName={dir}
- locked={tree[dir].find(file => file.locked)}
- files={tree[dir]}
- disabled={downloadRequest === 'inProgress'}
- onSelectionChange={this.onFileSelectionChange}
- />
- )}
- </Card.Content>
- {selectedFiles.length > 0 && <Card.Content extra>
- <span>
- <Button
- color='green'
- content='Download'
- icon='download'
- label={{
- as: 'a',
- basic: false,
- content: `${selectedFiles.length} file${selectedFiles.length === 1 ? '' : 's'}, ${selectedSize}`
- }}
- labelPosition='right'
- onClick={() => this.download(response.username, selectedFiles)}
- disabled={this.props.disabled || downloadRequest === 'inProgress'}
- />
- {downloadRequest === 'inProgress' && <Icon loading name='circle notch' size='large'/>}
- {downloadRequest === 'complete' && <Icon name='checkmark' color='green' size='large'/>}
- {downloadRequest === 'error' && <span>
- <Icon name='x' color='red' size='large'/>
- <Label>{downloadError.data + ` (HTTP ${downloadError.status} ${downloadError.statusText})`}</Label>
- </span>}
- </span>
- </Card.Content>}
- </Card>
- )
+ if (this.props.isInitiallyFolded !== prevProps.isInitiallyFolded) {
+ this.setState({ isFolded: this.props.isInitiallyFolded });
}
+ }
+
+ onFileSelectionChange = (file, state) => {
+ file.selected = state;
+ this.setState({ tree: this.state.tree, downloadRequest: undefined, downloadError: '' })
+ }
+
+ download = (username, files) => {
+ this.setState({ downloadRequest: 'inProgress' }, async () => {
+ try {
+ const requests = (files || []).map(({ filename, size }) => ({ filename, size }))
+ await transfers.download({ username, files: requests })
+
+ this.setState({ downloadRequest: 'complete' })
+ } catch (err) {
+ this.setState({ downloadRequest: 'error', downloadError: err.response })
+ }
+ });
+ }
+
+ toggleFolded = () => {
+ this.setState({ isFolded: !this.state.isFolded });
+ }
+
+ render = () => {
+ let {response} = this.props;
+ let free = response.freeUploadSlots > 0;
+
+ let { tree, downloadRequest, downloadError, isFolded } = this.state;
+
+ let selectedFiles = Object.keys(tree)
+ .reduce((list, dict) => list.concat(tree[dict]), [])
+ .filter(f => f.selected);
+
+ let selectedSize = formatBytes(selectedFiles.reduce((total, f) => total + f.size, 0));
+
+ return (
+ <Card className='result-card' raised>
+ <Card.Content>
+ <Card.Header>
+ <Icon
+ link
+ name={isFolded ? 'chevron right' : 'chevron down'}
+ onClick={this.toggleFolded}
+ />
+ <Icon name='circle' color={free ? 'green' : 'yellow'}/>
+ {response.username}
+ <Icon
+ className='close-button'
+ name='close'
+ color='red'
+ link
+ onClick={() => this.props.onHide()}
+ />
+ </Card.Header>
+ <Card.Meta className='result-meta'>
+ <span>
+ Upload Speed: {formatBytes(response.uploadSpeed)}/s,
+ Free Upload Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength}</span>
+ </Card.Meta>
+ {((!isFolded && Object.keys(tree)) || []).map((dir, i) =>
+ <FileList
+ key={i}
+ directoryName={dir}
+ locked={tree[dir].find(file => file.locked)}
+ files={tree[dir]}
+ disabled={downloadRequest === 'inProgress'}
+ onSelectionChange={this.onFileSelectionChange}
+ />
+ )}
+ </Card.Content>
+ {selectedFiles.length > 0 && <Card.Content extra>
+ <span>
+ <Button
+ color='green'
+ content='Download'
+ icon='download'
+ label={{
+ as: 'a',
+ basic: false,
+ content: `${selectedFiles.length} file${selectedFiles.length === 1 ? '' : 's'}, ${selectedSize}`,
+ }}
+ labelPosition='right'
+ onClick={() => this.download(response.username, selectedFiles)}
+ disabled={this.props.disabled || downloadRequest === 'inProgress'}
+ />
+ {downloadRequest === 'inProgress' && <Icon loading name='circle notch' size='large'/>}
+ {downloadRequest === 'complete' && <Icon name='checkmark' color='green' size='large'/>}
+ {downloadRequest === 'error' && <span>
+ <Icon name='x' color='red' size='large'/>
+ <Label>{downloadError.data + ` (HTTP ${downloadError.status} ${downloadError.statusText})`}</Label>
+ </span>}
+ </span>
+ </Card.Content>}
+ </Card>
+ )
+ }
}
export default Response;
diff --git a/src/web/src/components/Search/SearchStatusIcon.js b/src/web/src/components/Search/SearchStatusIcon.js
index 9ade1daf..8160d994 100644
--- a/src/web/src/components/Search/SearchStatusIcon.js
+++ b/src/web/src/components/Search/SearchStatusIcon.js
@@ -11,21 +11,21 @@ import { Icon, Popup } from 'semantic-ui-react';
const getIcon = ({ state, ...props }) => {
switch (state) {
- case 'None':
- case 'Requested':
- return <Icon name='time' {...props}/>
- case 'InProgress':
- return <Icon name='circle notch' loading color='green' {...props}/>
- case 'Completed, TimedOut':
- case 'Completed, ResponseLimitReached':
- case 'Completed, FileLimitReached':
- return <Icon name='check' color='green' {...props}/>
- case 'Completed, Cancelled':
- return <Icon name='stop circle' color='green' {...props}/>
- case 'Completed, Errored':
- return <Icon name='x' color='red' {...props}/>
- default:
- return <Icon name='question circle' color='yellow' {...props}/>
+ case 'None':
+ case 'Requested':
+ return <Icon name='time' {...props}/>
+ case 'InProgress':
+ return <Icon name='circle notch' loading color='green' {...props}/>
+ case 'Completed, TimedOut':
+ case 'Completed, ResponseLimitReached':
+ case 'Completed, FileLimitReached':
+ return <Icon name='check' color='green' {...props}/>
+ case 'Completed, Cancelled':
+ return <Icon name='stop circle' color='green' {...props}/>
+ case 'Completed, Errored':
+ return <Icon name='x' color='red' {...props}/>
+ default:
+ return <Icon name='question circle' color='yellow' {...props}/>
}
}
diff --git a/src/web/src/components/Search/Searches.js b/src/web/src/components/Search/Searches.js
index 9cc717ad..9caeb77e 100644
--- a/src/web/src/components/Search/Searches.js
+++ b/src/web/src/components/Search/Searches.js
@@ -95,7 +95,8 @@ const Searches = ({ server }) => {
// create a new search, and optionally navigate to it to display the details
// we do this if the user clicks the search icon, or repeats an existing search
const create = async ({ search, navigate = false } = {}) => {
- const searchText = search || inputRef.current.inputRef.current.value;
+ const ref = inputRef.current.inputRef.current;
+ const searchText = search || ref.value;
const id = uuidv4();
try {
@@ -103,7 +104,7 @@ const Searches = ({ server }) => {
await lib.create({ id, searchText })
try {
- inputRef.current.inputRef.current.value = '';
+ ref.value = '';
} catch {
// we are probably repeating an existing search; the input isn't mounted. no-op.
}
@@ -187,7 +188,12 @@ const Searches = ({ server }) => {
<>
<Segment className='search-segment' raised>
<Input
- input={<input placeholder={server.isConnected ? 'Search phrase' : 'Connect to server to perform a search'} type="search" data-lpignore="true"></input>}
+ input={
+ <input
+ placeholder={server.isConnected ? 'Search phrase' : 'Connect to server to perform a search'}
+ type="search"
+ data-lpignore="true"
+ ></input>}
size='big'
ref={inputRef}
loading={creating}
@@ -196,7 +202,11 @@ const Searches = ({ server }) => {
placeholder="Search phrase"
action={<>
<Button icon='plus' disabled={creating || !server.isConnected} onClick={create}/>
- <Button icon='search' disabled={creating || !server.isConnected} onClick={() => create({ navigate: true })}/>
+ <Button
+ icon='search'
+ disabled={creating || !server.isConnected}
+ onClick={() => create({ navigate: true })}
+ />
</>}
onKeyUp={(e) => e.key === 'Enter' ? create() : ''}
/>
diff --git a/src/web/src/components/Shared/ErrorSegment.js b/src/web/src/components/Shared/ErrorSegment.js
index 43c6fabb..dd5528de 100644
--- a/src/web/src/components/Shared/ErrorSegment.js
+++ b/src/web/src/components/Shared/ErrorSegment.js
@@ -4,11 +4,11 @@ import { Segment, Header, Icon } from 'semantic-ui-react';
const ErrorSegment = ({ icon = 'x', caption, suppressPrefix = false }) => (
<Segment className='error-segment' placeholder basic>
- <Header icon>
- <Icon name={icon} color='red'/>
- {!suppressPrefix && "Error: "}{caption}
- </Header>
-</Segment>
+ <Header icon>
+ <Icon name={icon} color='red'/>
+ {!suppressPrefix && 'Error: '}{caption}
+ </Header>
+ </Segment>
);
export default ErrorSegment; \ No newline at end of file
diff --git a/src/web/src/components/Shared/FileList.js b/src/web/src/components/Shared/FileList.js
index f38e602d..5c955d3b 100644
--- a/src/web/src/components/Shared/FileList.js
+++ b/src/web/src/components/Shared/FileList.js
@@ -3,11 +3,11 @@ import React from 'react';
import { formatSeconds, formatBytes, getFileName, formatAttributes } from '../../lib/util';
import {
- Header,
- Table,
- Icon,
- List,
- Checkbox
+ Header,
+ Table,
+ Icon,
+ List,
+ Checkbox,
} from 'semantic-ui-react';
const FileList = ({ directoryName, files, locked, onSelectionChange, disabled, onClose }) => (
@@ -18,15 +18,15 @@ const FileList = ({ directoryName, files, locked, onSelectionChange, disabled, o
>
<div>
<Icon size='large' name={locked ? 'lock' : 'folder'}/>
- {directoryName}
+ {directoryName}
{!!onClose && <Icon
- className='close-button'
- name='close'
- color='red'
- link
- onClick={() => onClose()}
- />}
+ className='close-button'
+ name='close'
+ color='red'
+ link
+ onClick={() => onClose()}
+ />}
</div>
</Header>
{files && files.length > 0 && <List>
@@ -59,7 +59,9 @@ const FileList = ({ directoryName, files, locked, onSelectionChange, disabled, o
disabled={disabled}
/>
</Table.Cell>
- <Table.Cell className='filelist-filename'>{locked ? <Icon name='lock'/> : ''}{getFileName(f.filename)}</Table.Cell>
+ <Table.Cell className='filelist-filename'>
+ {locked ? <Icon name='lock' /> : ''}{getFileName(f.filename)}
+ </Table.Cell>
<Table.Cell className='filelist-size'>{formatBytes(f.size)}</Table.Cell>
<Table.Cell className='filelist-attributes'>{formatAttributes(f)}</Table.Cell>
<Table.Cell className='filelist-length'>{formatSeconds(f.length)}</Table.Cell>
diff --git a/src/web/src/components/Shared/PlaceholderSegment.js b/src/web/src/components/Shared/PlaceholderSegment.js
index fe1ca7c6..0307b9e0 100644
--- a/src/web/src/components/Shared/PlaceholderSegment.js
+++ b/src/web/src/components/Shared/PlaceholderSegment.js
@@ -4,11 +4,11 @@ import { Segment, Header, Icon } from 'semantic-ui-react';
const PlaceholderSegment = ({ icon, caption, ...rest }) => (
<Segment className='placeholder-segment' placeholder basic {...rest}>
- <Header icon>
- <Icon name={icon}/>
- {caption}
- </Header>
-</Segment>
+ <Header icon>
+ <Icon name={icon}/>
+ {caption}
+ </Header>
+ </Segment>
);
export default PlaceholderSegment; \ No newline at end of file
diff --git a/src/web/src/components/System/Logs.js b/src/web/src/components/System/Logs.js
index aa545c63..945fd5e2 100644
--- a/src/web/src/components/System/Logs.js
+++ b/src/web/src/components/System/Logs.js
@@ -14,7 +14,7 @@ const levels = {
'Debug': 'DBG',
'Warning': 'WRN',
'Error': 'ERR',
- 'Information': 'INF'
+ 'Information': 'INF',
}
const maxLogs = 500;
@@ -42,7 +42,7 @@ class Logs extends Component {
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')}`;
+ 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 = () => {
@@ -61,7 +61,13 @@ class Logs extends Component {
</Table.Row>
</Table.Header>
<Table.Body className='logs-table-body'>
- {logs.map((log, index) => <Table.Row key={index} disabled={log.level === 'Debug'} warning={log.level === 'Warning'} negative={log.level === 'Error'}>
+ {logs.map((log, index) =>
+ <Table.Row
+ key={index}
+ disabled={log.level === 'Debug'}
+ warning={log.level === 'Warning'}
+ negative={log.level === 'Error'}
+ >
<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>
diff --git a/src/web/src/components/System/Options/Edit.js b/src/web/src/components/System/Options/Edit.js
index 54c0131f..825dd900 100644
--- a/src/web/src/components/System/Options/Edit.js
+++ b/src/web/src/components/System/Options/Edit.js
@@ -74,7 +74,8 @@ const Edit = ({ cancelAction }) => {
onChange={(value) => update(value)}
/>
</div>
- {(yamlError || updateError) && <Message className='no-grow' negative><Icon name='x'/>{(yamlError ?? '') + (updateError ?? '')}</Message>}
+ {(yamlError || updateError) &&
+ <Message className='no-grow' negative><Icon name='x' />{(yamlError ?? '') + (updateError ?? '')}</Message>}
<div className='footer-buttons'>
<Button primary disabled={!isDirty} onClick={() => save(yaml)}><Icon name='save'/>Save</Button>
<Button negative onClick={() => cancelAction()}><Icon name='close'/>Cancel</Button>
diff --git a/src/web/src/components/System/System.js b/src/web/src/components/System/System.js
index ca88c50d..a4c79e12 100644
--- a/src/web/src/components/System/System.js
+++ b/src/web/src/components/System/System.js
@@ -1,5 +1,5 @@
import React from 'react';
-import { useRouteMatch, useHistory, Redirect } from "react-router-dom";
+import { useRouteMatch, useHistory, Redirect } from 'react-router-dom';
import { Segment, Tab } from 'semantic-ui-react';
@@ -15,7 +15,10 @@ const System = ({ state = {}, options = {} }) => {
const panes = [
{ route: 'info', menuItem: 'Info', render: () => <Tab.Pane><Info state={state}/></Tab.Pane> },
- { route: 'options', menuItem: 'Options', render: () => <Tab.Pane className='full-height'><Options options={options}/></Tab.Pane> },
+ {
+ route: 'options', menuItem: 'Options', render: () =>
+ <Tab.Pane className='full-height'><Options options={options} /></Tab.Pane>,
+ },
{ route: 'logs', menuItem: 'Logs', render: () => <Tab.Pane><Logs/></Tab.Pane> },
]
diff --git a/src/web/src/components/Transfers/TransferGroup.js b/src/web/src/components/Transfers/TransferGroup.js
index 35955120..69b766a2 100644
--- a/src/web/src/components/Transfers/TransferGroup.js
+++ b/src/web/src/components/Transfers/TransferGroup.js
@@ -2,162 +2,164 @@ import React, { Component } from 'react';
import * as transfers from '../../lib/transfers';
import {
- Card,
- Button,
- Icon
+ Card,
+ Button,
+ Icon,
} from 'semantic-ui-react';
import TransferList from './TransferList';
class TransferGroup extends Component {
- state = {
- selections: new Set(),
- isFolded: false
- }
+ state = {
+ selections: new Set(),
+ isFolded: false,
+ }
- onSelectionChange = (directoryName, file, selected) => {
- const selections = this.state.selections;
- const obj = JSON.stringify({ directory: directoryName, filename: file.filename });
- selected ? selections.add(obj) : selections.delete(obj);
+ onSelectionChange = (directoryName, file, selected) => {
+ const {selections} = this.state;
+ const obj = JSON.stringify({ directory: directoryName, filename: file.filename });
+ selected ? selections.add(obj) : selections.delete(obj);
- this.setState({ selections });
- }
+ this.setState({ selections });
+ }
- isSelected = (directoryName, file) =>
- this.state.selections.has(JSON.stringify({ directory: directoryName, filename: file.filename }));
+ isSelected = (directoryName, file) =>
+ this.state.selections.has(JSON.stringify({ directory: directoryName, filename: file.filename }));
- getSelectedFiles = () => {
- const { user } = this.props;
+ getSelectedFiles = () => {
+ const { user } = this.props;
- return Array.from(this.state.selections)
- .map(s => JSON.parse(s))
- .map(s => user.directories
- .find(d => d.directory === s.directory)
- .files.find(f => f.filename === s.filename)
- ).filter(s => s !== undefined);
- }
-
- removeFileSelection = (file) => {
- const selections = this.state.selections;
-
- const match = Array.from(selections)
- .map(s => JSON.parse(s))
- .find(s => s.filename === file.filename);
-
- if (match) {
- selections.delete(JSON.stringify(match));
- this.setState({ selections });
- }
- }
-
- isStateRetryable = (state) => this.props.direction === 'download' && state.includes('Completed') && state !== 'Completed, Succeeded';
- isStateCancellable = (state) => ['InProgress', 'Requested', 'Queued', 'Queued, Remotely', 'Queued, Locally', 'Initializing'].find(s => s === state);
- isStateRemovable = (state) => state.includes('Completed');
-
- retryAll = async (selected) => {
- await Promise.all(selected.map(file => this.retry(file)));
- }
-
- cancelAll = async (direction, username, selected) => {
- await Promise.all(selected.map(file => transfers.cancel({ direction, username, id: file.id})));
- }
-
- removeAll = async (direction, username, selected) => {
- await Promise.all(selected.map(file =>
- transfers.cancel({ direction, username, id: file.id, remove: true })
- .then(() => this.removeFileSelection(file))));
+ return Array.from(this.state.selections)
+ .map(s => JSON.parse(s))
+ .map(s => user.directories
+ .find(d => d.directory === s.directory)
+ .files.find(f => f.filename === s.filename)
+ ).filter(s => s !== undefined);
+ }
+
+ removeFileSelection = (file) => {
+ const {selections} = this.state;
+
+ const match = Array.from(selections)
+ .map(s => JSON.parse(s))
+ .find(s => s.filename === file.filename);
+
+ if (match) {
+ selections.delete(JSON.stringify(match));
+ this.setState({ selections });
}
-
- retry = async (file) => {
- const { username, filename, size } = file;
+ }
+
+ isStateRetryable = (state) =>
+ this.props.direction === 'download' && state.includes('Completed') && state !== 'Completed, Succeeded';
+ isStateCancellable = (state) =>
+ ['InProgress', 'Requested', 'Queued', 'Queued, Remotely', 'Queued, Locally', 'Initializing'].find(s => s === state);
+ isStateRemovable = (state) => state.includes('Completed');
+
+ retryAll = async (selected) => {
+ await Promise.all(selected.map(file => this.retry(file)));
+ }
+
+ cancelAll = async (direction, username, selected) => {
+ await Promise.all(selected.map(file => transfers.cancel({ direction, username, id: file.id})));
+ }
+
+ removeAll = async (direction, username, selected) => {
+ await Promise.all(selected.map(file =>
+ transfers.cancel({ direction, username, id: file.id, remove: true })
+ .then(() => this.removeFileSelection(file))));
+ }
+
+ retry = async (file) => {
+ const { username, filename, size } = file;
- try {
- await transfers.download({username, files: [{filename, size }] });
- } catch (error) {
- console.log(error);
- }
+ try {
+ await transfers.download({username, files: [{filename, size }] });
+ } catch (error) {
+ console.log(error);
}
+ }
- fetchPlaceInQueue = async (file) => {
- const { username, id } = file;
+ fetchPlaceInQueue = async (file) => {
+ const { username, id } = file;
- try {
- await transfers.getPlaceInQueue({ username, id });
- } catch (error) {
- console.log(error);
- }
+ try {
+ await transfers.getPlaceInQueue({ username, id });
+ } catch (error) {
+ console.log(error);
}
+ }
- toggleFolded = () => {
- this.setState({'isFolded': !this.state.isFolded});
- }
+ toggleFolded = () => {
+ this.setState({'isFolded': !this.state.isFolded});
+ }
- render = () => {
- const { user, direction } = this.props;
- const isFolded = this.state.isFolded;
+ render = () => {
+ const { user, direction } = this.props;
+ const {isFolded} = this.state;
- const selected = this.getSelectedFiles();
- const all = selected.length > 1 ? ' Selected' : '';
+ const selected = this.getSelectedFiles();
+ const all = selected.length > 1 ? ' Selected' : '';
- const allRetryable = selected.filter(f => this.isStateRetryable(f.state)).length === selected.length;
- const anyCancellable = selected.filter(f => this.isStateCancellable(f.state)).length > 0;
- const allRemovable = selected.filter(f => this.isStateRemovable(f.state)).length === selected.length;
-
- return (
- <Card key={user.username} className='transfer-card' raised>
- <Card.Content>
- <Card.Header>
- <Icon
- link
- name={isFolded ? 'chevron right' : 'chevron down'}
- onClick={() => this.toggleFolded()}
- />
- {user.username}
- </Card.Header>
- {user.directories && !isFolded && user.directories
- .map((dir, index) =>
- <TransferList
- key={index}
- username={user.username}
- directoryName={dir.directory}
- files={(dir.files || []).map(f => ({ ...f, selected: this.isSelected(dir.directory, f) }))}
- onSelectionChange={this.onSelectionChange}
- direction={this.props.direction}
- onPlaceInQueueRequested={this.fetchPlaceInQueue}
- onRetryRequested={this.retry}
- />
- )}
- </Card.Content>
- {selected && selected.length > 0 &&
+ const allRetryable = selected.filter(f => this.isStateRetryable(f.state)).length === selected.length;
+ const anyCancellable = selected.filter(f => this.isStateCancellable(f.state)).length > 0;
+ const allRemovable = selected.filter(f => this.isStateRemovable(f.state)).length === selected.length;
+
+ return (
+ <Card key={user.username} className='transfer-card' raised>
+ <Card.Content>
+ <Card.Header>
+ <Icon
+ link
+ name={isFolded ? 'chevron right' : 'chevron down'}
+ onClick={() => this.toggleFolded()}
+ />
+ {user.username}
+ </Card.Header>
+ {user.directories && !isFolded && user.directories
+ .map((dir, index) =>
+ <TransferList
+ key={index}
+ username={user.username}
+ directoryName={dir.directory}
+ files={(dir.files || []).map(f => ({ ...f, selected: this.isSelected(dir.directory, f) }))}
+ onSelectionChange={this.onSelectionChange}
+ direction={this.props.direction}
+ onPlaceInQueueRequested={this.fetchPlaceInQueue}
+ onRetryRequested={this.retry}
+ />
+ )}
+ </Card.Content>
+ {selected && selected.length > 0 &&
<Card.Content extra>
- {<Button.Group>
- {allRetryable &&
+ {<Button.Group>
+ {allRetryable &&
<Button
- icon='redo'
- color='green'
- content={`Retry${all}`}
- onClick={() => this.retryAll(selected)}
+ icon='redo'
+ color='green'
+ content={`Retry${all}`}
+ onClick={() => this.retryAll(selected)}
/>}
- {allRetryable && anyCancellable && <Button.Or/>}
- {anyCancellable &&
+ {allRetryable && anyCancellable && <Button.Or/>}
+ {anyCancellable &&
<Button
- icon='x'
- color='red'
- content={`Cancel${all}`}
- onClick={() => this.cancelAll(direction, user.username, selected)}
+ icon='x'
+ color='red'
+ content={`Cancel${all}`}
+ onClick={() => this.cancelAll(direction, user.username, selected)}
/>}
- {(allRetryable || anyCancellable) && allRemovable && <Button.Or/>}
- {allRemovable &&
+ {(allRetryable || anyCancellable) && allRemovable && <Button.Or/>}
+ {allRemovable &&
<Button
- icon='delete'
- content={`Remove${all}`}
- onClick={() => this.removeAll(direction, user.username, selected)}
+ icon='delete'
+ content={`Remove${all}`}
+ onClick={() => this.removeAll(direction, user.username, selected)}
/>}
- </Button.Group>}
+ </Button.Group>}
</Card.Content>}
- </Card>
- );
- }
+ </Card>
+ );
+ }
}
export default TransferGroup;
diff --git a/src/web/src/components/Transfers/TransferList.js b/src/web/src/components/Transfers/TransferList.js
index 94b4b050..5908c9cb 100644
--- a/src/web/src/components/Transfers/TransferList.js
+++ b/src/web/src/components/Transfers/TransferList.js
@@ -1,147 +1,150 @@
import React, { Component } from 'react';
import {
- Checkbox
+ Checkbox,
} from 'semantic-ui-react';
import { formatBytes, getFileName } from '../../lib/util';
import {
- Header,
- Table,
- Icon,
- List,
- Progress,
- Button
+ Header,
+ Table,
+ Icon,
+ List,
+ Progress,
+ Button,
} from 'semantic-ui-react';
const getColor = (state) => {
- switch(state) {
- case 'InProgress':
- return { color: 'blue' };
- case 'Completed, Succeeded':
- return { color: 'green' };
- case 'Requested':
- case 'Queued, Locally':
- case 'Queued, Remotely':
- case 'Queued':
- return {};
- case 'Initializing':
- return { color: 'teal' };
- default:
- return { color: 'red' };
- }
+ switch(state) {
+ case 'InProgress':
+ return { color: 'blue' };
+ case 'Completed, Succeeded':
+ return { color: 'green' };
+ case 'Requested':
+ case 'Queued, Locally':
+ case 'Queued, Remotely':
+ case 'Queued':
+ return {};
+ case 'Initializing':
+ return { color: 'teal' };
+ default:
+ return { color: 'red' };
+ }
}
const isRetryableState = (state) => getColor(state).color === 'red';
const isQueuedState = (state) => state.includes('Queued');
const formatBytesTransferred = ({ transferred, size }) => {
- const [t, tExt] = formatBytes(transferred).split(' ')
- const [s, sExt] = formatBytes(size).split(' ')
+ const [t, tExt] = formatBytes(transferred).split(' ')
+ const [s, sExt] = formatBytes(size).split(' ')
- const fmt = (n) => parseFloat(n).toFixed(2);
+ const fmt = (n) => parseFloat(n).toFixed(2);
- // if less than 1 MB has been transferred, don't include decimals
- if (tExt === 'KB') {
- return `${t} KB/${fmt(s)} ${sExt}`
- }
+ // if less than 1 MB has been transferred, don't include decimals
+ if (tExt === 'KB') {
+ return `${t} KB/${fmt(s)} ${sExt}`
+ }
- // if the suffix for size and transferred doesn't match, include
- // the suffix for each
- if (tExt !== sExt) {
- return `${fmt(t)} ${tExt}/${fmt(s)} ${sExt}`
- }
+ // if the suffix for size and transferred doesn't match, include
+ // the suffix for each
+ if (tExt !== sExt) {
+ return `${fmt(t)} ${tExt}/${fmt(s)} ${sExt}`
+ }
- return `${fmt(t)}/${fmt(s)} ${sExt}`
+ return `${fmt(t)}/${fmt(s)} ${sExt}`
}
class TransferList extends Component {
- handleClick = (file) => {
- const { state, direction } = file;
+ handleClick = (file) => {
+ const { state, direction } = file;
- if (direction === 'Download') {
- if (isRetryableState(state)) {
- return this.props.onRetryRequested(file);
- }
+ if (direction === 'Download') {
+ if (isRetryableState(state)) {
+ return this.props.onRetryRequested(file);
+ }
- if (isQueuedState(state)) {
- return this.props.onPlaceInQueueRequested(file);
- }
- }
- }
+ if (isQueuedState(state)) {
+ return this.props.onPlaceInQueueRequested(file);
+ }
+ }
+ }
- render = () => {
- const { directoryName, onSelectionChange, files } = this.props;
+ render = () => {
+ const { directoryName, onSelectionChange, files } = this.props;
- return (
- <div>
- <Header
- size='small'
- className='filelist-header'
- >
- <Icon name='folder'/>{directoryName}
- </Header>
- <List>
- <List.Item>
- <Table>
- <Table.Header>
- <Table.Row>
- <Table.HeaderCell className='transferlist-selector'>
- <Checkbox
- fitted
- checked={files.filter(f => !f.selected).length === 0}
- onChange={(event, data) => files.map(file => onSelectionChange(directoryName, file, data.checked))}
- />
- </Table.HeaderCell>
- <Table.HeaderCell className='transferlist-filename'>File</Table.HeaderCell>
- <Table.HeaderCell className='transferlist-progress'>Progress</Table.HeaderCell>
- <Table.HeaderCell className='transferlist-size'>Size</Table.HeaderCell>
- </Table.Row>
- </Table.Header>
- <Table.Body>
- {files.sort((a, b) => getFileName(a.filename).localeCompare(getFileName(b.filename))).map((f, i) =>
- <Table.Row key={i}>
- <Table.Cell className='transferlist-selector'>
- <Checkbox
- fitted
- checked={f.selected}
- onChange={(event, data) => onSelectionChange(directoryName, f, data.checked)}
- />
- </Table.Cell>
- <Table.Cell className='transferlist-filename'>{getFileName(f.filename)}</Table.Cell>
- <Table.Cell className='transferlist-progress'>
- {f.state === 'InProgress' ?
- <Progress
- style={{ margin: 0 }}
- percent={Math.round(f.percentComplete)}
- progress color={getColor(f.state).color}
- /> :
- <Button
- fluid
- size='mini'
- style={{ margin: 0, padding: 7, cursor: f.direction === 'Upload' ? 'unset' : '' }}
- {...getColor(f.state)}
- onClick={() => this.handleClick(f)}
- active={f.direction === 'Upload'}
- >
- {f.direction === 'Download' && isQueuedState(f.state) && <Icon name='refresh'/>}
- {f.direction === 'Download' && isRetryableState(f.state) && <Icon name='redo'/>}
- {f.state}{f.placeInQueue ? ` (#${f.placeInQueue})` : ''}
- </Button>}
- </Table.Cell>
- <Table.Cell className='transferlist-size'>
- {f.bytesTransferred > 0 ? formatBytesTransferred({ transferred: f.bytesTransferred, size: f.size }) : ''}
- </Table.Cell>
- </Table.Row>
- )}
- </Table.Body>
- </Table>
- </List.Item>
- </List>
- </div>
- )
- }
-};
+ return (
+ <div>
+ <Header
+ size='small'
+ className='filelist-header'
+ >
+ <Icon name='folder'/>{directoryName}
+ </Header>
+ <List>
+ <List.Item>
+ <Table>
+ <Table.Header>
+ <Table.Row>
+ <Table.HeaderCell className='transferlist-selector'>
+ <Checkbox
+ fitted
+ checked={files.filter(f => !f.selected).length === 0}
+ onChange={(event, data) =>
+ files.map(file => onSelectionChange(directoryName, file, data.checked))}
+ />
+ </Table.HeaderCell>
+ <Table.HeaderCell className='transferlist-filename'>File</Table.HeaderCell>
+ <Table.HeaderCell className='transferlist-progress'>Progress</Table.HeaderCell>
+ <Table.HeaderCell className='transferlist-size'>Size</Table.HeaderCell>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {files.sort((a, b) => getFileName(a.filename).localeCompare(getFileName(b.filename))).map((f, i) =>
+ <Table.Row key={i}>
+ <Table.Cell className='transferlist-selector'>
+ <Checkbox
+ fitted
+ checked={f.selected}
+ onChange={(event, data) => onSelectionChange(directoryName, f, data.checked)}
+ />
+ </Table.Cell>
+ <Table.Cell className='transferlist-filename'>{getFileName(f.filename)}</Table.Cell>
+ <Table.Cell className='transferlist-progress'>
+ {f.state === 'InProgress' ?
+ <Progress
+ style={{ margin: 0 }}
+ percent={Math.round(f.percentComplete)}
+ progress color={getColor(f.state).color}
+ /> :
+ <Button
+ fluid
+ size='mini'
+ style={{ margin: 0, padding: 7, cursor: f.direction === 'Upload' ? 'unset' : '' }}
+ {...getColor(f.state)}
+ onClick={() => this.handleClick(f)}
+ active={f.direction === 'Upload'}
+ >
+ {f.direction === 'Download' && isQueuedState(f.state) && <Icon name='refresh'/>}
+ {f.direction === 'Download' && isRetryableState(f.state) && <Icon name='redo'/>}
+ {f.state}{f.placeInQueue ? ` (#${f.placeInQueue})` : ''}
+ </Button>}
+ </Table.Cell>
+ <Table.Cell className='transferlist-size'>
+ {f.bytesTransferred > 0
+ ? formatBytesTransferred({ transferred: f.bytesTransferred, size: f.size })
+ : ''}
+ </Table.Cell>
+ </Table.Row>
+ )}
+ </Table.Body>
+ </Table>
+ </List.Item>
+ </List>
+ </div>
+ )
+ }
+}
export default TransferList;
diff --git a/src/web/src/components/Transfers/Transfers.js b/src/web/src/components/Transfers/Transfers.js
index 3d65ca69..76e73a53 100644
--- a/src/web/src/components/Transfers/Transfers.js
+++ b/src/web/src/components/Transfers/Transfers.js
@@ -22,7 +22,7 @@ class Transfers extends Component {
try {
const response = await transfers.getAll({ direction: this.props.direction })
this.setState({
- fetchState: 'complete', downloads: response
+ fetchState: 'complete', downloads: response,
})
} catch (err) {
this.setState({ fetchState: 'failed' })
@@ -36,12 +36,12 @@ class Transfers extends Component {
return (
downloads.length === 0 ?
- <PlaceholderSegment icon={direction}/> :
- <div className='transfer-segment'>
- {downloads.map((user, index) =>
- <TransferGroup key={index} direction={this.props.direction} user={user}/>
- )}
- </div>
+ <PlaceholderSegment icon={direction}/> :
+ <div className='transfer-segment'>
+ {downloads.map((user, index) =>
+ <TransferGroup key={index} direction={this.props.direction} user={user}/>
+ )}
+ </div>
);
}
}
diff --git a/src/web/src/components/Users/User.js b/src/web/src/components/Users/User.js
index e196844e..38d11a22 100644
--- a/src/web/src/components/Users/User.js
+++ b/src/web/src/components/Users/User.js
@@ -1,6 +1,6 @@
import {
Item,
- Icon
+ Icon,
} from 'semantic-ui-react';
const ImagePlaceholder = () =>
@@ -9,7 +9,7 @@ const ImagePlaceholder = () =>
const Presence = ({ presence }) => {
const colors = {
Away: 'yellow',
- Online: 'green'
+ Online: 'green',
}
return <Icon name='circle' color={colors[presence] || 'grey'}/>
@@ -23,36 +23,37 @@ const FreeUploadSlot = ({ hasFreeUploadSlot }) => (
);
const User = ({
- username,
- description,
- hasFreeUploadSlot,
- hasPicture,
- picture,
- queueLength,
- uploadSlots,
- updatedAt,
- isPrivileged,
- presence,
- address,
- port,
- }) => (
- <>
- <Item>
- {hasPicture ?
- <Item.Image size='small' src={`data:image;base64,${picture}`} />
- : <ImagePlaceholder/>}
+ username,
+ description,
+ hasFreeUploadSlot,
+ hasPicture,
+ picture,
+ queueLength,
+ uploadSlots,
+ updatedAt,
+ isPrivileged,
+ presence,
+ address,
+ port,
+}) => (
+ <>
+ <Item>
+ {hasPicture ?
+ <Item.Image size='small' src={`data:image;base64,${picture}`} />
+ : <ImagePlaceholder/>}
- <Item.Content>
- <Item.Header as='a'><Presence presence={presence}/>{username}</Item.Header>
- <Item.Meta>
- Free Upload Slot: <FreeUploadSlot hasFreeUploadSlot/>, Total Upload Slots: {uploadSlots}, Queue Length: {queueLength}, IP Address: {address}, Port: {port}
- </Item.Meta>
- <Item.Description>
- {description || 'No user info.'}
- </Item.Description>
- </Item.Content>
- </Item>
- </>
+ <Item.Content>
+ <Item.Header as='a'><Presence presence={presence}/>{username}</Item.Header>
+ <Item.Meta>
+ Free Upload Slot: <FreeUploadSlot hasFreeUploadSlot />,
+ Total Upload Slots: {uploadSlots}, Queue Length: {queueLength}, IP Address: {address}, Port: {port}
+ </Item.Meta>
+ <Item.Description>
+ {description || 'No user info.'}
+ </Item.Description>
+ </Item.Content>
+ </Item>
+ </>
);
export default User; \ No newline at end of file
diff --git a/src/web/src/components/Users/Users.js b/src/web/src/components/Users/Users.js
index 7927b718..71084bcb 100644
--- a/src/web/src/components/Users/Users.js
+++ b/src/web/src/components/Users/Users.js
@@ -3,7 +3,7 @@ import {
Item,
Segment,
Loader,
- Input
+ Input,
} from 'semantic-ui-react';
import User from './User';
@@ -21,7 +21,7 @@ const Users = (props) => {
const [{ fetching, error }, setStatus] = useState({ fetching: false, error: undefined });
useEffect(() => {
- document.addEventListener("keyup", keyUp, false);
+ document.addEventListener('keyup', keyUp, false);
const storedUsername = localStorage.getItem(activeUserInfoKey);
@@ -47,7 +47,7 @@ const Users = (props) => {
const [info, status, endpoint] = await Promise.all([
users.getInfo({ username: selectedUsername }),
users.getStatus({ username: selectedUsername }),
- users.getEndpoint({ username: selectedUsername })
+ users.getEndpoint({ username: selectedUsername }),
]);
localStorage.setItem(activeUserInfoKey, selectedUsername);
@@ -83,7 +83,8 @@ const Users = (props) => {
<div className='users-container'>
<Segment className='users-selection' raised>
<Input
- input={<input placeholder="Username" type="search" data-lpignore="true" disabled={!!user || fetching}></input>}
+ input={
+ <input placeholder="Username" type="search" data-lpignore="true" disabled={!!user || fetching}></input>}
size='big'
loading={fetching}
disabled={fetching}
@@ -91,7 +92,9 @@ const Users = (props) => {
className='users-input'
placeholder="Username"
onChange={(e) => setUsernameInput(e.target.value)}
- action={!fetching && (!user ? { icon: 'search', onClick: () => setSelectedUsername(usernameInput) } : { icon: 'x', color: 'red', onClick: clear })}
+ action={!fetching && (!user
+ ? { icon: 'search', onClick: () => setSelectedUsername(usernameInput) }
+ : { icon: 'x', color: 'red', onClick: clear })}
onKeyUp={(e) => e.key === 'Enter' ? setSelectedUsername(usernameInput) : ''}
/>
</Segment>
diff --git a/src/web/src/config.js b/src/web/src/config.js
index b9dedf38..1cec9668 100644
--- a/src/web/src/config.js
+++ b/src/web/src/config.js
@@ -9,13 +9,13 @@ const activeRoomKey = 'slskd-active-room';
const activeUserInfoKey = 'slskd-active-user';
export {
- urlBase,
- rootUrl,
- apiBaseUrl,
- hubBaseUrl,
- tokenKey,
- tokenPassthroughValue,
- activeChatKey,
- activeRoomKey,
- activeUserInfoKey,
+ urlBase,
+ rootUrl,
+ apiBaseUrl,
+ hubBaseUrl,
+ tokenKey,
+ tokenPassthroughValue,
+ activeChatKey,
+ activeRoomKey,
+ activeUserInfoKey,
};
diff --git a/src/web/src/index.js b/src/web/src/index.js
index df18e558..b67f8f41 100644
--- a/src/web/src/index.js
+++ b/src/web/src/index.js
@@ -1,11 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom';
-import { BrowserRouter as Router } from "react-router-dom";
+import { BrowserRouter as Router } from 'react-router-dom';
import 'semantic-ui-css/semantic.min.css';
import App from './components/App';
ReactDOM.render(
- <Router>
- <App />
- </Router>
-, document.getElementById('root')); \ No newline at end of file
+ <Router>
+ <App />
+ </Router>, document.getElementById('root')); \ No newline at end of file
diff --git a/src/web/src/lib/api.js b/src/web/src/lib/api.js
index 0e7d8050..85c72d82 100644
--- a/src/web/src/lib/api.js
+++ b/src/web/src/lib/api.js
@@ -5,19 +5,19 @@ import * as session from './session';
axios.defaults.baseURL = apiBaseUrl;
const api = axios.create({
- withCredentials: true
+ withCredentials: true,
});
api.interceptors.request.use(config => {
- const token = session.getToken();
+ const token = session.getToken();
- config.headers['Content-Type'] = 'application/json';
+ config.headers['Content-Type'] = 'application/json';
- if (!session.isPassthroughEnabled() && token) {
- config.headers.Authorization = 'Bearer ' + token;
- }
+ if (!session.isPassthroughEnabled() && token) {
+ config.headers.Authorization = 'Bearer ' + token;
+ }
- return config;
+ return config;
});
api.interceptors.response.use(response => {
@@ -31,7 +31,7 @@ api.interceptors.response.use(response => {
return Promise.reject(error);
}
else {
- return Promise.reject(error);
+ return Promise.reject(error);
}
});
diff --git a/src/web/src/lib/hubFactory.js b/src/web/src/lib/hubFactory.js
index 8b41226e..effe3be0 100644
--- a/src/web/src/lib/hubFactory.js
+++ b/src/web/src/lib/hubFactory.js
@@ -1,7 +1,7 @@
import {
JsonHubProtocol,
HubConnectionBuilder,
- LogLevel
+ LogLevel,
} from '@microsoft/signalr'
import { hubBaseUrl } from '../config';
@@ -10,8 +10,8 @@ import * as session from '../lib/session';
export const createHubConnection = ({ url }) =>
new HubConnectionBuilder()
.withUrl(url, {
- withCredentials: true,
- accessTokenFactory: session.isPassthroughEnabled() ? undefined : session.getToken
+ withCredentials: true,
+ accessTokenFactory: session.isPassthroughEnabled() ? undefined : session.getToken,
})
.withAutomaticReconnect([0, 100, 250, 500, 1000, 2000, 3000, 5000, 5000, 5000, 5000, 5000])
.withHubProtocol(new JsonHubProtocol())
diff --git a/src/web/src/lib/searches.js b/src/web/src/lib/searches.js
index 9561ab40..46e506cb 100644
--- a/src/web/src/lib/searches.js
+++ b/src/web/src/lib/searches.js
@@ -13,7 +13,7 @@ export const remove = ({ id }) => {
}
export const create = ({ id, searchText }) => {
- return api.post(`/searches`, { id, searchText });
+ return api.post('/searches', { id, searchText });
};
export const getStatus = async ({ id, includeResponses = false }) => {
@@ -64,7 +64,8 @@ export const parseFiltersFromString = (string) => {
filters.isLossy = !!string.match(/islossy/i);
let terms = string.toLowerCase().split(' ')
- .filter(term => !term.includes(':') && term !== 'isvbr' && term !== 'iscbr' && term !== 'islossless' && term !== 'islossy');
+ .filter(term =>
+ !term.includes(':') && term !== 'isvbr' && term !== 'iscbr' && term !== 'islossless' && term !== 'islossy');
filters.include = terms.filter(term => !term.startsWith('-'));
filters.exclude = terms.filter(term => term.startsWith('-')).map(term => term.slice(1));
@@ -86,8 +87,8 @@ export const filterResponse = ({
},
response = {
files: [],
- lockedFiles: []
- }
+ lockedFiles: [],
+ },
}) => {
let { files = [], lockedFiles = [] } = response;
@@ -97,7 +98,11 @@ export const filterResponse = ({
const filterFiles = (files) => files.filter(file => {
const { bitRate, size, length, filename, sampleRate, bitDepth, isVariableBitRate } = file;
- const { isCBR, isVBR, isLossless, isLossy, minBitRate, minFileSize, minLength, include = [], exclude = [] } = filters;
+ const {
+ isCBR, isVBR, isLossless, isLossy,
+ minBitRate, minFileSize, minLength,
+ include = [], exclude = [],
+ } = filters;
if (isCBR && (isVariableBitRate === undefined || isVariableBitRate)) return false;
if (isVBR && (isVariableBitRate === undefined || !isVariableBitRate)) return false;
@@ -107,7 +112,10 @@ export const filterResponse = ({
if (size < minFileSize) return false;
if (length < minLength) return false;
- if (include.length > 0 && include.filter(term => filename.toLowerCase().includes(term)).length !== include.length) return false;
+ if (include.length > 0 && include.filter(term => filename.toLowerCase().includes(term)).length !== include.length) {
+ return false;
+ }
+
if (exclude.length > 0 && exclude.filter(term => filename.toLowerCase().includes(term)).length !== 0) return false;
return true;
@@ -121,6 +129,6 @@ export const filterResponse = ({
fileCount: filteredFiles.length,
lockedFileCount: filteredLockedFiles.length,
files: filteredFiles,
- lockedFiles: filteredLockedFiles
+ lockedFiles: filteredLockedFiles,
};
}; \ No newline at end of file
diff --git a/src/web/src/lib/searches.test.js b/src/web/src/lib/searches.test.js
index 737843ed..8baf02ab 100644
--- a/src/web/src/lib/searches.test.js
+++ b/src/web/src/lib/searches.test.js
@@ -5,16 +5,16 @@ describe('filterResponse', () => {
const response = {
files: [
{ bitRate: 123, isVariableBitRate: true },
- { bitRate: 320, isVariableBitRate: false }
- ]
+ { bitRate: 320, isVariableBitRate: false },
+ ],
};
const filters = { isCBR: true };
expect(search.filterResponse({ response, filters })).toMatchObject({
files: [
- { bitRate: 320, isVariableBitRate: false }
- ]
+ { bitRate: 320, isVariableBitRate: false },
+ ],
});
});
@@ -22,16 +22,16 @@ describe('filterResponse', () => {
const response = {
files: [
{ bitRate: 123, isVariableBitRate: true },
- { bitRate: 320, isVariableBitRate: false }
- ]
+ { bitRate: 320, isVariableBitRate: false },
+ ],
};
const filters = { isVBR: true };
expect(search.filterResponse({ response, filters })).toMatchObject({
files: [
- { bitRate: 123, isVariableBitRate: true }
- ]
+ { bitRate: 123, isVariableBitRate: true },
+ ],
});
});
@@ -39,14 +39,14 @@ describe('filterResponse', () => {
const response = {
files: [
{ isVariableBitrate: true },
- { isVariableBitrate: false }
- ]
+ { isVariableBitrate: false },
+ ],
};
const filters = { isCBR: true, isVBR: true };
expect(search.filterResponse({ response, filters })).toMatchObject({
- files: []
+ files: [],
});
});
@@ -54,16 +54,16 @@ describe('filterResponse', () => {
const response = {
files: [
{ sampleRate: 41000, bitDepth: 16 },
- { bitRate: 320, isVariableBitRate: false }
- ]
+ { bitRate: 320, isVariableBitRate: false },
+ ],
};
const filters = { isLossless: true };
expect(search.filterResponse({ response, filters })).toMatchObject({
files: [
- { sampleRate: 41000, bitDepth: 16 }
- ]
+ { sampleRate: 41000, bitDepth: 16 },
+ ],
});
});
@@ -71,16 +71,16 @@ describe('filterResponse', () => {
const response = {
files: [
{ sampleRate: 41000, bitDepth: 16 },
- { bitRate: 320, isVariableBitRate: false }
- ]
+ { bitRate: 320, isVariableBitRate: false },
+ ],
};
const filters = { isLossy: true };
expect(search.filterResponse({ response, filters })).toMatchObject({
files: [
- { bitRate: 320, isVariableBitRate: false }
- ]
+ { bitRate: 320, isVariableBitRate: false },
+ ],
});
});
@@ -88,16 +88,16 @@ describe('filterResponse', () => {
const response = {
files: [
{ bitRate: 100 },
- { bitRate: 99 }
- ]
+ { bitRate: 99 },
+ ],
};
const filters = { minBitRate: 100 };
expect(search.filterResponse({ response, filters })).toMatchObject({
files: [
- { bitRate: 100 }
- ]
+ { bitRate: 100 },
+ ],
});
});
@@ -105,16 +105,16 @@ describe('filterResponse', () => {
const response = {
files: [
{ size: 100 },
- { size: 99 }
- ]
+ { size: 99 },
+ ],
};
const filters = { minFileSize: 100 };
expect(search.filterResponse({ response, filters })).toMatchObject({
files: [
- { size: 100 }
- ]
+ { size: 100 },
+ ],
});
});
@@ -122,16 +122,16 @@ describe('filterResponse', () => {
const response = {
files: [
{ length: 100 },
- { length: 99 }
- ]
+ { length: 99 },
+ ],
};
const filters = { minLength: 100 };
expect(search.filterResponse({ response, filters })).toMatchObject({
files: [
- { length: 100 }
- ]
+ { length: 100 },
+ ],
});
});
@@ -143,8 +143,8 @@ describe('filterResponse', () => {
{ filename: '/path/to/baz.mp3' },
{ filename: '/path/to/qux.mp3' },
{ filename: '/path/to/info.nfo' },
- { filename: '/path/to/folder.jpg' }
- ]
+ { filename: '/path/to/folder.jpg' },
+ ],
};
it('removes files with filenames not containing included phrases', () => {
@@ -153,7 +153,7 @@ describe('filterResponse', () => {
expect(search.filterResponse({ response, filters })).toMatchObject({
files: [
{ filename: '/path/to/info.nfo' },
- ]
+ ],
});
});
@@ -165,21 +165,21 @@ describe('filterResponse', () => {
{ filename: '/path/to/foo.mp3' },
{ filename: '/path/to/baz.mp3' },
{ filename: '/path/to/info.nfo' },
- ]
+ ],
});
});
it('removes a mix of includes and excludes', () => {
const filters = {
include: ['path', '.mp3'],
- exclude: ['foo', 'bar']
+ exclude: ['foo', 'bar'],
};
expect(search.filterResponse({ response, filters })).toMatchObject({
files: [
{ filename: '/path/to/baz.mp3' },
{ filename: '/path/to/qux.mp3' },
- ]
+ ],
});
});
});
@@ -188,80 +188,80 @@ describe('filterResponse', () => {
describe('parseFiltersFromString', () => {
it('returns correct minBitrate', () => {
expect(search.parseFiltersFromString('foo minbr:42 bar')).toMatchObject({
- minBitRate: 42
+ minBitRate: 42,
});
expect(search.parseFiltersFromString('foo minbitrate:123 bar')).toMatchObject({
- minBitRate: 123
+ minBitRate: 123,
});
});
it('returns correct minFileSize', () => {
expect(search.parseFiltersFromString('foo minfs:42 bar')).toMatchObject({
- minFileSize: 42
+ minFileSize: 42,
});
expect(search.parseFiltersFromString('foo minfilesize:123 bar')).toMatchObject({
- minFileSize: 123
+ minFileSize: 123,
});
});
it('returns correct minLength', () => {
expect(search.parseFiltersFromString('foo minlen:42 bar')).toMatchObject({
- minLength: 42
+ minLength: 42,
});
expect(search.parseFiltersFromString('foo minlength:123 bar')).toMatchObject({
- minLength: 123
+ minLength: 123,
});
});
it('returns correct minFilesInFolder', () => {
expect(search.parseFiltersFromString('foo minfif:42 bar')).toMatchObject({
- minFilesInFolder: 42
+ minFilesInFolder: 42,
});
expect(search.parseFiltersFromString('foo minfilesinfolder:123 bar')).toMatchObject({
- minFilesInFolder: 123
+ minFilesInFolder: 123,
});
});
it('returns correct list of terms', () => {
expect(search.parseFiltersFromString('foo minbr:42 bar')).toMatchObject({
- include: [ 'foo', 'bar']
+ include: [ 'foo', 'bar'],
});
expect(search.parseFiltersFromString('foo iscbr isvbr bar')).toMatchObject({
- include: [ 'foo', 'bar']
+ include: [ 'foo', 'bar'],
});
expect(search.parseFiltersFromString('foo some:thing bar')).toMatchObject({
- include: [ 'foo', 'bar']
+ include: [ 'foo', 'bar'],
});
expect(search.parseFiltersFromString('foo -bar')).toMatchObject({
include: [ 'foo' ],
- exclude: [ 'bar' ]
+ exclude: [ 'bar' ],
});
expect(search.parseFiltersFromString('-foo -bar -baz qux')).toMatchObject({
exclude: [ 'foo', 'bar', 'baz' ],
- include: [ 'qux' ]
+ include: [ 'qux' ],
});
expect(search.parseFiltersFromString('foo bar baz -qux')).toMatchObject({
include: [ 'foo', 'bar', 'baz' ],
- exclude: [ 'qux' ]
+ exclude: [ 'qux' ],
});
});
it('returns isVBR and isCBR if terms are present', () => {
expect(search.parseFiltersFromString('isvbr')).toMatchObject({
- isVBR: true
+ isVBR: true,
});
expect(search.parseFiltersFromString('iscbr')).toMatchObject({
- isCBR: true
+ isCBR: true,
});
});
@@ -271,7 +271,7 @@ describe('parseFiltersFromString', () => {
exclude: [ 'mix' ],
isVBR: true,
isCBR: true,
- minBitRate: 42
+ minBitRate: 42,
});
});
}); \ No newline at end of file
diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js
index 1704a990..f00b0683 100644
--- a/src/web/src/lib/util.js
+++ b/src/web/src/lib/util.js
@@ -1,94 +1,102 @@
export const formatSeconds = (seconds) =>
{
- if (isNaN(seconds)) return '';
- var date = new Date(1970,0,1);
- date.setSeconds(seconds);
- return date.toTimeString().replace(/.*(\d{2}:\d{2}).*/, "$1");
+ if (isNaN(seconds)) return '';
+ var date = new Date(1970,0,1);
+ date.setSeconds(seconds);
+ return date.toTimeString().replace(/.*(\d{2}:\d{2}).*/, '$1');
}
export const formatBytes = (bytes, decimals = 2) => {
- if (bytes === 0) return '0 Bytes';
+ if (bytes === 0) return '0 Bytes';
- const k = 1024;
- const dm = decimals < 0 ? 0 : decimals;
- const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
+ const k = 1024;
+ const dm = decimals < 0 ? 0 : decimals;
+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
export const getFileName = (fullPath) => {
- return fullPath.split('\\').pop().split('/').pop();
+ return fullPath.split('\\').pop().split('/').pop();
}
export const getDirectoryName = (fullPath) => {
- let path = fullPath;
+ let path = fullPath;
- if (path.lastIndexOf('\\') > 0)
- path = path.substring(0, path.lastIndexOf('\\'));
+ if (path.lastIndexOf('\\') > 0)
+ {path = path.substring(0, path.lastIndexOf('\\'));}
- if (path.lastIndexOf('/') > 0)
- path = path.substring(0, path.lastIndexOf('/'));
+ if (path.lastIndexOf('/') > 0)
+ {path = path.substring(0, path.lastIndexOf('/'));}
- return path;
+ return path;
}
export const formatAttributes = ({ bitRate, isVariableBitRate, bitDepth, sampleRate }) => {
- const isLossless = !!sampleRate && !!bitDepth;
+ const isLossless = !!sampleRate && !!bitDepth;
- if (isLossless) {
- return `${bitDepth}/${sampleRate/1000}kHz`;
- }
+ if (isLossless) {
+ return `${bitDepth}/${sampleRate/1000}kHz`;
+ }
- if (isVariableBitRate) {
- return `${bitRate} Kbps, VBR`
- }
+ if (isVariableBitRate) {
+ return `${bitRate} Kbps, VBR`
+ }
- return bitRate ? `${bitRate} Kbps` : ''
+ return bitRate ? `${bitRate} Kbps` : ''
}
export const sleep = (milliseconds) => {
- return new Promise(resolve => setTimeout(resolve, milliseconds))
+ return new Promise(resolve => setTimeout(resolve, milliseconds))
}
/* https://www.npmjs.com/package/js-file-download
*
* Copyright 2017 Kenneth Jiang
*
- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+ * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
- * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions
+ * of the Software.
*
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE
*/
export const downloadFile = (data, filename, mime) => {
- var blob = new Blob([data], {type: mime || 'application/octet-stream'});
- if (typeof window.navigator.msSaveBlob !== 'undefined') {
- // IE workaround for "HTML7007: One or more blob URLs were
- // revoked by closing the blob for which they were created.
- // These URLs will no longer resolve as the data backing
- // the URL has been freed."
- window.navigator.msSaveBlob(blob, filename);
- }
- else {
- var blobURL = window.URL.createObjectURL(blob);
- var tempLink = document.createElement('a');
- tempLink.style.display = 'none';
- tempLink.href = blobURL;
- tempLink.setAttribute('download', filename);
+ var blob = new Blob([data], {type: mime || 'application/octet-stream'});
+ if (typeof window.navigator.msSaveBlob !== 'undefined') {
+ // IE workaround for "HTML7007: One or more blob URLs were
+ // revoked by closing the blob for which they were created.
+ // These URLs will no longer resolve as the data backing
+ // the URL has been freed."
+ window.navigator.msSaveBlob(blob, filename);
+ }
+ else {
+ var blobURL = window.URL.createObjectURL(blob);
+ var tempLink = document.createElement('a');
+ tempLink.style.display = 'none';
+ tempLink.href = blobURL;
+ tempLink.setAttribute('download', filename);
- // Safari thinks _blank anchor are pop ups. We only want to set _blank
- // target if the browser does not support the HTML5 download attribute.
- // This allows you to download files in desktop safari if pop up blocking
- // is enabled.
- if (typeof tempLink.download === 'undefined') {
- tempLink.setAttribute('target', '_blank');
- }
-
- document.body.appendChild(tempLink);
- tempLink.click();
- document.body.removeChild(tempLink);
- window.URL.revokeObjectURL(blobURL);
+ // Safari thinks _blank anchor are pop ups. We only want to set _blank
+ // target if the browser does not support the HTML5 download attribute.
+ // This allows you to download files in desktop safari if pop up blocking
+ // is enabled.
+ if (typeof tempLink.download === 'undefined') {
+ tempLink.setAttribute('target', '_blank');
}
+
+ document.body.appendChild(tempLink);
+ tempLink.click();
+ document.body.removeChild(tempLink);
+ window.URL.revokeObjectURL(blobURL);
+ }
} \ No newline at end of file