rewrite finished i believe

This commit is contained in:
2024-10-16 16:50:26 -05:00
parent c2858198ca
commit 3eeffb789f
15 changed files with 1184 additions and 86 deletions

View 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,
},
});

View 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',
},
});

View 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,
},
});

View 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,
},
});