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({
action: 'Routing to Message',
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');
@@ -82,7 +82,7 @@ export const ContactList = () => {
<Button onClick={() => startCall(contact.number)}>
<PhoneIcon />
</Button>
<Button onClick={() => handleMessage()}>
<Button onClick={() => handleMessage(contact.number)}>
<ChatIcon />
</Button>
<Button
@@ -19,23 +19,27 @@ const ALERT_TIMEOUT = 6000;
export default function AlertBar() {
const classes = useStyles();
const { t } = useTranslation();
const {
createMessageGroupResult,
clearCreateMessageGroupResult,
} = useAlerts();
const { createMessageGroupResult } = useAlerts();
const [severity, setSeverity] = useState<string | null>(null);
const [open, setOpen] = useState(false);
const [message, setMessage] = useState<string | null>(null);
const [alert, setAlert] = useState(null);
const handleClose = () => {
setOpen(false);
clearCreateMessageGroupResult();
setAlert(null);
};
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) {
const error = `${t('APPS_MESSAGES_INVALID_PHONE_NUMBER')}${phoneNumber}`;
setOpen(true);
@@ -54,7 +58,7 @@ export default function AlertBar() {
setSeverity('error');
setMessage(t('APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED'));
}
}, [createMessageGroupResult, t]);
}, [alert, t]);
return (
<Snackbar
@@ -1,5 +1,5 @@
import './messages.css';
import React from 'react';
import React, { useEffect } from 'react';
import { AppWrapper } from '../../../ui/components';
import { AppTitle } from '../../../ui/components/AppTitle';
import { AppContent } from '../../../ui/components/AppContent';
@@ -11,6 +11,50 @@ import { Route, Switch, useHistory } from 'react-router-dom';
import { MessageModal } from './modal/MessageModal';
import InjectDebugData from '../../../os/debug/InjectDebugData';
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([
{
@@ -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 { TextField, Button } from '@material-ui/core';
@@ -6,7 +6,13 @@ import useStyles from './form.styles';
import Nui from '../../../../os/nui-events/utils/Nui';
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 history = useHistory();
const { t } = useTranslation();
@@ -16,20 +22,28 @@ const NewMessageGroupForm = () => {
// handles phone numbers in a csv format and strips all spaces and
// external characters out of them:
// 123-4567, 987-6543, 333-4444
const parts = participants
.split(',')
.map((part) => part.replace(/[^0-9]/g, ''));
const getGroupParts = useCallback(
(numbers) => numbers.split(',').map((part) => part.replace(/[^0-9]/g, '')),
[]
);
const parts = useMemo(() => getGroupParts(participants), [participants, getGroupParts]);
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) => {
event.preventDefault();
if (parts.length > 0) {
const labelValue = label.trim();
Nui.send('phone:createMessageGroup', {
phoneNumbers: parts,
label: isGroupChat && labelValue ? labelValue : null,
});
sendNuiCreateMessageGroup({ parts, isGroupChat, labelValue });
setParticipants('');
history.push('/messages');
}
@@ -39,7 +53,7 @@ const NewMessageGroupForm = () => {
<form className={classes.newGroupForm} onSubmit={handleSubmit}>
<TextField
value={participants}
onChange={(e) => setParticipants(e.target.value)}
onChange={(e) => setParticipants(e.target.value || '')}
placeholder={t('APPS_MESSAGES_NEW_MESSAGE_GROUP')}
className={classes.newGroupinput}
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 qs from 'qs';
import { MessageGroup } from '../../../../common/typings/messages';
@@ -13,13 +13,35 @@ const MessagesList = (): any => {
const classes = useStyles();
const history = useHistory();
const { messageGroups } = useMessages();
const {
messageGroups,
createMessageGroupResult,
clearMessageGroupResult,
} = useMessages();
const [searchValue, setSearchValue] = useState('');
const goToConversation = useCallback(
(messageGroup) =>
history.push(
`/messages/conversations/${messageGroup.groupId}/?${qs.stringify(
messageGroup
)}`
),
[history]
);
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;
@@ -3,7 +3,7 @@ import { Slide, Paper, Button } from '@material-ui/core';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import useStyles from './modal.styles';
import NewMessageGroupForm from '../form/NewMessageGroupForm';
import { useHistory } from 'react-router-dom';
import { useHistory, useParams } from 'react-router-dom';
const MessageGroupModal = () => {
const classes = useStyles();
@@ -11,13 +11,15 @@ const MessageGroupModal = () => {
const handleClose = () => history.push('/messages');
const params = useParams<{ phoneNumber?: string }>();
return (
<Slide direction='left' in>
<Paper className={classes.modalRoot}>
<Button onClick={handleClose}>
<ArrowBackIcon fontSize='large' />
</Button>
<NewMessageGroupForm />
<NewMessageGroupForm phoneNumber={params.phoneNumber} />
</Paper>
</Slide>
);
+3 -8
View File
@@ -1,21 +1,16 @@
import { useRecoilState } from 'recoil';
import { useRecoilValue } from 'recoil';
import { CreateMessageGroupResult } from '../../../common/typings/messages';
import { messageState } from './state';
interface IUseAlerts {
createMessageGroupResult: CreateMessageGroupResult | null;
clearCreateMessageGroupResult: () => void;
}
export default (): IUseAlerts => {
const [
createMessageGroupResult,
setCreateMessageGroupResult,
] = useRecoilState<CreateMessageGroupResult | null>(
const createMessageGroupResult = useRecoilValue<CreateMessageGroupResult | null>(
messageState.createMessageGroupResult
);
const clearCreateMessageGroupResult = () => setCreateMessageGroupResult(null);
return { createMessageGroupResult, clearCreateMessageGroupResult };
return { createMessageGroupResult };
};
+11 -2
View File
@@ -1,11 +1,13 @@
import { useRecoilState, useRecoilValue } from 'recoil';
import { Message, MessageGroup } from '../../../common/typings/messages';
import { CreateMessageGroupResult, Message, MessageGroup } from '../../../common/typings/messages';
import { messageState } from './state';
interface IUseMessages {
messages?: Message[] | null;
setMessages: (messages: Message[] | null) => void;
messageGroups?: MessageGroup[] | null;
createMessageGroupResult?: CreateMessageGroupResult | null;
clearMessageGroupResult(): void;
}
export default (): IUseMessages => {
@@ -15,5 +17,12 @@ export default (): IUseMessages => {
const messageGroups = useRecoilValue<MessageGroup[] | null>(
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') {
for (const event of events) {
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
* we retrieve identifiers for each submitted phone number and
@@ -335,18 +353,9 @@ async function createMessageGroupsFromPhoneNumbers(
return { error: true, mine: true };
}
// 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!
const groupId = md5(mergedIdentifiers);
const groupId = createGroupHashID(identifiers);
if (await checkIfMessageGroupExists(groupId)) {
return { error: true, duplicate: true };
return { error: false, duplicate: true, groupId };
}
const queryPromises = [
@@ -382,7 +391,7 @@ onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, async () => {
const messageGroups = await getFormattedMessageGroups(identifier);
emitNet(
events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS,
getSource(),
_source,
messageGroups
);
} catch (e) {
@@ -406,18 +415,18 @@ onNet(
if (result.error) {
emitNet(
events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED,
getSource(),
_source,
result
);
} else {
emitNet(
events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS,
getSource(),
_source,
result
);
}
} 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}`, {
source: _source,
});