subtracks/app/screens/ServerView.tsx
austinried 8196704ccd
React Query refactor (#91)
* initial react-query experiments

* use queries for item screens

send the data we do have over routing to prepopulate (album/playlist)
use number for starred because sending Date freaks out react-navigation

* add in equiv. song cover art fix

* reorg, switch artistview over

start mapping song cover art when any are available

* refactor useStar to queries

fix caching for starred items and album cover art

* add hook to reset queries on server change

* refactor search to use query

* fix song cover art setting

* use query for artistInfo

* remove last bits of library state

* cleanup

* use query key factory

already fixed one wrong key...

* require coverart size

* let's try no promise queues on these for now

* image cache uses query

* perf fix for playlist parsing

also use placeholder data so we don't have to deal with staleness

* drill that disabled

also list controls doesn't need its own songs hook/copy

* switch to react-native-blob-util for downloads

slightly slower but allows us to use DownloadManager, which backgrounds downloads so they are no longer corrupted when the app suspends

* add a fake "top songs" based on artist search

then sorted by play count/ratings
artistview should load now even if topSongs fails

* try not to swap between topSongs/search on refetch

set queueContext by song list so the index isn't off if the list changes

* add content type validation for file fetching

also try to speed up existing file return by limiting fs ops

* if the HEAD fails, don't queue the download

* clean up params

* reimpl clear image cache

* precompute contextId

prevents wrong "is playing" when any mismatch between queue and list

* clear images from all servers

use external files dir instead of cache

* fix pressable disabled flicker

don't retry topsongs on failure
try to optimize setqueue and fixcoverart a bit

* wait for queries during clear

* break out fetchExistingFile from fetchFile

allows to tell if file is coming from disk or not
only show placeholder/loading spinner if actually fetching image

* forgot these wouldn't do anything with objects

* remove query cache when switching servers

* add content-disposition extension gathering

add support for progress hook (needs native support still)

* added custom RNBU pkg with progress changes

* fully unmount tabs when server changes

prevents unwanted requests, gives fresh start on switch
fix fixCoverArt not re-rendering in certain cases on search

* use serverId from fetch deps

* fix lint

* update licenses

* just use the whole lodash package

* make using cache buster optional
2022-04-11 09:40:51 +09:00

271 lines
7.3 KiB
TypeScript

import Button from '@app/components/Button'
import GradientScrollView from '@app/components/GradientScrollView'
import { Server } from '@app/models/settings'
import { useStore, useStoreDeep } from '@app/state/store'
import colors from '@app/styles/colors'
import font from '@app/styles/font'
import toast from '@app/util/toast'
import { useNavigation } from '@react-navigation/native'
import md5 from 'md5'
import React, { useCallback, useState } from 'react'
import { StyleSheet, Text, TextInput, View, ViewStyle } from 'react-native'
import uuid from 'react-native-uuid'
import SettingsSwitch from '@app/components/SettingsSwitch'
const PASSWORD_PLACEHOLDER = 'PASSWORD_PLACEHOLDER'
const ServerView: React.FC<{
id?: string
}> = ({ id }) => {
const navigation = useNavigation()
const activeServerId = useStore(store => store.settings.activeServerId)
const servers = useStoreDeep(store => store.settings.servers)
const addServer = useStore(store => store.addServer)
const updateServer = useStore(store => store.updateServer)
const removeServer = useStore(store => store.removeServer)
const server = id ? servers[id] : undefined
const pingServer = useStore(store => store.pingServer)
const [address, setAddress] = useState(server?.address || '')
const [username, setUsername] = useState(server?.username || '')
const [usePlainPassword, setUsePlainPassword] = useState(server?.usePlainPassword ?? false)
const [password, setPassword] = useState(
server?.usePlainPassword ? server.plainPassword || '' : server?.token ? PASSWORD_PLACEHOLDER : '',
)
const [testing, setTesting] = useState(false)
const validate = useCallback(() => {
return !!address && !!username && !!password
}, [address, username, password])
const canRemove = useCallback(() => {
return id && Object.keys(servers).length > 1 && activeServerId !== id
}, [id, servers, activeServerId])
const exit = useCallback(() => {
if (navigation.canGoBack()) {
navigation.goBack()
} else {
navigation.navigate('main')
}
}, [navigation])
const createServer = useCallback<() => Server>(() => {
if (usePlainPassword) {
return {
id: server?.id || '',
usePlainPassword,
plainPassword: password,
address,
username,
}
}
let token: string
let salt: string
if (server && !server.usePlainPassword && password === PASSWORD_PLACEHOLDER) {
salt = server.salt
token = server.token
} else {
salt = uuid.v4() as string
token = md5(password + salt)
}
return {
id: server?.id || '',
address,
username,
usePlainPassword,
salt,
token,
}
}, [usePlainPassword, server, address, username, password])
const save = useCallback(() => {
if (!validate()) {
return
}
const update = createServer()
if (id) {
updateServer(update)
} else {
addServer(update)
}
exit()
}, [addServer, createServer, exit, id, updateServer, validate])
const remove = useCallback(() => {
if (!canRemove()) {
return
}
removeServer(id as string)
exit()
}, [canRemove, exit, id, removeServer])
const togglePlainPassword = useCallback(
(value: boolean) => {
setUsePlainPassword(value)
if (value) {
if (server && server.usePlainPassword) {
setPassword(server.plainPassword)
} else if (server) {
setPassword('')
}
} else {
if (server && !server.usePlainPassword) {
setPassword(PASSWORD_PLACEHOLDER)
}
}
},
[server],
)
const test = useCallback(() => {
setTesting(true)
const potential = createServer()
const ping = async () => {
const res = await pingServer(potential)
if (res) {
toast(`Connection to ${potential.address} OK!`)
} else {
toast(`Connection to ${potential.address} failed, check settings or server`)
}
setTesting(false)
}
ping()
}, [createServer, pingServer])
const disableControls = useCallback(() => {
return !validate() || testing
}, [validate, testing])
const formatAddress = useCallback(() => {
let addressFormatted = address.trim()
if (addressFormatted.endsWith('/')) {
addressFormatted = addressFormatted.substr(0, addressFormatted.length - 1)
}
if (addressFormatted.length > 0 && !addressFormatted.includes(':/')) {
addressFormatted = `http://${addressFormatted}`
}
setAddress(addressFormatted)
}, [address])
const deleteStyle: ViewStyle = {
display: canRemove() ? 'flex' : 'none',
}
return (
<GradientScrollView style={styles.scroll}>
<View style={styles.content}>
<Text style={styles.inputTitle}>Address</Text>
<TextInput
style={styles.input}
placeholderTextColor="grey"
selectionColor={colors.text.secondary}
textContentType="URL"
placeholder="http://demo.navidrome.org"
autoCorrect={false}
autoCapitalize="none"
value={address}
onChangeText={setAddress}
onBlur={formatAddress}
/>
<Text style={styles.inputTitle}>Username</Text>
<TextInput
style={styles.input}
placeholderTextColor="grey"
selectionColor={colors.text.secondary}
textContentType="username"
autoComplete="username"
importantForAutofill="yes"
autoCapitalize="none"
placeholder="demo"
value={username}
onChangeText={setUsername}
/>
<Text style={styles.inputTitle}>Password</Text>
<TextInput
style={styles.input}
placeholderTextColor="grey"
selectionColor={colors.text.secondary}
textContentType="password"
autoComplete="password"
autoCapitalize="none"
importantForAutofill="yes"
secureTextEntry={true}
placeholder="demo"
value={password}
onChangeText={setPassword}
/>
<SettingsSwitch
title="Force plain text password"
subtitle={
usePlainPassword
? 'Send password in plain text (legacy, make sure your connection is secure!)'
: 'Send password as token + salt'
}
value={usePlainPassword}
setValue={togglePlainPassword}
/>
<Button
disabled={disableControls()}
style={styles.button}
title="Test Connection"
buttonStyle="hollow"
onPress={test}
/>
<Button
disabled={disableControls()}
style={[styles.button, styles.delete, deleteStyle]}
title="Delete"
onPress={remove}
/>
<Button disabled={disableControls()} style={styles.button} title="Save" onPress={save} />
</View>
</GradientScrollView>
)
}
const styles = StyleSheet.create({
scroll: {
flex: 1,
},
content: {
paddingHorizontal: 20,
},
inputTitle: {
fontFamily: font.semiBold,
fontSize: 16,
color: colors.text.primary,
marginTop: 10,
},
input: {
borderBottomWidth: 1.5,
borderColor: colors.text.primary,
fontFamily: font.regular,
fontSize: 16,
color: colors.text.primary,
marginBottom: 26,
},
button: {
marginTop: 16,
},
delete: {
backgroundColor: 'red',
},
})
export default ServerView