From 0ec2b682e737561fcdcd7f49afd6d9fa923cabc7 Mon Sep 17 00:00:00 2001 From: J Francisco Rader Date: Thu, 18 Mar 2021 23:01:54 -0300 Subject: [PATCH] Messages bugfix again :D (#164) * Handle offline messages | Fetch messages when broadcasted | Fetch message groups * Fetch messages on notification click * Dont fetch groups if duplicate group * Only submit new message on click submit * Fix infinite loading when duplicated group is creatded * Fix infinite loading when group already existed * Make code prettier * Centralize fetch messages on goToConversation * Remove duplicated event * Improve message groups mapping to include yourself for unreadCount + Fix redirection after adding contact + General improvements * Remove conflicts * Fix media paths --- phone/src/Phone.tsx | 4 +- .../apps/example/components/ExampleApp.tsx | 2 +- .../components/form/NewMessageGroupForm.tsx | 42 +++++------ .../components/list/MessageGroupItem.tsx | 2 +- .../messages/components/list/MessagesList.tsx | 20 ++++-- .../components/modal/MessageModal.tsx | 8 +-- .../messages/hooks/useMessageNotifications.ts | 6 +- .../apps/messages/hooks/useMessageService.ts | 32 ++++++++- .../apps/messages/utils/goToConversation.ts | 7 +- .../apps/settings/utils/getRingtonePath.ts | 5 +- phone/src/apps/twitter/utils/constants.ts | 4 +- resources/server/sv_messages.ts | 69 +++++++++++++------ 12 files changed, 132 insertions(+), 69 deletions(-) diff --git a/phone/src/Phone.tsx b/phone/src/Phone.tsx index 31b7fe0..da6d5f8 100644 --- a/phone/src/Phone.tsx +++ b/phone/src/Phone.tsx @@ -80,14 +80,14 @@ function Phone() {
{isPhoneReady ? ( diff --git a/phone/src/apps/example/components/ExampleApp.tsx b/phone/src/apps/example/components/ExampleApp.tsx index 9de4d9d..65caba2 100644 --- a/phone/src/apps/example/components/ExampleApp.tsx +++ b/phone/src/apps/example/components/ExampleApp.tsx @@ -16,7 +16,7 @@ export const ExampleApp = () => { const exampleString = useExample(); const example = useApp('EXAMPLE'); const [soundName, setSound] = useState('pixel.ogg'); - const { play, playing, stop } = useSound('./media/ringtones/' + soundName); + const { play, playing, stop } = useSound('media/ringtones/' + soundName); const toggleSound = () => { if (soundName === 'pixel.ogg') { diff --git a/phone/src/apps/messages/components/form/NewMessageGroupForm.tsx b/phone/src/apps/messages/components/form/NewMessageGroupForm.tsx index 2db31dd..f524bed 100644 --- a/phone/src/apps/messages/components/form/NewMessageGroupForm.tsx +++ b/phone/src/apps/messages/components/form/NewMessageGroupForm.tsx @@ -1,4 +1,4 @@ -import React, { FormEvent, useCallback, useEffect, useState } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Box, Button, TextField } from '@material-ui/core'; @@ -24,27 +24,22 @@ const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => { const isGroupChat = participants.length > 1; - const handleSubmit = useCallback( - (event: FormEvent) => { - event.preventDefault(); + const handleSubmit = useCallback(() => { + // handles phone numbers in a csv format and strips all spaces and + // external characters out of them: + // 123-4567, 987-6543, 333-4444 + const phoneNumbers = participants.map(({ number }) => number.replace(/[^0-9]/g, '')); + const labelValue = isGroupChat ? label.trim() : null; - // handles phone numbers in a csv format and strips all spaces and - // external characters out of them: - // 123-4567, 987-6543, 333-4444 - const phoneNumbers = participants.map(({ number }) => number.replace(/[^0-9]/g, '')); - const labelValue = isGroupChat ? label.trim() : null; - - if (phoneNumbers.length) { - Nui.send('phone:createMessageGroup', { - phoneNumbers, - label: labelValue, - }); - setParticipants([]); - history.push('/messages'); - } - }, - [history, label, participants, isGroupChat], - ); + if (phoneNumbers.length) { + Nui.send('phone:createMessageGroup', { + phoneNumbers, + label: labelValue, + }); + setParticipants([]); + history.push('/messages'); + } + }, [history, label, participants, isGroupChat]); const onAutocompleteChange = (_e, value: any) => { const lastIdx = value.length - 1; @@ -77,7 +72,7 @@ const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => { const submitDisabled = !participants.length || (isGroupChat && !label); return ( -
+ value={participants} @@ -102,6 +97,7 @@ const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => { )} - + ); }; diff --git a/phone/src/apps/messages/components/list/MessageGroupItem.tsx b/phone/src/apps/messages/components/list/MessageGroupItem.tsx index 69f4324..4715058 100644 --- a/phone/src/apps/messages/components/list/MessageGroupItem.tsx +++ b/phone/src/apps/messages/components/list/MessageGroupItem.tsx @@ -23,7 +23,7 @@ const MessageGroupItem = ({ messageGroup, handleClick }: IProps): any => { - + {messageGroup.label || messageGroup.groupDisplay} diff --git a/phone/src/apps/messages/components/list/MessagesList.tsx b/phone/src/apps/messages/components/list/MessagesList.tsx index 0bf4628..a4707de 100644 --- a/phone/src/apps/messages/components/list/MessagesList.tsx +++ b/phone/src/apps/messages/components/list/MessagesList.tsx @@ -15,7 +15,13 @@ const MessagesList = (): any => { const history = useHistory(); const { t } = useTranslation(); - const { messageGroups, createMessageGroupResult, clearMessageGroupResult } = useMessages(); + const { + messageGroups, + createMessageGroupResult, + clearMessageGroupResult, + getMessageGroupById, + setActiveMessageGroup, + } = useMessages(); const [searchValue, setSearchValue] = useState(''); @@ -32,18 +38,24 @@ const MessagesList = (): any => { useEffect(() => { if (createMessageGroupResult?.groupId) { - const findGroup = messageGroups.find((g) => g.groupId === createMessageGroupResult.groupId); + const findGroup = getMessageGroupById(createMessageGroupResult.groupId); clearMessageGroupResult(); if (findGroup) { goToConversation(findGroup, history); } } - }, [messageGroups, createMessageGroupResult, clearMessageGroupResult, history]); + }, [ + messageGroups, + createMessageGroupResult, + clearMessageGroupResult, + history, + setActiveMessageGroup, + getMessageGroupById, + ]); if (!messageGroups) return null; const handleClick = (messageGroup: MessageGroup) => () => { - Nui.send('phone:fetchMessages', { groupId: messageGroup.groupId }); goToConversation(messageGroup, history); }; diff --git a/phone/src/apps/messages/components/modal/MessageModal.tsx b/phone/src/apps/messages/components/modal/MessageModal.tsx index 3e775cd..debf82b 100644 --- a/phone/src/apps/messages/components/modal/MessageModal.tsx +++ b/phone/src/apps/messages/components/modal/MessageModal.tsx @@ -77,7 +77,6 @@ export const MessageModal = () => { useEffect(() => { if (!groupId) return; - setActiveMessageGroup(groupId); }, [groupId, setActiveMessageGroup]); @@ -109,10 +108,11 @@ export const MessageModal = () => { const handleAddContact = (number) => { const exists = getContactByNumber(number); + const referal = encodeURIComponent(pathname); if (exists) { - return history.push(`/contacts/${exists.id}/?referal=${pathname}`); + return history.push(`/contacts/${exists.id}/?referal=${referal}`); } - return history.push(`/contacts/-1/?addNumber=${number}&referal=${pathname}`); + return history.push(`/contacts/-1/?addNumber=${number}&referal=${referal}`); }; const phoneNumbers = activeMessageGroup?.phoneNumbers || []; @@ -164,7 +164,7 @@ export const MessageModal = () => { ) : null}
- {isLoaded ? ( + {isLoaded && activeMessageGroup ? ( { const { t } = useTranslation(); const history = useHistory(); - const { - removeId, - addNotification, - addNotificationAlert, - } = useNotifications(); + const { removeId, addNotification, addNotificationAlert } = useNotifications(); const { icon, notificationIcon } = useApp('MESSAGES'); const { getMessageGroupById } = useMessages(); diff --git a/phone/src/apps/messages/hooks/useMessageService.ts b/phone/src/apps/messages/hooks/useMessageService.ts index 60c37e0..458a21e 100644 --- a/phone/src/apps/messages/hooks/useMessageService.ts +++ b/phone/src/apps/messages/hooks/useMessageService.ts @@ -1,12 +1,16 @@ -import { useSetRecoilState } from 'recoil'; +import { useRecoilState, useSetRecoilState } from 'recoil'; import { messageState } from './state'; import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent'; import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar'; import { useTranslation } from 'react-i18next'; import { useMessageNotifications } from './useMessageNotifications'; import { useCallback } from 'react'; +import Nui from '../../../os/nui-events/utils/Nui'; export const useMessagesService = () => { + const [activeMessageGroup, setActiveMessageGroup] = useRecoilState( + messageState.activeMessageGroup, + ); const setMessageGroups = useSetRecoilState(messageState.messageGroups); const setMessages = useSetRecoilState(messageState.messages); const setCreateMessageGroupResult = useSetRecoilState(messageState.createMessageGroupResult); @@ -24,10 +28,32 @@ export const useMessagesService = () => { [addAlert, t], ); - useNuiEvent('MESSAGES', 'phone:fetchMessageGroupsSuccess', setMessageGroups); + const handleMessageBroadcast = useCallback( + ({ groupId, message }) => { + if (groupId === activeMessageGroup?.groupId) { + Nui.send('phone:fetchMessages', { groupId: activeMessageGroup.groupId }); + } + setNotification({ groupId, message }); + }, + [activeMessageGroup, setNotification], + ); + + const _setMessageGroups = useCallback( + (groups) => { + if (activeMessageGroup && activeMessageGroup.groupId) { + setActiveMessageGroup( + (curr) => groups.find((g) => g.groupId === activeMessageGroup.groupId) || curr, + ); + } + setMessageGroups(groups); + }, + [activeMessageGroup, setActiveMessageGroup, setMessageGroups], + ); + + useNuiEvent('MESSAGES', 'phone:fetchMessageGroupsSuccess', _setMessageGroups); useNuiEvent('MESSAGES', 'phone:fetchMessagesSuccess', setMessages); useNuiEvent('MESSAGES', 'phone:createMessageGroupSuccess', setCreateMessageGroupResult); useNuiEvent('MESSAGES', 'phone:createMessageGroupFailed', setCreateMessageGroupResult); - useNuiEvent('MESSAGES', 'createMessagesBroadcast', setNotification); + useNuiEvent('MESSAGES', 'createMessagesBroadcast', handleMessageBroadcast); useNuiEvent('MESSAGES', 'phone:setMessagesAlert', handleAddAlert); }; diff --git a/phone/src/apps/messages/utils/goToConversation.ts b/phone/src/apps/messages/utils/goToConversation.ts index f7c74b2..52b5905 100644 --- a/phone/src/apps/messages/utils/goToConversation.ts +++ b/phone/src/apps/messages/utils/goToConversation.ts @@ -1,2 +1,7 @@ -export const goToConversation = (messageGroup, history) => +import Nui from '../../../os/nui-events/utils/Nui'; + +export const goToConversation = (messageGroup, history) => { + if (!messageGroup?.groupId || !history) return; history.push(`/messages/conversations/${messageGroup.groupId}`); + Nui.send('phone:fetchMessages', { groupId: messageGroup.groupId }); +}; diff --git a/phone/src/apps/settings/utils/getRingtonePath.ts b/phone/src/apps/settings/utils/getRingtonePath.ts index e95bc46..a438cd5 100644 --- a/phone/src/apps/settings/utils/getRingtonePath.ts +++ b/phone/src/apps/settings/utils/getRingtonePath.ts @@ -1,4 +1,3 @@ -export const getRingtonePath = (name?: string) => `./media/ringtones/${name || 'pixel'}.ogg`; +export const getRingtonePath = (name?: string) => `media/ringtones/${name || 'pixel'}.ogg`; -export const getNotificationPath = (name?: string) => - `./media/notifications/${name || 'online'}.ogg`; +export const getNotificationPath = (name?: string) => `media/notifications/${name || 'online'}.ogg`; diff --git a/phone/src/apps/twitter/utils/constants.ts b/phone/src/apps/twitter/utils/constants.ts index ec04269..3cd4533 100644 --- a/phone/src/apps/twitter/utils/constants.ts +++ b/phone/src/apps/twitter/utils/constants.ts @@ -1,5 +1,5 @@ -export const IMG_DEFAULT_AVATAR = './media/twitter/egg.png'; -export const IMG_INVALID_AVATAR = './media/twitter/invalid.png'; +export const IMG_DEFAULT_AVATAR = 'media/twitter/egg.png'; +export const IMG_INVALID_AVATAR = 'media/twitter/invalid.png'; export const APP_TWITTER = 'TWITTER'; export const SETTING_MENTIONS = 'mentions'; diff --git a/resources/server/sv_messages.ts b/resources/server/sv_messages.ts index 71d80da..b510e8e 100644 --- a/resources/server/sv_messages.ts +++ b/resources/server/sv_messages.ts @@ -28,6 +28,7 @@ interface UnformattedMessageGroup { interface MessageGroupMapping { [groupId: string]: { user_identifier: string; + // Participant displays participants: string[]; phoneNumbers: string[]; label?: string; @@ -97,7 +98,6 @@ async function getMessageGroups(userIdentifier: string): Promise { const groupId = messageGroup.group_id; const displayTerm = messageGroup.display || messageGroup.phone_number || '???'; - + const isUser = messageGroup.participant_identifier === userIdentifier; + // Is already mapped? if (groupId in mapping) { - mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm); + // Add participant phone number mapping[groupId].phoneNumbers = mapping[groupId].phoneNumbers.concat( messageGroup.phone_number, ); - if (messageGroup.participant_identifier === userIdentifier) { + if (isUser) { + // Add unread count if its user's message group mapping[groupId].unreadCount = messageGroup.unreadCount; + return mapping; } - } else { + // Add participant if its not user's message group + mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm); + return mapping; + } + if (isUser) { + // Group not mapped and its current user mapping[groupId] = { user_identifier: messageGroup.user_identifier, - unreadCount: - messageGroup.participant_identifier === userIdentifier ? messageGroup.unreadCount : 0, - avatar: messageGroup.avatar, - label: messageGroup.label, - participants: [displayTerm], + unreadCount: messageGroup.unreadCount, + avatar: null, + label: null, + participants: [], phoneNumbers: [messageGroup.phone_number], updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null, }; + return mapping; } + // Group not mapped and its not current user + mapping[groupId] = { + user_identifier: messageGroup.user_identifier, + unreadCount: 0, + avatar: messageGroup.avatar, + label: messageGroup.label, + participants: [displayTerm], + phoneNumbers: [messageGroup.phone_number], + updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null, + }; return mapping; }, {}, @@ -287,7 +305,7 @@ async function getFormattedMessageGroups(userIdentifier: string): Promise 1, }; }); @@ -436,15 +454,21 @@ onNet( message: `MESSAGES_MESSAGE_GROUP_CREATE_FAILED:`, type: 'error', }); - } - - emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, _source, result); - if (result.identifiers) { - for (const participantId of result.identifiers) { - // we don't broadcast to the source of the event. - if (participantId !== _identifier) { - const participantPlayer = getPlayerFromIdentifier(participantId); - emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, participantPlayer.source); + } else { + emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, _source, result); + if (result.duplicate) { + return; + } + if (result.identifiers) { + for (const participantId of result.identifiers) { + // we don't broadcast to the source of the event. + if (participantId !== _identifier) { + const participantPlayer = getPlayerFromIdentifier(participantId); + if (!participantPlayer) { + return; + } + emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, participantPlayer.source); + } } } } @@ -493,6 +517,10 @@ onNet(events.MESSAGES_SEND_MESSAGE, async (groupId: string, message: string, gro // we don't broadcast to the source of the event. if (participantId !== _identifier) { const participantPlayer = getPlayerFromIdentifier(participantId); + if (!participantPlayer) { + return; + } + emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, participantPlayer.source); emitNet(events.MESSAGES_CREATE_MESSAGE_BROADCAST, participantPlayer.source, { groupName, groupId, @@ -522,6 +550,7 @@ onNet(events.MESSAGES_SET_MESSAGE_READ, async (groupId: string) => { try { const identifier = getIdentifier(pSource); await setMessageRead(groupId, identifier); + emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, pSource); } catch (e) { messageLogger.error(`Failed to set message as read, ${e.message}`, { source: pSource,