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
This commit is contained in:
J Francisco Rader authored and GitHub committed 2021-03-18 23:01:54 -03:00
1 parent a2c0f94bd8
commit 0ec2b682e7
12 files changed
+132 -69

No files matched your search

+2 -2
View File
@@ -80,14 +80,14 @@ function Phone() {
<div <div
className="PhoneFrame" className="PhoneFrame"
style={{ style={{
backgroundImage: `url(./media/frames/${settings.frame.value})`, backgroundImage: `url(media/frames/${settings.frame.value})`,
}} }}
/> />
<div <div
id="phone" id="phone"
className="PhoneScreen" className="PhoneScreen"
style={{ style={{
backgroundImage: `url(./media/backgrounds/${settings.wallpaper.value})`, backgroundImage: `url(media/backgrounds/${settings.wallpaper.value})`,
}} }}
> >
{isPhoneReady ? ( {isPhoneReady ? (
@@ -16,7 +16,7 @@ export const ExampleApp = () => {
const exampleString = useExample(); const exampleString = useExample();
const example = useApp('EXAMPLE'); const example = useApp('EXAMPLE');
const [soundName, setSound] = useState('pixel.ogg'); const [soundName, setSound] = useState('pixel.ogg');
const { play, playing, stop } = useSound('./media/ringtones/' + soundName); const { play, playing, stop } = useSound('media/ringtones/' + soundName);
const toggleSound = () => { const toggleSound = () => {
if (soundName === 'pixel.ogg') { if (soundName === 'pixel.ogg') {
@@ -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 { useTranslation } from 'react-i18next';
import { Box, Button, TextField } from '@material-ui/core'; import { Box, Button, TextField } from '@material-ui/core';
@@ -24,27 +24,22 @@ const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => {
const isGroupChat = participants.length > 1; const isGroupChat = participants.length > 1;
const handleSubmit = useCallback( const handleSubmit = useCallback(() => {
(event: FormEvent) => { // handles phone numbers in a csv format and strips all spaces and
event.preventDefault(); // 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 if (phoneNumbers.length) {
// external characters out of them: Nui.send('phone:createMessageGroup', {
// 123-4567, 987-6543, 333-4444 phoneNumbers,
const phoneNumbers = participants.map(({ number }) => number.replace(/[^0-9]/g, '')); label: labelValue,
const labelValue = isGroupChat ? label.trim() : null; });
setParticipants([]);
if (phoneNumbers.length) { history.push('/messages');
Nui.send('phone:createMessageGroup', { }
phoneNumbers, }, [history, label, participants, isGroupChat]);
label: labelValue,
});
setParticipants([]);
history.push('/messages');
}
},
[history, label, participants, isGroupChat],
);
const onAutocompleteChange = (_e, value: any) => { const onAutocompleteChange = (_e, value: any) => {
const lastIdx = value.length - 1; const lastIdx = value.length - 1;
@@ -77,7 +72,7 @@ const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => {
const submitDisabled = !participants.length || (isGroupChat && !label); const submitDisabled = !participants.length || (isGroupChat && !label);
return ( return (
<form onSubmit={handleSubmit}> <Box>
<Box px={2} py={3}> <Box px={2} py={3}>
<Autocomplete<Contact, boolean, boolean, boolean> <Autocomplete<Contact, boolean, boolean, boolean>
value={participants} value={participants}
@@ -102,6 +97,7 @@ const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => {
)} )}
<Box px={2} py={3}> <Box px={2} py={3}>
<Button <Button
onClick={() => handleSubmit()}
disabled={submitDisabled} disabled={submitDisabled}
variant="contained" variant="contained"
fullWidth fullWidth
@@ -111,7 +107,7 @@ const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => {
{t('APPS_MESSAGES_NEW_MESSAGE_GROUP_SUBMIT')} {t('APPS_MESSAGES_NEW_MESSAGE_GROUP_SUBMIT')}
</Button> </Button>
</Box> </Box>
</form> </Box>
); );
}; };
@@ -23,7 +23,7 @@ const MessageGroupItem = ({ messageGroup, handleClick }: IProps): any => {
<ListItem key={messageGroup.groupId} onClick={handleClick(messageGroup)} divider button> <ListItem key={messageGroup.groupId} onClick={handleClick(messageGroup)} divider button>
<ListItemAvatar> <ListItemAvatar>
<Badge color="error" variant="dot" invisible={!hasUnread}> <Badge color="error" variant="dot" invisible={!hasUnread}>
<MuiAvatar src={messageGroup?.avatar} /> <MuiAvatar src={messageGroup.avatar} />
</Badge> </Badge>
</ListItemAvatar> </ListItemAvatar>
<ListItemText>{messageGroup.label || messageGroup.groupDisplay}</ListItemText> <ListItemText>{messageGroup.label || messageGroup.groupDisplay}</ListItemText>
@@ -15,7 +15,13 @@ const MessagesList = (): any => {
const history = useHistory(); const history = useHistory();
const { t } = useTranslation(); const { t } = useTranslation();
const { messageGroups, createMessageGroupResult, clearMessageGroupResult } = useMessages(); const {
messageGroups,
createMessageGroupResult,
clearMessageGroupResult,
getMessageGroupById,
setActiveMessageGroup,
} = useMessages();
const [searchValue, setSearchValue] = useState(''); const [searchValue, setSearchValue] = useState('');
@@ -32,18 +38,24 @@ const MessagesList = (): any => {
useEffect(() => { useEffect(() => {
if (createMessageGroupResult?.groupId) { if (createMessageGroupResult?.groupId) {
const findGroup = messageGroups.find((g) => g.groupId === createMessageGroupResult.groupId); const findGroup = getMessageGroupById(createMessageGroupResult.groupId);
clearMessageGroupResult(); clearMessageGroupResult();
if (findGroup) { if (findGroup) {
goToConversation(findGroup, history); goToConversation(findGroup, history);
} }
} }
}, [messageGroups, createMessageGroupResult, clearMessageGroupResult, history]); }, [
messageGroups,
createMessageGroupResult,
clearMessageGroupResult,
history,
setActiveMessageGroup,
getMessageGroupById,
]);
if (!messageGroups) return null; if (!messageGroups) return null;
const handleClick = (messageGroup: MessageGroup) => () => { const handleClick = (messageGroup: MessageGroup) => () => {
Nui.send('phone:fetchMessages', { groupId: messageGroup.groupId });
goToConversation(messageGroup, history); goToConversation(messageGroup, history);
}; };
@@ -77,7 +77,6 @@ export const MessageModal = () => {
useEffect(() => { useEffect(() => {
if (!groupId) return; if (!groupId) return;
setActiveMessageGroup(groupId); setActiveMessageGroup(groupId);
}, [groupId, setActiveMessageGroup]); }, [groupId, setActiveMessageGroup]);
@@ -109,10 +108,11 @@ export const MessageModal = () => {
const handleAddContact = (number) => { const handleAddContact = (number) => {
const exists = getContactByNumber(number); const exists = getContactByNumber(number);
const referal = encodeURIComponent(pathname);
if (exists) { 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 || []; const phoneNumbers = activeMessageGroup?.phoneNumbers || [];
@@ -164,7 +164,7 @@ export const MessageModal = () => {
) : null} ) : null}
</Box> </Box>
</Paper> </Paper>
{isLoaded ? ( {isLoaded && activeMessageGroup ? (
<Conversation <Conversation
onClickDisplay={handleAddContact} onClickDisplay={handleAddContact}
messages={messages} messages={messages}
@@ -10,11 +10,7 @@ const NOTIFICATION_ID = 'messages:broadcast';
export const useMessageNotifications = () => { export const useMessageNotifications = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const history = useHistory(); const history = useHistory();
const { const { removeId, addNotification, addNotificationAlert } = useNotifications();
removeId,
addNotification,
addNotificationAlert,
} = useNotifications();
const { icon, notificationIcon } = useApp('MESSAGES'); const { icon, notificationIcon } = useApp('MESSAGES');
const { getMessageGroupById } = useMessages(); const { getMessageGroupById } = useMessages();
@@ -1,12 +1,16 @@
import { useSetRecoilState } from 'recoil'; import { useRecoilState, useSetRecoilState } from 'recoil';
import { messageState } from './state'; import { messageState } from './state';
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent'; import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar'; import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useMessageNotifications } from './useMessageNotifications'; import { useMessageNotifications } from './useMessageNotifications';
import { useCallback } from 'react'; import { useCallback } from 'react';
import Nui from '../../../os/nui-events/utils/Nui';
export const useMessagesService = () => { export const useMessagesService = () => {
const [activeMessageGroup, setActiveMessageGroup] = useRecoilState(
messageState.activeMessageGroup,
);
const setMessageGroups = useSetRecoilState(messageState.messageGroups); const setMessageGroups = useSetRecoilState(messageState.messageGroups);
const setMessages = useSetRecoilState(messageState.messages); const setMessages = useSetRecoilState(messageState.messages);
const setCreateMessageGroupResult = useSetRecoilState(messageState.createMessageGroupResult); const setCreateMessageGroupResult = useSetRecoilState(messageState.createMessageGroupResult);
@@ -24,10 +28,32 @@ export const useMessagesService = () => {
[addAlert, t], [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:fetchMessagesSuccess', setMessages);
useNuiEvent('MESSAGES', 'phone:createMessageGroupSuccess', setCreateMessageGroupResult); useNuiEvent('MESSAGES', 'phone:createMessageGroupSuccess', setCreateMessageGroupResult);
useNuiEvent('MESSAGES', 'phone:createMessageGroupFailed', setCreateMessageGroupResult); useNuiEvent('MESSAGES', 'phone:createMessageGroupFailed', setCreateMessageGroupResult);
useNuiEvent('MESSAGES', 'createMessagesBroadcast', setNotification); useNuiEvent('MESSAGES', 'createMessagesBroadcast', handleMessageBroadcast);
useNuiEvent('MESSAGES', 'phone:setMessagesAlert', handleAddAlert); useNuiEvent('MESSAGES', 'phone:setMessagesAlert', handleAddAlert);
}; };
@@ -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}`); history.push(`/messages/conversations/${messageGroup.groupId}`);
Nui.send('phone:fetchMessages', { groupId: messageGroup.groupId });
};
@@ -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) => export const getNotificationPath = (name?: string) => `media/notifications/${name || 'online'}.ogg`;
`./media/notifications/${name || 'online'}.ogg`;
+2 -2
View File
@@ -1,5 +1,5 @@
export const IMG_DEFAULT_AVATAR = './media/twitter/egg.png'; export const IMG_DEFAULT_AVATAR = 'media/twitter/egg.png';
export const IMG_INVALID_AVATAR = './media/twitter/invalid.png'; export const IMG_INVALID_AVATAR = 'media/twitter/invalid.png';
export const APP_TWITTER = 'TWITTER'; export const APP_TWITTER = 'TWITTER';
export const SETTING_MENTIONS = 'mentions'; export const SETTING_MENTIONS = 'mentions';
+49 -20
View File
@@ -28,6 +28,7 @@ interface UnformattedMessageGroup {
interface MessageGroupMapping { interface MessageGroupMapping {
[groupId: string]: { [groupId: string]: {
user_identifier: string; user_identifier: string;
// Participant displays
participants: string[]; participants: string[];
phoneNumbers: string[]; phoneNumbers: string[];
label?: string; label?: string;
@@ -97,7 +98,6 @@ async function getMessageGroups(userIdentifier: string): Promise<UnformattedMess
LEFT OUTER JOIN users on users.identifier = npwd_messages_groups.participant_identifier LEFT OUTER JOIN users on users.identifier = npwd_messages_groups.participant_identifier
LEFT OUTER JOIN npwd_messages_labels on npwd_messages_labels.group_id = npwd_messages_groups.group_id LEFT OUTER JOIN npwd_messages_labels on npwd_messages_labels.group_id = npwd_messages_groups.group_id
LEFT OUTER JOIN npwd_phone_contacts on REGEXP_REPLACE(npwd_phone_contacts.number, '[^0-9]', '') = REGEXP_REPLACE(users.phone_number, '[^0-9]', '') AND npwd_phone_contacts.identifier = ? LEFT OUTER JOIN npwd_phone_contacts on REGEXP_REPLACE(npwd_phone_contacts.number, '[^0-9]', '') = REGEXP_REPLACE(users.phone_number, '[^0-9]', '') AND npwd_phone_contacts.identifier = ?
WHERE npwd_messages_groups.participant_identifier != ?
ORDER BY npwd_messages_groups.createdAt DESC ORDER BY npwd_messages_groups.createdAt DESC
`; `;
const [results] = await pool.query(query, [userIdentifier, userIdentifier, userIdentifier]); const [results] = await pool.query(query, [userIdentifier, userIdentifier, userIdentifier]);
@@ -231,27 +231,45 @@ async function getConsolidatedMessageGroups(userIdentifier: string): Promise<Mes
(mapping: MessageGroupMapping, messageGroup: UnformattedMessageGroup) => { (mapping: MessageGroupMapping, messageGroup: UnformattedMessageGroup) => {
const groupId = messageGroup.group_id; const groupId = messageGroup.group_id;
const displayTerm = messageGroup.display || messageGroup.phone_number || '???'; const displayTerm = messageGroup.display || messageGroup.phone_number || '???';
const isUser = messageGroup.participant_identifier === userIdentifier;
// Is already mapped?
if (groupId in mapping) { if (groupId in mapping) {
mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm); // Add participant phone number
mapping[groupId].phoneNumbers = mapping[groupId].phoneNumbers.concat( mapping[groupId].phoneNumbers = mapping[groupId].phoneNumbers.concat(
messageGroup.phone_number, messageGroup.phone_number,
); );
if (messageGroup.participant_identifier === userIdentifier) { if (isUser) {
// Add unread count if its user's message group
mapping[groupId].unreadCount = messageGroup.unreadCount; 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] = { mapping[groupId] = {
user_identifier: messageGroup.user_identifier, user_identifier: messageGroup.user_identifier,
unreadCount: unreadCount: messageGroup.unreadCount,
messageGroup.participant_identifier === userIdentifier ? messageGroup.unreadCount : 0, avatar: null,
avatar: messageGroup.avatar, label: null,
label: messageGroup.label, participants: [],
participants: [displayTerm],
phoneNumbers: [messageGroup.phone_number], phoneNumbers: [messageGroup.phone_number],
updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null, 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; return mapping;
}, },
{}, {},
@@ -287,7 +305,7 @@ async function getFormattedMessageGroups(userIdentifier: string): Promise<Messag
...group, ...group,
groupId, groupId,
groupDisplay: group.participants.join(', '), groupDisplay: group.participants.join(', '),
// note that 1 here references how many participants besides the user // note that the 1 here references how many participants besides the user
isGroupChat: group.participants.length > 1, isGroupChat: group.participants.length > 1,
}; };
}); });
@@ -436,15 +454,21 @@ onNet(
message: `MESSAGES_MESSAGE_GROUP_CREATE_FAILED:`, message: `MESSAGES_MESSAGE_GROUP_CREATE_FAILED:`,
type: 'error', type: 'error',
}); });
} } else {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, _source, result);
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, _source, result); if (result.duplicate) {
if (result.identifiers) { return;
for (const participantId of result.identifiers) { }
// we don't broadcast to the source of the event. if (result.identifiers) {
if (participantId !== _identifier) { for (const participantId of result.identifiers) {
const participantPlayer = getPlayerFromIdentifier(participantId); // we don't broadcast to the source of the event.
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, participantPlayer.source); 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. // we don't broadcast to the source of the event.
if (participantId !== _identifier) { if (participantId !== _identifier) {
const participantPlayer = getPlayerFromIdentifier(participantId); const participantPlayer = getPlayerFromIdentifier(participantId);
if (!participantPlayer) {
return;
}
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, participantPlayer.source);
emitNet(events.MESSAGES_CREATE_MESSAGE_BROADCAST, participantPlayer.source, { emitNet(events.MESSAGES_CREATE_MESSAGE_BROADCAST, participantPlayer.source, {
groupName, groupName,
groupId, groupId,
@@ -522,6 +550,7 @@ onNet(events.MESSAGES_SET_MESSAGE_READ, async (groupId: string) => {
try { try {
const identifier = getIdentifier(pSource); const identifier = getIdentifier(pSource);
await setMessageRead(groupId, identifier); await setMessageRead(groupId, identifier);
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, pSource);
} catch (e) { } catch (e) {
messageLogger.error(`Failed to set message as read, ${e.message}`, { messageLogger.error(`Failed to set message as read, ${e.message}`, {
source: pSource, source: pSource,