rewrite finished i believe
This commit is contained in:
@ -1,14 +1,19 @@
|
||||
import React from "react";
|
||||
import * as AppleAuthentication from "expo-apple-authentication";
|
||||
import { StyleSheet, Alert } from "react-native";
|
||||
import { ThemedView } from "@/components/theme/Theme";
|
||||
import { useColorScheme } from "@/hooks/useColorScheme";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import Constants from "expo-constants";
|
||||
import { saveUser, saveInitialData } from "@/components/services/SecureStore";
|
||||
import type { InitialData, User } from "@/constants/Types";
|
||||
import React from 'react';
|
||||
import * as AppleAuthentication from 'expo-apple-authentication';
|
||||
import { StyleSheet, Alert } from 'react-native';
|
||||
import { ThemedView } from '@/components/theme/Theme';
|
||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||
import * as Notifications from 'expo-notifications';
|
||||
import Constants from 'expo-constants';
|
||||
import { saveUser, saveInitialData } from '@/components/services/SecureStore';
|
||||
import {
|
||||
getInitialDataByAppleId,
|
||||
createUser,
|
||||
updatePushToken
|
||||
} from '@/constants/APIs';
|
||||
import type { InitialData, User } from '@/constants/Types';
|
||||
|
||||
const SignInScreen({onSignIn}: {onSignIn: () => void}) => {
|
||||
const SignInScreen = ({onSignIn}: {onSignIn: () => void}) => {
|
||||
const scheme = useColorScheme() ?? 'dark';
|
||||
|
||||
const handleAppleSignIn = async () => {
|
||||
@ -30,17 +35,10 @@ const SignInScreen({onSignIn}: {onSignIn: () => void}) => {
|
||||
credential.fullName?.familyName, pushToken
|
||||
);
|
||||
|
||||
const initialData = await
|
||||
fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/users/getUserByAppleId` +
|
||||
`?appleId=${credential.user}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': process.env.NEXT_PUBLIC_API_KEY ?? '',
|
||||
},
|
||||
});
|
||||
console.log(initialData);
|
||||
if (initialData.status === 404 || !initialData.ok) {
|
||||
const initialDataResponse = await getInitialDataByAppleId(credential.user);
|
||||
|
||||
console.log(initialDataResponse);
|
||||
if (initialDataResponse.status === 404 || !initialDataResponse.ok) {
|
||||
if (!credential.user || !credential.email ||
|
||||
!credential.fullName?.givenName || !credential.fullName?.familyName ||
|
||||
!pushToken || credential.email.length === 0) {
|
||||
@ -55,62 +53,30 @@ const SignInScreen({onSignIn}: {onSignIn: () => void}) => {
|
||||
'save in the database.'
|
||||
);
|
||||
}
|
||||
|
||||
const userResponse = await
|
||||
fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/users/createUser`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': process.env.NEXT_PUBLIC_API_KEY ?? '',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
appleId: credential.user,
|
||||
email: credential.email,
|
||||
fullName:
|
||||
`${credential.fullName?.givenName} ${credential.fullName?.familyName}`,
|
||||
pushToken: pushToken,
|
||||
}),
|
||||
});
|
||||
if (!userResponse.ok) {
|
||||
const errorBody = await userResponse.text();
|
||||
console.error(
|
||||
'API error: No user returned: ',
|
||||
userResponse.status, errorBody
|
||||
);
|
||||
throw new Error(`Failed to create user: ${userResponse.status} ${errorBody}`);
|
||||
}
|
||||
const user: User = await userResponse.json() as User;
|
||||
const user: User = await createUser(
|
||||
credential.user,
|
||||
credential.email,
|
||||
credential.fullName?.givenName + credential.fullName?.familyName,
|
||||
pushToken.data
|
||||
) as User;
|
||||
await saveUser(user);
|
||||
} else if (initialData.ok) {
|
||||
const allData: InitialData = await initialData.json() as InitialData;
|
||||
} else if (initialDataResponse.ok) {
|
||||
const initialData: InitialData = await initialDataResponse.json() as InitialData;
|
||||
console.log('Existing user found! Saving data...');
|
||||
|
||||
if (allData.user.pushToken !== pushToken.data) {
|
||||
const updatePushTokenResponse =
|
||||
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/users/updatePushToken`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': process.env.NEXT_PUBLIC_API_KEY ?? '',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userId: allData.user.id,
|
||||
pushToken: pushToken.data,
|
||||
}),
|
||||
});
|
||||
if (!updatePushTokenResponse.ok) {
|
||||
throw new Error(
|
||||
`Failed to update push token: ${updatePushTokenResponse.status}`
|
||||
);
|
||||
}
|
||||
if (initialData.user.pushToken !== pushToken.data) {
|
||||
const updatePushTokenResponse = await updatePushToken(
|
||||
initialData.user.id,
|
||||
pushToken.data
|
||||
);
|
||||
} else {
|
||||
console.log('Push token is up to date.');
|
||||
}
|
||||
allData.user.pushToken = pushToken.data;
|
||||
await saveInitialData(allData);
|
||||
initialData.user.pushToken = pushToken.data;
|
||||
await saveInitialData(initialData);
|
||||
}
|
||||
onSignIn();
|
||||
} catch (error) {
|
||||
} catch (error: unknown) {
|
||||
console.error('Error signing in:', error);
|
||||
if (error.code === 'ERR_REQUEST_CANCELLED') {
|
||||
Alert.alert('Sign in error', 'Sign in was cancelled.');
|
||||
|
299
components/home/Relationship.tsx
Normal file
299
components/home/Relationship.tsx
Normal file
@ -0,0 +1,299 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Image, StyleSheet, AppState } from 'react-native';
|
||||
import { ThemedText, ThemedView } from '@/components/theme/Theme';
|
||||
import { getUser, getRelationship, getPartner, saveRelationshipData } from '@/components/services/SecureStore';
|
||||
import RequestRelationship from '@/components/home/RequestRelationship';
|
||||
import TextButton from '@/components/theme/buttons/TextButton';
|
||||
import { checkRelationshipStatus, updateRelationshipStatus } from '@/constants/APIs';
|
||||
import type { User, Relationship, RelationshipData } from '@/constants/Types';
|
||||
|
||||
const CHECK_TIME = 2; // In minutes
|
||||
|
||||
type RelationshipProps = {
|
||||
pfpUrl: string | null;
|
||||
};
|
||||
|
||||
const Relationship: React.FC<RelationshipProps> = ({ pfpUrl }) => {
|
||||
const [status, setStatus] = useState<RelationshipData | null>(null);
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [showRequestRelationship, setShowRequestRelationship] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
fetchRelationshipStatus();
|
||||
setUpPeriodicCheck();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (pfpUrl && user) {
|
||||
setUser(prevUser =>
|
||||
prevUser ? {...prevUser, pfpUrl: pfpUrl} : null);
|
||||
}
|
||||
}, [pfpUrl]);
|
||||
|
||||
const handleRequestSent = (relationshipData: RelationshipData) => {
|
||||
setStatus(relationshipData);
|
||||
setShowRequestRelationship(false);
|
||||
};
|
||||
|
||||
const setUpPeriodicCheck = () => {
|
||||
let intervalId: NodeJS.Timeout | null = null;
|
||||
const startChecking = () => {
|
||||
handleCheckRelationshipStatus();
|
||||
intervalId = setInterval(handleCheckRelationshipStatus, 60000*CHECK_TIME);
|
||||
};
|
||||
const stopChecking = () => {
|
||||
if (intervalId) {
|
||||
clearInterval(intervalId);
|
||||
intervalId = null;
|
||||
}
|
||||
};
|
||||
const handleAppStateChange = (nextAppState: string) => {
|
||||
if (nextAppState === 'active') startChecking();
|
||||
else stopChecking();
|
||||
};
|
||||
const subscription = AppState.addEventListener('change', handleAppStateChange);
|
||||
if (AppState.currentState === 'active') startChecking();
|
||||
return () => {
|
||||
stopChecking();
|
||||
subscription.remove();
|
||||
};
|
||||
};
|
||||
|
||||
const fetchRelationshipStatus = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const userFromStore: User = await getUser() as User;
|
||||
if (!userFromStore) throw new Error('User not found in store.');
|
||||
setUser(userFromStore);
|
||||
const relationshipFromStore: Relationship = await getRelationship() as Relationship;
|
||||
const partnerFromStore: User = await getPartner() as User;
|
||||
if (!relationshipFromStore || !partnerFromStore)
|
||||
throw new Error('Relationship not found in store.');
|
||||
setStatus({
|
||||
relationship: relationshipFromStore,
|
||||
partner: partnerFromStore,
|
||||
});
|
||||
await handleCheckRelationshipStatus();
|
||||
} catch (error) {
|
||||
console.log('Error fetching relationship status:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCheckRelationshipStatus = async () => {
|
||||
try {
|
||||
const userFromStore: User = await getUser() as User;
|
||||
if (!userFromStore) throw new Error('User not found in store.');
|
||||
const relationshipData: RelationshipData = await checkRelationshipStatus(userFromStore.id);
|
||||
setStatus(relationshipData);
|
||||
await saveRelationshipData(relationshipData);
|
||||
} catch (error) {
|
||||
console.log('No relationship found or error checking relationship status:', error);
|
||||
setStatus(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateRelationshipStatus = async (newStatus: 'accepted' | 'rejected') => {
|
||||
if (!status || !status.relationship || !user || !user.id) {
|
||||
console.error('No relationship found.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (newStatus === 'accepted') {
|
||||
const updatedRelationshipData: RelationshipData =
|
||||
await updateRelationshipStatus(user.id, newStatus);
|
||||
setStatus(updatedRelationshipData);
|
||||
await saveRelationshipData(updatedRelationshipData);
|
||||
} else {
|
||||
await updateRelationshipStatus(user.id, newStatus);
|
||||
console.log('Rejected relationship. Relationship deleted.');
|
||||
setStatus(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating relationship status:', error);
|
||||
}
|
||||
};
|
||||
const handleAcceptRequest = () => handleUpdateRelationshipStatus('accepted');
|
||||
const handleRejectRequest = () => handleUpdateRelationshipStatus('rejected');
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<ThemedText>
|
||||
Loading...
|
||||
</ThemedText>
|
||||
);
|
||||
}
|
||||
|
||||
const renderRelationshipContent = () => {
|
||||
if (!status || !status.relationship) {
|
||||
// Case 1: Not in a relationship
|
||||
return showRequestRelationship ? (
|
||||
<RequestRelationship onRequestSent={handleRequestSent} />
|
||||
) : (
|
||||
<TextButton
|
||||
width={220} height={60} text='Request Relationship' fontSize={18}
|
||||
onPress={() => setShowRequestRelationship(true)}
|
||||
/>
|
||||
);
|
||||
} else if (!status.relationship.isAccepted && user?.id === status.relationship.requestorId) {
|
||||
// Case 2: Pending relationship & our user requested it
|
||||
return (
|
||||
<>
|
||||
<ThemedText style={styles.title}>
|
||||
Pending Relationship
|
||||
</ThemedText>
|
||||
<ThemedView style={styles.profileContainer}>
|
||||
<ThemedView style={styles.profileWrapper}>
|
||||
<Image
|
||||
source={{
|
||||
uri: `${process.env.EXPO_PUBLIC_URL}` +
|
||||
`${status.partner.pfpUrl}`
|
||||
}}
|
||||
style={styles.profilePicture}
|
||||
/>
|
||||
<ThemedText style={styles.name}>
|
||||
{status.partner.fullName}
|
||||
</ThemedText>
|
||||
</ThemedView>
|
||||
</ThemedView>
|
||||
<ThemedView style={styles.buttonContainer}>
|
||||
<TextButton
|
||||
width={100} height={40}
|
||||
text='Accept' fontSize={18}
|
||||
onPress={handleAcceptRequest}
|
||||
/>
|
||||
<TextButton
|
||||
width={100} height={40}
|
||||
text='Reject' fontSize={18}
|
||||
onPress={handleRejectRequest}
|
||||
/>
|
||||
</ThemedView>
|
||||
</>
|
||||
);
|
||||
} else if (!status.relationship.isAccepted && user?.id !== status.relationship.requestorId) {
|
||||
// Case 3: Pending relationship & someone else requested it
|
||||
return (
|
||||
<>
|
||||
<ThemedText style={styles.title}>
|
||||
Pending Relationship
|
||||
</ThemedText>
|
||||
<ThemedView style={styles.profileContainer}>
|
||||
<ThemedView style={styles.profileWrapper}>
|
||||
<Image
|
||||
source={{
|
||||
uri: `${process.env.EXPO_PUBLIC_URL}` +
|
||||
`${status.partner.pfpUrl}`
|
||||
}}
|
||||
style={styles.profilePicture}
|
||||
/>
|
||||
<ThemedText style={styles.name}>
|
||||
{status.partner.fullName}
|
||||
</ThemedText>
|
||||
</ThemedView>
|
||||
</ThemedView>
|
||||
<ThemedView style={styles.buttonContainer}>
|
||||
<TextButton
|
||||
width={100} height={40}
|
||||
text='Accept' fontSize={18}
|
||||
onPress={handleAcceptRequest}
|
||||
/>
|
||||
<TextButton
|
||||
width={100} height={40}
|
||||
text='Reject' fontSize={18}
|
||||
onPress={handleRejectRequest}
|
||||
/>
|
||||
</ThemedView>
|
||||
</>
|
||||
);
|
||||
|
||||
} else if (status.relationship.isAccepted) {
|
||||
// Case 4: In an accepted relationship
|
||||
return (
|
||||
<>
|
||||
<ThemedText style={styles.title}>
|
||||
{status.relationship.title}
|
||||
</ThemedText>
|
||||
<ThemedView style={styles.profileContainer}>
|
||||
{user && (
|
||||
<ThemedView style={styles.profileWrapper}>
|
||||
<Image
|
||||
source={{ uri: `${process.env.EXPO_PUBLIC_URL}${user.pfpUrl}` }}
|
||||
style={styles.profilePicture}
|
||||
/>
|
||||
<ThemedText style={styles.name}>
|
||||
{user.fullName.split(' ')[0]}
|
||||
</ThemedText>
|
||||
</ThemedView>
|
||||
)}
|
||||
{status.partner && (
|
||||
<ThemedView style={styles.profileWrapper}>
|
||||
<Image
|
||||
source={{ uri: `${process.env.EXPO_PUBLIC_URL}` +
|
||||
`${status.partner.pfpUrl}` }}
|
||||
style={styles.profilePicture}
|
||||
/>
|
||||
<ThemedText style={styles.name}>
|
||||
{status.partner.fullName.split(' ')[0]}
|
||||
</ThemedText>
|
||||
</ThemedView>
|
||||
)}
|
||||
</ThemedView>
|
||||
</>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemedView style={styles.container}>
|
||||
{renderRelationshipContent()}
|
||||
</ThemedView>
|
||||
);
|
||||
};
|
||||
export default Relationship;
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
title: {
|
||||
fontSize: 24,
|
||||
fontWeight: 'bold',
|
||||
marginBottom: 20,
|
||||
},
|
||||
profileContainer: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
marginTop: 20,
|
||||
},
|
||||
profileWrapper: {
|
||||
alignItems: 'center',
|
||||
marginHorizontal: 10,
|
||||
},
|
||||
profilePicture: {
|
||||
width: 100,
|
||||
height: 100,
|
||||
borderRadius: 50,
|
||||
marginBottom: 10,
|
||||
},
|
||||
name: {
|
||||
fontSize: 12,
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
lastChecked: {
|
||||
fontSize: 12,
|
||||
marginBottom: 10,
|
||||
},
|
||||
buttonContainer: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-around',
|
||||
width: '100%',
|
||||
marginTop: 20,
|
||||
},
|
||||
});
|
112
components/home/RequestRelationship.tsx
Normal file
112
components/home/RequestRelationship.tsx
Normal file
@ -0,0 +1,112 @@
|
||||
import React, { useState, useCallback, useEffect } from 'react';
|
||||
import {
|
||||
TextInput,
|
||||
FlatList,
|
||||
TouchableOpacity,
|
||||
StyleSheet,
|
||||
ActivityIndicator
|
||||
} from 'react-native';
|
||||
import { ThemedText, ThemedView } from '@/components/theme/Theme';
|
||||
import { getUser } from '@/components/services/SecureStore';
|
||||
import { Colors } from '@/constants/Colors';
|
||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||
import debounce from 'lodash.debounce';
|
||||
import { searchUsers, sendRelationshipRequest } from '@/constants/APIs';
|
||||
import type { User, RelationshipData } from '@/constants/Types';
|
||||
|
||||
const RequestRelationship:
|
||||
React.FC<{ onRequestSent: (data: RelationshipData) => void }> = ({ onRequestSent }) => {
|
||||
const scheme = useColorScheme() ?? 'dark';
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [searchResults, setSearchResults] = useState<User[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [currentUserId, setCurrentUserId] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchCurrentUser = async () => {
|
||||
const user = await getUser();
|
||||
if (user) {
|
||||
setCurrentUserId(user.id);
|
||||
}
|
||||
};
|
||||
fetchCurrentUser();
|
||||
}, []);
|
||||
|
||||
const handleSearchUsers = useCallback(debounce(async (term: string) => {
|
||||
if (term.length < 3) {
|
||||
setSearchResults([]);
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
const users: User[] = await searchUsers(encodeURIComponent(term)) as User[];
|
||||
setSearchResults(users);
|
||||
}, 300), []);
|
||||
|
||||
const handleSearch = async (text: string) => {
|
||||
setSearchTerm(text);
|
||||
handleSearchUsers(text);
|
||||
};
|
||||
|
||||
const handleSendRequest = async (targetUserId: number) => {
|
||||
if (!currentUserId) return;
|
||||
try {
|
||||
const relationshipData: RelationshipData =
|
||||
await sendRelationshipRequest(currentUserId, targetUserId) as RelationshipData;
|
||||
onRequestSent(relationshipData);
|
||||
} catch (error) {
|
||||
console.error('Error sending relationship request:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const renderUserItem = ({ item }: { item: User }) => (
|
||||
<TouchableOpacity style={styles.userItem} onPress={() => handleSendRequest(item.id)}>
|
||||
<ThemedText>{item.fullName}</ThemedText>
|
||||
<ThemedText>{item.email}</ThemedText>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
|
||||
return (
|
||||
<ThemedView style={styles.container}>
|
||||
<TextInput
|
||||
style={[
|
||||
styles.searchInput,
|
||||
{color: Colors[scheme].text}
|
||||
]}
|
||||
placeholder="Search users..."
|
||||
value={searchTerm}
|
||||
onChangeText={handleSearch}
|
||||
/>
|
||||
{isLoading ? (
|
||||
<ActivityIndicator />
|
||||
) : (
|
||||
<FlatList
|
||||
data={searchResults}
|
||||
renderItem={renderUserItem}
|
||||
keyExtractor={(item) => item.id.toString()}
|
||||
ListEmptyComponent={<ThemedText>No users found</ThemedText>}
|
||||
/>
|
||||
)}
|
||||
</ThemedView>
|
||||
);
|
||||
};
|
||||
export default RequestRelationship;
|
||||
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
padding: 20,
|
||||
},
|
||||
searchInput: {
|
||||
height: 40,
|
||||
borderColor: 'gray',
|
||||
borderWidth: 1,
|
||||
marginBottom: 20,
|
||||
paddingHorizontal: 10,
|
||||
},
|
||||
userItem: {
|
||||
padding: 10,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: 'gray',
|
||||
},
|
||||
});
|
74
components/home/TestPush.tsx
Normal file
74
components/home/TestPush.tsx
Normal file
@ -0,0 +1,74 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { StyleSheet, Alert } from 'react-native';
|
||||
import { ThemedText } from '@/components/theme/Theme';
|
||||
import { Colors } from '@/constants/Colors';
|
||||
import { useColorScheme } from '@/hooks/useColorScheme';
|
||||
import FontAwesome from '@expo/vector-icons/FontAwesome';
|
||||
import Button from '@/components/theme/buttons/DefaultButton';
|
||||
import { getUser } from '@/components/services/SecureStore';
|
||||
import { sendPushNotification } from '@/components/services/notifications/PushNotificationManager';
|
||||
import type { NotificationMessage } from '@/constants/Types';
|
||||
|
||||
const TestPush = () => {
|
||||
const scheme = useColorScheme() ?? 'dark';
|
||||
const [pushToken, setPushToken] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUserData = async () => {
|
||||
const user = await getUser();
|
||||
if (user) {
|
||||
setPushToken(user.pushToken);
|
||||
}
|
||||
};
|
||||
fetchUserData();
|
||||
}, []);
|
||||
|
||||
const message: NotificationMessage = {
|
||||
sound: 'default',
|
||||
title: 'Test push notification',
|
||||
body: 'This is a test push notification',
|
||||
data: {
|
||||
test: 'test',
|
||||
},
|
||||
};
|
||||
|
||||
const handleSendPushNotification = async () => {
|
||||
try {
|
||||
await sendPushNotification(pushToken, message);
|
||||
Alert.alert('Success', 'Push notification sent successfully.');
|
||||
} catch (error) {
|
||||
Alert.alert('Error', 'Failed to send push notification.');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
width={220} height={60}
|
||||
onPress={handleSendPushNotification}
|
||||
>
|
||||
<FontAwesome
|
||||
name='bell' size={18}
|
||||
color={Colors[scheme].background}
|
||||
style={styles.buttonIcon}
|
||||
/>
|
||||
<ThemedText
|
||||
style={[
|
||||
styles.buttonLabel,
|
||||
{color: Colors[scheme].background}
|
||||
]}
|
||||
>
|
||||
Send Push Notification
|
||||
</ThemedText>
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
export default TestPush;
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
buttonLabel: {
|
||||
fontSize: 16,
|
||||
},
|
||||
buttonIcon: {
|
||||
paddingRight: 8,
|
||||
},
|
||||
});
|
118
components/home/UserInfo.tsx
Normal file
118
components/home/UserInfo.tsx
Normal file
@ -0,0 +1,118 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { StyleSheet, Alert, Image, TouchableOpacity } from 'react-native';
|
||||
import { ThemedText, ThemedView } from '@/components/theme/Theme';
|
||||
import { getUser, updateUser } from '@/components/services/SecureStore';
|
||||
import { manipulateAsync, SaveFormat } from 'expo-image-manipulator';
|
||||
import * as ImagePicker from 'expo-image-picker';
|
||||
import { updateProfilePicture } from '@/constants/APIs';
|
||||
import type { User } from '@/constants/Types';
|
||||
|
||||
type UserInfoProps = {
|
||||
onPfpUpdate: (url: string) => void;
|
||||
};
|
||||
|
||||
const UserInfo: React.FC<UserInfoProps> = ({ onPfpUpdate }) => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUserData = async () => {
|
||||
try {
|
||||
const user: User = await getUser() as User;
|
||||
setUser(user);
|
||||
if (user.pfpUrl)
|
||||
onPfpUpdate(user.pfpUrl);
|
||||
} catch (error) {
|
||||
console.error('Error fetching user data:', error);
|
||||
Alert.alert('Error', 'Failed to fetch user data.');
|
||||
}
|
||||
};
|
||||
fetchUserData();
|
||||
}, [onPfpUpdate]);
|
||||
|
||||
const handleUpdateProfilePicture = async () => {
|
||||
const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
|
||||
if (permissionResult.granted === false) {
|
||||
Alert.alert(
|
||||
'Permission Required',
|
||||
'You need to grant permission to access your photo library.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
const result = await ImagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ImagePicker.MediaTypeOptions.Images,
|
||||
allowsEditing: true,
|
||||
aspect: [4, 3],
|
||||
quality: 1,
|
||||
});
|
||||
if (!result.canceled && result.assets[0].uri) {
|
||||
try {
|
||||
const manipulateResult = await manipulateAsync(
|
||||
result.assets[0].uri,
|
||||
[{resize: {width: 300, height: 300}}],
|
||||
{compress: 0.7, format: SaveFormat.JPEG}
|
||||
);
|
||||
const user = await getUser() as User;
|
||||
const updatedUser = await updateProfilePicture(user.id, manipulateResult.uri);
|
||||
if (!updatedUser || !updatedUser.pfpUrl) throw new Error('Failed to update user profile picture.');
|
||||
setUser(prevData => prevData ? {...prevData, pfpUrl: updatedUser.pfpUrl} as User : updatedUser as User);
|
||||
await updateUser({pfpUrl: updatedUser.pfpUrl});
|
||||
onPfpUpdate(updatedUser.pfpUrl);
|
||||
} catch (error) {
|
||||
console.error('Error updating profile picture:', error);
|
||||
Alert.alert('Error', 'Failed to update profile picture.');
|
||||
}
|
||||
} else {
|
||||
Alert.alert('Error', 'Failed to select an image.');
|
||||
}
|
||||
};
|
||||
return (
|
||||
<ThemedView style={styles.container}>
|
||||
{user ? (
|
||||
<ThemedView style={styles.profileContainer}>
|
||||
<TouchableOpacity onPress={handleUpdateProfilePicture}>
|
||||
<Image
|
||||
source={user.pfpUrl ? {
|
||||
uri: `${process.env.EXPO_PUBLIC_URL}${user.pfpUrl}`} :
|
||||
require('@/assets/images/default-profile.png')}
|
||||
style={styles.profilePicture}
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
<ThemedText style={styles.name}>{user.fullName}</ThemedText>
|
||||
<ThemedText style={styles.email}>{user.email}</ThemedText>
|
||||
</ThemedView>
|
||||
) : (
|
||||
<ThemedText>Loading user data...</ThemedText>
|
||||
)}
|
||||
</ThemedView>
|
||||
);
|
||||
};
|
||||
export default UserInfo;
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
alignItems: 'center',
|
||||
},
|
||||
profileContainer: {
|
||||
alignItems: 'center',
|
||||
marginTop: 20,
|
||||
marginBottom: 20,
|
||||
},
|
||||
profilePicture: {
|
||||
width: 100,
|
||||
height: 100,
|
||||
borderRadius: 50,
|
||||
marginBottom: 10,
|
||||
},
|
||||
name: {
|
||||
fontSize: 24,
|
||||
fontWeight: 'bold',
|
||||
marginBottom: 5,
|
||||
},
|
||||
email: {
|
||||
fontSize: 16,
|
||||
marginBottom: 20,
|
||||
},
|
||||
});
|
||||
|
||||
|
@ -23,6 +23,18 @@ export const getUser = async () => {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
export const updateUser = async (updatedFields: Partial<any>) => {
|
||||
try {
|
||||
const currentUser: User = await getUser() as User;
|
||||
if (!currentUser) return null;
|
||||
const updatedUser: User = { ...currentUser, ...updatedFields };
|
||||
await saveUser(updatedUser);
|
||||
return updatedUser as User;
|
||||
} catch (error) {
|
||||
console.error('Error updating user data: ', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
export const savePartner = async (partner: User) => {
|
||||
try {
|
||||
await SecureStore.setItemAsync('partner', JSON.stringify(partner));
|
||||
@ -39,6 +51,18 @@ export const getPartner = async () => {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
export const updatePartner = async (updatedFields: Partial<any>) => {
|
||||
try {
|
||||
const currentPartner: User = await getPartner() as User;
|
||||
if (!currentPartner) return null;
|
||||
const updatedPartner: User = { ...currentPartner, ...updatedFields };
|
||||
await saveUser(updatedPartner);
|
||||
return updatedPartner as User;
|
||||
} catch (error) {
|
||||
console.error('Error updating user data: ', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
export const saveRelationship = async (relationship: Relationship) => {
|
||||
try {
|
||||
await SecureStore.setItemAsync('relationship', JSON.stringify(relationship));
|
||||
@ -55,6 +79,18 @@ export const getRelationship = async () => {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
export const updateRelationship = async (updatedFields: Partial<any>) => {
|
||||
try {
|
||||
const currentRelationship: Relationship = await getRelationship() as Relationship;
|
||||
if (!currentRelationship) return null;
|
||||
const updatedRelationship: Relationship = { ...currentRelationship, ...updatedFields };
|
||||
await saveRelationship(updatedRelationship);
|
||||
return updatedRelationship as Relationship;
|
||||
} catch (error) {
|
||||
console.error('Error updating relationship data: ', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
export const saveCountdown = async (countdown: Countdown) => {
|
||||
try {
|
||||
await SecureStore.setItemAsync('countdown', JSON.stringify(countdown));
|
||||
@ -71,6 +107,18 @@ export const getCountdown = async () => {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
export const updateCountdown = async (updatedFields: Partial<any>) => {
|
||||
try {
|
||||
const currentCountdown: Countdown = await getCountdown() as Countdown;
|
||||
if (!currentCountdown) return null;
|
||||
const updatedCountdown: Countdown = { ...currentCountdown, ...updatedFields };
|
||||
await saveCountdown(updatedCountdown);
|
||||
return updatedCountdown as Countdown;
|
||||
} catch (error) {
|
||||
console.error('Error updating countdown data: ', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
export const saveRelationshipData = async (relationshipData: RelationshipData) => {
|
||||
try {
|
||||
await SecureStore.setItemAsync('partner', JSON.stringify(relationshipData.Partner));
|
||||
|
@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Platform } from 'react-native';
|
||||
import { Alert, Platform } from 'react-native';
|
||||
import * as Device from 'expo-device';
|
||||
import * as Notifications from 'expo-notifications';
|
||||
import Constants from 'expo-constants';
|
||||
@ -13,7 +13,11 @@ Notifications.setNotificationHandler({
|
||||
}),
|
||||
});
|
||||
|
||||
export const sendPushNotification = async(expoPushToken: string, notification: NotificationMessage) => {
|
||||
export const sendPushNotification = async(expoPushToken: string | null, notification: NotificationMessage) => {
|
||||
if (!expoPushToken) {
|
||||
Alert.alert('Error', 'No push token found.');
|
||||
return;
|
||||
}
|
||||
const message = {
|
||||
to: expoPushToken,
|
||||
sound: notification.sound ?? 'default',
|
||||
@ -21,15 +25,22 @@ export const sendPushNotification = async(expoPushToken: string, notification: N
|
||||
body: notification.body,
|
||||
data: notification.data ?? {},
|
||||
};
|
||||
await fetch('https://exp.host/--/api/v2/push/send', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Accept-encoding': 'gzip, deflate',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(message),
|
||||
try {
|
||||
const response = await fetch('https://exp.host/--/api/v2/push/send', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Accept-encoding': 'gzip, deflate',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(message),
|
||||
});
|
||||
const result = await response.json();
|
||||
console.log('Push notification sent:', result);
|
||||
} catch (error) {
|
||||
console.error('Error sending push notification:', error);
|
||||
Alert.alert('Error', 'Failed to send push notification.');
|
||||
}
|
||||
};
|
||||
|
||||
const handleRegistrationError = (errorMessage: string) => {
|
||||
|
Reference in New Issue
Block a user