diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-09-06 19:47:54 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-09-06 19:47:54 -0500 |
| commit | 3d645132c2613bcd376ec710e6d1d02e9912cf15 (patch) | |
| tree | 19513e231e54929aeaf901f8544726f9ac5e2fc6 /src | |
| parent | 1f250f40561a0923f57ed374e0595c8027b66af0 (diff) | |
| parent | c83b9bb7444e1e6af25fe27d584db6154275396a (diff) | |
| download | slskd-3d645132c2613bcd376ec710e6d1d02e9912cf15.tar.gz | |
Merge pull request #190 from slskd/array-errors
Trap and attempt to recover from unexpected API responses in the UI
Diffstat (limited to 'src')
| -rw-r--r-- | src/web/src/components/App.js | 50 | ||||
| -rw-r--r-- | src/web/src/components/Chat/Chat.js | 374 | ||||
| -rw-r--r-- | src/web/src/components/Rooms/Rooms.js | 2 | ||||
| -rw-r--r-- | src/web/src/components/Search/Search.js | 518 | ||||
| -rw-r--r-- | src/web/src/components/Shared/ErrorSegment.js | 14 | ||||
| -rw-r--r-- | src/web/src/components/Transfers/Transfers.js | 65 | ||||
| -rw-r--r-- | src/web/src/lib/chat.js | 9 | ||||
| -rw-r--r-- | src/web/src/lib/rooms.js | 36 | ||||
| -rw-r--r-- | src/web/src/lib/search.js | 9 | ||||
| -rw-r--r-- | src/web/src/lib/transfers.js | 9 |
10 files changed, 580 insertions, 506 deletions
diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index eb91e88e..d6d80492 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -21,6 +21,7 @@ import { Header } from 'semantic-ui-react'; import Rooms from './Rooms/Rooms'; +import ErrorSegment from './Shared/ErrorSegment'; const initialState = { token: undefined, @@ -30,7 +31,8 @@ const initialState = { error: undefined }, serverStateInterval: undefined, - serverState: {} + serverState: {}, + error: false, }; class App extends Component { @@ -39,23 +41,28 @@ class App extends Component { componentDidMount = async () => { const { login } = this.state; - await this.fetchServerState(); - const securityEnabled = await session.getSecurityEnabled(); - - if (!securityEnabled) { - this.setToken(sessionStorage, tokenPassthroughValue) + try { + await this.fetchServerState(); + const securityEnabled = await session.getSecurityEnabled(); + + if (!securityEnabled) { + this.setToken(sessionStorage, tokenPassthroughValue) + } + + this.setState({ + token: this.getToken(), + login: { + ...login, + initialized: true + }, + serverStateInterval: window.setInterval(this.fetchServerState, 5000) + }); + + await this.checkToken(); + } catch (err) { + console.error(err) + this.setState({ error: true }) } - - this.setState({ - token: this.getToken(), - login: { - ...login, - initialized: true - }, - serverStateInterval: window.setInterval(this.fetchServerState, 5000) - }); - - await this.checkToken(); }; componentWillUnmount = () => { @@ -110,19 +117,20 @@ class App extends Component { fetchServerState = async () => { try { this.setState({ - serverState: await server.getState() + serverState: await server.getState(), + error: false, }); } catch (err) { - // noop + this.setState({ error: true }) } }; render = () => { - const { token, login, serverState } = this.state; + const { token, login, serverState, error } = this.state; return ( <> - {!token ? + {error ? <ErrorSegment caption='slskd appears to be offline' /> : !token ? <LoginForm onLoginAttempt={this.login} initialized={login.initialized} diff --git a/src/web/src/components/Chat/Chat.js b/src/web/src/components/Chat/Chat.js index 026d0632..53651cde 100644 --- a/src/web/src/components/Chat/Chat.js +++ b/src/web/src/components/Chat/Chat.js @@ -3,213 +3,213 @@ import { activeChatKey } from '../../config'; import * as chat from '../../lib/chat'; import './Chat.css'; import { - Segment, - List, Input, Card, Icon, Ref, Dimmer, Loader + Segment, + List, Input, Card, Icon, Ref, Dimmer, Loader } from 'semantic-ui-react'; import ChatMenu from './ChatMenu'; import PlaceholderSegment from '../Shared/PlaceholderSegment'; const initialState = { - active: '', - conversations: {}, - interval: undefined, - loading: false + active: '', + conversations: {}, + interval: undefined, + loading: false }; class Chat extends Component { - state = initialState; - messageRef = undefined; - listRef = createRef(); - - componentDidMount = async () => { - this.setState({ - interval: window.setInterval(this.fetchConversations, 5000), - active: sessionStorage.getItem(activeChatKey) || '' - }, async () => { - await this.fetchConversations(); - this.selectConversation(this.state.active || this.getFirstConversation()); - }); - } - - componentWillUnmount = () => { - clearInterval(this.state.interval); - this.setState({ interval: undefined }); - } - - getFirstConversation = () => { - const names = [...Object.keys(this.state.conversations)]; - return names.length > 0 ? names[0] : ''; - } - - fetchConversations = async () => { - const { active } = this.state; - let conversations = await chat.getAll(); - - const unAckedActiveMessages = (conversations[active] || []) - .filter(message => !message.acknowledged); - - if (unAckedActiveMessages.length > 0) { - await this.acknowledgeMessages(active, { force: true }); - conversations = { - ...conversations, - [active]: conversations[active].map(message => ({...message, acknowledged: true })) - }; - }; - - this.setState({ conversations }, () => { - if (!this.state.conversations[this.state.active]) { - this.selectConversation(this.getFirstConversation()); - } else { - this.acknowledgeMessages(this.state.active); - } - }); - } - - acknowledgeMessages = async (username, { force = false } = {}) => { - if (!username) return; - - const unAckedMessages = (this.state.conversations[username] || []) - .filter(message => !message.acknowledged); - - if (!force && unAckedMessages.length === 0) return; - - await chat.acknowledge({ username }); - } - - sendMessage = async (username, message) => { - await chat.send({ username, message }); - } - - sendReply = async () => { - const { active } = this.state; - const message = this.messageRef.current.value; - - if (!this.validInput()) { - return; - } + state = initialState; + messageRef = undefined; + listRef = createRef(); + + componentDidMount = async () => { + this.setState({ + interval: window.setInterval(this.fetchConversations, 5000), + active: sessionStorage.getItem(activeChatKey) || '' + }, async () => { + await this.fetchConversations(); + this.selectConversation(this.state.active || this.getFirstConversation()); + }); + } + + componentWillUnmount = () => { + clearInterval(this.state.interval); + this.setState({ interval: undefined }); + } + + getFirstConversation = () => { + const names = [...Object.keys(this.state.conversations)]; + return names.length > 0 ? names[0] : ''; + } + + fetchConversations = async () => { + const { active } = this.state; + let conversations = await chat.getAll(); + + const unAckedActiveMessages = (conversations[active] || []) + .filter(message => !message.acknowledged); + + if (unAckedActiveMessages.length > 0) { + await this.acknowledgeMessages(active, { force: true }); + conversations = { + ...conversations, + [active]: conversations[active].map(message => ({...message, acknowledged: true })) + }; + }; + + this.setState({ conversations }, () => { + if (!this.state.conversations[this.state.active]) { + this.selectConversation(this.getFirstConversation()); + } else { + this.acknowledgeMessages(this.state.active); + } + }); + } - await this.sendMessage(active, message); - this.messageRef.current.value = ''; - } + acknowledgeMessages = async (username, { force = false } = {}) => { + if (!username) return; - validInput = () => (this.state.active || '').length > 0 && ((this.messageRef && this.messageRef.current && this.messageRef.current.value) || '').length > 0; + const unAckedMessages = (this.state.conversations[username] || []) + .filter(message => !message.acknowledged); - focusInput = () => { - this.messageRef.current.focus(); - } + if (!force && unAckedMessages.length === 0) return; - formatTimestamp = (timestamp) => { - const date = new Date(timestamp); - const dtfUS = new Intl.DateTimeFormat('en', { - month: 'numeric', - day: 'numeric', - hour: 'numeric', - minute: '2-digit' - }); + await chat.acknowledge({ username }); + } - return dtfUS.format(date); - } + sendMessage = async (username, message) => { + await chat.send({ username, message }); + } - selectConversation = (username) => { - this.setState({ - active: username, - loading: true - }, async () => { - const { active } = this.state; - - sessionStorage.setItem(activeChatKey, active); - - this.setState({ loading: false }, () => { - try { - this.listRef.current.lastChild.scrollIntoView(); - } catch {} - }); - }); - } - - initiateConversation = async (username, message) => { - await this.sendMessage(username, message); - await this.fetchConversations(); - this.selectConversation(username); - } + sendReply = async () => { + const { active } = this.state; + const message = this.messageRef.current.value; - deleteConversation = async (username) => { - await chat.remove({ username }); - await this.fetchConversations(); - this.selectConversation(this.getFirstConversation()); + if (!this.validInput()) { + return; } - render = () => { - const { conversations, active, loading } = this.state; - const messages = conversations[active] || []; - - return ( - <div className='chats'> - <Segment raised> - <ChatMenu - conversations={conversations} - active={active} - onConversationChange={(name) => this.selectConversation(name)} - initiateConversation={this.initiateConversation} - /> + await this.sendMessage(active, message); + this.messageRef.current.value = ''; + } + + 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); + } + + selectConversation = (username) => { + this.setState({ + active: username, + loading: true + }, async () => { + const { active } = this.state; + + sessionStorage.setItem(activeChatKey, active); + + this.setState({ loading: false }, () => { + try { + this.listRef.current.lastChild.scrollIntoView(); + } catch {} + }); + }); + } + + initiateConversation = async (username, message) => { + await this.sendMessage(username, message); + await this.fetchConversations(); + this.selectConversation(username); + } + + deleteConversation = async (username) => { + await chat.remove({ username }); + await this.fetchConversations(); + this.selectConversation(this.getFirstConversation()); + } + + render = () => { + const { conversations = [], active, loading } = this.state; + const messages = conversations[active] || []; + + return ( + <div className='chats'> + <Segment raised> + <ChatMenu + conversations={conversations} + active={active} + onConversationChange={(name) => this.selectConversation(name)} + initiateConversation={this.initiateConversation} + /> + </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> - {!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>} + </Segment.Group>} </div> - ) - } + </Card.Content> + </Card>} + </div> + ) + } } export default Chat;
\ No newline at end of file diff --git a/src/web/src/components/Rooms/Rooms.js b/src/web/src/components/Rooms/Rooms.js index 306696bb..524aeee9 100644 --- a/src/web/src/components/Rooms/Rooms.js +++ b/src/web/src/components/Rooms/Rooms.js @@ -142,7 +142,7 @@ class Rooms extends Component { }; render = () => { - const { joined, active, room, loading } = this.state; + const { joined = [], active = [], room, loading } = this.state; return ( <div className='rooms'> diff --git a/src/web/src/components/Search/Search.js b/src/web/src/components/Search/Search.js index cb334e16..ef08306d 100644 --- a/src/web/src/components/Search/Search.js +++ b/src/web/src/components/Search/Search.js @@ -8,290 +8,290 @@ import Response from './Response'; import PlaceholderSegment from '../Shared/PlaceholderSegment'; import { - Segment, - Input, - Loader, - Button, - Dropdown, - Checkbox + Segment, + Input, + Loader, + Button, + Dropdown, + Checkbox } from 'semantic-ui-react'; const initialState = { - searchPhrase: '', - searchId: undefined, - searchState: 'idle', - searchStatus: { - responseCount: 0, - fileCount: 0 - }, - results: [], - interval: undefined, - displayCount: 5, - resultSort: 'uploadSpeed', - hideNoFreeSlots: true, - hiddenResults: [], - hideLocked: true, - fetching: false, - resultFilters: '' + searchPhrase: '', + searchId: undefined, + searchState: 'idle', + searchStatus: { + responseCount: 0, + fileCount: 0 + }, + results: [], + interval: undefined, + displayCount: 5, + resultSort: 'uploadSpeed', + hideNoFreeSlots: true, + hiddenResults: [], + hideLocked: true, + fetching: false, + resultFilters: '' }; const sortOptions = { - uploadSpeed: { field: 'uploadSpeed', order: 'desc' }, - queueLength: { field: 'queueLength', order: 'asc' } + uploadSpeed: { field: 'uploadSpeed', order: 'desc' }, + queueLength: { field: 'queueLength', order: 'asc' } } const sortDropdownOptions = [ - { key: 'uploadSpeed', text: 'Upload Speed (Fastest to Slowest)', value: 'uploadSpeed' }, - { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' } + { key: 'uploadSpeed', text: 'Upload Speed (Fastest to Slowest)', value: 'uploadSpeed' }, + { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' } ]; class Search extends Component { - state = initialState; - - search = () => { - const searchPhrase = this.inputtext.inputRef.current.value; - const searchId = uuidv4(); - - this.setState({ searchPhrase, searchId, searchState: 'pending' }, async () => { - this.saveState(); - search.search({ id: searchId, searchText: searchPhrase }); - }); - } - - clear = () => { - this.setState(initialState, () => { - this.saveState(); - this.setSearchText(); - this.inputtext.focus(); - }); - } - - keyUp = (event) => event.key === 'Escape' ? this.clear() : ''; - - onSearchPhraseChange = (event, data) => { - this.setState({ searchPhrase: data.value }); + state = initialState; + + search = () => { + const searchPhrase = this.inputtext.inputRef.current.value; + const searchId = uuidv4(); + + this.setState({ searchPhrase, searchId, searchState: 'pending' }, async () => { + this.saveState(); + search.search({ id: searchId, searchText: searchPhrase }); + }); + } + + clear = () => { + this.setState(initialState, () => { + this.saveState(); + this.setSearchText(); + this.inputtext.focus(); + }); + } + + keyUp = (event) => event.key === 'Escape' ? this.clear() : ''; + + onSearchPhraseChange = (event, data) => { + this.setState({ searchPhrase: data.value }); + } + + onResultFilterChange = (event, data) => { + this.setState({ resultFilters: data.value }, () => this.saveState()); + } + + clearResultFilter = () => { + this.setState({ resultFilters: '' }, () => this.saveState()); + } + + saveState = () => { + try { + localStorage.setItem('soulseek-example-search-state', JSON.stringify({ ...this.state, results: [] })); + } catch(error) { + console.log(error); } - - onResultFilterChange = (event, data) => { - this.setState({ resultFilters: data.value }, () => this.saveState()); - } - - clearResultFilter = () => { - this.setState({ resultFilters: '' }, () => this.saveState()); - } - - saveState = () => { + } + + loadState = () => { + return new Promise((resolve) => + this.setState(JSON.parse(localStorage.getItem('soulseek-example-search-state')) || initialState, resolve)); + } + + componentDidMount = async () => { + await this.loadState(); + this.fetchResults(); + this.setState({ + interval: window.setInterval(this.fetchStatus, 500) + }, () => this.setSearchText()); + + document.addEventListener("keyup", this.keyUp, false); + } + + setSearchText = () => { + this.inputtext.inputRef.current.value = this.state.searchPhrase; + this.inputtext.inputRef.current.disabled = this.state.searchState !== 'idle'; + } + + componentWillUnmount = () => { + clearInterval(this.state.interval); + this.setState({ interval: undefined }); + document.removeEventListener("keyup", this.keyUp, false); + } + + fetchResults = async () => { + const { searchId } = this.state; + + if (!!searchId) { + this.setState({ fetching: true }, async () => { try { - localStorage.setItem('soulseek-example-search-state', JSON.stringify({ ...this.state, results: [] })); - } catch(error) { - console.log(error); + const responses = await search.getResponses({ id: searchId }); + + this.setState({ + results: responses, + fetching: false + }, this.saveState); + } catch (error) { + console.log(error); + this.clear(); } + }); } - - loadState = () => { - return new Promise((resolve) => - this.setState(JSON.parse(localStorage.getItem('soulseek-example-search-state')) || initialState, resolve)); + } + + fetchStatus = async () => { + const { searchState, searchId } = this.state; + + if (searchState === 'pending') { + this.setState({ fetching: true }, async () => { + const response = await search.getStatus({ id: searchId }); + + if (response.isComplete) { + this.setState({ + searchState: 'complete' + }, this.fetchResults); + } else { + this.setState({ + searchStatus: response, + fetching: false + }, this.saveState); + } + }); } + } - componentDidMount = async () => { - await this.loadState(); - this.fetchResults(); - this.setState({ - interval: window.setInterval(this.fetchStatus, 500) - }, () => this.setSearchText()); + showMore = () => { + this.setState({ displayCount: this.state.displayCount + 5 }, () => this.saveState()); + } - document.addEventListener("keyup", this.keyUp, false); - } - - setSearchText = () => { - this.inputtext.inputRef.current.value = this.state.searchPhrase; - this.inputtext.inputRef.current.disabled = this.state.searchState !== 'idle'; - } + sortAndFilterResults = () => { + const { results = [], hideNoFreeSlots, resultSort, resultFilters = '', hideLocked, hiddenResults = [] } = this.state; + const { field, order } = sortOptions[resultSort]; - componentWillUnmount = () => { - clearInterval(this.state.interval); - this.setState({ interval: undefined }); - document.removeEventListener("keyup", this.keyUp, false); - } + const filters = search.parseFiltersFromString(resultFilters); - fetchResults = async () => { - const { searchId } = this.state; - - if (!!searchId) { - this.setState({ fetching: true }, async () => { - try { - const responses = await search.getResponses({ id: searchId }); - - this.setState({ - results: responses, - fetching: false - }, this.saveState); - } catch (error) { - console.log(error); - this.clear(); - } - }); + return results + .filter(r => !hiddenResults.includes(r.username)) + .map(r => { + if (hideLocked) { + return { ...r, lockedFileCount: 0, lockedFiles: [] } } - } - - fetchStatus = async () => { - const { searchState, searchId } = this.state; - - if (searchState === 'pending') { - this.setState({ fetching: true }, async () => { - const response = await search.getStatus({ id: searchId }); - - if (response.isComplete) { - this.setState({ - searchState: 'complete' - }, this.fetchResults); - } else { - this.setState({ - searchStatus: response, - fetching: false - }, this.saveState); - } - }); + return r; + }) + .map(response => search.filterResponse({ response, filters })) + .filter(r => r.fileCount + r.lockedFileCount > 0) + .filter(r => !(hideNoFreeSlots && r.freeUploadSlots === 0)) + .sort((a, b) => { + if (order === 'asc') { + return a[field] - b[field]; } - } - showMore = () => { - this.setState({ displayCount: this.state.displayCount + 5 }, () => this.saveState()); - } - - sortAndFilterResults = () => { - const { results = [], hideNoFreeSlots, resultSort, resultFilters = '', hideLocked, hiddenResults = [] } = this.state; - const { field, order } = sortOptions[resultSort]; - - const filters = search.parseFiltersFromString(resultFilters); - - return results - .filter(r => !hiddenResults.includes(r.username)) - .map(r => { - if (hideLocked) { - return { ...r, lockedFileCount: 0, lockedFiles: [] } - } - return r; - }) - .map(response => search.filterResponse({ response, filters })) - .filter(r => r.fileCount + r.lockedFileCount > 0) - .filter(r => !(hideNoFreeSlots && r.freeUploadSlots === 0)) - .sort((a, b) => { - if (order === 'asc') { - return a[field] - b[field]; - } - - return b[field] - a[field]; - }); - } - - hideResult = (result) => { - this.setState({ hiddenResults: [...this.state.hiddenResults, result.username]}, () => { - if (this.state.hiddenResults.length === this.state.results.length) { - this.clear(); - } else { - this.saveState(); + return b[field] - a[field]; + }); + } + + hideResult = (result) => { + this.setState({ hiddenResults: [...this.state.hiddenResults, result.username]}, () => { + if (this.state.hiddenResults.length === this.state.results.length) { + this.clear(); + } else { + this.saveState(); + } + }); + } + + render = () => { + let { searchState, searchStatus, results = [], displayCount, resultSort, hideNoFreeSlots, hideLocked, hiddenResults = [], fetching, resultFilters } = this.state; + let pending = fetching || searchState === 'pending'; + + const sortedAndFilteredResults = this.sortAndFilterResults(); + + const remainingCount = sortedAndFilteredResults.length - displayCount; + const showMoreCount = remainingCount >= 5 ? 5 : remainingCount; + const hiddenCount = results.length - hiddenResults.length - sortedAndFilteredResults.length; + + return ( + <div className='search-container'> + <Segment className='search-segment' raised> + <Input + input={<input placeholder="Search phrase" type="search" data-lpignore="true"></input>} + size='big' + ref={input => this.inputtext = input} + loading={pending} + disabled={pending} + className='search-input' + placeholder="Search phrase" + action={!pending && (searchState === 'idle' ? { icon: 'search', onClick: this.search } : { icon: 'x', color: 'red', onClick: this.clear })} + onKeyUp={(e) => e.key === 'Enter' ? this.search() : ''} + /> + </Segment> + {pending ? + <Loader + className='search-loader' + active + inline='centered' + size='big' + > + {searchState === 'pending' ? <span>Found {searchStatus.fileCount} files {searchStatus.lockedFileCount > 0 ? `(plus ${searchStatus.lockedFileCount} locked) ` : ''}from {searchStatus.responseCount} users</span> + : 'Loading results...'} + </Loader> + : + <div> + {(results && results.length > 0) ? + <Segment className='search-options' raised> + <Dropdown + button + className='search-options-sort icon' + floating + labeled + icon='sort' + options={sortDropdownOptions} + onChange={(e, { value }) => this.setState({ resultSort: value }, () => this.saveState())} + text={sortDropdownOptions.find(o => o.value === resultSort).text} + /> + <div className='search-option-toggles'> + <Checkbox + className='search-options-hide-locked' + toggle + onChange={() => this.setState({ hideLocked: !hideLocked }, () => this.saveState())} + checked={hideLocked} + label='Hide Locked Results' + /> + <Checkbox + className='search-options-hide-no-slots' + toggle + onChange={() => this.setState({ hideNoFreeSlots: !hideNoFreeSlots }, () => this.saveState())} + checked={hideNoFreeSlots} + label='Hide Results with No Free Slots' + /> + </div> + <Input + className='search-filter' + placeholder='lackluster container -bothersome iscbr|isvbr minbitrate:320 minfilesize:10 minfilesinfolder:8 minlength:5000' + label={{ icon: 'filter', content: 'Filter' }} + value={resultFilters} + onChange={this.onResultFilterChange} + action={!!resultFilters && { icon: 'x', color: 'red', onClick: this.clearResultFilter }} + /> + </Segment> : <PlaceholderSegment icon='search'/> } - }); - } - - render = () => { - let { searchState, searchStatus, results = [], displayCount, resultSort, hideNoFreeSlots, hideLocked, hiddenResults = [], fetching, resultFilters } = this.state; - let pending = fetching || searchState === 'pending'; - - const sortedAndFilteredResults = this.sortAndFilterResults(); - - const remainingCount = sortedAndFilteredResults.length - displayCount; - const showMoreCount = remainingCount >= 5 ? 5 : remainingCount; - const hiddenCount = results.length - hiddenResults.length - sortedAndFilteredResults.length; - - return ( - <div className='search-container'> - <Segment className='search-segment' raised> - <Input - input={<input placeholder="Search phrase" type="search" data-lpignore="true"></input>} - size='big' - ref={input => this.inputtext = input} - loading={pending} - disabled={pending} - className='search-input' - placeholder="Search phrase" - action={!pending && (searchState === 'idle' ? { icon: 'search', onClick: this.search } : { icon: 'x', color: 'red', onClick: this.clear })} - onKeyUp={(e) => e.key === 'Enter' ? this.search() : ''} - /> - </Segment> - {pending ? - <Loader - className='search-loader' - active - inline='centered' - size='big' - > - {searchState === 'pending' ? <span>Found {searchStatus.fileCount} files {searchStatus.lockedFileCount > 0 ? `(plus ${searchStatus.lockedFileCount} locked) ` : ''}from {searchStatus.responseCount} users</span> - : 'Loading results...'} - </Loader> - : - <div> - {(results && results.length > 0) ? - <Segment className='search-options' raised> - <Dropdown - button - className='search-options-sort icon' - floating - labeled - icon='sort' - options={sortDropdownOptions} - onChange={(e, { value }) => this.setState({ resultSort: value }, () => this.saveState())} - text={sortDropdownOptions.find(o => o.value === resultSort).text} - /> - <div className='search-option-toggles'> - <Checkbox - className='search-options-hide-locked' - toggle - onChange={() => this.setState({ hideLocked: !hideLocked }, () => this.saveState())} - checked={hideLocked} - label='Hide Locked Results' - /> - <Checkbox - className='search-options-hide-no-slots' - toggle - onChange={() => this.setState({ hideNoFreeSlots: !hideNoFreeSlots }, () => this.saveState())} - checked={hideNoFreeSlots} - label='Hide Results with No Free Slots' - /> - </div> - <Input - className='search-filter' - placeholder='lackluster container -bothersome iscbr|isvbr minbitrate:320 minfilesize:10 minfilesinfolder:8 minlength:5000' - label={{ icon: 'filter', content: 'Filter' }} - value={resultFilters} - onChange={this.onResultFilterChange} - action={!!resultFilters && { icon: 'x', color: 'red', onClick: this.clearResultFilter }} - /> - </Segment> : <PlaceholderSegment icon='search'/> - } - {sortedAndFilteredResults.slice(0, displayCount).map((r, i) => - <Response - key={i} - response={r} - onDownload={this.props.onDownload} - onHide={() => this.hideResult(r)} - /> - )} - {remainingCount > 0 ? - <Button - className='showmore-button' - size='large' - fluid - primary - onClick={() => this.showMore()}> - Show {showMoreCount} More Results {remainingCount > 5 ? `(${remainingCount} remaining, ${hiddenCount} hidden by filter(s))` : ''} - </Button> - : ''} - </div>} - </div> - ) - } + {sortedAndFilteredResults.slice(0, displayCount).map((r, i) => + <Response + key={i} + response={r} + onDownload={this.props.onDownload} + onHide={() => this.hideResult(r)} + /> + )} + {remainingCount > 0 ? + <Button + className='showmore-button' + size='large' + fluid + primary + onClick={() => this.showMore()}> + Show {showMoreCount} More Results {remainingCount > 5 ? `(${remainingCount} remaining, ${hiddenCount} hidden by filter(s))` : ''} + </Button> + : ''} + </div>} + </div> + ) + } } export default Search;
\ No newline at end of file diff --git a/src/web/src/components/Shared/ErrorSegment.js b/src/web/src/components/Shared/ErrorSegment.js new file mode 100644 index 00000000..7a6caa9d --- /dev/null +++ b/src/web/src/components/Shared/ErrorSegment.js @@ -0,0 +1,14 @@ +import React from 'react'; + +import { Segment, Header, Icon } from 'semantic-ui-react'; + +const ErrorSegment = ({ icon, caption }) => ( + <Segment className='error-segment' placeholder basic> + <Header icon> + <Icon name='x' color='red'/> + Error: {caption} + </Header> +</Segment> +); + +export default ErrorSegment;
\ No newline at end of file diff --git a/src/web/src/components/Transfers/Transfers.js b/src/web/src/components/Transfers/Transfers.js index eeb48a7a..3d65ca69 100644 --- a/src/web/src/components/Transfers/Transfers.js +++ b/src/web/src/components/Transfers/Transfers.js @@ -5,42 +5,45 @@ import PlaceholderSegment from '../Shared/PlaceholderSegment'; import TransferGroup from './TransferGroup'; class Transfers extends Component { - state = { fetchState: '', downloads: [], interval: undefined } + state = { fetchState: '', downloads: [], interval: undefined } - componentDidMount = () => { - this.fetch(); - this.setState({ interval: window.setInterval(this.fetch, 500) }); - } + componentDidMount = () => { + this.fetch(); + this.setState({ interval: window.setInterval(this.fetch, 500) }); + } - componentWillUnmount = () => { - clearInterval(this.state.interval); - this.setState({ interval: undefined }); - } + componentWillUnmount = () => { + clearInterval(this.state.interval); + this.setState({ interval: undefined }); + } - fetch = () => { - this.setState({ fetchState: 'pending' }, () => { - transfers.getAll({ direction: this.props.direction }) - .then(response => this.setState({ - fetchState: 'complete', downloads: response - })) - .catch(err => this.setState({ fetchState: 'failed' })) + fetch = () => { + this.setState({ fetchState: 'pending' }, async () => { + try { + const response = await transfers.getAll({ direction: this.props.direction }) + this.setState({ + fetchState: 'complete', downloads: response }) - } - - render = () => { - const { downloads } = this.state; - const { direction } = this.props; + } catch (err) { + this.setState({ fetchState: 'failed' }) + } + }) + } + + render = () => { + const { downloads = [] } = this.state; + const { direction } = this.props; - 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> - ); - } + 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> + ); + } } export default Transfers;
\ No newline at end of file diff --git a/src/web/src/lib/chat.js b/src/web/src/lib/chat.js index e0205f4c..088e2598 100644 --- a/src/web/src/lib/chat.js +++ b/src/web/src/lib/chat.js @@ -1,7 +1,14 @@ import api from './api'; export const getAll = async () => { - return (await api.get('/conversations')).data; + const response = (await api.get('/conversations')).data; + + if (!Array.isArray(response)) { + console.warn('got non-array response from conversations API', response) + return undefined; + } + + return response; }; export const acknowledge = ({ username }) => { diff --git a/src/web/src/lib/rooms.js b/src/web/src/lib/rooms.js index 82736073..c2a36187 100644 --- a/src/web/src/lib/rooms.js +++ b/src/web/src/lib/rooms.js @@ -1,19 +1,47 @@ import api from './api'; export const getAvailable = async () => { - return (await api.get('/rooms/available')).data; + const response = (await api.get('/rooms/available')).data; + + if (!Array.isArray(response)) { + console.warn('got non-array response from rooms API', response) + return undefined; + } + + return response; }; export const getJoined = async () => { - return (await api.get('/rooms/joined')).data; + const response = (await api.get('/rooms/joined')).data; + + if (!Array.isArray(response)) { + console.warn('got non-array response from rooms API', response) + return undefined; + } + + return response; }; export const getMessages = async ({ roomName }) => { - return (await api.get(`/rooms/joined/${roomName}/messages`)).data; + const response = (await api.get(`/rooms/joined/${roomName}/messages`)).data; + + if (!Array.isArray(response)) { + console.warn('got non-array response from rooms API', response) + return undefined; + } + + return response; }; export const getUsers = async ({ roomName }) => { - return (await api.get(`/rooms/joined/${roomName}/users`)).data; + const response = (await api.get(`/rooms/joined/${roomName}/users`)).data; + + if (!Array.isArray(response)) { + console.warn('got non-array response from rooms API', response) + return undefined; + } + + return response; }; export const join = async ({ roomName }) => { diff --git a/src/web/src/lib/search.js b/src/web/src/lib/search.js index ff5f72de..ab0742ce 100644 --- a/src/web/src/lib/search.js +++ b/src/web/src/lib/search.js @@ -9,7 +9,14 @@ export const getStatus = async ({ id, includeResponses = false }) => { }; export const getResponses = async ({ id }) => { - return (await api.get(`/searches/${encodeURIComponent(id)}/responses`)).data; + const response = (await api.get(`/searches/${encodeURIComponent(id)}/responses`)).data; + + if (!Array.isArray(response)) { + console.warn('got non-array response from searches API', response) + return undefined; + } + + return response; }; export const isConstantBitRate = (bitRate) => { diff --git a/src/web/src/lib/transfers.js b/src/web/src/lib/transfers.js index 2b529339..84f6ecd9 100644 --- a/src/web/src/lib/transfers.js +++ b/src/web/src/lib/transfers.js @@ -1,7 +1,14 @@ import api from './api'; export const getAll = async ({ direction }) => { - return (await api.get(`/transfers/${direction}s`)).data; + const response = (await api.get(`/transfers/${direction}s`)).data; + + if (!Array.isArray(response)) { + console.warn('got non-array response from transfers API', response) + return undefined; + } + + return response; }; export const download = ({ username, filename, size }) => { |
