tooot/src/startup/netInfo.ts

69 lines
2.1 KiB
TypeScript
Raw Normal View History

2021-02-20 19:12:44 +01:00
import apiInstance from '@api/instance'
2021-01-07 19:13:09 +01:00
import NetInfo from '@react-native-community/netinfo'
import { store } from '@root/store'
2021-02-20 19:12:44 +01:00
import removeInstance from '@utils/slices/instances/remove'
2022-12-09 21:09:00 +01:00
import { getInstance, updateInstanceAccount } from '@utils/slices/instancesSlice'
import { onlineManager } from '@tanstack/react-query'
2021-01-07 19:13:09 +01:00
import log from './log'
const netInfo = async (): Promise<{
2022-01-16 23:26:05 +01:00
connected?: boolean
2021-01-07 19:13:09 +01:00
corrupted?: string
2022-01-16 23:26:05 +01:00
} | void> => {
2021-01-07 19:13:09 +01:00
log('log', 'netInfo', 'initializing')
2021-03-15 22:30:29 +01:00
2021-01-07 19:13:09 +01:00
const netInfo = await NetInfo.fetch()
2021-03-01 00:28:14 +01:00
const instance = getInstance(store.getState())
2021-01-07 19:13:09 +01:00
2022-01-16 23:26:05 +01:00
onlineManager.setEventListener(setOnline => {
return NetInfo.addEventListener(state => {
setOnline(!!state.isConnected)
2022-01-16 23:26:05 +01:00
})
})
2021-01-07 19:13:09 +01:00
if (netInfo.isConnected) {
log('log', 'netInfo', 'network connected')
2021-03-01 00:28:14 +01:00
if (instance) {
2021-01-07 19:13:09 +01:00
log('log', 'netInfo', 'checking locally stored credentials')
2022-01-16 23:26:05 +01:00
let resVerify: Mastodon.Account
try {
resVerify = await apiInstance<Mastodon.Account>({
method: 'get',
url: `accounts/verify_credentials`
}).then(res => res.body)
} catch (error: any) {
log('error', 'netInfo', 'local credential check failed')
2022-05-17 23:18:49 +02:00
if (error?.status && error.status == 401) {
2022-01-16 23:26:05 +01:00
store.dispatch(removeInstance(instance))
}
2022-05-17 23:18:49 +02:00
return Promise.resolve({ corrupted: error.data?.error })
2022-01-16 23:26:05 +01:00
}
log('log', 'netInfo', 'local credential check passed')
if (resVerify.id !== instance.account.id) {
log('error', 'netInfo', 'local id does not match remote id')
store.dispatch(removeInstance(instance))
return Promise.resolve({ connected: true, corrupted: '' })
2022-01-16 23:26:05 +01:00
} else {
store.dispatch(
updateInstanceAccount({
acct: resVerify.acct,
avatarStatic: resVerify.avatar_static
})
)
return Promise.resolve({ connected: true })
}
2021-01-07 19:13:09 +01:00
} else {
log('log', 'netInfo', 'no local credential found')
2022-01-16 23:26:05 +01:00
return Promise.resolve()
2021-01-07 19:13:09 +01:00
}
} else {
log('warn', 'netInfo', 'network not connected')
2022-01-16 23:26:05 +01:00
return Promise.resolve()
2021-01-07 19:13:09 +01:00
}
}
export default netInfo