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'
|
2021-01-23 02:41:50 +01:00
|
|
|
import {
|
2021-03-01 00:28:14 +01:00
|
|
|
getInstance,
|
2021-02-20 19:12:44 +01:00
|
|
|
updateInstanceAccount
|
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')
|
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
|
|
|
|
|
|
|
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')
|
2021-02-20 19:12:44 +01:00
|
|
|
return apiInstance<Mastodon.Account>({
|
2021-01-07 19:13:09 +01:00
|
|
|
method: 'get',
|
|
|
|
url: `accounts/verify_credentials`
|
|
|
|
})
|
|
|
|
.then(res => {
|
|
|
|
log('log', 'netInfo', 'local credential check passed')
|
2021-03-01 00:28:14 +01:00
|
|
|
if (res.body.id !== instance.account.id) {
|
2021-01-07 19:13:09 +01:00
|
|
|
log('error', 'netInfo', 'local id does not match remote id')
|
2021-03-01 00:28:14 +01:00
|
|
|
store.dispatch(removeInstance(instance))
|
2021-01-07 19:13:09 +01:00
|
|
|
return Promise.resolve({ connected: true, corruputed: '' })
|
|
|
|
} else {
|
2021-01-23 02:41:50 +01:00
|
|
|
store.dispatch(
|
2021-02-20 19:12:44 +01:00
|
|
|
updateInstanceAccount({
|
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')
|
2021-05-30 15:40:06 +02:00
|
|
|
if (error.status && error.status == 401) {
|
2021-03-01 00:28:14 +01:00
|
|
|
store.dispatch(removeInstance(instance))
|
2021-01-07 19:13:09 +01:00
|
|
|
}
|
|
|
|
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
|