import { onRequest } from "firebase-functions/v2/https"; import { initializeApp } from "firebase-admin/app"; import { getMessaging } from "firebase-admin/messaging"; import { v4 as uuidv4 } from "uuid"; initializeApp(); const messaging = getMessaging(); const FCM_TOKENS = { phone: "PASTE IPHONE FCM TOKEN HERE", watch: "PASTE APPLE WATCH FCM TOKEN HERE", }; export const sendNotificationToPhoneAndWatch = onRequest(async (request, response) => { await sendToMultipleDevices( [FCM_TOKENS.phone, FCM_TOKENS.watch], "Phone&Watch", response ); }); export const sendNotificationToPhoneAfterWatch = onRequest(async (request, response) => { await sendSequentialNotifications( FCM_TOKENS.watch, "Watch", FCM_TOKENS.phone, "Phone", response ); }); export const sendNotificationToWatchAfterPhone = onRequest(async (request, response) => { await sendSequentialNotifications( FCM_TOKENS.phone, "Phone", FCM_TOKENS.watch, "Watch", response ); }); async function sendToMultipleDevices(tokens, deviceType, response) { const collapseID = uuidv4(); const message = { tokens, apns: createApnsObject(deviceType, collapseID), }; try { const messagingResponse = await messaging.sendEachForMulticast(message); const successCount = messagingResponse.successCount; const failureCount = messagingResponse.failureCount; const failureMessages = messagingResponse.responses .filter(response => !response.success) .map(response => response.error.message); response.send({ message: "SUCCESS!", successCount, failureCount, failureMessages, collapseID, }); } catch (error) { response.status(500).send({ error: "Failed to send notification", details: error.message }); } } async function sendSequentialNotifications(firstToken, firstDeviceType, secondToken, secondDeviceType, response) { const collapseID = uuidv4(); try { await messaging.send({ token: firstToken, apns: createApnsObject(firstDeviceType, collapseID), }); await new Promise(resolve => setTimeout(resolve, 100)); // Wait for 0.1 second await messaging.send({ token: secondToken, apns: createApnsObject(secondDeviceType, collapseID), }); response.send({ message: "SUCCESS!", collapseID }); } catch (error) { response.status(500).send({ error: "Failed to send sequential notifications", details: error.message }); } } function createApnsObject(deviceType, collapseID) { return { payload: { aps: { sound: "default", alert: { title: `HEY for ${deviceType}`, body: collapseID, }, }, }, headers: { "apns-push-type": "alert", "apns-collapse-id": collapseID, }, }; }