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}}
|
||||
|
@ -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);
|
||||
@ -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));
|
||||
|
@ -1,15 +1,15 @@
|
||||
import { useMutation } from "react-query";
|
||||
import { useAuthContext } from "@/contexts/AuthContext";
|
||||
import { useCreateEventsFromProvider } from "@/hooks/firebase/useCreateEvent";
|
||||
import { fetchMicrosoftCalendarEvents } from "@/calendar-integration/microsoft-calendar-utils";
|
||||
import {useMutation} from "react-query";
|
||||
import {useAuthContext} from "@/contexts/AuthContext";
|
||||
import {useCreateEventsFromProvider} from "@/hooks/firebase/useCreateEvent";
|
||||
import {fetchMicrosoftCalendarEvents} from "@/calendar-integration/microsoft-calendar-utils";
|
||||
|
||||
export const useFetchAndSaveOutlookEvents = () => {
|
||||
const { profileData } = useAuthContext();
|
||||
const { mutateAsync: createEventsFromProvider } = useCreateEventsFromProvider();
|
||||
const {profileData} = useAuthContext();
|
||||
const {mutateAsync: createEventsFromProvider} = useCreateEventsFromProvider();
|
||||
|
||||
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