56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
import { PushNotifications } from '@capacitor/push-notifications';
|
|
import type {
|
|
ActionPerformed,
|
|
PushNotificationSchema,
|
|
} from '@capacitor/push-notifications';
|
|
import { supabase } from '../supabase';
|
|
|
|
export async function setupPushNotifications(userId: string, history: any) {
|
|
const handleNotificationTap = (notification: PushNotificationSchema) => {
|
|
if (notification.data?.deep_link) {
|
|
history.push(notification.data.deep_link);
|
|
} else if (notification.data?.type === 'message') {
|
|
history.push(`/chat/${notification.data.conversation_id}`);
|
|
}
|
|
};
|
|
|
|
const launch = await (PushNotifications as any).getLaunchNotification();
|
|
if (launch) handleNotificationTap(launch.notification);
|
|
|
|
const status = await PushNotifications.checkPermissions();
|
|
|
|
if (status.receive === 'granted') {
|
|
await PushNotifications.register();
|
|
} else if (status.receive === 'prompt') {
|
|
const result = await PushNotifications.requestPermissions();
|
|
if (result.receive === 'granted') await PushNotifications.register();
|
|
}
|
|
|
|
PushNotifications.addListener('registration', async (token) => {
|
|
await supabase
|
|
.from('profiles')
|
|
.update({ fcm_token: token.value })
|
|
.eq('id', userId);
|
|
});
|
|
|
|
PushNotifications.addListener('registrationError', (err) => {
|
|
console.error('Push registration error', err);
|
|
});
|
|
|
|
PushNotifications.addListener(
|
|
'pushNotificationReceived',
|
|
async (notification: PushNotificationSchema) => {
|
|
console.log('Push received', notification);
|
|
}
|
|
);
|
|
|
|
PushNotifications.addListener(
|
|
'pushNotificationActionPerformed',
|
|
(action: ActionPerformed) => {
|
|
handleNotificationTap(action.notification);
|
|
}
|
|
);
|
|
|
|
await PushNotifications.removeAllDeliveredNotifications();
|
|
}
|