mirror of
https://github.com/urosran/cally.git
synced 2025-07-10 15:17:17 +00:00
Syncing logic improvements... Notification logic refactor (stop spamming notifications on sync)
This commit is contained in:
@ -94,7 +94,7 @@ const CalendarSettingsPage = (props: {
|
||||
newUserData: {googleToken: accessToken, googleMail: googleMail},
|
||||
});
|
||||
|
||||
await fetchAndSaveGoogleEvents(accessToken, googleMail)
|
||||
await fetchAndSaveGoogleEvents({token: accessToken, email: googleMail})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error during Google sign-in:", error);
|
||||
@ -207,12 +207,12 @@ const CalendarSettingsPage = (props: {
|
||||
if (appleToken) {
|
||||
console.log("Apple ID token received. Fetch user info if needed...");
|
||||
|
||||
// Example: Store user token and email
|
||||
await updateUserData({
|
||||
newUserData: {appleToken, appleMail},
|
||||
});
|
||||
|
||||
console.log("User data updated with Apple ID token.");
|
||||
await fetchAndSaveAppleEvents({token: appleToken, email: appleMail!});
|
||||
} else {
|
||||
console.warn("Apple authentication was not successful or email was hidden.");
|
||||
}
|
||||
@ -252,7 +252,7 @@ const CalendarSettingsPage = (props: {
|
||||
[]
|
||||
);
|
||||
|
||||
const handleChangeFirstDayOfWeek = () => {
|
||||
const handleChangeFirstDayOfWeek = (firstDayOfWeek: string) => {
|
||||
setFirstDayOfWeek(firstDayOfWeek === "Sundays" ? "Mondays" : "Sundays");
|
||||
debouncedUpdateFirstDayOfWeek(firstDayOfWeek === "Sundays" ? "Mondays" : "Sundays");
|
||||
}
|
||||
@ -436,12 +436,18 @@ const CalendarSettingsPage = (props: {
|
||||
<View style={{marginTop: 20}}>
|
||||
{!!profileData?.googleMail && (
|
||||
<TouchableOpacity
|
||||
onPress={() => fetchAndSaveGoogleEvents(undefined, undefined)}
|
||||
onPress={() => fetchAndSaveGoogleEvents({
|
||||
token: profileData?.googleToken!,
|
||||
email: profileData?.googleMail!
|
||||
})}
|
||||
>
|
||||
<View row paddingR-20 center>
|
||||
<Button
|
||||
disabled={isSyncingGoogle}
|
||||
onPress={() => fetchAndSaveGoogleEvents(undefined, undefined)}
|
||||
onPress={() => fetchAndSaveGoogleEvents({
|
||||
token: profileData?.googleToken!,
|
||||
email: profileData?.googleMail!
|
||||
})}
|
||||
label={`Sync ${profileData?.googleMail}`}
|
||||
labelStyle={styles.addCalLbl}
|
||||
labelProps={{numberOfLines: 3}}
|
||||
@ -466,11 +472,18 @@ const CalendarSettingsPage = (props: {
|
||||
|
||||
|
||||
{!!profileData?.appleMail && (
|
||||
<TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
onPress={() => fetchAndSaveAppleEvents({
|
||||
email: profileData?.appleMail!,
|
||||
token: profileData?.appleToken!
|
||||
})}>
|
||||
<View row paddingR-20 center>
|
||||
<Button
|
||||
disabled={isSyncingApple}
|
||||
onPress={() => fetchAndSaveAppleEvents(undefined, undefined)}
|
||||
onPress={() => fetchAndSaveAppleEvents({
|
||||
email: profileData?.appleMail!,
|
||||
token: profileData?.appleToken!
|
||||
})}
|
||||
label={`Sync ${profileData?.appleMail}`}
|
||||
labelStyle={styles.addCalLbl}
|
||||
labelProps={{numberOfLines: 3}}
|
||||
@ -494,12 +507,18 @@ const CalendarSettingsPage = (props: {
|
||||
|
||||
{!!profileData?.outlookMail && (
|
||||
<TouchableOpacity
|
||||
onPress={() => fetchAndSaveOutlookEvents(undefined, undefined)}
|
||||
onPress={() => fetchAndSaveOutlookEvents({
|
||||
token: profileData?.microsoftToken!,
|
||||
email: profileData?.outlookMail!
|
||||
})}
|
||||
>
|
||||
<View row paddingR-20 center>
|
||||
<Button
|
||||
disabled={isSyncingOutlook}
|
||||
onPress={() => fetchAndSaveOutlookEvents(undefined, undefined)}
|
||||
onPress={() => fetchAndSaveOutlookEvents({
|
||||
token: profileData?.microsoftToken!,
|
||||
email: profileData?.outlookMail!
|
||||
})}
|
||||
label={`Sync ${profileData?.outlookMail}`}
|
||||
labelStyle={styles.addCalLbl}
|
||||
labelProps={{numberOfLines: 3}}
|
||||
|
@ -10,6 +10,9 @@ admin.initializeApp();
|
||||
const db = admin.firestore();
|
||||
|
||||
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}')
|
||||
@ -22,12 +25,26 @@ exports.sendNotificationOnEventCreation = functions.firestore
|
||||
return;
|
||||
}
|
||||
|
||||
const pushTokens = await getPushTokensForFamilyExcludingCreator(familyId, creatorId);
|
||||
|
||||
if (!pushTokens.length) {
|
||||
pushTokens = await getPushTokensForFamilyExcludingCreator(familyId, creatorId);
|
||||
if (!pushTokens.length) {
|
||||
console.log('No push tokens available for the event.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
@ -39,14 +56,15 @@ exports.sendNotificationOnEventCreation = functions.firestore
|
||||
messages.push({
|
||||
to: pushToken,
|
||||
sound: 'default',
|
||||
title: 'New Event Added!',
|
||||
body: `An event "${eventData.title}" has been added. Check it out!`,
|
||||
title: 'New Events Added!',
|
||||
body: eventMessage,
|
||||
data: {eventId: context.params.eventId},
|
||||
});
|
||||
}
|
||||
|
||||
let chunks = expo.chunkPushNotifications(messages);
|
||||
let tickets = [];
|
||||
|
||||
for (let chunk of chunks) {
|
||||
try {
|
||||
let ticketChunk = await expo.sendPushNotificationsAsync(chunk);
|
||||
@ -57,53 +75,23 @@ exports.sendNotificationOnEventCreation = functions.firestore
|
||||
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}`);
|
||||
if (ticket.details && ticket.details.error === 'DeviceNotRegistered') {
|
||||
await removeInvalidPushToken(ticket.to);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} 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');
|
||||
|
||||
@ -290,3 +278,7 @@ async function getPushTokensForFamilyExcludingCreator(familyId, creatorId) {
|
||||
|
||||
return pushTokens;
|
||||
}
|
||||
|
||||
async function removeInvalidPushToken(pushToken) {
|
||||
// TODO
|
||||
}
|
@ -9,7 +9,8 @@ export const useFetchAndSaveAppleEvents = () => {
|
||||
|
||||
return useMutation({
|
||||
mutationKey: ["fetchAndSaveAppleEvents"],
|
||||
mutationFn: async (token?: string, email?: string) => {
|
||||
mutationFn: async ({token, email}: { token?: string, email?: string }) => {
|
||||
console.log("CALLL")
|
||||
const timeMin = new Date(new Date().setFullYear(new Date().getFullYear() - 1));
|
||||
const timeMax = new Date(new Date().setFullYear(new Date().getFullYear() + 5));
|
||||
try {
|
||||
|
@ -9,7 +9,7 @@ export const useFetchAndSaveGoogleEvents = () => {
|
||||
|
||||
return useMutation({
|
||||
mutationKey: ["fetchAndSaveGoogleEvents"],
|
||||
mutationFn: async (token?: string, email?: string) => {
|
||||
mutationFn: async ({token, email}: { token?: string; email?: string }) => {
|
||||
console.log("Fetching Google Calendar events...");
|
||||
const timeMin = new Date(new Date().setFullYear(new Date().getFullYear() - 1));
|
||||
const timeMax = new Date(new Date().setFullYear(new Date().getFullYear() + 5));
|
||||
|
@ -9,7 +9,7 @@ export const useFetchAndSaveOutlookEvents = () => {
|
||||
|
||||
return useMutation({
|
||||
mutationKey: ["fetchAndSaveOutlookEvents"],
|
||||
mutationFn: async (token?: string, email?: string) => {
|
||||
mutationFn: async ({token, email}: { token?: string; email?: string }) => {
|
||||
const timeMin = new Date(new Date().setFullYear(new Date().getFullYear() - 1));
|
||||
const timeMax = new Date(new Date().setFullYear(new Date().getFullYear() + 3));
|
||||
|
||||
|
Reference in New Issue
Block a user