Merge pull request #92 from project-error/feature/message-from-contacts

Feature/message from contacts
This commit is contained in:
Christopher Gjelten authored and GitHub committed 2021-02-16 23:47:44 +01:00
commit 6f0a2ba30d
10 files changed
+157 -92

No files matched your search

@@ -43,13 +43,13 @@ export const ContactList = () => {
}); });
}; };
const handleMessage = () => { const handleMessage = (phoneNumber: string) => {
LogDebugEvent({ LogDebugEvent({
action: 'Routing to Message', action: 'Routing to Message',
level: 1, level: 1,
data: true, data: { phoneNumber },
}); });
// TODO: Integrate to send to message event when route becomes available history.push(`/messages/new/${phoneNumber}`);
}; };
const filteredRegEx = new RegExp(filteredContacts, 'gi'); const filteredRegEx = new RegExp(filteredContacts, 'gi');
@@ -82,7 +82,7 @@ export const ContactList = () => {
<Button onClick={() => startCall(contact.number)}> <Button onClick={() => startCall(contact.number)}>
<PhoneIcon /> <PhoneIcon />
</Button> </Button>
<Button onClick={() => handleMessage()}> <Button onClick={() => handleMessage(contact.number)}>
<ChatIcon /> <ChatIcon />
</Button> </Button>
<Button <Button
@@ -19,23 +19,27 @@ const ALERT_TIMEOUT = 6000;
export default function AlertBar() { export default function AlertBar() {
const classes = useStyles(); const classes = useStyles();
const { t } = useTranslation(); const { t } = useTranslation();
const { const { createMessageGroupResult } = useAlerts();
createMessageGroupResult,
clearCreateMessageGroupResult,
} = useAlerts();
const [severity, setSeverity] = useState<string | null>(null); const [severity, setSeverity] = useState<string | null>(null);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [message, setMessage] = useState<string | null>(null); const [message, setMessage] = useState<string | null>(null);
const [alert, setAlert] = useState(null);
const handleClose = () => { const handleClose = () => {
setOpen(false); setOpen(false);
clearCreateMessageGroupResult(); setAlert(null);
}; };
useEffect(() => { useEffect(() => {
if (!createMessageGroupResult) return; if (createMessageGroupResult) {
setAlert(createMessageGroupResult);
}
}, [createMessageGroupResult]);
const { error, phoneNumber, duplicate, mine } = createMessageGroupResult; useEffect(() => {
if (!alert) return;
const { error, phoneNumber, duplicate, mine } = alert;
if (error && phoneNumber) { if (error && phoneNumber) {
const error = `${t('APPS_MESSAGES_INVALID_PHONE_NUMBER')}${phoneNumber}`; const error = `${t('APPS_MESSAGES_INVALID_PHONE_NUMBER')}${phoneNumber}`;
setOpen(true); setOpen(true);
@@ -54,7 +58,7 @@ export default function AlertBar() {
setSeverity('error'); setSeverity('error');
setMessage(t('APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED')); setMessage(t('APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED'));
} }
}, [createMessageGroupResult, t]); }, [alert, t]);
return ( return (
<Snackbar <Snackbar
@@ -1,5 +1,5 @@
import './messages.css'; import './messages.css';
import React from 'react'; import React, { useEffect } from 'react';
import { AppWrapper } from '../../../ui/components'; import { AppWrapper } from '../../../ui/components';
import { AppTitle } from '../../../ui/components/AppTitle'; import { AppTitle } from '../../../ui/components/AppTitle';
import { AppContent } from '../../../ui/components/AppContent'; import { AppContent } from '../../../ui/components/AppContent';
@@ -11,6 +11,50 @@ import { Route, Switch, useHistory } from 'react-router-dom';
import { MessageModal } from './modal/MessageModal'; import { MessageModal } from './modal/MessageModal';
import InjectDebugData from '../../../os/debug/InjectDebugData'; import InjectDebugData from '../../../os/debug/InjectDebugData';
import NewMessageGroupButton from './buttons/NewMessageGroupButton'; import NewMessageGroupButton from './buttons/NewMessageGroupButton';
import Nui from '../../../os/nui-events/utils/Nui';
export const MessagesApp = () => {
const messages = useApp('MESSAGES');
const history = useHistory();
useEffect(() => {
Nui.send('phone:fetchMessageGroups');
}, []);
return (
<AppWrapper id='messages-app'>
<AppTitle app={messages} />
<AppContent>
<Switch>
<Route
path='/messages/conversations/:groupId'
component={MessageModal}
/>
<Route
exact
path='/messages'
render={() => (
<>
<MessagesList />
<NewMessageGroupButton
onClick={() => history.push('/messages/new')}
/>
</>
)}
/>
</Switch>
<Switch>
<Route
exact
path={['/messages/new/:phoneNumber', '/messages/new']}
render={() => <MessageGroupModal />}
/>
</Switch>
</AppContent>
<AlertBar />
</AppWrapper>
);
};
InjectDebugData([ InjectDebugData([
{ {
@@ -45,37 +89,3 @@ InjectDebugData([
], ],
}, },
]); ]);
export const MessagesApp = () => {
const messages = useApp('MESSAGES');
const history = useHistory();
return (
<AppWrapper id='messages-app'>
<AppTitle app={messages} />
<AppContent>
<Switch>
<Route
exact
path='/messages/conversations/:groupId'
component={MessageModal}
/>
</Switch>
<Switch>
<Route
path='/messages'
render={() => (
<>
<MessagesList />
<NewMessageGroupButton
onClick={() => history.push('/messages/new')}
/>
</>
)}
/>
<Route exact path='/messages/new' component={MessageGroupModal} />
</Switch>
</AppContent>
<AlertBar />
</AppWrapper>
);
};
@@ -1,4 +1,4 @@
import React, { FormEvent, useState } from 'react'; import React, { FormEvent, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { TextField, Button } from '@material-ui/core'; import { TextField, Button } from '@material-ui/core';
@@ -6,7 +6,13 @@ import useStyles from './form.styles';
import Nui from '../../../../os/nui-events/utils/Nui'; import Nui from '../../../../os/nui-events/utils/Nui';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
const NewMessageGroupForm = () => { const sendNuiCreateMessageGroup = ({ parts, isGroupChat, labelValue }) =>
Nui.send('phone:createMessageGroup', {
phoneNumbers: parts,
label: isGroupChat && labelValue ? labelValue : null,
});
const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => {
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const { t } = useTranslation(); const { t } = useTranslation();
@@ -16,20 +22,28 @@ const NewMessageGroupForm = () => {
// handles phone numbers in a csv format and strips all spaces and // handles phone numbers in a csv format and strips all spaces and
// external characters out of them: // external characters out of them:
// 123-4567, 987-6543, 333-4444 // 123-4567, 987-6543, 333-4444
const parts = participants const getGroupParts = useCallback(
.split(',') (numbers) => numbers.split(',').map((part) => part.replace(/[^0-9]/g, '')),
.map((part) => part.replace(/[^0-9]/g, '')); []
);
const parts = useMemo(() => getGroupParts(participants), [participants, getGroupParts]);
const isGroupChat = parts.length > 1; const isGroupChat = parts.length > 1;
const labelValue = label.trim();
useEffect(() => {
if (phoneNumber) {
sendNuiCreateMessageGroup({ parts: getGroupParts(phoneNumber), isGroupChat: false, labelValue: null });
history.push('/messages');
}
}, [phoneNumber, labelValue, history, getGroupParts]);
const handleSubmit = (event: FormEvent) => { const handleSubmit = (event: FormEvent) => {
event.preventDefault(); event.preventDefault();
if (parts.length > 0) { if (parts.length > 0) {
const labelValue = label.trim(); sendNuiCreateMessageGroup({ parts, isGroupChat, labelValue });
Nui.send('phone:createMessageGroup', {
phoneNumbers: parts,
label: isGroupChat && labelValue ? labelValue : null,
});
setParticipants(''); setParticipants('');
history.push('/messages'); history.push('/messages');
} }
@@ -39,7 +53,7 @@ const NewMessageGroupForm = () => {
<form className={classes.newGroupForm} onSubmit={handleSubmit}> <form className={classes.newGroupForm} onSubmit={handleSubmit}>
<TextField <TextField
value={participants} value={participants}
onChange={(e) => setParticipants(e.target.value)} onChange={(e) => setParticipants(e.target.value || '')}
placeholder={t('APPS_MESSAGES_NEW_MESSAGE_GROUP')} placeholder={t('APPS_MESSAGES_NEW_MESSAGE_GROUP')}
className={classes.newGroupinput} className={classes.newGroupinput}
autoFocus autoFocus
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { List } from '@material-ui/core'; import { List } from '@material-ui/core';
import qs from 'qs'; import qs from 'qs';
import { MessageGroup } from '../../../../common/typings/messages'; import { MessageGroup } from '../../../../common/typings/messages';
@@ -13,13 +13,35 @@ const MessagesList = (): any => {
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const { messageGroups } = useMessages(); const {
messageGroups,
createMessageGroupResult,
clearMessageGroupResult,
} = useMessages();
const [searchValue, setSearchValue] = useState(''); const [searchValue, setSearchValue] = useState('');
const goToConversation = useCallback(
(messageGroup) =>
history.push(
`/messages/conversations/${messageGroup.groupId}/?${qs.stringify(
messageGroup
)}`
),
[history]
);
useEffect(() => { useEffect(() => {
Nui.send('phone:fetchMessageGroups'); if (createMessageGroupResult?.groupId) {
}, []); const findGroup = messageGroups.find(
(g) => g.groupId === createMessageGroupResult.groupId
);
clearMessageGroupResult();
if (findGroup) {
goToConversation(findGroup);
}
}
}, [messageGroups, createMessageGroupResult, goToConversation, clearMessageGroupResult]);
if (!messageGroups) return null; if (!messageGroups) return null;
@@ -3,7 +3,7 @@ import { Slide, Paper, Button } from '@material-ui/core';
import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import useStyles from './modal.styles'; import useStyles from './modal.styles';
import NewMessageGroupForm from '../form/NewMessageGroupForm'; import NewMessageGroupForm from '../form/NewMessageGroupForm';
import { useHistory } from 'react-router-dom'; import { useHistory, useParams } from 'react-router-dom';
const MessageGroupModal = () => { const MessageGroupModal = () => {
const classes = useStyles(); const classes = useStyles();
@@ -11,13 +11,15 @@ const MessageGroupModal = () => {
const handleClose = () => history.push('/messages'); const handleClose = () => history.push('/messages');
const params = useParams<{ phoneNumber?: string }>();
return ( return (
<Slide direction='left' in> <Slide direction='left' in>
<Paper className={classes.modalRoot}> <Paper className={classes.modalRoot}>
<Button onClick={handleClose}> <Button onClick={handleClose}>
<ArrowBackIcon fontSize='large' /> <ArrowBackIcon fontSize='large' />
</Button> </Button>
<NewMessageGroupForm /> <NewMessageGroupForm phoneNumber={params.phoneNumber} />
</Paper> </Paper>
</Slide> </Slide>
); );
+3 -8
View File
@@ -1,21 +1,16 @@
import { useRecoilState } from 'recoil'; import { useRecoilValue } from 'recoil';
import { CreateMessageGroupResult } from '../../../common/typings/messages'; import { CreateMessageGroupResult } from '../../../common/typings/messages';
import { messageState } from './state'; import { messageState } from './state';
interface IUseAlerts { interface IUseAlerts {
createMessageGroupResult: CreateMessageGroupResult | null; createMessageGroupResult: CreateMessageGroupResult | null;
clearCreateMessageGroupResult: () => void;
} }
export default (): IUseAlerts => { export default (): IUseAlerts => {
const [ const createMessageGroupResult = useRecoilValue<CreateMessageGroupResult | null>(
createMessageGroupResult,
setCreateMessageGroupResult,
] = useRecoilState<CreateMessageGroupResult | null>(
messageState.createMessageGroupResult messageState.createMessageGroupResult
); );
const clearCreateMessageGroupResult = () => setCreateMessageGroupResult(null); return { createMessageGroupResult };
return { createMessageGroupResult, clearCreateMessageGroupResult };
}; };
+11 -2
View File
@@ -1,11 +1,13 @@
import { useRecoilState, useRecoilValue } from 'recoil'; import { useRecoilState, useRecoilValue } from 'recoil';
import { Message, MessageGroup } from '../../../common/typings/messages'; import { CreateMessageGroupResult, Message, MessageGroup } from '../../../common/typings/messages';
import { messageState } from './state'; import { messageState } from './state';
interface IUseMessages { interface IUseMessages {
messages?: Message[] | null; messages?: Message[] | null;
setMessages: (messages: Message[] | null) => void; setMessages: (messages: Message[] | null) => void;
messageGroups?: MessageGroup[] | null; messageGroups?: MessageGroup[] | null;
createMessageGroupResult?: CreateMessageGroupResult | null;
clearMessageGroupResult(): void;
} }
export default (): IUseMessages => { export default (): IUseMessages => {
@@ -15,5 +17,12 @@ export default (): IUseMessages => {
const messageGroups = useRecoilValue<MessageGroup[] | null>( const messageGroups = useRecoilValue<MessageGroup[] | null>(
messageState.messageGroups messageState.messageGroups
); );
return { messages, setMessages, messageGroups };
const [createMessageGroupResult, setCreateMessageGroupResult] = useRecoilState<CreateMessageGroupResult | null>(
messageState.createMessageGroupResult
);
const clearMessageGroupResult = () => setCreateMessageGroupResult(null);
return { messages, setMessages, messageGroups, createMessageGroupResult, clearMessageGroupResult };
}; };
+2 -2
View File
@@ -27,7 +27,7 @@ interface DebugEvent {
* } * }
* ]) * ])
**/ **/
const InjectDebugData = (events: DebugEvent[]) => { const InjectDebugData = (events: DebugEvent[], timer = 1000) => {
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
for (const event of events) { for (const event of events) {
setTimeout(() => { setTimeout(() => {
@@ -40,7 +40,7 @@ const InjectDebugData = (events: DebugEvent[]) => {
}, },
}) })
); );
}, 1000); }, timer);
} }
} }
}; };
+24 -15
View File
@@ -298,6 +298,24 @@ async function getFormattedMessageGroups(
}); });
} }
/**
* Create the same unique ID from an identifiers array.
* They will be always be sorted to ensure always the same ID.
* @param identifiers array of player identifiers
*/
function createGroupHashID(identifiers: string[]) {
// make sure we are always in a consistent order. It is very important
// that this not change! Changing this order can result in the ability
// of duplicate message groups being created.
identifiers.sort();
const mergedIdentifiers = identifiers.join('-');
// we don't need this to be secure. Its purpose is to create a unique
// string derived from the identifiers. In this way we can check
// that this groupId isn't used before. If it has then it means
// we are trying to create a duplicate message group!
return md5(mergedIdentifiers);
}
/** /**
* Main method to handle creation of new message groups. First * Main method to handle creation of new message groups. First
* we retrieve identifiers for each submitted phone number and * we retrieve identifiers for each submitted phone number and
@@ -335,18 +353,9 @@ async function createMessageGroupsFromPhoneNumbers(
return { error: true, mine: true }; return { error: true, mine: true };
} }
// make sure we are always in a consistent order. It is very important const groupId = createGroupHashID(identifiers);
// that this not change! Changing this order can result in the ability
// of duplicate message groups being created.
identifiers.sort();
const mergedIdentifiers = identifiers.join('-');
// we don't need this to be secure. Its purpose is to create a unique
// string derived from the identifiers. In this way we can check
// that this groupId isn't used before. If it has then it means
// we are trying to create a duplicate message group!
const groupId = md5(mergedIdentifiers);
if (await checkIfMessageGroupExists(groupId)) { if (await checkIfMessageGroupExists(groupId)) {
return { error: true, duplicate: true }; return { error: false, duplicate: true, groupId };
} }
const queryPromises = [ const queryPromises = [
@@ -382,7 +391,7 @@ onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, async () => {
const messageGroups = await getFormattedMessageGroups(identifier); const messageGroups = await getFormattedMessageGroups(identifier);
emitNet( emitNet(
events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS, events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS,
getSource(), _source,
messageGroups messageGroups
); );
} catch (e) { } catch (e) {
@@ -406,18 +415,18 @@ onNet(
if (result.error) { if (result.error) {
emitNet( emitNet(
events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED,
getSource(), _source,
result result
); );
} else { } else {
emitNet( emitNet(
events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS,
getSource(), _source,
result result
); );
} }
} catch (e) { } catch (e) {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, getSource()); emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, _source);
messageLogger.error(`Failed to create message group, ${e.message}`, { messageLogger.error(`Failed to create message group, ${e.message}`, {
source: _source, source: _source,
}); });