mirror of
https://github.com/darksaid98/new-phone-who-dis.git
synced 2026-12-02 22:17:39 +00:00
working groups & messages
This commit is contained in:
1 parent
ccbc2d3b87
commit
681ce16912
25 files changed
+476
-162
No files matched your search
@@ -61,7 +61,7 @@ export const InfoModal = () => {
|
||||
className={showContactModal ? classes.modalRoot : classes.modalHide}
|
||||
>
|
||||
<Button style={{ margin: 10 }} onClick={closeModal}>
|
||||
<ArrowBackIcon />
|
||||
<ArrowBackIcon fontSize="large" />
|
||||
</Button>
|
||||
<div className={classes.listContainer}>
|
||||
<MuiAvatar className={classes.avatar} src={avatar} />
|
||||
|
||||
@@ -5,6 +5,7 @@ import { AppContent } from "../../../ui/components/AppContent";
|
||||
import { useApp } from "../../../os/apps/hooks/useApps";
|
||||
import MessagesList from "./list/MessagesList";
|
||||
import { MessageModal } from "./modal/MessageModal";
|
||||
import MessageGroupModal from "./modal/MessageGroupModal";
|
||||
import NewMessageGroupButton from "./buttons/NewMessageGroupButton";
|
||||
import './messages.css'
|
||||
|
||||
@@ -14,6 +15,7 @@ export const MessagesApp = () => {
|
||||
<AppWrapper id="messages-app">
|
||||
<AppTitle app={messages} />
|
||||
<MessageModal />
|
||||
<MessageGroupModal />
|
||||
<AppContent>
|
||||
<MessagesList />
|
||||
<NewMessageGroupButton />
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import React from "react";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import { Fab } from "@material-ui/core";
|
||||
import { amber } from "@material-ui/core/colors";
|
||||
import AddIcon from "@material-ui/icons/Add";
|
||||
import useModals from "../../hooks/useModals";
|
||||
|
||||
const useStyles = makeStyles(() => ({
|
||||
root: {
|
||||
@@ -14,10 +14,13 @@ const useStyles = makeStyles(() => ({
|
||||
|
||||
export function NewMessageGroupButton() {
|
||||
const classes = useStyles();
|
||||
const { setShowNewMessageGroup } = useModals()
|
||||
|
||||
const handleClick = () => setShowNewMessageGroup(true);
|
||||
|
||||
return (
|
||||
<div className={classes.root}>
|
||||
<Fab color="primary">
|
||||
<Fab color="primary" onClick={handleClick}>
|
||||
<AddIcon />
|
||||
</Fab>
|
||||
</div>
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
import React, { useState } from 'react'
|
||||
import React, { FormEvent, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Paper, TextField, Button } from '@material-ui/core'
|
||||
import useStyles from './form.styles';
|
||||
import SendIcon from '@material-ui/icons/Send';
|
||||
import Nui from '../../../../os/nui-events/utils/Nui';
|
||||
|
||||
export const MessageInput = ({ messageGroupId }) => {
|
||||
interface IProps {
|
||||
messageGroupId: string | undefined;
|
||||
}
|
||||
|
||||
const MessageInput = ({ messageGroupId }: IProps) => {
|
||||
const classes = useStyles();
|
||||
const { t } = useTranslation();
|
||||
const [ message, setMessage ] = useState('')
|
||||
|
||||
const handleSubmit = () => {
|
||||
const handleSubmit = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
Nui.send('phone:sendMessage', {
|
||||
groupId: messageGroupId,
|
||||
message
|
||||
@@ -16,21 +23,26 @@ export const MessageInput = ({ messageGroupId }) => {
|
||||
setMessage('');
|
||||
}
|
||||
|
||||
if (!messageGroupId) return null;
|
||||
|
||||
return (
|
||||
<Paper
|
||||
className={classes.form}
|
||||
variant="outlined"
|
||||
>
|
||||
<TextField
|
||||
value={message}
|
||||
onChange={e => setMessage(e.target.value)}
|
||||
placeholder="Message..."
|
||||
className={classes.input}
|
||||
inputProps={{
|
||||
className: classes.messagesInput
|
||||
}}
|
||||
/>
|
||||
<Button className={classes.sendButton} onClick={handleSubmit}><SendIcon /></Button>
|
||||
<Paper className={classes.paper} variant="outlined" >
|
||||
<form className={classes.form} onSubmit={handleSubmit}>
|
||||
<TextField
|
||||
value={message}
|
||||
onChange={e => setMessage(e.target.value)}
|
||||
placeholder={t("APPS_MESSAGES_NEW_MESSAGE")}
|
||||
className={classes.input}
|
||||
inputProps={{
|
||||
className: classes.messagesInput
|
||||
}}
|
||||
/>
|
||||
<Button className={classes.sendButton} type="submit" >
|
||||
<SendIcon />
|
||||
</Button>
|
||||
</form>
|
||||
</Paper>
|
||||
)
|
||||
}
|
||||
|
||||
export default MessageInput;
|
||||
@@ -0,0 +1,44 @@
|
||||
import React, { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { TextField, Button } from '@material-ui/core'
|
||||
import AddIcon from '@material-ui/icons/Add';
|
||||
|
||||
import useStyles from './form.styles';
|
||||
import useModals from '../../hooks/useModals';
|
||||
import Nui from '../../../../os/nui-events/utils/Nui';
|
||||
|
||||
const NewMessageGroupForm = () => {
|
||||
const classes = useStyles();
|
||||
const { t } = useTranslation();
|
||||
const { setShowNewMessageGroup } = useModals();
|
||||
const [ participants, setParticipants ] = useState('');
|
||||
|
||||
const handleSubmit = () => {
|
||||
// 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, ''));
|
||||
Nui.send('phone:createMessageGroup', { phoneNumbers: parts });
|
||||
setParticipants('');
|
||||
setShowNewMessageGroup(false); // close modal after submission
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={classes.formTop}>
|
||||
<TextField
|
||||
value={participants}
|
||||
onChange={e => setParticipants(e.target.value)}
|
||||
placeholder={t("APPS_MESSAGES_NEW_MESSAGE_GROUP")}
|
||||
className={classes.input}
|
||||
inputProps={{
|
||||
className: classes.messagesInput
|
||||
}}
|
||||
/>
|
||||
<Button className={classes.sendButton} onClick={handleSubmit} >
|
||||
<AddIcon fontSize="large" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default NewMessageGroupForm;
|
||||
@@ -4,9 +4,17 @@ const useStyles = makeStyles((theme) => ({
|
||||
sendButton: {
|
||||
float: 'right'
|
||||
},
|
||||
form: {
|
||||
paper: {
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
width: '100%',
|
||||
},
|
||||
form: {
|
||||
display: 'flex',
|
||||
},
|
||||
formTop: {
|
||||
position: 'absolute',
|
||||
top: 65,
|
||||
display: 'flex',
|
||||
width: '100%',
|
||||
},
|
||||
|
||||
@@ -1,19 +1,30 @@
|
||||
import React from 'react'
|
||||
import { List, ListItem, ListItemText, ListItemAvatar, Avatar as MuiAvatar } from '@material-ui/core';
|
||||
|
||||
import { useMessages } from '../../hooks/useMessages';
|
||||
import { MessageGroup } from '../../../../common/interfaces/messages';
|
||||
import Nui from '../../../../os/nui-events/utils/Nui';
|
||||
import useMessages from '../../hooks/useMessages';
|
||||
import useModals from '../../hooks/useModals';
|
||||
import useStyles from './list.styles';
|
||||
|
||||
const MessagesList = (): any => {
|
||||
const classes = useStyles();
|
||||
const { messages, setActiveMessageGroupId } = useMessages();
|
||||
const { messageGroups } = useMessages();
|
||||
const { setActiveMessageGroup } = useModals();
|
||||
|
||||
if (!messageGroups) return null;
|
||||
|
||||
const handleClick = (messageGroup: MessageGroup) => () => {
|
||||
setActiveMessageGroup(messageGroup);
|
||||
Nui.send('phone:fetchMessages', { groupId: messageGroup.groupId });
|
||||
}
|
||||
|
||||
return (
|
||||
<List className={classes.root}>
|
||||
{messages.map((messageGroup) => (
|
||||
{messageGroups.map((messageGroup) => (
|
||||
<ListItem
|
||||
key={messageGroup.groupId}
|
||||
onClick={() => setActiveMessageGroupId(messageGroup.groupId)}
|
||||
onClick={handleClick(messageGroup)}
|
||||
divider
|
||||
button
|
||||
>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import React from 'react';
|
||||
import { Paper } from '@material-ui/core'
|
||||
|
||||
import { Message } from '../../../../common/interfaces/messages';
|
||||
import MessageInput from '../form/MessageInput';
|
||||
import useStyles from './modal.styles';
|
||||
|
||||
interface IProps {
|
||||
activeMessageGroupId: string | undefined;
|
||||
messages: Message[]
|
||||
}
|
||||
|
||||
export const CONVERSATION_ELEMENT_ID = 'message-modal-conversation';
|
||||
|
||||
const Conversation = ({ activeMessageGroupId, messages }: IProps) => {
|
||||
const classes = useStyles();
|
||||
return (
|
||||
<>
|
||||
<div id={CONVERSATION_ELEMENT_ID} className={classes.messageList}>
|
||||
{messages.map((message) => (
|
||||
<div key={message.id} className={classes.messageContainer}>
|
||||
<Paper className={message.isMine ? classes.sourceSms : classes.sms} variant="outlined">
|
||||
{message.message}
|
||||
</Paper>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<MessageInput messageGroupId={activeMessageGroupId} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default Conversation;
|
||||
@@ -0,0 +1,25 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react'
|
||||
import { Slide, Paper, Button } from '@material-ui/core'
|
||||
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
|
||||
import useStyles from './modal.styles';
|
||||
|
||||
import useModals from '../../hooks/useModals';
|
||||
import NewMessageGroupForm from '../form/NewMessageGroupForm';
|
||||
|
||||
const MessageGroupModal = () => {
|
||||
const classes = useStyles();
|
||||
const { showNewMessageGroup, setShowNewMessageGroup } = useModals();
|
||||
|
||||
const handleClose = () => setShowNewMessageGroup(false);
|
||||
|
||||
return (
|
||||
<Slide direction="left" in={showNewMessageGroup}>
|
||||
<Paper className={showNewMessageGroup ? classes.modalRoot : classes.modalHide}>
|
||||
<Button onClick={handleClose}><ArrowBackIcon fontSize="large" /></Button>
|
||||
<NewMessageGroupForm />
|
||||
</Paper>
|
||||
</Slide>
|
||||
)
|
||||
}
|
||||
|
||||
export default MessageGroupModal;
|
||||
@@ -1,50 +1,50 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react'
|
||||
import { Slide, Paper, Button } from '@material-ui/core'
|
||||
import useStyles from './modal.styles';
|
||||
import React, { useEffect } from 'react'
|
||||
import { Slide, Paper, Button, Typography } from '@material-ui/core'
|
||||
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
|
||||
|
||||
import { useMessages } from '../../hooks/useMessages';
|
||||
import { MessageInput } from '../form/MessageInput';
|
||||
|
||||
const LIST_ID = 'message-modal-list';
|
||||
import useStyles from './modal.styles';
|
||||
import useMessages from '../../hooks/useMessages';
|
||||
import useModals from '../../hooks/useModals';
|
||||
import Conversation, { CONVERSATION_ELEMENT_ID } from './Conversation';
|
||||
|
||||
export const MessageModal = () => {
|
||||
const classes = useStyles();
|
||||
const [, updateState] = React.useState();
|
||||
const { messages, activeMessageGroupId, setActiveMessageGroupId } = useMessages();
|
||||
const { messages, setMessages } = useMessages();
|
||||
const { activeMessageGroup, setActiveMessageGroup } = useModals();
|
||||
|
||||
const closeModal = () => {
|
||||
setActiveMessageGroup(null);
|
||||
setMessages(null);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// when we get a new message group we should scroll to the
|
||||
// bottom to show the latest messages
|
||||
if (activeMessageGroupId) {
|
||||
const element = document.getElementById(LIST_ID);
|
||||
if (activeMessageGroup) {
|
||||
const element = document.getElementById(CONVERSATION_ELEMENT_ID);
|
||||
if (element) {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
}
|
||||
}
|
||||
}, [activeMessageGroupId, messages]);
|
||||
}, [ messages?.length]);
|
||||
|
||||
const forceRerender = () => useCallback(() => updateState({}), []);
|
||||
|
||||
const closeModal = () => setActiveMessageGroupId(null);
|
||||
const isOpen = activeMessageGroupId !== null;
|
||||
const activeMessageGroup = messages.find(messageGroup => messageGroup.groupId === activeMessageGroupId);
|
||||
const activeMessages = activeMessageGroup ? activeMessageGroup.messages : [];
|
||||
const isOpen = activeMessageGroup !== null;
|
||||
|
||||
return (
|
||||
<Slide direction="left" in={isOpen}>
|
||||
<Paper className={activeMessageGroupId ? classes.modalRoot : classes.modalHide}>
|
||||
<Button onClick={closeModal}><ArrowBackIcon /></Button>
|
||||
<div id={LIST_ID} className={classes.messageList}>
|
||||
{activeMessages.map((message) => (
|
||||
<div key={message.id} className={classes.messageContainer}>
|
||||
<Paper className={message.isMine ? classes.sourceSms : classes.sms} variant="outlined">
|
||||
{message.message}
|
||||
</Paper>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<MessageInput messageGroupId={activeMessageGroupId} />
|
||||
<Paper className={isOpen ? classes.modalRoot : classes.modalHide}>
|
||||
<Paper className={classes.topContainer}>
|
||||
<Button onClick={closeModal}><ArrowBackIcon fontSize="large" /></Button>
|
||||
<Typography variant="h5" className={classes.groupdisplay} >
|
||||
{activeMessageGroup ? activeMessageGroup.groupDisplay : ''}
|
||||
</Typography>
|
||||
</Paper>
|
||||
{messages ? (
|
||||
<Conversation
|
||||
messages={messages}
|
||||
activeMessageGroupId={activeMessageGroup?.groupId}
|
||||
/>
|
||||
) : <h1>LOADING</h1>}
|
||||
</Paper>
|
||||
</Slide>
|
||||
)
|
||||
|
||||
@@ -10,10 +10,23 @@ const useStyles = makeStyles((theme) => ({
|
||||
modalHide: {
|
||||
display: 'none'
|
||||
},
|
||||
topContainer: {
|
||||
display: 'flex',
|
||||
flexFlow: 'row nowrap',
|
||||
padding: '3px 0px',
|
||||
},
|
||||
groupdisplay: {
|
||||
width: '300px',
|
||||
paddingTop: '8px',
|
||||
fontSize: '24px',
|
||||
whiteSpace: 'nowrap',
|
||||
overflowX: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
},
|
||||
messageList: {
|
||||
height: '90%',
|
||||
overflowY: 'auto',
|
||||
paddingBottom: '25px',
|
||||
paddingBottom: '40px',
|
||||
},
|
||||
messageContainer: {
|
||||
marginTop: 25,
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { atom } from 'recoil';
|
||||
|
||||
export const messageState = {
|
||||
messageGroups: atom({
|
||||
key: 'messageGroups',
|
||||
default: null
|
||||
}),
|
||||
messages: atom({
|
||||
key: 'messages',
|
||||
default: null
|
||||
@@ -9,8 +13,8 @@ export const messageState = {
|
||||
key: 'activeMessageGroup',
|
||||
default: null
|
||||
}),
|
||||
filter: atom({
|
||||
key: 'messageFilter',
|
||||
default: null
|
||||
})
|
||||
showNewMessageGroup: atom({
|
||||
key: 'showNewMessageGroup',
|
||||
default: false
|
||||
}),
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import { useRecoilValue } from 'recoil';
|
||||
import { messageState } from './state';
|
||||
|
||||
export const useConversation = (): any => {
|
||||
const conversation = useRecoilValue(messageState.conversation);
|
||||
return { conversation }
|
||||
}
|
||||
@@ -4,10 +4,9 @@ import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
|
||||
|
||||
|
||||
export const useMessagesService = () => {
|
||||
const setMessageGroups = useSetRecoilState(messageState.messageGroups);
|
||||
const setMessages = useSetRecoilState(messageState.messages);
|
||||
|
||||
const test = result => console.log(result);
|
||||
|
||||
useNuiEvent('MESSAGES', 'phone:getMessageGroupsSuccess', setMessageGroups);
|
||||
useNuiEvent('MESSAGES', 'phone:fetchMessagesSuccess', setMessages);
|
||||
useNuiEvent('MESSAGES', 'phone:sendMessageSuccess', test);
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
import { useRecoilState } from 'recoil';
|
||||
import { MessageGroup } from '../../../common/interfaces/messages';
|
||||
import { useRecoilState, useRecoilValue } from 'recoil';
|
||||
import { Message, MessageGroup } from '../../../common/interfaces/messages';
|
||||
import { messageState } from './state';
|
||||
|
||||
interface IUseMessages {
|
||||
messages: MessageGroup[];
|
||||
setMessages: any;
|
||||
setActiveMessageGroupId: (id: string | null) => void;
|
||||
activeMessageGroupId: null | string;
|
||||
messages?: Message[] | null;
|
||||
setMessages: (messages: Message[] | null) => void;
|
||||
messageGroups?: MessageGroup[] | null;
|
||||
}
|
||||
|
||||
export const useMessages = (): IUseMessages => {
|
||||
const [ activeMessageGroupId, setActiveMessageGroupId ] = useRecoilState<any>(messageState.activeMessageGroup)
|
||||
const [messages, setMessages] = useRecoilState<any>(messageState.messages);
|
||||
return { messages, setMessages, activeMessageGroupId, setActiveMessageGroupId };
|
||||
export default (): IUseMessages => {
|
||||
const [messages, setMessages] = useRecoilState<Message[] | null>(messageState.messages);
|
||||
const messageGroups = useRecoilValue<MessageGroup[] | null>(messageState.messageGroups)
|
||||
return { messages, setMessages, messageGroups };
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useRecoilState } from 'recoil';
|
||||
import { MessageGroup } from '../../../common/interfaces/messages';
|
||||
import { messageState } from './state';
|
||||
|
||||
interface IUseModal {
|
||||
activeMessageGroup: MessageGroup | null;
|
||||
setActiveMessageGroup: (group: MessageGroup | null) => void;
|
||||
showNewMessageGroup: boolean;
|
||||
setShowNewMessageGroup: (value: boolean) => void;
|
||||
}
|
||||
|
||||
export default (): IUseModal => {
|
||||
const [ activeMessageGroup, setActiveMessageGroup ] = useRecoilState<MessageGroup | null>(messageState.activeMessageGroup)
|
||||
const [ showNewMessageGroup, setShowNewMessageGroup ] = useRecoilState<boolean>(messageState.showNewMessageGroup)
|
||||
return { activeMessageGroup, setActiveMessageGroup, showNewMessageGroup, setShowNewMessageGroup };
|
||||
}
|
||||
@@ -61,7 +61,7 @@ export const NoteModal = () => {
|
||||
<Slide direction="left" in={noteModal} mountOnEnter unmountOnExit>
|
||||
<div>
|
||||
<Button className={classes.closeButton} onClick={_handleClose}>
|
||||
<ArrowBackIcon />
|
||||
<ArrowBackIcon fontSize="large" />
|
||||
</Button>
|
||||
<div id="notes-modal" className={classes.noteContainer}>
|
||||
<TextField
|
||||
|
||||
@@ -1,21 +1,17 @@
|
||||
export interface Message {
|
||||
id?: number;
|
||||
id: number;
|
||||
message: string;
|
||||
user_identifier: string;
|
||||
group_id: number;
|
||||
phone_number: string;
|
||||
display?: string;
|
||||
avatar?: string;
|
||||
isRead: boolean;
|
||||
isMine: boolean;
|
||||
avatar?: string;
|
||||
phone_number?: string;
|
||||
display?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface MessageGroup {
|
||||
groupId: string;
|
||||
messages: Message[];
|
||||
groupDisplay: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -51,7 +51,9 @@
|
||||
|
||||
"APPS_CONTACT_FORM_NAME": "Name",
|
||||
"APPS_CONTACT_FORM_NUMBER": "Number",
|
||||
"APPS_CONTACT_FORM_AVATAR": "Avatar URL"
|
||||
"APPS_CONTACT_FORM_AVATAR": "Avatar URL",
|
||||
|
||||
"APPS_MESSAGES_NEW_MESSAGE": "Message...",
|
||||
"APPS_MESSAGES_NEW_MESSAGE_GROUP": "Phone numbers..."
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,64 @@
|
||||
import events from '../utils/events';
|
||||
import { Message } from '../../phone/src/common/interfaces/messages';
|
||||
import { Message, MessageGroup } from '../../phone/src/common/interfaces/messages';
|
||||
import { sendMessageEvent } from '../utils/messages';
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Twitter fetch messages
|
||||
* Messages get message groups
|
||||
*/
|
||||
RegisterNuiCallbackType(events.MESSAGES_FETCH_MESSAGES);
|
||||
on(`__cfx_nui:${events.MESSAGES_FETCH_MESSAGES}`, () => {
|
||||
emitNet(events.MESSAGES_FETCH_MESSAGES);
|
||||
RegisterNuiCallbackType(events.MESSAGES_GET_MESSAGE_GROUPS);
|
||||
on(`__cfx_nui:${events.MESSAGES_GET_MESSAGE_GROUPS}`, (): void => {
|
||||
emitNet(events.MESSAGES_GET_MESSAGE_GROUPS);
|
||||
});
|
||||
|
||||
onNet(events.MESSAGES_FETCH_MESSAGES_SUCCESS, (messages: Message[]) => {
|
||||
onNet(events.MESSAGES_GET_MESSAGE_GROUPS_SUCCESS, (messageGroups: MessageGroup[]): void => {
|
||||
sendMessageEvent(events.MESSAGES_GET_MESSAGE_GROUPS_SUCCESS, messageGroups);
|
||||
emitNet(events.MESSAGES_GET_MESSAGE_GROUPS_SUCCESS);
|
||||
});
|
||||
|
||||
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, () => {
|
||||
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED);
|
||||
});
|
||||
|
||||
// fetch message groups on client launch
|
||||
emitNet(events.MESSAGES_GET_MESSAGE_GROUPS);
|
||||
|
||||
|
||||
/**
|
||||
* Messages create message group
|
||||
*/
|
||||
RegisterNuiCallbackType(events.MESSAGES_CREATE_MESSAGE_GROUP);
|
||||
on(`__cfx_nui:${events.MESSAGES_CREATE_MESSAGE_GROUP}`, ({ phoneNumbers }: any): void => {
|
||||
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP, phoneNumbers);
|
||||
});
|
||||
|
||||
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, (result: any): void => {
|
||||
console.log(result);
|
||||
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, result);
|
||||
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS);
|
||||
});
|
||||
|
||||
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, (): void => {
|
||||
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED);
|
||||
});
|
||||
|
||||
/**
|
||||
* Messages fetch messages
|
||||
*/
|
||||
RegisterNuiCallbackType(events.MESSAGES_FETCH_MESSAGES);
|
||||
on(`__cfx_nui:${events.MESSAGES_FETCH_MESSAGES}`, ({ groupId }: any): void => {
|
||||
emitNet(events.MESSAGES_FETCH_MESSAGES, groupId);
|
||||
});
|
||||
|
||||
onNet(events.MESSAGES_FETCH_MESSAGES_SUCCESS, (messages: Message[]): void => {
|
||||
sendMessageEvent(events.MESSAGES_FETCH_MESSAGES_SUCCESS, messages);
|
||||
});
|
||||
|
||||
onNet(events.MESSAGES_FETCH_MESSAGES_FAILED, () => {
|
||||
onNet(events.MESSAGES_FETCH_MESSAGES_FAILED, (): void => {
|
||||
sendMessageEvent(events.MESSAGES_FETCH_MESSAGES_FAILED);
|
||||
});
|
||||
|
||||
// fetch messages on client launch
|
||||
emitNet(events.MESSAGES_FETCH_MESSAGES);
|
||||
|
||||
|
||||
/**
|
||||
* Messages send message
|
||||
@@ -31,12 +68,11 @@ on(`__cfx_nui:${events.MESSAGES_SEND_MESSAGE}`, (data: any) => {
|
||||
emitNet(events.MESSAGES_SEND_MESSAGE, data.groupId, data.message);
|
||||
});
|
||||
|
||||
onNet(events.MESSAGES_SEND_MESSAGE_SUCCESS, (result: any) => {
|
||||
console.log(result);
|
||||
sendMessageEvent(events.MESSAGES_SEND_MESSAGE_SUCCESS, result);
|
||||
emitNet(events.MESSAGES_FETCH_MESSAGES);
|
||||
onNet(events.MESSAGES_SEND_MESSAGE_SUCCESS, (groupId: string) => {
|
||||
sendMessageEvent(events.MESSAGES_SEND_MESSAGE_SUCCESS);
|
||||
emitNet(events.MESSAGES_FETCH_MESSAGES, groupId);
|
||||
});
|
||||
|
||||
onNet(events.MESSAGES_SEND_MESSAGE_FAILED, () => {
|
||||
sendMessageEvent(events.MESSAGES_SEND_MESSAGE_FAILED);
|
||||
});
|
||||
});
|
||||
@@ -21,12 +21,14 @@
|
||||
"connection-string-parser": "^1.0.3",
|
||||
"fivem-esx-js": "^0.1.12",
|
||||
"fivem-js": "^1.3.1",
|
||||
"mysql2": "^2.2.5"
|
||||
"mysql2": "^2.2.5",
|
||||
"uuid": "^8.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/preset-env": "^7.12.1",
|
||||
"@babel/preset-typescript": "^7.12.1",
|
||||
"@types/jest": "^26.0.14",
|
||||
"@types/uuid": "^8.3.0",
|
||||
"@typescript-eslint/eslint-plugin": "^3.8.0",
|
||||
"@typescript-eslint/parser": "^4.4.0",
|
||||
"eslint": "^7.6.0",
|
||||
|
||||
@@ -64,3 +64,21 @@ export function generateConnectionPool() {
|
||||
}
|
||||
|
||||
export const pool = generateConnectionPool();
|
||||
|
||||
|
||||
export async function withTransaction(queries: Promise<any>[]): Promise<any[]> {
|
||||
const connection = await pool.getConnection()
|
||||
connection.beginTransaction();
|
||||
|
||||
try {
|
||||
const results = await Promise.all(queries)
|
||||
await connection.commit()
|
||||
await connection.release()
|
||||
return results;
|
||||
} catch (err) {
|
||||
console.warn('Error when submitting queries');
|
||||
await connection.rollback()
|
||||
await connection.release()
|
||||
return Promise.reject(err)
|
||||
}
|
||||
}
|
||||
+140
-53
@@ -1,21 +1,23 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import events from '../utils/events';
|
||||
import { pool } from "./db";
|
||||
import { Message, MessageGroup } from '../../phone/src/common/interfaces/messages';
|
||||
import { pool, withTransaction } from "./db";
|
||||
import { getSource, useIdentifier } from './functions';
|
||||
|
||||
interface GroupMapping {
|
||||
[channelId: string]: {
|
||||
messages: Message[];
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
interface UnformattedMessageGroup {
|
||||
group_id: string;
|
||||
participant_identifier: string;
|
||||
phone_number: string;
|
||||
display: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface GroupMessages {
|
||||
channelId: string;
|
||||
messages: Message[];
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
interface MessageGroupMapping {
|
||||
[groupId: string]: {
|
||||
participants: string[];
|
||||
updatedAt: string;
|
||||
}
|
||||
}
|
||||
|
||||
async function createMessage(userIdentifier: string, groupId: string, message: string): Promise<any> {
|
||||
@@ -32,79 +34,153 @@ async function createMessage(userIdentifier: string, groupId: string, message: s
|
||||
return results;
|
||||
}
|
||||
|
||||
async function getMessages(userIdentifier: string): Promise<Message[]> {
|
||||
async function getMessageGroups(userIdentifier: string): Promise<UnformattedMessageGroup[]> {
|
||||
const query = `
|
||||
SELECT
|
||||
npwd_messages.*,
|
||||
npwd_messages_groups.group_id,
|
||||
npwd_messages_groups.participant_identifier,
|
||||
users.phone_number,
|
||||
MAX(npwd_messages.updatedAt) AS updatedAt,
|
||||
npwd_phone_contacts.display
|
||||
FROM npwd_messages_groups
|
||||
LEFT OUTER JOIN users on users.identifier = npwd_messages_groups.participant_identifier
|
||||
LEFT OUTER JOIN npwd_phone_contacts on npwd_phone_contacts.number = users.phone_number
|
||||
LEFT OUTER JOIN npwd_messages on npwd_messages.group_id = npwd_messages_groups.group_id
|
||||
WHERE npwd_messages_groups.user_identifier = ? AND npwd_messages_groups.participant_identifier != ?
|
||||
ORDER BY updatedAt DESC
|
||||
`
|
||||
const [results] = await pool.query(query, [ userIdentifier, userIdentifier]);
|
||||
return <UnformattedMessageGroup[]>results;
|
||||
}
|
||||
|
||||
async function getMessages(userIdentifier: string, groupId: string): Promise<Message[]> {
|
||||
const query = `
|
||||
SELECT
|
||||
npwd_messages.id,
|
||||
npwd_messages.message,
|
||||
npwd_messages.user_identifier,
|
||||
npwd_messages.isRead,
|
||||
npwd_messages.updatedAt,
|
||||
users.phone_number,
|
||||
npwd_phone_contacts.display,
|
||||
npwd_phone_contacts.avatar
|
||||
FROM (
|
||||
SELECT group_id
|
||||
FROM npwd_messages_groups
|
||||
WHERE user_identifier = ?
|
||||
) as t
|
||||
LEFT OUTER JOIN npwd_messages on t.group_id = npwd_messages.group_id
|
||||
FROM npwd_messages
|
||||
LEFT OUTER JOIN users on users.identifier = npwd_messages.user_identifier
|
||||
LEFT OUTER JOIN npwd_phone_contacts on npwd_phone_contacts.number = users.phone_number
|
||||
WHERE (users.phone_number IS NOT NULL OR npwd_phone_contacts.display IS NOT NULL)
|
||||
WHERE npwd_messages.group_id = ?
|
||||
ORDER BY updatedAt ASC;
|
||||
`;
|
||||
const [results] = await pool.query(query, [ userIdentifier]);
|
||||
const [results] = await pool.query(query, [ groupId]);
|
||||
const messages = <Message[]>results;
|
||||
return messages.map(message => ({
|
||||
...message,
|
||||
isMine: message.user_identifier === userIdentifier,
|
||||
createdAt: message.createdAt.toString(),
|
||||
updatedAt: message.updatedAt.toString(),
|
||||
}));
|
||||
}
|
||||
|
||||
async function groupMessagesByGroup(useIdentifier: string): Promise<GroupMapping> {
|
||||
const messages = await getMessages(useIdentifier);
|
||||
return messages.reduce((mapping: GroupMapping, message: Message) => {
|
||||
const groupId = message.group_id;
|
||||
async function getConsolidatedMessageGroups(useIdentifier: string): Promise<MessageGroupMapping> {
|
||||
const messageGroups = await getMessageGroups(useIdentifier);
|
||||
return messageGroups.reduce((mapping: MessageGroupMapping, messageGroup: UnformattedMessageGroup) => {
|
||||
const groupId = messageGroup.group_id;
|
||||
const displayTerm = messageGroup.display || messageGroup.phone_number || '???';
|
||||
|
||||
if (groupId in mapping) {
|
||||
// we sort by updatedAt ASCENDING in the SQL query so we can always assume the
|
||||
// first participant added has the lastest updatedAt. Therefore we don't
|
||||
// need to updatedAt here
|
||||
mapping[groupId].messages = mapping[groupId].messages.concat(message);
|
||||
mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm)
|
||||
} else {
|
||||
mapping[groupId] = {
|
||||
messages: [message],
|
||||
updatedAt: message.updatedAt,
|
||||
createdAt: message.createdAt,
|
||||
participants: [displayTerm],
|
||||
updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null
|
||||
}
|
||||
}
|
||||
return mapping;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function getGroupDisplayName(userIdentifier: string, messages: Message[]): string {
|
||||
return messages.reduce((displayTerms, message) => {
|
||||
if (message.user_identifier === userIdentifier) return displayTerms; // don't display our name
|
||||
|
||||
const display = message.display || message.phone_number;
|
||||
return displayTerms.includes(display) ? [] : displayTerms.concat(display)
|
||||
}, []).join(', ');
|
||||
}
|
||||
|
||||
async function getFormattedMessages(userIdentifier: string): Promise<MessageGroup[]> {
|
||||
const groupMapping = await groupMessagesByGroup(userIdentifier);
|
||||
const groups = Object.keys(groupMapping);
|
||||
return groups.map(group => {
|
||||
async function getFormattedMessageGroups(userIdentifier: string): Promise<MessageGroup[]> {
|
||||
const groupMapping = await getConsolidatedMessageGroups(userIdentifier);
|
||||
const groupIds = Object.keys(groupMapping);
|
||||
return groupIds.map(groupId => {
|
||||
const group = groupMapping[groupId];
|
||||
return {
|
||||
...groupMapping[group],
|
||||
groupId: group,
|
||||
groupDisplay: getGroupDisplayName(userIdentifier, groupMapping[group].messages)
|
||||
groupId,
|
||||
groupDisplay: group.participants.join(','),
|
||||
updatedAt: group.updatedAt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onNet(events.MESSAGES_FETCH_MESSAGES, async () => {
|
||||
async function createMessageGroup(userIdentifier: string, groupId: string, participantIdentifier: string): Promise<any> {
|
||||
const query = `
|
||||
INSERT INTO npwd_messages_groups
|
||||
(user_identifier, group_id, participant_identifier)
|
||||
VALUES (?, ?, ?)
|
||||
`;
|
||||
const [results] = await pool.query(query, [
|
||||
userIdentifier,
|
||||
groupId,
|
||||
participantIdentifier
|
||||
]);
|
||||
}
|
||||
|
||||
async function getIdentifierFromPhoneNumber(phoneNumber: string): Promise<string> {
|
||||
const query = `
|
||||
SELECT identifier
|
||||
FROM users
|
||||
WHERE REGEXP_REPLACE(phone_number, '[^0-9]', '') = ?
|
||||
LIMIT 1
|
||||
`;
|
||||
const [results] = await pool.query(query, [ phoneNumber]);
|
||||
const identifiers = <any>results;
|
||||
return identifiers[0]['identifier']
|
||||
}
|
||||
|
||||
async function createMessageGroupsFromPhoneNumbers(userIdentifier: string, phoneNumbers: string[]): Promise<string> {
|
||||
const groupId = uuidv4();
|
||||
|
||||
// we check that each phoneNumber exists before we create the group
|
||||
const identifiers: string[] = [];
|
||||
for (const phoneNumber of phoneNumbers) {
|
||||
const identifier = await getIdentifierFromPhoneNumber(phoneNumber)
|
||||
identifiers.push(identifier);
|
||||
}
|
||||
|
||||
const connection = await pool.getConnection()
|
||||
connection.beginTransaction();
|
||||
|
||||
const queryPromises = [
|
||||
// create a row that contains ourselves so others can reference it
|
||||
createMessageGroup(userIdentifier, groupId, userIdentifier),
|
||||
...identifiers.map(identifier => createMessageGroup(userIdentifier, groupId, identifier))
|
||||
]
|
||||
|
||||
// wrap this in a transaction to make sure ALL of these INSERTs succeed
|
||||
//so we are not left in a situation where only some of the member of the
|
||||
// group exist while other are left off.
|
||||
const results = withTransaction(queryPromises);
|
||||
console.log(results);
|
||||
|
||||
return groupId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
onNet(events.MESSAGES_GET_MESSAGE_GROUPS, async () => {
|
||||
try {
|
||||
const _identifier = await useIdentifier();
|
||||
const messages = await getFormattedMessages(_identifier);
|
||||
const messageGroups = await getFormattedMessageGroups(_identifier);
|
||||
emitNet(events.MESSAGES_GET_MESSAGE_GROUPS_SUCCESS, getSource(), messageGroups);
|
||||
} catch (e) {
|
||||
emitNet(events.MESSAGES_GET_MESSAGE_GROUPS_FAILED, getSource());
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
onNet(events.MESSAGES_FETCH_MESSAGES, async (groupId: string) => {
|
||||
try {
|
||||
const _identifier = await useIdentifier();
|
||||
const messages = await getMessages(_identifier, groupId);
|
||||
emitNet(events.MESSAGES_FETCH_MESSAGES_SUCCESS, getSource(), messages);
|
||||
} catch (e) {
|
||||
emitNet(events.MESSAGES_FETCH_MESSAGES_FAILED, getSource());
|
||||
@@ -114,9 +190,20 @@ onNet(events.MESSAGES_FETCH_MESSAGES, async () => {
|
||||
onNet(events.MESSAGES_SEND_MESSAGE, async (groupId: string, message: string) => {
|
||||
try {
|
||||
const _identifier = await useIdentifier();
|
||||
const result = await createMessage(_identifier, groupId, message)
|
||||
emitNet(events.MESSAGES_SEND_MESSAGE_SUCCESS, getSource(), result);
|
||||
await createMessage(_identifier, groupId, message)
|
||||
emitNet(events.MESSAGES_SEND_MESSAGE_SUCCESS, getSource(), groupId);
|
||||
} catch (e) {
|
||||
emitNet(events.MESSAGES_SEND_MESSAGE_FAILED, getSource());
|
||||
}
|
||||
});
|
||||
|
||||
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP, async (phoneNumbers: string[]) => {
|
||||
try {
|
||||
console.log(phoneNumbers);
|
||||
const _identifier = await useIdentifier();
|
||||
const groupId = await createMessageGroupsFromPhoneNumbers(_identifier, phoneNumbers)
|
||||
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, getSource(), groupId);
|
||||
} catch (e) {
|
||||
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, getSource());
|
||||
}
|
||||
});
|
||||
@@ -54,6 +54,12 @@ export default {
|
||||
BANK_GET_CREDENTIALS: 'phone:getBankCredentials',
|
||||
|
||||
//messages
|
||||
MESSAGES_GET_MESSAGE_GROUPS: 'phone:getMessageGroups',
|
||||
MESSAGES_GET_MESSAGE_GROUPS_SUCCESS: 'phone:getMessageGroupsSuccess',
|
||||
MESSAGES_GET_MESSAGE_GROUPS_FAILED: 'phone:getMessageGroupsFailed',
|
||||
MESSAGES_CREATE_MESSAGE_GROUP: 'phone:createMessageGroup',
|
||||
MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS: 'phone:createMessageGroupSuccess',
|
||||
MESSAGES_CREATE_MESSAGE_GROUP_FAILED: 'phone:createMessageGroupFailed',
|
||||
MESSAGES_SEND_MESSAGE: 'phone:sendMessage',
|
||||
MESSAGES_SEND_MESSAGE_SUCCESS: 'phone:sendMessageSuccess',
|
||||
MESSAGES_SEND_MESSAGE_FAILED: 'phone:sendMessageFailed',
|
||||
|
||||
+6
-1
@@ -1292,6 +1292,11 @@
|
||||
dependencies:
|
||||
source-map "^0.6.1"
|
||||
|
||||
"@types/uuid@^8.3.0":
|
||||
version "8.3.0"
|
||||
resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-8.3.0.tgz#215c231dff736d5ba92410e6d602050cce7e273f"
|
||||
integrity sha512-eQ9qFW/fhfGJF8WKHGEHZEyVWfZxrT+6CLIJGBcZPfxUh/+BnEj+UCGYMlr9qZuX/2AltsvwrGqp0LhEW8D0zQ==
|
||||
|
||||
"@types/webpack-sources@*":
|
||||
version "2.0.0"
|
||||
resolved "https://registry.yarnpkg.com/@types/webpack-sources/-/webpack-sources-2.0.0.tgz#08216ab9be2be2e1499beaebc4d469cec81e82a7"
|
||||
@@ -6872,7 +6877,7 @@ uuid@^3.3.2:
|
||||
resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee"
|
||||
integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==
|
||||
|
||||
uuid@^8.3.0:
|
||||
uuid@^8.3.0, uuid@^8.3.1:
|
||||
version "8.3.1"
|
||||
resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.1.tgz#2ba2e6ca000da60fce5a196954ab241131e05a31"
|
||||
integrity sha512-FOmRr+FmWEIG8uhZv6C2bTgEVXsHk08kE7mPlrBbEe+c3r9pjceVPgupIfNIhc4yx55H69OXANrUaSuu9eInKg==
|
||||
|
||||
Reference in new issue
Block a user