From 8f1068ac3135bcccf09374bc787ef22049b43461 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 30 Dec 2020 21:16:50 -0600 Subject: copy files from example --- src/web/.gitignore | 23 + src/web/README.md | 68 + src/web/package.json | 38 + src/web/public/index.html | 12 + src/web/src/components/App.css | 125 + src/web/src/components/App.js | 170 + src/web/src/components/Browse/Browse.css | 68 + src/web/src/components/Browse/Browse.js | 233 + src/web/src/components/Browse/Directory.js | 101 + src/web/src/components/Browse/DirectoryTree.js | 40 + src/web/src/components/Chat/Chat.css | 100 + src/web/src/components/Chat/Chat.js | 215 + src/web/src/components/Chat/ChatMenu.js | 50 + src/web/src/components/Chat/SendMessageModal.js | 75 + src/web/src/components/LoginForm.js | 83 + src/web/src/components/Rooms/RoomJoinModal.js | 142 + src/web/src/components/Rooms/RoomMenu.js | 41 + src/web/src/components/Rooms/RoomUserList.js | 44 + src/web/src/components/Rooms/Rooms.css | 132 + src/web/src/components/Rooms/Rooms.js | 219 + src/web/src/components/Search/Response.js | 127 + src/web/src/components/Search/Search.css | 61 + src/web/src/components/Search/Search.js | 244 + src/web/src/components/Shared/FileList.js | 75 + .../src/components/Shared/PlaceholderSegment.js | 14 + src/web/src/components/Transfers/TransferGroup.js | 147 + src/web/src/components/Transfers/TransferList.js | 121 + src/web/src/components/Transfers/Transfers.js | 46 + src/web/src/config.js | 13 + src/web/src/index.js | 11 + src/web/src/lib/api.js | 39 + src/web/src/lib/chat.js | 17 + src/web/src/lib/rooms.js | 29 + src/web/src/lib/search.js | 9 + src/web/src/lib/session.js | 13 + src/web/src/lib/transfers.js | 17 + src/web/src/lib/user.js | 9 + src/web/src/lib/util.js | 76 + src/web/yarn.lock | 10498 +++++++++++++++++++ 39 files changed, 13545 insertions(+) create mode 100644 src/web/.gitignore create mode 100644 src/web/README.md create mode 100644 src/web/package.json create mode 100644 src/web/public/index.html create mode 100644 src/web/src/components/App.css create mode 100644 src/web/src/components/App.js create mode 100644 src/web/src/components/Browse/Browse.css create mode 100644 src/web/src/components/Browse/Browse.js create mode 100644 src/web/src/components/Browse/Directory.js create mode 100644 src/web/src/components/Browse/DirectoryTree.js create mode 100644 src/web/src/components/Chat/Chat.css create mode 100644 src/web/src/components/Chat/Chat.js create mode 100644 src/web/src/components/Chat/ChatMenu.js create mode 100644 src/web/src/components/Chat/SendMessageModal.js create mode 100644 src/web/src/components/LoginForm.js create mode 100644 src/web/src/components/Rooms/RoomJoinModal.js create mode 100644 src/web/src/components/Rooms/RoomMenu.js create mode 100644 src/web/src/components/Rooms/RoomUserList.js create mode 100644 src/web/src/components/Rooms/Rooms.css create mode 100644 src/web/src/components/Rooms/Rooms.js create mode 100644 src/web/src/components/Search/Response.js create mode 100644 src/web/src/components/Search/Search.css create mode 100644 src/web/src/components/Search/Search.js create mode 100644 src/web/src/components/Shared/FileList.js create mode 100644 src/web/src/components/Shared/PlaceholderSegment.js create mode 100644 src/web/src/components/Transfers/TransferGroup.js create mode 100644 src/web/src/components/Transfers/TransferList.js create mode 100644 src/web/src/components/Transfers/Transfers.js create mode 100644 src/web/src/config.js create mode 100644 src/web/src/index.js create mode 100644 src/web/src/lib/api.js create mode 100644 src/web/src/lib/chat.js create mode 100644 src/web/src/lib/rooms.js create mode 100644 src/web/src/lib/search.js create mode 100644 src/web/src/lib/session.js create mode 100644 src/web/src/lib/transfers.js create mode 100644 src/web/src/lib/user.js create mode 100644 src/web/src/lib/util.js create mode 100644 src/web/yarn.lock (limited to 'src/web') diff --git a/src/web/.gitignore b/src/web/.gitignore new file mode 100644 index 00000000..4d29575d --- /dev/null +++ b/src/web/.gitignore @@ -0,0 +1,23 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/src/web/README.md b/src/web/README.md new file mode 100644 index 00000000..9d9614c4 --- /dev/null +++ b/src/web/README.md @@ -0,0 +1,68 @@ +This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). + +## Available Scripts + +In the project directory, you can run: + +### `npm start` + +Runs the app in the development mode.
+Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.
+You will also see any lint errors in the console. + +### `npm test` + +Launches the test runner in the interactive watch mode.
+See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. + +### `npm run build` + +Builds the app for production to the `build` folder.
+It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.
+Your app is ready to be deployed! + +See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. + +### `npm run eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. + +Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. + +You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. + +## Learn More + +You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). + +To learn React, check out the [React documentation](https://reactjs.org/). + +### Code Splitting + +This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting + +### Analyzing the Bundle Size + +This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size + +### Making a Progressive Web App + +This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app + +### Advanced Configuration + +This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration + +### Deployment + +This section has moved here: https://facebook.github.io/create-react-app/docs/deployment + +### `npm run build` fails to minify + +This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify diff --git a/src/web/package.json b/src/web/package.json new file mode 100644 index 00000000..6fdc55c1 --- /dev/null +++ b/src/web/package.json @@ -0,0 +1,38 @@ +{ + "name": "web", + "version": "0.1.0", + "private": true, + "homepage": ".", + "dependencies": { + "axios": "^0.19.0", + "react": "^16.8.6", + "react-dom": "^16.8.6", + "react-router-dom": "^5.0.0", + "react-scripts": "3.0.1", + "semantic-ui-css": "^2.4.1", + "semantic-ui-react": "^2.0.0", + "signalr": "^2.4.1", + "uuid": "^8.3.0" + }, + "scripts": { + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test", + "eject": "react-scripts eject" + }, + "eslintConfig": { + "extends": "react-app" + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } +} diff --git a/src/web/public/index.html b/src/web/public/index.html new file mode 100644 index 00000000..f12c2697 --- /dev/null +++ b/src/web/public/index.html @@ -0,0 +1,12 @@ + + + + + + Soulseek.NET + + + +
+ + diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css new file mode 100644 index 00000000..99d3767a --- /dev/null +++ b/src/web/src/components/App.css @@ -0,0 +1,125 @@ +body { + background: #c8c8c8 !important; +} + +.ui.table td, th { + padding-top: 5px !important; + padding-bottom: 5px !important; +} + +.app { + margin: auto; + border: 0px !important; + border-radius: 0% !important; + box-shadow: none !important; +} + +.app-content { + margin-top: 70px; + background: #c8c8c8 !important; +} + +.result-card { + width: 100% !important; +} + +.result-card:last-child, .transfer-card:last-child { + margin-bottom: 17px !important; +} + +.result-meta { + margin-top: 5px; +} + +@media only screen and (min-width: 768px) { + .transferlist-progress { + max-width: 300px; + width: 300px; + } +} + +@media only screen and (max-width: 767px) { + .transferlist-progress { + width: 100%; + } +} + +.filelist-header { + margin-top: 20px !important; +} + +.filelist-selector, .transferlist-selector { + width: 40px; +} + +.filelist-filename { + word-wrap: break-word !important; +} + +.filelist-size { + width: 100px; +} + +.filelist-bitrate { + width: 70px; +} + +.filelist-length{ + width: 65px; +} + +.transfer-button { + color: black; +} + +.transfer-card { + width: 1200px !important; + margin-left: auto !important; + margin-right: auto !important; +} + +.transfer-segment { + margin-top: 16px; + padding-left: 15px; + padding-right: 15px; +} + +.transfer-placeholder { + font-weight: 100; + text-align: center; + margin-top: 50px !important; +} + +.transferlist-size { + width: 150px; + min-width: 150px; +} + +.transferlist-filename { + word-wrap: break-word !important; +} + +.showmore-button { + padding: 20px !important; + max-width: 1200px !important; + margin-bottom: 17px !important; +} + +.login-button { + margin-top: 0px !important; +} + +.login-failure { + text-align: left; +} + +.close-button { + float: right; + margin-right: 0px !important; + font-size: 16pt !important; + line-height: 1.15 !important; +} + +.placeholder-segment { + opacity: .25; +} \ No newline at end of file diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js new file mode 100644 index 00000000..46bbcf72 --- /dev/null +++ b/src/web/src/components/App.js @@ -0,0 +1,170 @@ +import React, { Component } from 'react'; +import { Route, Link, Switch } from "react-router-dom"; +import { tokenKey, tokenPassthroughValue } from '../config'; +import * as session from '../lib/session'; + +import './App.css'; +import Search from './Search/Search'; +import Browse from './Browse/Browse'; +import Transfers from './Transfers/Transfers'; +import Chat from './Chat/Chat'; +import LoginForm from './LoginForm'; + +import { + Sidebar, + Segment, + Menu, + Icon, + Modal, + Header +} from 'semantic-ui-react'; +import Rooms from './Rooms/Rooms'; + +const initialState = { + token: undefined, + login: { + initialized: false, + pending: false, + error: undefined + } +}; + +class App extends Component { + state = initialState; + + componentDidMount = async () => { + const { login } = this.state; + const securityEnabled = await session.getSecurityEnabled(); + + if (!securityEnabled) { + this.setToken(sessionStorage, tokenPassthroughValue) + } + + this.setState({ + token: this.getToken(), + login: { + ...login, + initialized: true + } + }); + + await this.checkToken(); + } + + checkToken = async () => { + try { + await session.check(); + } catch (error) { + this.logout(); + } + } + + getToken = () => JSON.parse(sessionStorage.getItem(tokenKey) || localStorage.getItem(tokenKey)); + setToken = (storage, token) => storage.setItem(tokenKey, JSON.stringify(token)); + + login = (username, password, rememberMe) => { + this.setState({ login: { ...this.state.login, pending: true, error: undefined }}, async () => { + try { + const response = await session.login({ username, password }); + this.setToken(rememberMe ? localStorage : sessionStorage, response.data.token); + window.location.reload(); + } catch (error) { + this.setState({ login: { ...this.state.login, pending: false, error }}); + } + }); + } + + logout = () => { + localStorage.removeItem(tokenKey); + sessionStorage.removeItem(tokenKey); + this.setState({ ...initialState, login: { ...initialState.login, initialized: true }}); + } + + withTokenCheck = (component) => { + this.checkToken(); // async, runs in the background + return { ...component }; + } + + render = () => { + const { token, login } = this.state; + + return ( + <> + {!token ? + : + login.initialized && + + + + Search + + + + + Downloads + + + + + Uploads + + + + + Browse + + + + + Rooms + + + + + Chat + + + {token !== tokenPassthroughValue && + Log Out + + } + centered + size='mini' + header={
} + content='Are you sure you want to log out?' + actions={['Cancel', { key: 'done', content: 'Log Out', negative: true, onClick: this.logout }]} + />} + + + + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + + + + } + + ) + } +} + +export default App; diff --git a/src/web/src/components/Browse/Browse.css b/src/web/src/components/Browse/Browse.css new file mode 100644 index 00000000..336dfd6c --- /dev/null +++ b/src/web/src/components/Browse/Browse.css @@ -0,0 +1,68 @@ +.browse-results { + margin: unset !important; +} + +.browse-error { + display: block; + text-align: center; + font-size: 18px; + margin-top: 50px; +} + +.browse-results-row { + padding-top: 0px !important; +} + +.browse-results-row:last-child { + padding-bottom: 0px !important; +} + +.browse-folderlist { + width: 100% !important; + white-space: pre; + overflow: auto !important; + max-height: 400px; + padding: 1em !important; + box-shadow: unset !important; +} + +.browse-folderlist-list { + margin: 0px !important; + margin-bottom: 1px !important; +} + +.browse-folderlist-header { + cursor: pointer; + margin-left: 3px !important; +} + +.browse-folderlist-icon { + float: left; +} + +.browse-filelist { + width: 100% !important; + padding: 1em !important; +} + +.ui.list .list, ol.ui.list ol, ul.ui.list ul { + padding-left: 0px !important; + padding-top: 3px !important; + padding-bottom: 0px !important; +} + +.ui.list .list>.item>.icon+.content, .ui.list .list>.item>.image+.content, .ui.list>.item>.icon+.content, .ui.list>.item>.image+.content { + padding-left: 0px !important; +} + +.browse-tree-card { + width: 100% !important; +} + +.browse-container:last-child { + margin-bottom: 17px; +} + +.browse-meta { + margin-top: 5px; +} \ No newline at end of file diff --git a/src/web/src/components/Browse/Browse.js b/src/web/src/components/Browse/Browse.js new file mode 100644 index 00000000..27a7591b --- /dev/null +++ b/src/web/src/components/Browse/Browse.js @@ -0,0 +1,233 @@ +import React, { Component } from 'react'; +import * as user from '../../lib/user'; + +import './Browse.css'; + +import DirectoryTree from './DirectoryTree'; + +import { + Segment, + Input, + Loader, + Card, + Icon, +} from 'semantic-ui-react'; + +import Directory from './Directory'; +import PlaceholderSegment from '../Shared/PlaceholderSegment'; + +const initialState = { + username: '', + browseState: 'idle', + browseStatus: 0, + browseError: undefined, + interval: undefined, + selectedDirectory: {}, + selectedFiles: [], + tree: [], + info: { + directories: 0, + files: 0, + lockedDirectories: 0, + lockedFiles: 0 + } +}; + +class Browse extends Component { + state = initialState; + + browse = () => { + let username = this.inputtext.inputRef.current.value; + + this.setState({ username , browseState: 'pending', browseError: undefined }, () => { + user.browse({ username }) + .then(response => { + let { directories, lockedDirectories } = response; + + const directoryCount = directories.length; + const fileCount = directories.reduce((acc, dir) => acc += dir.fileCount, 0); + + const lockedDirectoryCount = lockedDirectories.length; + const lockedFileCount = lockedDirectories.reduce((acc, dir) => acc += dir.fileCount, 0); + + directories = directories.concat(lockedDirectories.map(d => ({ ...d, locked: true }))); + + this.setState({ + tree: this.getDirectoryTree(directories), + info: { + directories: directoryCount, + files: fileCount, + lockedDirectories: lockedDirectoryCount, + lockedFiles: lockedFileCount + } + }); + }) + .then(() => this.setState({ browseState: 'complete', browseError: undefined }, () => { + this.saveState(); + })) + .catch(err => this.setState({ browseState: 'error', browseError: err })) + }); + } + + clear = () => { + this.setState(initialState, () => { + this.saveState(); + this.inputtext.focus(); + }); + } + + keyUp = (event) => event.key === 'Escape' ? this.clear() : ''; + + onUsernameChange = (event, data) => { + this.setState({ username: data.value }); + } + + saveState = () => { + this.inputtext.inputRef.current.value = this.state.username; + this.inputtext.inputRef.current.disabled = this.state.browseState !== 'idle'; + + try { + localStorage.setItem('soulseek-example-browse-state', JSON.stringify(this.state)); + } catch (error) { + console.log(error); + } + } + + loadState = () => { + this.setState(JSON.parse(localStorage.getItem('soulseek-example-browse-state')) || initialState); + } + + componentDidMount = () => { + this.fetchStatus(); + this.loadState(); + this.setState({ + interval: window.setInterval(this.fetchStatus, 500) + }, () => this.saveState()); + + document.addEventListener("keyup", this.keyUp, false); + } + + componentWillUnmount = () => { + clearInterval(this.state.interval); + this.setState({ interval: undefined }); + document.removeEventListener("keyup", this.keyUp, false); + } + + fetchStatus = () => { + const { browseState, username } = this.state; + if (browseState === 'pending') { + user.getBrowseStatus({ username }) + .then(response => this.setState({ + browseStatus: response.data + })); + } + } + + getDirectoryTree = (directories) => { + if (directories.length === 0 || directories[0].directoryName === undefined) { + return []; + } + + const separator = this.sep(directories[0].directoryName); + const depth = Math.min.apply(null, directories.map(d => d.directoryName.split(separator).length)); + + const topLevelDirs = directories + .filter(d => d.directoryName.split(separator).length === depth); + + return topLevelDirs.map(directory => this.getChildDirectories(directories, directory, separator, depth)); + } + + getChildDirectories = (directories, root, separator, depth) => { + const children = directories + .filter(d => d.directoryName !== root.directoryName) + .filter(d => d.directoryName.split(separator).length === depth + 1) + .filter(d => d.directoryName.startsWith(root.directoryName)); + + return { ...root, children: children.map(c => this.getChildDirectories(directories, c, separator, depth + 1)) }; + } + + selectDirectory = (directory) => { + this.setState({ selectedDirectory: { ...directory, children: [] }}, () => this.saveState()); + } + + deselectDirectory = () => { + this.setState({ selectedDirectory: initialState.selectedDirectory }, () => this.saveState()); + } + + sep = (directoryName) => directoryName.includes('\\') ? '\\' : '/'; + + render = () => { + const { browseState, browseStatus, browseError, tree, selectedDirectory, username, info } = this.state; + const { directoryName, locked } = selectedDirectory; + const pending = browseState === 'pending'; + + const emptyTree = !(tree && tree.length > 0); + + const files = (selectedDirectory.files || []).map(f => ({ ...f, filename: `${directoryName}${this.sep(directoryName)}${f.filename}`})); + + return ( +
+ + } + size='big' + ref={input => this.inputtext = input} + loading={pending} + disabled={pending} + className='search-input' + placeholder="Username" + action={!pending && (browseState === 'idle' ? { icon: 'search', onClick: this.browse } : { icon: 'x', color: 'red', onClick: this.clear })} + onKeyUp={(e) => e.key === 'Enter' ? this.browse() : ''} + /> + + {pending ? + + Downloaded {Math.round(browseStatus.percentComplete || 0)}% of Response + + : +
+ {browseError ? + Failed to browse {username} : +
+ {emptyTree ? + : + + + + + {username} + + + {`${info.files + info.lockedFiles} files in ${info.directories + info.lockedDirectories} directories (including ${info.lockedFiles} files in ${info.lockedDirectories} locked directories)`} + + + this.selectDirectory(value)} + /> + + + } + {directoryName && } +
+ } +
} +
+ ) + } +} + +export default Browse; \ No newline at end of file diff --git a/src/web/src/components/Browse/Directory.js b/src/web/src/components/Browse/Directory.js new file mode 100644 index 00000000..8b49a3e6 --- /dev/null +++ b/src/web/src/components/Browse/Directory.js @@ -0,0 +1,101 @@ +import React, { Component } from 'react'; +import * as transfers from '../../lib/transfers'; + +import { formatBytes } from '../../lib/util'; + +import FileList from '../Shared/FileList' + +import { + Button, + Card, + Icon, + Label +} from 'semantic-ui-react'; + +const initialState = { + downloadRequest: undefined, + downloadError: '' +} + +class Directory extends Component { + state = { + ...initialState, + files: this.props.files.map(f => ({ selected: false, ...f })) + } + + onFileSelectionChange = (file, state) => { + file.selected = state; + this.setState({ tree: this.state.tree, downloadRequest: undefined, downloadError: '' }) + } + + download = (username, files) => { + this.setState({ downloadRequest: 'inProgress' }, () => { + Promise.all(files.map(f => this.downloadOne(username, f))) + .then(() => this.setState({ downloadRequest: 'complete' })) + .catch(err => this.setState({ downloadRequest: 'error', downloadError: err.response })) + }); + } + + componentDidUpdate = (prevProps) => { + if (this.props.name !== prevProps.name) { + this.setState({ files: this.props.files.map(f => ({ selected: false, ...f }))}); + } + } + + downloadOne = (username, file) => { + const { filename, size } = file; + return transfers.download({ username, filename, size }); + } + + render = () => { + let { username, name, locked, marginTop, onClose } = this.props; + let { files, downloadRequest, downloadError } = this.state; + + let selectedFiles = files + .filter(f => f.selected); + + let selectedSize = formatBytes(selectedFiles.reduce((total, f) => total + f.size, 0)); + + return ( + + +
+ +
+
+ {selectedFiles.length > 0 && + + + } + centered + size='small' + {...rest} + /> + + + ) +} + +export default ChatMenu; \ No newline at end of file diff --git a/src/web/src/components/Chat/SendMessageModal.js b/src/web/src/components/Chat/SendMessageModal.js new file mode 100644 index 00000000..3c91d570 --- /dev/null +++ b/src/web/src/components/Chat/SendMessageModal.js @@ -0,0 +1,75 @@ +import React, { useEffect } from 'react'; +import './Chat.css'; + +import { + Icon, Button, Modal, Form, Header, Input +} from 'semantic-ui-react'; + +const usernameRef = React.createRef(); + +const SendMessageModal = ({ initiateConversation, ...rest }) => { + const [open, setOpen] = React.useState(false); + const [username, setUsername] = React.useState(''); + const [message, setMessage] = React.useState(''); + + useEffect(() => { + if (open) { + usernameRef.current.focus(); + } + }, [open]); + + const sendMessage = async () => { + if (!validInput()) { + usernameRef.current.focus(); + return; + } + + await initiateConversation(username, message); + setOpen(false); + } + + const validInput = () => { + return username.length > 0 && message.length > 0 + } + + return ( + setOpen(false)} + onOpen={() => setOpen(true)} + {...rest} + > +
+ + Send Private Message +
+ +
+ + setUsername(data.value)} + /> + + + setMessage(data.value)} + /> + +
+
+ + + + +
+ ) +} + +export default SendMessageModal; \ No newline at end of file diff --git a/src/web/src/components/LoginForm.js b/src/web/src/components/LoginForm.js new file mode 100644 index 00000000..e76b6cfc --- /dev/null +++ b/src/web/src/components/LoginForm.js @@ -0,0 +1,83 @@ +import React, { Component } from 'react' +import { Button, Form, Grid, Header, Icon, Segment, Checkbox, Message } from 'semantic-ui-react' + +const initialState = { + username: '', + password: '', + rememberMe: true, + ready: false, +} + +class LoginForm extends Component { + state = initialState; + + handleChange = (field, value) => { + this.setState({ + [field]: value, + }, () => { + if (this.state.username !== '' && this.state.password !== '') { + this.setState({ ready: true }) + } else { + this.setState({ ready: false }) + } + }); + } + + render = () => { + const { initialized, onLoginAttempt, loading, error } = this.props; + const { username, password, rememberMe, ready } = this.state; + + return ( + <> + {initialized && + +
+ Soulseek Web Example +
+
+ + this.handleChange('username', event.target.value)} + /> + this.handleChange('password', event.target.value)} + /> + this.handleChange('rememberMe', !rememberMe)} + checked={rememberMe} + /> + + + {error && + + {error.message} + } +
+
+
} + + ) + } +} + +export default LoginForm \ No newline at end of file diff --git a/src/web/src/components/Rooms/RoomJoinModal.js b/src/web/src/components/Rooms/RoomJoinModal.js new file mode 100644 index 00000000..4dffe840 --- /dev/null +++ b/src/web/src/components/Rooms/RoomJoinModal.js @@ -0,0 +1,142 @@ +import React, { useEffect, useState, useMemo } from 'react'; +import * as rooms from '../../lib/rooms'; +import './Rooms.css'; + +import { + Icon, Button, Modal, Table, Header, Input, Loader, Dimmer +} from 'semantic-ui-react'; + +const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => { + const [open, setOpen] = useState(false); + const [available, setAvailable] = useState([]); + const [selected, setSelected] = useState(undefined); + const [sortBy, setSortBy] = useState('name'); + const [sortOrder, setSortOrder] = useState('desc'); + const [filter, setFilter] = useState(''); + const [loading, setLoading] = useState(true); + + useEffect(() => { + const getAvailableRooms = async () => { + setLoading(true); + const available = await rooms.getAvailable(); + setAvailable(available); + setLoading(false); + } + + if (open) getAvailableRooms(); + }, [open]); + + const sortedAvailable = useMemo(() => { + const sorted = [...available].filter(room => room.name.includes(filter)); + + sorted.sort((a, b) => { + if (sortOrder === 'asc') { + if (typeof(a[sortBy]) === 'string') { + return b[sortBy].localeCompare(a[sortBy]); + } + + return a[sortBy] - b[sortBy]; + } + + if (typeof(a[sortBy]) === 'string') { + return a[sortBy].localeCompare(b[sortBy]); + } + + return b[sortBy] - a[sortBy] + }); + + return sorted; + }, [available, sortBy, sortOrder, filter]); + + const joinRoom = async () => { + await parentJoinRoom(selected); + close(); + } + + const isSelected = (room) => selected === room.name; + + const close = () => { + setAvailable([]); + setSelected(undefined); + setSortBy('name'); + setSortOrder('desc'); + setFilter(''); + setOpen(false); + } + + return ( + close()} + onOpen={() => setOpen(true)} + {...modalOptions} + > +
+ + Join Room +
+ + {loading ? : + <> + setFilter(e.value)} + placeholder='Room Filter' + icon='filter' + /> + + + + setSortBy('name')}> + Name + setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')} + /> + + setSortBy('userCount')}> + Users + setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')} + /> + + + + + {sortedAvailable.map((room, index) => + setSelected(room.name)} + > + + {isSelected(room) && } + {room.isPrivate && } + {room.isOwned && } + {room.isModerated && } + {room.name} + + {room.userCount} + + )} + +
+ } +
+ + + + +
+ ) +} + +export default RoomJoinModal; \ No newline at end of file diff --git a/src/web/src/components/Rooms/RoomMenu.js b/src/web/src/components/Rooms/RoomMenu.js new file mode 100644 index 00000000..c77dd8fb --- /dev/null +++ b/src/web/src/components/Rooms/RoomMenu.js @@ -0,0 +1,41 @@ +import React from 'react'; +import './Rooms.css'; + +import { + Icon, Button, Menu +} from 'semantic-ui-react'; +import RoomJoinModal from './RoomJoinModal'; + +const RoomMenu = ({ joined, active, onRoomChange, ...rest }) => { + const names = [...joined]; + const isActive = (name) => active === name; + + return ( + + {names.map((name, index) => + onRoomChange(name)} + > + + {name} + + )} + + + } + centered + size='small' + {...rest} + /> + + + ) +} + +export default RoomMenu; \ No newline at end of file diff --git a/src/web/src/components/Rooms/RoomUserList.js b/src/web/src/components/Rooms/RoomUserList.js new file mode 100644 index 00000000..c719e5f1 --- /dev/null +++ b/src/web/src/components/Rooms/RoomUserList.js @@ -0,0 +1,44 @@ +import React, { useMemo } from 'react'; +import './Rooms.css'; + +import { + Icon, Flag, List, Popup +} from 'semantic-ui-react'; + +const RoomUserList = ({ users }) => { + const getFlag = (user) => { + if (!(user || {}).countryCode) return ; + + return ; + } + + const getDetails = (user) => { + return user.countryCode || '?'; + } + + const sortedUsers = useMemo(() => { + const filtered = [...users] + .sort((a, b) => a.username.localeCompare(b.username)) + .reduce((acc, user) => { + (user.status === 'Online' ? acc.online : acc.offline).push(user); + return acc; + }, { online: [], offline: []}); + + return [...filtered.online, ...filtered.offline]; + }, [users]); + + return ( + + {sortedUsers.map((user, index) => + + + + {user.username} + + + )} + + ) +} + +export default RoomUserList; \ No newline at end of file diff --git a/src/web/src/components/Rooms/Rooms.css b/src/web/src/components/Rooms/Rooms.css new file mode 100644 index 00000000..87180fd5 --- /dev/null +++ b/src/web/src/components/Rooms/Rooms.css @@ -0,0 +1,132 @@ +.rooms { + padding-left: 15px; + padding-right: 15px; + max-width: 1200px !important; + margin-left: auto !important; + margin-right: auto !important; + margin-bottom: 17px; +} + +.rooms > .segment:first-child { + margin-top: 15px !important; + height: 78px; +} + +.room-menu { + overflow-x: auto; + box-shadow: unset !important; + height: 47px; +} + +.room-menu > .menu-item { + font-size: 14pt; +} + +.room-menu > .menu-active { + font-weight: bold !important; +} + +.room-menu > .menu > .add-button { + margin: 0px; + border-top-left-radius: 0%; + border-bottom-left-radius: 0%; + border-radius: 0%; +} + +.join-room-modal > .content > .table > thead > tr > th > .icon { + float: right !important; +} + +@media only screen and (max-width: 767px) { + .room-users { + display: none; + } +} + +.room { + display: flex; + margin-top: 1rem; + height: calc(100vh - 255px); +} + +.room-active-card { + width: 100% !important; +} + +.room-active-card > .content > .room > .segments { + box-shadow: unset !important; + margin-bottom: 0px; + border-top-right-radius: unset !important; + border-bottom-right-radius: unset !important; + width: 100% !important; +} + +.room-history { + padding: .5em .5em 0 .5em !important; + overflow-y: auto; + overscroll-behavior-y: contain; + scroll-snap-type: y proximity; + display: grid; + height: calc(100vh - 292px); +} + +.room-history > .list { + align-self: end; + margin-bottom: .5em !important; +} + +.room-users { + margin-top: 0px !important; + overflow-y: auto; + overscroll-behavior-y: contain; + scroll-snap-type: y proximity; + overflow-x: hidden; + min-width: 250px; + max-width: 250px; + box-shadow: unset !important; + border-left: unset !important; + border-bottom-left-radius: unset !important; + border-top-left-radius: unset !important; + padding: 7px !important; +} + +.room-message-name { + font-weight: bold; +} + +.room-message-time { + float:right; + opacity: .5; + font-size: smaller; + font-variant: small-caps; + font-style: italic; +} + +.room-message-self, .room-user-self { + color: blue; +} + +.room-input { + padding: 0px 0px 0px 1em !important; +} + +.room-message-button { + background-color: transparent !important; +} + +#room-history-scroll-anchor { + scroll-snap-align: start +} + +/* semantic-ui-react colors the border of inputs + when a right aligned action is used, even when + transparent is specified, and it uses !important. + this had to be added to an id to override the class + declaration. */ +#room-message-input { + border-right-color: transparent !important; +} + +.unknown-user-flag { + opacity: .1 !important; +} \ No newline at end of file diff --git a/src/web/src/components/Rooms/Rooms.js b/src/web/src/components/Rooms/Rooms.js new file mode 100644 index 00000000..306696bb --- /dev/null +++ b/src/web/src/components/Rooms/Rooms.js @@ -0,0 +1,219 @@ +import React, { Component, createRef } from 'react'; +import * as rooms from '../../lib/rooms'; +import { activeRoomKey } from '../../config'; + +import { Segment, Card, Icon, Input, Ref, List, Loader, Dimmer } from 'semantic-ui-react'; + +import RoomMenu from './RoomMenu'; +import RoomUserList from './RoomUserList'; +import PlaceholderSegment from '../Shared/PlaceholderSegment'; + +const initialState = { + active: '', + joined: [], + room: { + messages: [], + users: [] + }, + intervals: { + rooms: undefined, + messages: undefined + }, + loading: false +} + +class Rooms extends Component { + state = initialState; + messageRef = undefined; + listRef = createRef(); + + componentDidMount = async () => { + this.setState({ + intervals: { + rooms: window.setInterval(this.fetchJoinedRooms, 500), + messages: window.setInterval(this.fetchActiveRoom, 1000) + }, + active: sessionStorage.getItem(activeRoomKey) || '' + }, async () => { + await this.fetchJoinedRooms(); + this.selectRoom(this.state.active || this.getFirstRoom()) + }); + }; + + componentWillUnmount = () => { + const { rooms, messages } = this.state.intervals; + + clearInterval(rooms); + clearInterval(messages); + + this.setState({ intervals: initialState.intervals }); + } + + getFirstRoom = () => { + return this.state.joined.length > 0 ? this.state.joined[0] : ''; + } + + fetchJoinedRooms = async () => { + const joined = await rooms.getJoined();; + this.setState({ + joined + }, () => { + if (!this.state.joined.includes(this.state.active)) { + this.selectRoom(this.getFirstRoom()); + } + }); + }; + + fetchActiveRoom = async () => { + const { active } = this.state; + + if (active.length === 0) return; + + const messages = await rooms.getMessages({ roomName: active }); + const users = await rooms.getUsers({ roomName: active }); + + this.setState({ + room: { + users, + messages + } + }); + }; + + selectRoom = async (roomName) => { + this.setState({ + active: roomName, + room: initialState.room, + loading: true + }, async () => { + const { active } = this.state; + + sessionStorage.setItem(activeRoomKey, active); + + await this.fetchActiveRoom(); + this.setState({ loading: false }, () => { + try { + this.listRef.current.lastChild.scrollIntoView(); + } catch {} + }); + }); + }; + + joinRoom = async (roomName) => { + await rooms.join({ roomName }); + await this.fetchJoinedRooms(); + this.selectRoom(roomName); + }; + + leaveRoom = async (roomName) => { + await rooms.leave({ roomName }); + await this.fetchJoinedRooms(); + this.selectRoom(this.getFirstRoom()); + }; + + validInput = () => (this.state.active || '').length > 0 && ((this.messageRef && this.messageRef.current && this.messageRef.current.value) || '').length > 0; + + focusInput = () => { + this.messageRef.current.focus(); + }; + + formatTimestamp = (timestamp) => { + const date = new Date(timestamp); + const dtfUS = new Intl.DateTimeFormat('en', { + month: 'numeric', + day: 'numeric', + hour: 'numeric', + minute: '2-digit' + }); + + return dtfUS.format(date); + }; + + sendMessage = async () => { + const { active } = this.state; + const message = this.messageRef.current.value; + + if (!this.validInput()) { + return; + } + + await rooms.sendMessage({ roomName: active, message }); + this.messageRef.current.value = ''; + }; + + render = () => { + const { joined, active, room, loading } = this.state; + + return ( +
+ + this.selectRoom(name)} + joinRoom={this.joinRoom} + /> + + {!active ? + : + + this.focusInput()}> + + + {active} + this.leaveRoom(active)} + /> + +
+ {loading ? : <> + + + + + {room.messages.map((message, index) => + + {this.formatTimestamp(message.timestamp)} + {message.username}: + {message.message} + + )} + + + + + + } + ref={input => this.messageRef = input && input.inputRef} + action={{ + icon: , + className: 'room-message-button', onClick: this.sendMessage, + disabled: !this.validInput() + }} + onKeyUp={(e) => e.key === 'Enter' ? this.sendMessage() : ''} + /> + + + + + + } +
+
+
} +
+ ) + }; +}; + +export default Rooms; \ No newline at end of file diff --git a/src/web/src/components/Search/Response.js b/src/web/src/components/Search/Response.js new file mode 100644 index 00000000..74b96b93 --- /dev/null +++ b/src/web/src/components/Search/Response.js @@ -0,0 +1,127 @@ +import React, { Component } from 'react'; +import * as transfers from '../../lib/transfers'; + +import { formatBytes, getDirectoryName } from '../../lib/util'; + +import FileList from '../Shared/FileList' + +import { + 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; + }, {}); +} + +class Response extends Component { + state = { + tree: buildTree(this.props.response), + downloadRequest: undefined, + downloadError: '' + } + + componentDidUpdate = (prevProps) => { + if (this.props.response !== prevProps.response) { + this.setState({ tree: buildTree(this.props.response) }); + } + } + + onFileSelectionChange = (file, state) => { + file.selected = state; + console.log(this.state.tree); + this.setState({ tree: this.state.tree, downloadRequest: undefined, downloadError: '' }) + } + + download = (username, files) => { + this.setState({ downloadRequest: 'inProgress' }, () => { + Promise.all((files || []).map(f => this.downloadOne(username, f))) + .then(() => this.setState({ downloadRequest: 'complete' })) + .catch(err => this.setState({ downloadRequest: 'error', downloadError: err.response })) + }); + } + + downloadOne = (username, file) => { + const { filename, size } = file; + return transfers.download({ username, filename, size }); + } + + render = () => { + let response = this.props.response; + let free = response.freeUploadSlots > 0; + + let { tree, downloadRequest, downloadError } = 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 ( + + + + + {response.username} + this.props.onHide()} + /> + + + Upload Speed: {formatBytes(response.uploadSpeed)}/s, Free Upload Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength} + + {(Object.keys(tree) || []).map((dir, i) => + file.locked)} + files={tree[dir]} + disabled={downloadRequest === 'inProgress'} + onSelectionChange={this.onFileSelectionChange} + /> + )} + + {selectedFiles.length > 0 && + + + : ''} + } + + ) + } +} + +export default Search; \ No newline at end of file diff --git a/src/web/src/components/Shared/FileList.js b/src/web/src/components/Shared/FileList.js new file mode 100644 index 00000000..e470563f --- /dev/null +++ b/src/web/src/components/Shared/FileList.js @@ -0,0 +1,75 @@ +import React from 'react'; + +import { formatSeconds, formatBytes, getFileName } from '../../lib/util'; + +import { + Header, + Table, + Icon, + List, + Checkbox +} from 'semantic-ui-react'; + +const FileList = ({ directoryName, files, locked, onSelectionChange, disabled, onClose }) => ( +
+
+
+ + {directoryName} + + {!!onClose && onClose()} + />} +
+
+ {files && files.length > 0 && + + + + + + files.map(f => onSelectionChange(f, data.checked))} + checked={files.filter(f => !f.selected).length === 0} + disabled={disabled} + /> + + File + Size + Bitrate + Length + + + + {files.sort((a, b) => a.filename > b.filename ? 1 : -1).map((f, i) => + + + onSelectionChange(f, data.checked)} + checked={f.selected} + disabled={disabled} + /> + + {locked ? : ''}{getFileName(f.filename)} + {formatBytes(f.size)} + {f.bitRate} + {formatSeconds(f.length)} + + )} + +
+
+
} +
+); + +export default FileList; diff --git a/src/web/src/components/Shared/PlaceholderSegment.js b/src/web/src/components/Shared/PlaceholderSegment.js new file mode 100644 index 00000000..4bea0846 --- /dev/null +++ b/src/web/src/components/Shared/PlaceholderSegment.js @@ -0,0 +1,14 @@ +import React from 'react'; + +import { Segment, Header, Icon } from 'semantic-ui-react'; + +const PlaceholderSegment = ({ icon, caption }) => ( + +
+ + {caption} +
+
+); + +export default PlaceholderSegment; \ No newline at end of file diff --git a/src/web/src/components/Transfers/TransferGroup.js b/src/web/src/components/Transfers/TransferGroup.js new file mode 100644 index 00000000..db093303 --- /dev/null +++ b/src/web/src/components/Transfers/TransferGroup.js @@ -0,0 +1,147 @@ +import React, { Component } from 'react'; +import * as transfers from '../../lib/transfers'; + +import { + Card, + Button +} from 'semantic-ui-react'; + +import TransferList from './TransferList'; + +class TransferGroup extends Component { + state = { selections: new Set() } + + 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 }); + } + + isSelected = (directoryName, file) => + this.state.selections.has(JSON.stringify({ directory: directoryName, filename: file.filename })); + + 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; + + 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', '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, filename, size }); + } catch (error) { + console.log(error); + } + } + + fetchPlaceInQueue = async (file) => { + const { username, id } = file; + + try { + await transfers.getPlaceInQueue({ username, id }); + } catch (error) { + console.log(error); + } + } + + render = () => { + const { user, direction } = this.props; + + 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 ( + + + {user.username} + {user.directories && user.directories + .map((dir, index) => + ({ ...f, selected: this.isSelected(dir.directory, f) }))} + onSelectionChange={this.onSelectionChange} + direction={this.props.direction} + onPlaceInQueueRequested={this.fetchPlaceInQueue} + onRetryRequested={this.retry} + /> + )} + + {selected && selected.length > 0 && + + { + {allRetryable && +