wavelength_app/app/(tabs)/messages.tsx

392 lines
12 KiB
TypeScript
Raw Normal View History

2024-10-25 16:57:25 -05:00
import React, { useCallback, useEffect, useReducer, useState } from 'react';
import { io } from 'socket.io-client';
import { ThemedText, ThemedView } from '@/components/theme/Theme';
2024-10-25 16:57:25 -05:00
import { Alert, Linking, Platform, StyleSheet } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
import {
GiftedChat,
IMessage,
Send,
SendProps,
SystemMessage,
} from 'react-native-gifted-chat';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import CustomActions from '@/components/chat/CustomActions';
import CustomView from '@/components/chat/CustomView';
import * as Clipboard from 'expo-clipboard';
import {
GCUser,
GCState,
GCStateAction,
ActionKind,
2024-10-21 16:58:41 -05:00
User,
Message,
2024-10-22 16:38:06 -05:00
NotificationMessage,
} from '@/constants/Types';
2024-10-22 16:38:06 -05:00
import {getMessages, sendMessage} from '@/constants/APIs';
2024-10-21 16:58:41 -05:00
import { getUser, getPartner } from '@/components/services/SecureStore';
2024-10-22 16:38:06 -05:00
import { sendPushNotification } from '@/components/services/notifications/PushNotificationManager';
// Reducer function for managing state
const reducer = (state: GCState, action: GCStateAction) => {
switch (action.type) {
case ActionKind.SEND_MESSAGE: {
return {
...state,
messages: action.payload
};
}
case ActionKind.LOAD_EARLIER_MESSAGES: {
return {
...state,
loadEarlier: true,
isLoadingEarlier: false,
messages: action.payload
};
}
case ActionKind.LOAD_EARLIER_START: {
2024-10-22 16:38:06 -05:00
return { ...state, isLoadingEarlier: true }
}
case ActionKind.SET_IS_TYPING: {
2024-10-22 16:38:06 -05:00
return { ...state, isTyping: action.payload }
}
2024-10-22 16:38:06 -05:00
default: return state;
}
};
const MessagesScreen = () => {
2024-10-21 16:58:41 -05:00
const [user, setUser] = useState<User | null>(null);
const [partner, setPartner] = useState<User | null>(null);
const [state, dispatch] = useReducer(reducer, {
2024-10-21 16:58:41 -05:00
messages: [],
loadEarlier: true,
isLoadingEarlier: false,
isTyping: false,
2024-10-21 16:58:41 -05:00
});
// Get user and partner data from SecureStore
2024-10-21 16:58:41 -05:00
const msgUser: GCUser = {
2024-10-22 16:38:06 -05:00
_id: user?.id ?? 0,
2024-10-21 16:58:41 -05:00
name: user?.fullName ?? 'You',
2024-10-22 16:38:06 -05:00
avatar: `${process.env.EXPO_PUBLIC_API_URL}${user?.pfpUrl}` ??
`${process.env.EXPO_PUBLIC_API_URL}/images/default-profile.png`,
2024-10-21 16:58:41 -05:00
};
const msgPartner: GCUser = {
2024-10-22 16:38:06 -05:00
_id: partner?.id ?? 0,
2024-10-21 16:58:41 -05:00
name: partner?.fullName ?? 'Your Partner',
2024-10-22 16:38:06 -05:00
avatar: `${process.env.EXPO_PUBLIC_API_URL}${partner?.pfpUrl}` ??
`${process.env.EXPO_PUBLIC_API_URL}/images/default-profile.png`,
2024-10-21 16:58:41 -05:00
};
// Initialize users & (trying to) fetch & display initial messages
2024-10-21 16:58:41 -05:00
useEffect(() => {
2024-10-22 16:38:06 -05:00
const initialize = async () => {
try{
const userData: User = await getUser() as User;
const partnerData: User = await getPartner() as User;
if (userData && partnerData) {
setUser(userData);
setPartner(partnerData);
} else
throw new Error('User or partner not found');
} catch (error) {
console.error('Error initializing users:', error);
Alert.alert('Error', 'Failed to initialize users. Please try again.');
2024-10-21 16:58:41 -05:00
}
};
2024-10-22 16:38:06 -05:00
initialize();
2024-10-21 16:58:41 -05:00
}, []);
useEffect(() => {
2024-10-25 16:57:25 -05:00
if (!user || !partner) {
console.log('User or partner not found');
return;
}
const socket = io(process.env.EXPO_PUBLIC_WEBSOCKET_URL as string, {
transports: ['websocket'],
});
socket.on('connect', () => {
2024-10-25 16:57:25 -05:00
console.log('Connected to WebSocket server');
socket.emit('join', { userId: user.id });
});
socket.on('connect_error', (error) => {
console.error('Error connecting to WebSocket server:', error);
});
socket.on('new_message', async (newMessage) => {
2024-10-25 16:57:25 -05:00
const initialMessages = await getMessages(user.id, 20, 0);
if (!initialMessages) return;
const formattedMessages = formatMessages(initialMessages);
dispatch({
type: ActionKind.SEND_MESSAGE,
2024-10-25 16:57:25 -05:00
payload: formattedMessages,
});
});
return () => {
socket.disconnect();
};
}, [user, partner]);
useEffect(() => {
const fetchMessages = async () => {
if (user && partner) {
dispatch({ type: ActionKind.LOAD_EARLIER_START });
2024-10-25 16:57:25 -05:00
const initialMessages = await getMessages(user.id);
if (initialMessages) {
const formattedMessages = formatMessages(initialMessages);
dispatch({ type: ActionKind.LOAD_EARLIER_MESSAGES, payload: formattedMessages });
}
2024-10-21 16:58:41 -05:00
}
};
fetchMessages();
}, [user, partner]);
2024-10-21 16:58:41 -05:00
// Format messages for GiftedChat
2024-10-21 16:58:41 -05:00
const formatMessages = (dbMessages: Message[]): IMessage[] => {
if (!user || !partner) return [];
return dbMessages.map((msg) => ({
_id: msg.id,
text: msg.text,
createdAt: new Date(msg.createdAt),
user: msg.senderId === user.id ? msgUser : msgPartner,
})) as IMessage[];
};
2024-10-21 16:58:41 -05:00
/* -------- Send message function -------- */
const onSend = useCallback(async (messages: any[]) => {
if (!user || !partner) return;
2024-10-22 16:38:06 -05:00
// Prepare the message to be sent
const createdAt = new Date();
const tempId = Math.round(Math.random() * -1000000); // Temporary ID
2024-10-22 16:38:06 -05:00
const messageToSend: Message = {
id: tempId,
senderId: user.id,
receiverId: partner?.id ?? 0,
text: messages[0].text,
createdAt,
isRead: false,
hasLocation: false,
hasMedia: false,
hasQuickReply: false,
};
const notificationMessage: NotificationMessage = {
sound: 'default',
title: 'New message from ' + user.fullName,
body: messageToSend.text,
data: {
message: messageToSend,
},
};
2024-10-25 16:57:25 -05:00
sendPushNotification(partner.pushToken, notificationMessage);
2024-10-22 16:38:06 -05:00
// Add the message with a tempId immediately to the state
const tempFormattedMessages = formatMessages([messageToSend]);
const updatedMessages = GiftedChat.append(state.messages, tempFormattedMessages);
dispatch({
type: ActionKind.SEND_MESSAGE,
payload: updatedMessages,
});
2024-10-22 16:38:06 -05:00
try {
// Send the message to the server
const sentMessage = await sendMessage(messageToSend);
2024-10-25 16:57:25 -05:00
if (!user || isNaN(user.id)) {
console.error('User not found');
throw new Error('User not found');
}
// Fetch the latest messages from the server to ensure consistency
2024-10-25 16:57:25 -05:00
const updatedMessages = await getMessages(user.id);
if (updatedMessages) {
const formattedMessages = formatMessages(updatedMessages);
dispatch({ type: ActionKind.SEND_MESSAGE, payload: formattedMessages });
}
} catch (error) {
console.error('Error sending message:', error);
// In case of an error, remove the temporary message from the state
const updatedMessages = state.messages.filter((msg) => msg._id !== tempId);
dispatch({ type: ActionKind.SEND_MESSAGE, payload: updatedMessages });
Alert.alert('Error', 'Failed to send message. Please try again.');
2024-10-21 16:58:41 -05:00
}
}, [user, partner, state.messages]);
2024-10-21 16:58:41 -05:00
const onLoadEarlier = useCallback(async () => {
if (!user) {
console.log('User not found');
return;
}
2024-10-22 16:38:06 -05:00
// Set loading state
2024-10-16 16:50:26 -05:00
dispatch({ type: ActionKind.LOAD_EARLIER_START });
2024-10-22 16:38:06 -05:00
// Fetch the current size of messages already in chat to calculate the new offset
const offset = state.messages.length;
try {
const earlierMessages = await getMessages(user.id, 20, offset);
2024-10-21 16:58:41 -05:00
if (earlierMessages) {
const formattedMessages = formatMessages(earlierMessages);
const updatedMessages = GiftedChat.prepend(state.messages, formattedMessages);
dispatch({ type: ActionKind.LOAD_EARLIER_MESSAGES, payload: updatedMessages });
2024-10-21 16:58:41 -05:00
}
} catch (error) {
2024-10-22 16:38:06 -05:00
console.error('Error loading earlier messages:', error);
dispatch({ type: ActionKind.LOAD_EARLIER_MESSAGES, payload: [] });
2024-10-21 16:58:41 -05:00
}
2024-10-22 16:38:06 -05:00
}, [user, state.messages]);
2024-10-16 16:50:26 -05:00
const parsePatterns = useCallback(() => {
return [
{
pattern: /#(\w+)/g,
style: { textDecorationLine: 'underline', color: 'darkorange' },
onPress: () => Linking.openURL('https://www.gbrown.org'),
},
]
}, []);
const onLongPressAvatar = useCallback((pressedUser: any) => {
Alert.alert(JSON.stringify(pressedUser))
}, []);
const onPressAvatar = useCallback(() => {
Alert.alert('Pressed avatar!')
}, []);
const handleLongPress = useCallback((context: unknown, currentMessage: object) => {
if (!currentMessage.text) return;
const options = [
'Copy text',
'Cancel',
]
const cancelButtonIndex = options.length - 1;
(context as any).actionSheet().showActionSheetWithOptions(
{ options, cancelButtonIndex },
(buttonIndex: number) => {
switch (buttonIndex) {
case 0:
Clipboard.setStringAsync(currentMessage.text);
break;
default: break;
}
}
)
}, []);
const onQuickReply = useCallback((replies: any[]) => {
const createdAt = new Date();
if (replies.length === 1)
onSend([
{
createdAt,
_id: Math.round(Math.random() * 1000000),
text: replies[0].title,
2024-10-21 16:58:41 -05:00
user: msgUser,
2024-10-16 16:50:26 -05:00
},
]);
else if (replies.length > 1)
onSend([
{
createdAt,
_id: Math.round(Math.random() * 1000000),
text: replies.map(reply => reply.title).join(', '),
2024-10-21 16:58:41 -05:00
user: msgUser,
2024-10-16 16:50:26 -05:00
},
]);
else console.warn('replies param is not set correctly');
2024-10-22 16:38:06 -05:00
}, [msgUser, onSend]);
2024-10-16 16:50:26 -05:00
const renderQuickReplySend = useCallback(() => {
return <ThemedText>{'custom send =>'}</ThemedText>
}, []);
const setIsTyping = useCallback((isTyping: boolean) => {
dispatch({ type: ActionKind.SET_IS_TYPING, payload: isTyping });
}, [dispatch]);
const renderCustomActions = useCallback(
props =>
Platform.OS === 'web' ? null : (
2024-10-21 16:58:41 -05:00
<CustomActions {...props} onSend={onSend} />
2024-10-16 16:50:26 -05:00
),
2024-10-21 16:58:41 -05:00
[onSend]
2024-10-16 16:50:26 -05:00
);
const renderSystemMessage = useCallback(props => {
return (
<SystemMessage
{...props}
containerStyle={{marginBottom: 15}}
textStyle={{fontSize: 14}}
/>
);
}, []);
const renderCustomView = useCallback(props => {
return <CustomView {...props} />
}, []);
const renderSend = useCallback((props: SendProps<IMessage>) => {
return (
<Send
{...props}
containerStyle={{justifyContent: 'center', paddingHorizontal: 10}}
>
<MaterialIcons size={30} color={'tomato'} name={'send'} />
</Send>
);
}, []);
2024-10-21 16:58:41 -05:00
2024-10-16 16:50:26 -05:00
return (
<SafeAreaView style={styles.fill}>
<ThemedView style={styles.fill}>
<GiftedChat
messages={state.messages}
onSend={onSend}
loadEarlier={state.loadEarlier}
onLoadEarlier={onLoadEarlier}
isLoadingEarlier={state.isLoadingEarlier}
parsePatterns={parsePatterns}
2024-10-22 16:38:06 -05:00
user={msgUser}
2024-10-16 16:50:26 -05:00
scrollToBottom
onPressAvatar={onPressAvatar}
onLongPressAvatar={onLongPressAvatar}
onLongPress={handleLongPress}
onQuickReply={onQuickReply}
quickReplyStyle={{ borderRadius: 2 }}
quickReplyTextStyle={{
fontWeight: '200',
}}
renderQuickReplySend={renderQuickReplySend}
renderActions={renderCustomActions}
renderSystemMessage={renderSystemMessage}
renderCustomView={renderCustomView}
renderSend={renderSend}
keyboardShouldPersistTaps='never'
timeTextStyle={{
left: { color: 'red' },
right: { color: 'yellow' },
}}
isTyping={state.isTyping}
inverted={Platform.OS !== 'web'}
infiniteScroll
/>
</ThemedView>
</SafeAreaView>
)
};
2024-10-16 16:50:26 -05:00
const ChatWrapper = () => {
return (
2024-10-21 16:58:41 -05:00
<SafeAreaProvider>
<MessagesScreen />
</SafeAreaProvider>
2024-10-16 16:50:26 -05:00
);
};
export default ChatWrapper;
const styles = StyleSheet.create({
fill: {
flex: 1,
},
});