mirror of
https://github.com/urosran/cally.git
synced 2025-07-10 15:17:17 +00:00
Small fixes, calendar token refresh for google
This commit is contained in:
@ -2,8 +2,9 @@ import * as Calendar from 'expo-calendar';
|
|||||||
|
|
||||||
export async function fetchiPhoneCalendarEvents(familyId, email, startDate, endDate) {
|
export async function fetchiPhoneCalendarEvents(familyId, email, startDate, endDate) {
|
||||||
try {
|
try {
|
||||||
const {status} = await Calendar.requestCalendarPermissionsAsync();
|
const {granted} = await Calendar.requestCalendarPermissionsAsync();
|
||||||
if (status !== 'granted') {
|
|
||||||
|
if (!granted) {
|
||||||
throw new Error("Calendar permission not granted");
|
throw new Error("Calendar permission not granted");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -22,7 +23,11 @@ export async function fetchiPhoneCalendarEvents(familyId, email, startDate, endD
|
|||||||
return events.map((event) => {
|
return events.map((event) => {
|
||||||
let isAllDay = event.allDay || false;
|
let isAllDay = event.allDay || false;
|
||||||
const startDateTime = new Date(event.startDate);
|
const startDateTime = new Date(event.startDate);
|
||||||
const endDateTime = new Date(event.endDate);
|
let endDateTime = new Date(event.endDate);
|
||||||
|
|
||||||
|
if (isAllDay) {
|
||||||
|
endDateTime = startDateTime
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: event.id,
|
id: event.id,
|
||||||
|
@ -8,7 +8,9 @@ export async function fetchGoogleCalendarEvents(token, email, familyId, startDat
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
const googleEvents = [];
|
const googleEvents = [];
|
||||||
data.items?.forEach((item) => {
|
data.items?.forEach((item) => {
|
||||||
let isAllDay = false;
|
let isAllDay = false;
|
||||||
@ -49,5 +51,5 @@ export async function fetchGoogleCalendarEvents(token, email, familyId, startDat
|
|||||||
googleEvents.push(googleEvent);
|
googleEvents.push(googleEvent);
|
||||||
});
|
});
|
||||||
|
|
||||||
return googleEvents;
|
return {googleEvents, success: response.ok};
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,12 @@
|
|||||||
import {StyleSheet} from "react-native";
|
import {Dimensions, StyleSheet} from "react-native";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
import {Button, View,} from "react-native-ui-lib";
|
import {Button, View,} from "react-native-ui-lib";
|
||||||
import {useGroceryContext} from "@/contexts/GroceryContext";
|
import {useGroceryContext} from "@/contexts/GroceryContext";
|
||||||
import {FontAwesome6} from "@expo/vector-icons";
|
import {FontAwesome6} from "@expo/vector-icons";
|
||||||
import PlusIcon from "@/assets/svgs/PlusIcon";
|
import PlusIcon from "@/assets/svgs/PlusIcon";
|
||||||
|
|
||||||
|
const { width } = Dimensions.get("screen");
|
||||||
|
|
||||||
const AddGroceryItem = () => {
|
const AddGroceryItem = () => {
|
||||||
const {setIsAddingGrocery} = useGroceryContext();
|
const {setIsAddingGrocery} = useGroceryContext();
|
||||||
|
|
||||||
@ -65,8 +67,14 @@ const styles = StyleSheet.create({
|
|||||||
marginVertical: 10,
|
marginVertical: 10,
|
||||||
},
|
},
|
||||||
btnContainer: {
|
btnContainer: {
|
||||||
width: "100%",
|
position:"absolute",
|
||||||
|
bottom: 30,
|
||||||
|
width: width,
|
||||||
|
padding: 20,
|
||||||
|
paddingBottom: 0,
|
||||||
justifyContent: "center",
|
justifyContent: "center",
|
||||||
|
alignItems:"center",
|
||||||
|
zIndex: 10,
|
||||||
},
|
},
|
||||||
finishShopBtn: {
|
finishShopBtn: {
|
||||||
width: "100%",
|
width: "100%",
|
||||||
|
@ -1,218 +1,214 @@
|
|||||||
import {
|
import {Button, ButtonSize, Dialog, Text, TextField, TextFieldRef, View,} from "react-native-ui-lib";
|
||||||
Button,
|
import React, {useRef, useState} from "react";
|
||||||
ButtonSize,
|
import {useSignIn} from "@/hooks/firebase/useSignIn";
|
||||||
Dialog,
|
import {StyleSheet} from "react-native";
|
||||||
Text,
|
|
||||||
TextField,
|
|
||||||
TextFieldRef,
|
|
||||||
View,
|
|
||||||
} from "react-native-ui-lib";
|
|
||||||
import React, { useRef, useState } from "react";
|
|
||||||
import { useSignIn } from "@/hooks/firebase/useSignIn";
|
|
||||||
import { StyleSheet } from "react-native";
|
|
||||||
import Toast from "react-native-toast-message";
|
import Toast from "react-native-toast-message";
|
||||||
import { useLoginWithQrCode } from "@/hooks/firebase/useLoginWithQrCode";
|
import {useLoginWithQrCode} from "@/hooks/firebase/useLoginWithQrCode";
|
||||||
import { Camera, CameraView } from "expo-camera";
|
import {Camera, CameraView} from "expo-camera";
|
||||||
|
|
||||||
const SignInPage = ({
|
const SignInPage = ({
|
||||||
setTab,
|
setTab,
|
||||||
}: {
|
}: {
|
||||||
setTab: React.Dispatch<
|
setTab: React.Dispatch<
|
||||||
React.SetStateAction<"register" | "login" | "reset-password">
|
React.SetStateAction<"register" | "login" | "reset-password">
|
||||||
>;
|
>;
|
||||||
}) => {
|
}) => {
|
||||||
const [email, setEmail] = useState<string>("");
|
const [email, setEmail] = useState<string>("");
|
||||||
const [password, setPassword] = useState<string>("");
|
const [password, setPassword] = useState<string>("");
|
||||||
const [hasPermission, setHasPermission] = useState<boolean | null>(null);
|
const [hasPermission, setHasPermission] = useState<boolean | null>(null);
|
||||||
const [showCameraDialog, setShowCameraDialog] = useState<boolean>(false);
|
const [showCameraDialog, setShowCameraDialog] = useState<boolean>(false);
|
||||||
const passwordRef = useRef<TextFieldRef>(null);
|
const passwordRef = useRef<TextFieldRef>(null);
|
||||||
|
|
||||||
const { mutateAsync: signIn, error, isError } = useSignIn();
|
const {mutateAsync: signIn, error, isError} = useSignIn();
|
||||||
const { mutateAsync: signInWithQrCode } = useLoginWithQrCode();
|
const {mutateAsync: signInWithQrCode} = useLoginWithQrCode();
|
||||||
|
|
||||||
const handleSignIn = async () => {
|
const handleSignIn = async () => {
|
||||||
await signIn({ email, password });
|
await signIn({email, password});
|
||||||
if (!isError) {
|
if (!isError) {
|
||||||
Toast.show({
|
Toast.show({
|
||||||
type: "success",
|
type: "success",
|
||||||
text1: "Login successful!",
|
text1: "Login successful!",
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
Toast.show({
|
Toast.show({
|
||||||
type: "error",
|
type: "error",
|
||||||
text1: "Error logging in",
|
text1: "Error logging in",
|
||||||
text2: `${error}`,
|
text2: `${error}`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleQrCodeScanned = async ({ data }: { data: string }) => {
|
const handleQrCodeScanned = async ({data}: { data: string }) => {
|
||||||
setShowCameraDialog(false);
|
setShowCameraDialog(false);
|
||||||
try {
|
try {
|
||||||
await signInWithQrCode({ userId: data });
|
await signInWithQrCode({userId: data});
|
||||||
Toast.show({
|
Toast.show({
|
||||||
type: "success",
|
type: "success",
|
||||||
text1: "Login successful with QR code!",
|
text1: "Login successful with QR code!",
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
Toast.show({
|
Toast.show({
|
||||||
type: "error",
|
type: "error",
|
||||||
text1: "Error logging in with QR code",
|
text1: "Error logging in with QR code",
|
||||||
text2: `${err}`,
|
text2: `${err}`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getCameraPermissions = async (callback: () => void) => {
|
const getCameraPermissions = async (callback: () => void) => {
|
||||||
const { status } = await Camera.requestCameraPermissionsAsync();
|
const {status} = await Camera.requestCameraPermissionsAsync();
|
||||||
setHasPermission(status === "granted");
|
setHasPermission(status === "granted");
|
||||||
if (status === "granted") {
|
if (status === "granted") {
|
||||||
callback();
|
callback();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View padding-10 centerV height={"100%"}>
|
<View padding-10 centerV height={"100%"}>
|
||||||
<TextField
|
<TextField
|
||||||
placeholder="Email"
|
placeholder="Email"
|
||||||
value={email}
|
keyboardType={"email-address"}
|
||||||
|
returnKeyType={"next"}
|
||||||
onChangeText={setEmail}
|
textContentType={"emailAddress"}
|
||||||
style={styles.textfield}
|
defaultValue={email}
|
||||||
onSubmitEditing={() => {
|
onChangeText={setEmail}
|
||||||
// Move focus to the description field
|
style={styles.textfield}
|
||||||
passwordRef.current?.focus();
|
onSubmitEditing={() => {
|
||||||
}}
|
// Move focus to the description field
|
||||||
/>
|
passwordRef.current?.focus();
|
||||||
<TextField
|
}}
|
||||||
ref={passwordRef}
|
/>
|
||||||
placeholder="Password"
|
<TextField
|
||||||
value={password}
|
ref={passwordRef}
|
||||||
onChangeText={setPassword}
|
placeholder="Password"
|
||||||
secureTextEntry
|
textContentType={"oneTimeCode"}
|
||||||
style={styles.textfield}
|
value={password}
|
||||||
/>
|
onChangeText={setPassword}
|
||||||
<Button
|
secureTextEntry
|
||||||
label="Log in"
|
style={styles.textfield}
|
||||||
marginT-50
|
autoCorrect={false}
|
||||||
labelStyle={{
|
/>
|
||||||
fontFamily: "PlusJakartaSans_600SemiBold",
|
<Button
|
||||||
fontSize: 16,
|
label="Log in"
|
||||||
}}
|
marginT-50
|
||||||
onPress={handleSignIn}
|
labelStyle={{
|
||||||
style={{ marginBottom: 20, height: 50 }}
|
fontFamily: "PlusJakartaSans_600SemiBold",
|
||||||
backgroundColor="#fd1775"
|
fontSize: 16,
|
||||||
/>
|
}}
|
||||||
<Button
|
onPress={handleSignIn}
|
||||||
label="Log in with a QR Code"
|
style={{marginBottom: 20, height: 50}}
|
||||||
labelStyle={{
|
backgroundColor="#fd1775"
|
||||||
fontFamily: "PlusJakartaSans_600SemiBold",
|
/>
|
||||||
fontSize: 16,
|
<Button
|
||||||
}}
|
label="Log in with a QR Code"
|
||||||
onPress={() => {
|
labelStyle={{
|
||||||
getCameraPermissions(() => setShowCameraDialog(true));
|
fontFamily: "PlusJakartaSans_600SemiBold",
|
||||||
}}
|
fontSize: 16,
|
||||||
style={{ marginBottom: 20, height: 50 }}
|
}}
|
||||||
backgroundColor="#fd1775"
|
onPress={() => {
|
||||||
/>
|
getCameraPermissions(() => setShowCameraDialog(true));
|
||||||
{isError && (
|
}}
|
||||||
<Text center style={{ marginBottom: 20 }}>{`${
|
style={{marginBottom: 20, height: 50}}
|
||||||
error?.toString()?.split("]")?.[1]
|
backgroundColor="#fd1775"
|
||||||
}`}</Text>
|
/>
|
||||||
)}
|
{isError && (
|
||||||
|
<Text center style={{marginBottom: 20}}>{`${
|
||||||
|
error?.toString()?.split("]")?.[1]
|
||||||
|
}`}</Text>
|
||||||
|
)}
|
||||||
|
|
||||||
<View row centerH marginB-5 gap-5>
|
<View row centerH marginB-5 gap-5>
|
||||||
<Text style={styles.jakartaLight}>Don't have an account?</Text>
|
<Text style={styles.jakartaLight}>Don't have an account?</Text>
|
||||||
<Button
|
<Button
|
||||||
onPress={() => setTab("register")}
|
onPress={() => setTab("register")}
|
||||||
label="Sign Up"
|
label="Sign Up"
|
||||||
labelStyle={[
|
labelStyle={[
|
||||||
styles.jakartaMedium,
|
styles.jakartaMedium,
|
||||||
{ textDecorationLine: "none", color: "#fd1575" },
|
{textDecorationLine: "none", color: "#fd1575"},
|
||||||
]}
|
]}
|
||||||
link
|
link
|
||||||
size={ButtonSize.xSmall}
|
size={ButtonSize.xSmall}
|
||||||
padding-0
|
padding-0
|
||||||
margin-0
|
margin-0
|
||||||
text70
|
text70
|
||||||
left
|
left
|
||||||
color="#fd1775"
|
color="#fd1775"
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View row centerH marginB-5 gap-5>
|
<View row centerH marginB-5 gap-5>
|
||||||
<Text text70>Forgot your password?</Text>
|
<Text text70>Forgot your password?</Text>
|
||||||
<Button
|
<Button
|
||||||
onPress={() => setTab("reset-password")}
|
onPress={() => setTab("reset-password")}
|
||||||
label="Reset password"
|
label="Reset password"
|
||||||
labelStyle={[
|
labelStyle={[
|
||||||
styles.jakartaMedium,
|
styles.jakartaMedium,
|
||||||
{ textDecorationLine: "none", color: "#fd1575" },
|
{textDecorationLine: "none", color: "#fd1575"},
|
||||||
]}
|
]}
|
||||||
link
|
link
|
||||||
size={ButtonSize.xSmall}
|
size={ButtonSize.xSmall}
|
||||||
padding-0
|
padding-0
|
||||||
margin-0
|
margin-0
|
||||||
text70
|
text70
|
||||||
left
|
left
|
||||||
avoidInnerPadding
|
avoidInnerPadding
|
||||||
color="#fd1775"
|
color="#fd1775"
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
{/* Camera Dialog */}
|
{/* Camera Dialog */}
|
||||||
<Dialog
|
<Dialog
|
||||||
visible={showCameraDialog}
|
visible={showCameraDialog}
|
||||||
onDismiss={() => setShowCameraDialog(false)}
|
onDismiss={() => setShowCameraDialog(false)}
|
||||||
bottom
|
bottom
|
||||||
width="100%"
|
width="100%"
|
||||||
height="70%"
|
height="70%"
|
||||||
containerStyle={{ padding: 15, backgroundColor:"white" }}
|
containerStyle={{padding: 15, backgroundColor: "white"}}
|
||||||
>
|
>
|
||||||
{hasPermission === null ? (
|
{hasPermission === null ? (
|
||||||
<Text>Requesting camera permissions...</Text>
|
<Text>Requesting camera permissions...</Text>
|
||||||
) : !hasPermission ? (
|
) : !hasPermission ? (
|
||||||
<Text>No access to camera</Text>
|
<Text>No access to camera</Text>
|
||||||
) : (
|
) : (
|
||||||
<CameraView
|
<CameraView
|
||||||
style={{ flex: 1, borderRadius: 15 }}
|
style={{flex: 1, borderRadius: 15}}
|
||||||
onBarcodeScanned={handleQrCodeScanned}
|
onBarcodeScanned={handleQrCodeScanned}
|
||||||
barcodeScannerSettings={{
|
barcodeScannerSettings={{
|
||||||
barcodeTypes: ["qr"],
|
barcodeTypes: ["qr"],
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
<Button
|
<Button
|
||||||
label="Cancel"
|
label="Cancel"
|
||||||
onPress={() => setShowCameraDialog(false)}
|
onPress={() => setShowCameraDialog(false)}
|
||||||
backgroundColor="#fd1775"
|
backgroundColor="#fd1775"
|
||||||
style={{ margin: 10, marginBottom: 30 }}
|
style={{margin: 10, marginBottom: 30}}
|
||||||
/>
|
/>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const styles = StyleSheet.create({
|
const styles = StyleSheet.create({
|
||||||
textfield: {
|
textfield: {
|
||||||
backgroundColor: "white",
|
backgroundColor: "white",
|
||||||
marginVertical: 10,
|
marginVertical: 10,
|
||||||
padding: 30,
|
padding: 30,
|
||||||
height: 45,
|
height: 45,
|
||||||
borderRadius: 50,
|
borderRadius: 50,
|
||||||
fontFamily: "PlusJakartaSans_300Light",
|
fontFamily: "PlusJakartaSans_300Light",
|
||||||
},
|
},
|
||||||
jakartaLight: {
|
jakartaLight: {
|
||||||
fontFamily: "PlusJakartaSans_300Light",
|
fontFamily: "PlusJakartaSans_300Light",
|
||||||
fontSize: 16,
|
fontSize: 16,
|
||||||
color: "#484848",
|
color: "#484848",
|
||||||
},
|
},
|
||||||
jakartaMedium: {
|
jakartaMedium: {
|
||||||
fontFamily: "PlusJakartaSans_500Medium",
|
fontFamily: "PlusJakartaSans_500Medium",
|
||||||
fontSize: 16,
|
fontSize: 16,
|
||||||
color: "#919191",
|
color: "#919191",
|
||||||
textDecorationLine: "underline",
|
textDecorationLine: "underline",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export default SignInPage;
|
export default SignInPage;
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -181,7 +181,7 @@ exports.generateCustomToken = onRequest(async (request, response) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
exports.refreshTokens = functions.pubsub.schedule('every 12 hours').onRun(async (context) => {
|
exports.refreshTokens = functions.pubsub.schedule('every 1 hours').onRun(async (context) => {
|
||||||
console.log('Running token refresh job...');
|
console.log('Running token refresh job...');
|
||||||
|
|
||||||
const profilesSnapshot = await db.collection('Profiles').get();
|
const profilesSnapshot = await db.collection('Profiles').get();
|
||||||
@ -192,7 +192,7 @@ exports.refreshTokens = functions.pubsub.schedule('every 12 hours').onRun(async
|
|||||||
if (profileData.googleAccounts) {
|
if (profileData.googleAccounts) {
|
||||||
try {
|
try {
|
||||||
for (const googleEmail of Object.keys(profileData?.googleAccounts)) {
|
for (const googleEmail of Object.keys(profileData?.googleAccounts)) {
|
||||||
const googleToken = profileData?.googleAccounts?.[googleEmail];
|
const googleToken = profileData?.googleAccounts?.[googleEmail]?.refreshToken;
|
||||||
if (googleToken) {
|
if (googleToken) {
|
||||||
const refreshedGoogleToken = await refreshGoogleToken(googleToken);
|
const refreshedGoogleToken = await refreshGoogleToken(googleToken);
|
||||||
const updatedGoogleAccounts = {...profileData.googleAccounts, [googleEmail]: refreshedGoogleToken};
|
const updatedGoogleAccounts = {...profileData.googleAccounts, [googleEmail]: refreshedGoogleToken};
|
||||||
@ -239,29 +239,35 @@ exports.refreshTokens = functions.pubsub.schedule('every 12 hours').onRun(async
|
|||||||
return null;
|
return null;
|
||||||
});
|
});
|
||||||
|
|
||||||
// Function to refresh Google token
|
async function refreshGoogleToken(refreshToken) {
|
||||||
async function refreshGoogleToken(token) {
|
try {
|
||||||
// Assuming you use OAuth2 token refresh flow
|
const response = await axios.post('https://oauth2.googleapis.com/token', {
|
||||||
const response = await axios.post('https://oauth2.googleapis.com/token', {
|
grant_type: 'refresh_token',
|
||||||
grant_type: 'refresh_token',
|
refresh_token: refreshToken,
|
||||||
refresh_token: token, // Add refresh token stored previously
|
client_id: "406146460310-2u67ab2nbhu23trp8auho1fq4om29fc0.apps.googleusercontent.com", // Web client ID from googleConfig
|
||||||
client_id: 'YOUR_GOOGLE_CLIENT_ID',
|
});
|
||||||
client_secret: 'YOUR_GOOGLE_CLIENT_SECRET',
|
|
||||||
});
|
|
||||||
|
|
||||||
return response.data.access_token; // Return new access token
|
return response.data.access_token; // Return the new access token
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error refreshing Google token:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function refreshMicrosoftToken(token) {
|
async function refreshMicrosoftToken(refreshToken) {
|
||||||
const response = await axios.post('https://login.microsoftonline.com/common/oauth2/v2.0/token', {
|
try {
|
||||||
grant_type: 'refresh_token',
|
const response = await axios.post('https://login.microsoftonline.com/common/oauth2/v2.0/token', {
|
||||||
refresh_token: token, // Add refresh token stored previously
|
grant_type: 'refresh_token',
|
||||||
client_id: 'YOUR_MICROSOFT_CLIENT_ID',
|
refresh_token: refreshToken,
|
||||||
client_secret: 'YOUR_MICROSOFT_CLIENT_SECRET',
|
client_id: "13c79071-1066-40a9-9f71-b8c4b138b4af", // Client ID from microsoftConfig
|
||||||
scope: 'https://graph.microsoft.com/Calendars.ReadWrite offline_access',
|
scope: "openid profile email offline_access Calendars.ReadWrite User.Read", // Scope from microsoftConfig
|
||||||
});
|
});
|
||||||
|
|
||||||
return response.data.access_token; // Return new access token
|
return response.data.access_token; // Return the new access token
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error refreshing Microsoft token:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getPushTokensForEvent() {
|
async function getPushTokensForEvent() {
|
||||||
|
39
hooks/firebase/useClearTokens.ts
Normal file
39
hooks/firebase/useClearTokens.ts
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
import {useMutation} from "react-query";
|
||||||
|
import {UserProfile} from "@firebase/auth";
|
||||||
|
import {useAuthContext} from "@/contexts/AuthContext";
|
||||||
|
import {useUpdateUserData} from "@/hooks/firebase/useUpdateUserData";
|
||||||
|
|
||||||
|
export const useClearTokens = () => {
|
||||||
|
const {profileData} = useAuthContext();
|
||||||
|
const {mutateAsync: updateUserData} = useUpdateUserData();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationKey: ["clearTokens"],
|
||||||
|
mutationFn: async ({provider, email}: {
|
||||||
|
provider: "google" | "outlook" | "apple",
|
||||||
|
email: string
|
||||||
|
}) => {
|
||||||
|
const newUserData: Partial<UserProfile> = {};
|
||||||
|
if (provider === "google") {
|
||||||
|
let googleAccounts = profileData?.googleAccounts;
|
||||||
|
if (googleAccounts) {
|
||||||
|
googleAccounts[email] = null;
|
||||||
|
newUserData.googleAccounts = googleAccounts;
|
||||||
|
}
|
||||||
|
} else if (provider === "outlook") {
|
||||||
|
let microsoftAccounts = profileData?.microsoftAccounts;
|
||||||
|
if (microsoftAccounts) {
|
||||||
|
microsoftAccounts[email] = null;
|
||||||
|
newUserData.microsoftAccounts = microsoftAccounts;
|
||||||
|
}
|
||||||
|
} else if (provider === "apple") {
|
||||||
|
let appleAccounts = profileData?.appleAccounts;
|
||||||
|
if (appleAccounts) {
|
||||||
|
appleAccounts[email] = null;
|
||||||
|
newUserData.appleAccounts = appleAccounts;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await updateUserData({newUserData});
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
@ -45,34 +45,41 @@ export const useCreateEvent = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const useCreateEventsFromProvider = () => {
|
export const useCreateEventsFromProvider = () => {
|
||||||
const {user: currentUser} = useAuthContext();
|
const { user: currentUser } = useAuthContext();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationKey: ["createEventsFromProvider"],
|
mutationKey: ["createEventsFromProvider"],
|
||||||
mutationFn: async (eventDataArray: Partial<EventData>[]) => {
|
mutationFn: async (eventDataArray: Partial<EventData>[]) => {
|
||||||
try {
|
try {
|
||||||
for (const eventData of eventDataArray) {
|
// Create an array of promises for each event's Firestore read/write operation
|
||||||
|
const promises = eventDataArray.map(async (eventData) => {
|
||||||
console.log("Processing EventData: ", eventData);
|
console.log("Processing EventData: ", eventData);
|
||||||
|
|
||||||
|
// Check if the event already exists
|
||||||
const snapshot = await firestore()
|
const snapshot = await firestore()
|
||||||
.collection("Events")
|
.collection("Events")
|
||||||
.where("id", "==", eventData.id)
|
.where("id", "==", eventData.id)
|
||||||
.get();
|
.get();
|
||||||
|
|
||||||
if (snapshot.empty) {
|
if (snapshot.empty) {
|
||||||
await firestore()
|
// Event doesn't exist, so add it
|
||||||
|
return firestore()
|
||||||
.collection("Events")
|
.collection("Events")
|
||||||
.add({...eventData, creatorId: currentUser?.uid});
|
.add({ ...eventData, creatorId: currentUser?.uid });
|
||||||
} else {
|
} else {
|
||||||
console.log("Event already exists, updating...");
|
// Event exists, update it
|
||||||
const docId = snapshot.docs[0].id;
|
const docId = snapshot.docs[0].id;
|
||||||
await firestore()
|
return firestore()
|
||||||
.collection("Events")
|
.collection("Events")
|
||||||
.doc(docId)
|
.doc(docId)
|
||||||
.set({...eventData, creatorId: currentUser?.uid}, {merge: true});
|
.set({ ...eventData, creatorId: currentUser?.uid }, { merge: true });
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
|
|
||||||
|
// Execute all promises in parallel
|
||||||
|
await Promise.all(promises);
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Error creating/updating events: ", e);
|
console.error("Error creating/updating events: ", e);
|
||||||
}
|
}
|
||||||
|
@ -2,11 +2,13 @@ import {useMutation, useQueryClient} from "react-query";
|
|||||||
import {fetchGoogleCalendarEvents} from "@/calendar-integration/google-calendar-utils";
|
import {fetchGoogleCalendarEvents} from "@/calendar-integration/google-calendar-utils";
|
||||||
import {useAuthContext} from "@/contexts/AuthContext";
|
import {useAuthContext} from "@/contexts/AuthContext";
|
||||||
import {useCreateEventsFromProvider} from "@/hooks/firebase/useCreateEvent";
|
import {useCreateEventsFromProvider} from "@/hooks/firebase/useCreateEvent";
|
||||||
|
import {useClearTokens} from "@/hooks/firebase/useClearTokens";
|
||||||
|
|
||||||
export const useFetchAndSaveGoogleEvents = () => {
|
export const useFetchAndSaveGoogleEvents = () => {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const {profileData} = useAuthContext();
|
const {profileData} = useAuthContext();
|
||||||
const {mutateAsync: createEventsFromProvider} = useCreateEventsFromProvider();
|
const {mutateAsync: createEventsFromProvider} = useCreateEventsFromProvider();
|
||||||
|
const {mutateAsync: clearToken} = useClearTokens();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationKey: ["fetchAndSaveGoogleEvents"],
|
mutationKey: ["fetchAndSaveGoogleEvents"],
|
||||||
@ -26,9 +28,14 @@ export const useFetchAndSaveGoogleEvents = () => {
|
|||||||
timeMax.toISOString().slice(0, -5) + "Z"
|
timeMax.toISOString().slice(0, -5) + "Z"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if(!response.success) {
|
||||||
|
await clearToken({email: email!, provider: "google"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
console.log("Google Calendar events fetched:", response);
|
console.log("Google Calendar events fetched:", response);
|
||||||
|
|
||||||
const items = response?.map((item) => {
|
const items = response?.googleEvents?.map((item) => {
|
||||||
if (item.allDay) {
|
if (item.allDay) {
|
||||||
item.startDate = new Date(new Date(item.startDate).setHours(0, 0, 0, 0));
|
item.startDate = new Date(new Date(item.startDate).setHours(0, 0, 0, 0));
|
||||||
item.endDate = item.startDate;
|
item.endDate = item.startDate;
|
||||||
|
Reference in New Issue
Block a user