tooot/src/startup/netInfo.ts

71 lines
2.2 KiB
TypeScript
Raw Normal View History

2021-01-07 19:13:09 +01:00
import client from '@api/client'
import NetInfo from '@react-native-community/netinfo'
import { store } from '@root/store'
2021-01-23 02:41:50 +01:00
import {
localRemoveInstance,
2021-02-07 00:39:11 +01:00
updateLocalAccount
2021-01-23 02:41:50 +01:00
} from '@utils/slices/instancesSlice'
2021-01-07 19:13:09 +01:00
import log from './log'
const netInfo = async (): Promise<{
connected: boolean
corrupted?: string
}> => {
log('log', 'netInfo', 'initializing')
const netInfo = await NetInfo.fetch()
const activeIndex = store.getState().instances.local?.activeIndex
if (netInfo.isConnected) {
log('log', 'netInfo', 'network connected')
2021-01-24 02:25:43 +01:00
if (activeIndex !== null) {
2021-01-07 19:13:09 +01:00
log('log', 'netInfo', 'checking locally stored credentials')
return client<Mastodon.Account>({
method: 'get',
instance: 'local',
url: `accounts/verify_credentials`
})
.then(res => {
log('log', 'netInfo', 'local credential check passed')
if (
2021-02-11 01:33:31 +01:00
res.body.id !==
2021-01-07 19:13:09 +01:00
store.getState().instances.local?.instances[activeIndex].account.id
) {
log('error', 'netInfo', 'local id does not match remote id')
store.dispatch(localRemoveInstance(activeIndex))
return Promise.resolve({ connected: true, corruputed: '' })
} else {
2021-01-23 02:41:50 +01:00
store.dispatch(
2021-02-07 00:39:11 +01:00
updateLocalAccount({
2021-02-11 01:33:31 +01:00
acct: res.body.acct,
avatarStatic: res.body.avatar_static
2021-01-23 02:41:50 +01:00
})
)
2021-01-07 19:13:09 +01:00
return Promise.resolve({ connected: true })
}
})
.catch(error => {
log('error', 'netInfo', 'local credential check failed')
if (
error.status &&
typeof error.status === 'number' &&
error.status === 401
) {
store.dispatch(localRemoveInstance(activeIndex))
}
return Promise.resolve({
connected: true,
corrupted: error.data.error
})
})
} else {
log('log', 'netInfo', 'no local credential found')
return Promise.resolve({ connected: true })
}
} else {
log('warn', 'netInfo', 'network not connected')
return Promise.resolve({ connected: true })
}
}
export default netInfo