Syncing logic improvements... Notification logic refactor (stop spamming notifications on sync)

This commit is contained in:
Milan Paunovic
2024-10-20 13:16:54 +02:00
parent da071736d0
commit 055c40d1e6
5 changed files with 100 additions and 88 deletions

View File

@ -9,101 +9,89 @@ const {Expo} = require('expo-server-sdk');
admin.initializeApp();
const db = admin.firestore();
let expo = new Expo({accessToken: process.env.EXPO_ACCESS_TOKEN});
let expo = new Expo({ accessToken: process.env.EXPO_ACCESS_TOKEN });
let notificationTimeout = null;
let eventCount = 0;
let pushTokens = [];
exports.sendNotificationOnEventCreation = functions.firestore
.document('Events/{eventId}')
.onCreate(async (snapshot, context) => {
const eventData = snapshot.data();
const { familyId, creatorId } = eventData;
const {familyId, creatorId} = eventData;
if (!familyId || !creatorId) {
console.error('Missing familyId or creatorId in event data');
return;
}
const pushTokens = await getPushTokensForFamilyExcludingCreator(familyId, creatorId);
if (!pushTokens.length) {
console.log('No push tokens available for the event.');
return;
pushTokens = await getPushTokensForFamilyExcludingCreator(familyId, creatorId);
if (!pushTokens.length) {
console.log('No push tokens available for the event.');
return;
}
}
let messages = [];
for (let pushToken of pushTokens) {
if (!Expo.isExpoPushToken(pushToken)) {
console.error(`Push token ${pushToken} is not a valid Expo push token`);
continue;
// Increment event count for debouncing
eventCount++;
if (notificationTimeout) {
clearTimeout(notificationTimeout); // Reset the timer if events keep coming
}
// Set a debounce time (e.g., 5 seconds)
notificationTimeout = setTimeout(async () => {
const eventMessage = eventCount === 1
? `An event "${eventData.title}" has been added. Check it out!`
: `${eventCount} new events have been added.`;
let messages = [];
for (let pushToken of pushTokens) {
if (!Expo.isExpoPushToken(pushToken)) {
console.error(`Push token ${pushToken} is not a valid Expo push token`);
continue;
}
messages.push({
to: pushToken,
sound: 'default',
title: 'New Events Added!',
body: eventMessage,
data: {eventId: context.params.eventId},
});
}
messages.push({
to: pushToken,
sound: 'default',
title: 'New Event Added!',
body: `An event "${eventData.title}" has been added. Check it out!`,
data: { eventId: context.params.eventId },
});
}
let chunks = expo.chunkPushNotifications(messages);
let tickets = [];
let chunks = expo.chunkPushNotifications(messages);
let tickets = [];
for (let chunk of chunks) {
try {
let ticketChunk = await expo.sendPushNotificationsAsync(chunk);
tickets.push(...ticketChunk);
for (let chunk of chunks) {
try {
let ticketChunk = await expo.sendPushNotificationsAsync(chunk);
tickets.push(...ticketChunk);
for (let ticket of ticketChunk) {
if (ticket.status === 'ok') {
console.log('Notification successfully sent:', ticket.id);
} else if (ticket.status === 'error') {
console.error(`Notification error: ${ticket.message}`);
if (ticket.details && ticket.details.error) {
console.error('Error details:', ticket.details.error);
if (ticket.details.error === 'DeviceNotRegistered') {
console.log(`Removing invalid push token: ${ticket.to}`);
for (let ticket of ticketChunk) {
if (ticket.status === 'ok') {
console.log('Notification successfully sent:', ticket.id);
} else if (ticket.status === 'error') {
console.error(`Notification error: ${ticket.message}`);
if (ticket.details && ticket.details.error === 'DeviceNotRegistered') {
await removeInvalidPushToken(ticket.to);
}
}
}
} catch (error) {
console.error('Error sending notification:', error);
}
} catch (error) {
console.error('Error sending notification:', error);
}
}
// Retrieve and handle notification receipts
let receiptIds = [];
for (let ticket of tickets) {
if (ticket.id) {
receiptIds.push(ticket.id);
}
}
eventCount = 0; // Reset the event count after sending notification
pushTokens = []; // Reset push tokens for the next round
let receiptIdChunks = expo.chunkPushNotificationReceiptIds(receiptIds);
for (let chunk of receiptIdChunks) {
try {
let receipts = await expo.getPushNotificationReceiptsAsync(chunk);
console.log('Receipts:', receipts);
for (let receiptId in receipts) {
let { status, message, details } = receipts[receiptId];
if (status === 'ok') {
console.log(`Notification with receipt ID ${receiptId} was delivered successfully`);
} else if (status === 'error') {
console.error(`Notification error: ${message}`);
if (details && details.error) {
console.error(`Error details: ${details.error}`);
}
}
}
} catch (error) {
console.error('Error retrieving receipts:', error);
}
}
return null;
}, 5000); // Debounce time (5 seconds)
});
exports.createSubUser = onRequest(async (request, response) => {
const authHeader = request.get('Authorization');
@ -203,7 +191,7 @@ exports.refreshTokens = functions.pubsub.schedule('every 12 hours').onRun(async
if (profileData.googleToken) {
try {
const refreshedGoogleToken = await refreshGoogleToken(profileData.googleToken);
await profileDoc.ref.update({ googleToken: refreshedGoogleToken });
await profileDoc.ref.update({googleToken: refreshedGoogleToken});
console.log(`Google token updated for user ${profileDoc.id}`);
} catch (error) {
console.error(`Error refreshing Google token for user ${profileDoc.id}:`, error.message);
@ -213,7 +201,7 @@ exports.refreshTokens = functions.pubsub.schedule('every 12 hours').onRun(async
if (profileData.microsoftToken) {
try {
const refreshedMicrosoftToken = await refreshMicrosoftToken(profileData.microsoftToken);
await profileDoc.ref.update({ microsoftToken: refreshedMicrosoftToken });
await profileDoc.ref.update({microsoftToken: refreshedMicrosoftToken});
console.log(`Microsoft token updated for user ${profileDoc.id}`);
} catch (error) {
console.error(`Error refreshing Microsoft token for user ${profileDoc.id}:`, error.message);
@ -223,7 +211,7 @@ exports.refreshTokens = functions.pubsub.schedule('every 12 hours').onRun(async
if (profileData.appleToken) {
try {
const refreshedAppleToken = await refreshAppleToken(profileData.appleToken);
await profileDoc.ref.update({ appleToken: refreshedAppleToken });
await profileDoc.ref.update({appleToken: refreshedAppleToken});
console.log(`Apple token updated for user ${profileDoc.id}`);
} catch (error) {
console.error(`Error refreshing Apple token for user ${profileDoc.id}:`, error.message);
@ -289,4 +277,8 @@ async function getPushTokensForFamilyExcludingCreator(familyId, creatorId) {
});
return pushTokens;
}
async function removeInvalidPushToken(pushToken) {
// TODO
}