mobile download
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
import {
|
||||
registerFcmToken,
|
||||
deleteFcmToken,
|
||||
} from '../lib/shared';
|
||||
import { PushNotifications } from '@capacitor/push-notifications';
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
|
||||
export interface FcmPayload {
|
||||
type?: string;
|
||||
market?: string;
|
||||
signalId?: string;
|
||||
signalType?: string;
|
||||
price?: string;
|
||||
}
|
||||
|
||||
type FcmHandlers = {
|
||||
onForeground?: (title: string, body: string, data?: FcmPayload) => void;
|
||||
onTap?: (data: FcmPayload) => void;
|
||||
};
|
||||
|
||||
let initialized = false;
|
||||
|
||||
export async function initFcmPush(handlers: FcmHandlers = {}): Promise<boolean> {
|
||||
if (!Capacitor.isNativePlatform()) {
|
||||
console.info('[FCM] Web dev — native push skipped');
|
||||
return false;
|
||||
}
|
||||
if (initialized) return true;
|
||||
|
||||
const perm = await PushNotifications.requestPermissions();
|
||||
if (perm.receive !== 'granted') return false;
|
||||
|
||||
await PushNotifications.addListener('registration', async token => {
|
||||
try {
|
||||
await registerFcmToken(token.value);
|
||||
console.info('[FCM] token registered');
|
||||
} catch (e) {
|
||||
console.warn('[FCM] token register failed', e);
|
||||
}
|
||||
});
|
||||
|
||||
await PushNotifications.addListener('registrationError', err => {
|
||||
console.warn('[FCM] registration error', err);
|
||||
});
|
||||
|
||||
await PushNotifications.addListener('pushNotificationReceived', notification => {
|
||||
const title = notification.title ?? 'GoldenChart';
|
||||
const body = notification.body ?? '';
|
||||
handlers.onForeground?.(title, body, notification.data as FcmPayload);
|
||||
});
|
||||
|
||||
await PushNotifications.addListener('pushNotificationActionPerformed', action => {
|
||||
handlers.onTap?.(action.notification.data as FcmPayload);
|
||||
});
|
||||
|
||||
await PushNotifications.register();
|
||||
initialized = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function unregisterFcmPush(): Promise<void> {
|
||||
if (!Capacitor.isNativePlatform()) return;
|
||||
try {
|
||||
await deleteFcmToken();
|
||||
} catch { /* ignore */ }
|
||||
initialized = false;
|
||||
}
|
||||
|
||||
export async function checkPushPermission(): Promise<'granted' | 'denied' | 'prompt'> {
|
||||
if (!Capacitor.isNativePlatform()) return 'prompt';
|
||||
const perm = await PushNotifications.checkPermissions();
|
||||
if (perm.receive === 'granted') return 'granted';
|
||||
if (perm.receive === 'denied') return 'denied';
|
||||
return 'prompt';
|
||||
}
|
||||
Reference in New Issue
Block a user