tooot/src/utils/push/useConnect.ts

86 lines
2.4 KiB
TypeScript
Raw Normal View History

2021-03-04 01:03:53 +01:00
import apiGeneral from '@api/general'
2021-06-21 11:59:29 +02:00
import apiTooot from '@api/tooot'
2021-03-04 01:03:53 +01:00
import { displayMessage } from '@components/Message'
2021-08-29 15:25:38 +02:00
import navigationRef from '@helpers/navigationRef'
2022-01-02 22:28:33 +01:00
import { isDevelopment } from '@utils/checkEnvironment'
2021-06-21 11:59:29 +02:00
import { disableAllPushes, Instance } from '@utils/slices/instancesSlice'
2022-01-30 22:51:03 +01:00
import { useTheme } from '@utils/styles/ThemeManager'
2021-03-04 01:03:53 +01:00
import * as Notifications from 'expo-notifications'
import { useEffect } from 'react'
import { TFunction } from 'react-i18next'
2022-01-30 22:51:03 +01:00
import { useDispatch } from 'react-redux'
2021-03-04 01:03:53 +01:00
export interface Params {
2021-03-28 23:31:10 +02:00
t: TFunction<'screens'>
2021-03-04 01:03:53 +01:00
instances: Instance[]
}
2022-01-30 22:51:03 +01:00
const pushUseConnect = ({ t, instances }: Params) => {
const dispatch = useDispatch()
const { mode } = useTheme()
2021-03-04 01:03:53 +01:00
return useEffect(() => {
const connect = async () => {
2022-01-02 22:28:33 +01:00
const expoToken = isDevelopment
2022-01-30 22:51:03 +01:00
? 'DEVELOPMENT_TOKEN_1'
: (
await Notifications.getExpoPushTokenAsync({
experienceId: '@xmflsct/tooot'
})
).data
2021-03-04 01:03:53 +01:00
2021-06-21 11:59:29 +02:00
apiTooot({
2021-12-12 22:09:18 +01:00
method: 'get',
url: `push/connect/${expoToken}`,
2021-03-12 00:19:45 +01:00
sentry: true
2021-03-14 00:47:55 +01:00
}).catch(error => {
2021-12-31 11:38:21 +01:00
if (error.status == 404) {
2021-03-14 00:47:55 +01:00
displayMessage({
mode,
type: 'error',
duration: 'long',
2021-03-28 23:31:10 +02:00
message: t('pushError.message'),
description: t('pushError.description'),
2021-03-14 00:47:55 +01:00
onPress: () => {
2021-08-29 15:25:38 +02:00
navigationRef.navigate('Screen-Tabs', {
2021-03-14 00:47:55 +01:00
screen: 'Tab-Me',
params: {
screen: 'Tab-Me-Root'
}
})
2021-08-29 15:25:38 +02:00
navigationRef.navigate('Screen-Tabs', {
2021-03-14 00:47:55 +01:00
screen: 'Tab-Me',
params: {
screen: 'Tab-Me-Settings'
}
})
}
})
2021-03-04 01:03:53 +01:00
2021-03-14 00:47:55 +01:00
dispatch(disableAllPushes())
2021-03-04 01:03:53 +01:00
2021-03-14 00:47:55 +01:00
instances.forEach(instance => {
if (instance.push.global.value) {
apiGeneral<{}>({
method: 'delete',
domain: instance.url,
url: 'api/v1/push/subscription',
headers: {
Authorization: `Bearer ${instance.token}`
}
}).catch(() => console.log('error!!!'))
}
})
}
2021-03-04 01:03:53 +01:00
})
}
const pushEnabled = instances.filter(instance => instance.push.global.value)
if (pushEnabled.length) {
2021-12-12 22:09:18 +01:00
connect()
2021-03-04 01:03:53 +01:00
}
}, [instances])
}
export default pushUseConnect