From 681ce16912ce3fd61e95453020d801c8a188fa0d Mon Sep 17 00:00:00 2001 From: erik-sn Date: Fri, 20 Nov 2020 18:14:07 -0500 Subject: [PATCH] working groups & messages --- .../contacts/components/modal/InfoModal.tsx | 2 +- .../apps/messages/components/MessagesApp.tsx | 2 + .../buttons/NewMessageGroupButton.tsx | 7 +- .../messages/components/form/MessageInput.tsx | 46 +++-- .../components/form/NewMessageGroupForm.tsx | 44 ++++ .../messages/components/form/form.styles.ts | 10 +- .../messages/components/list/MessagesList.tsx | 19 +- .../components/modal/Conversation.tsx | 33 +++ .../components/modal/MessageGroupModal.tsx | 25 +++ .../components/modal/MessageModal.tsx | 60 +++--- .../messages/components/modal/modal.styles.ts | 15 +- phone/src/apps/messages/hooks/state.ts | 12 +- .../apps/messages/hooks/useConversation.ts | 7 - .../apps/messages/hooks/useMessageService.ts | 5 +- phone/src/apps/messages/hooks/useMessages.ts | 19 +- phone/src/apps/messages/hooks/useModals.ts | 16 ++ phone/src/apps/notes/modal/NoteModal.tsx | 2 +- phone/src/common/interfaces/messages.ts | 16 +- phone/src/locale/en.json | 4 +- resources/client/cl_messages.ts | 66 ++++-- resources/package.json | 4 +- resources/server/db.ts | 18 ++ resources/server/sv_messages.ts | 193 +++++++++++++----- resources/utils/events.ts | 6 + resources/yarn.lock | 7 +- 25 files changed, 476 insertions(+), 162 deletions(-) create mode 100644 phone/src/apps/messages/components/form/NewMessageGroupForm.tsx create mode 100644 phone/src/apps/messages/components/modal/Conversation.tsx create mode 100644 phone/src/apps/messages/components/modal/MessageGroupModal.tsx delete mode 100644 phone/src/apps/messages/hooks/useConversation.ts create mode 100644 phone/src/apps/messages/hooks/useModals.ts diff --git a/phone/src/apps/contacts/components/modal/InfoModal.tsx b/phone/src/apps/contacts/components/modal/InfoModal.tsx index 07456b3..8da0a68 100644 --- a/phone/src/apps/contacts/components/modal/InfoModal.tsx +++ b/phone/src/apps/contacts/components/modal/InfoModal.tsx @@ -61,7 +61,7 @@ export const InfoModal = () => { className={showContactModal ? classes.modalRoot : classes.modalHide} >
diff --git a/phone/src/apps/messages/components/MessagesApp.tsx b/phone/src/apps/messages/components/MessagesApp.tsx index 0dd8d8f..d98026f 100644 --- a/phone/src/apps/messages/components/MessagesApp.tsx +++ b/phone/src/apps/messages/components/MessagesApp.tsx @@ -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 = () => { + diff --git a/phone/src/apps/messages/components/buttons/NewMessageGroupButton.tsx b/phone/src/apps/messages/components/buttons/NewMessageGroupButton.tsx index ab21f03..edd4443 100644 --- a/phone/src/apps/messages/components/buttons/NewMessageGroupButton.tsx +++ b/phone/src/apps/messages/components/buttons/NewMessageGroupButton.tsx @@ -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 (
- +
diff --git a/phone/src/apps/messages/components/form/MessageInput.tsx b/phone/src/apps/messages/components/form/MessageInput.tsx index 227f8bf..18e57ff 100644 --- a/phone/src/apps/messages/components/form/MessageInput.tsx +++ b/phone/src/apps/messages/components/form/MessageInput.tsx @@ -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 ( - - setMessage(e.target.value)} - placeholder="Message..." - className={classes.input} - inputProps={{ - className: classes.messagesInput - }} - /> - + +
+ setMessage(e.target.value)} + placeholder={t("APPS_MESSAGES_NEW_MESSAGE")} + className={classes.input} + inputProps={{ + className: classes.messagesInput + }} + /> + +
) } + +export default MessageInput; \ No newline at end of file diff --git a/phone/src/apps/messages/components/form/NewMessageGroupForm.tsx b/phone/src/apps/messages/components/form/NewMessageGroupForm.tsx new file mode 100644 index 0000000..ef78335 --- /dev/null +++ b/phone/src/apps/messages/components/form/NewMessageGroupForm.tsx @@ -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 ( +
+ setParticipants(e.target.value)} + placeholder={t("APPS_MESSAGES_NEW_MESSAGE_GROUP")} + className={classes.input} + inputProps={{ + className: classes.messagesInput + }} + /> + +
+ ) +} + +export default NewMessageGroupForm; diff --git a/phone/src/apps/messages/components/form/form.styles.ts b/phone/src/apps/messages/components/form/form.styles.ts index 1951d71..fb4591f 100644 --- a/phone/src/apps/messages/components/form/form.styles.ts +++ b/phone/src/apps/messages/components/form/form.styles.ts @@ -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%', }, diff --git a/phone/src/apps/messages/components/list/MessagesList.tsx b/phone/src/apps/messages/components/list/MessagesList.tsx index 09a7720..e4f3307 100644 --- a/phone/src/apps/messages/components/list/MessagesList.tsx +++ b/phone/src/apps/messages/components/list/MessagesList.tsx @@ -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 ( - {messages.map((messageGroup) => ( + {messageGroups.map((messageGroup) => ( setActiveMessageGroupId(messageGroup.groupId)} + onClick={handleClick(messageGroup)} divider button > diff --git a/phone/src/apps/messages/components/modal/Conversation.tsx b/phone/src/apps/messages/components/modal/Conversation.tsx new file mode 100644 index 0000000..f085ebd --- /dev/null +++ b/phone/src/apps/messages/components/modal/Conversation.tsx @@ -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 ( + <> +
+ {messages.map((message) => ( +
+ + {message.message} + +
+ ))} +
+ + + ); +} + +export default Conversation; diff --git a/phone/src/apps/messages/components/modal/MessageGroupModal.tsx b/phone/src/apps/messages/components/modal/MessageGroupModal.tsx new file mode 100644 index 0000000..2af9254 --- /dev/null +++ b/phone/src/apps/messages/components/modal/MessageGroupModal.tsx @@ -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 ( + + + + + + + ) +} + +export default MessageGroupModal; diff --git a/phone/src/apps/messages/components/modal/MessageModal.tsx b/phone/src/apps/messages/components/modal/MessageModal.tsx index f417c6d..3e65be2 100644 --- a/phone/src/apps/messages/components/modal/MessageModal.tsx +++ b/phone/src/apps/messages/components/modal/MessageModal.tsx @@ -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 ( - - -
- {activeMessages.map((message) => ( -
- - {message.message} - -
- ))} -
- + + + + + {activeMessageGroup ? activeMessageGroup.groupDisplay : ''} + + + {messages ? ( + + ) :

LOADING

}
) diff --git a/phone/src/apps/messages/components/modal/modal.styles.ts b/phone/src/apps/messages/components/modal/modal.styles.ts index b796eb5..129ab9a 100644 --- a/phone/src/apps/messages/components/modal/modal.styles.ts +++ b/phone/src/apps/messages/components/modal/modal.styles.ts @@ -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, diff --git a/phone/src/apps/messages/hooks/state.ts b/phone/src/apps/messages/hooks/state.ts index 363e5cc..c38b542 100644 --- a/phone/src/apps/messages/hooks/state.ts +++ b/phone/src/apps/messages/hooks/state.ts @@ -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 + }), } \ No newline at end of file diff --git a/phone/src/apps/messages/hooks/useConversation.ts b/phone/src/apps/messages/hooks/useConversation.ts deleted file mode 100644 index 6edac57..0000000 --- a/phone/src/apps/messages/hooks/useConversation.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { useRecoilValue } from 'recoil'; -import { messageState } from './state'; - -export const useConversation = (): any => { - const conversation = useRecoilValue(messageState.conversation); - return { conversation } -} \ No newline at end of file diff --git a/phone/src/apps/messages/hooks/useMessageService.ts b/phone/src/apps/messages/hooks/useMessageService.ts index 492a25d..e834f64 100644 --- a/phone/src/apps/messages/hooks/useMessageService.ts +++ b/phone/src/apps/messages/hooks/useMessageService.ts @@ -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); } \ No newline at end of file diff --git a/phone/src/apps/messages/hooks/useMessages.ts b/phone/src/apps/messages/hooks/useMessages.ts index dc7e6d7..3bc9dd9 100644 --- a/phone/src/apps/messages/hooks/useMessages.ts +++ b/phone/src/apps/messages/hooks/useMessages.ts @@ -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(messageState.activeMessageGroup) - const [messages, setMessages] = useRecoilState(messageState.messages); - return { messages, setMessages, activeMessageGroupId, setActiveMessageGroupId }; +export default (): IUseMessages => { + const [messages, setMessages] = useRecoilState(messageState.messages); + const messageGroups = useRecoilValue(messageState.messageGroups) + return { messages, setMessages, messageGroups }; } \ No newline at end of file diff --git a/phone/src/apps/messages/hooks/useModals.ts b/phone/src/apps/messages/hooks/useModals.ts new file mode 100644 index 0000000..08becd1 --- /dev/null +++ b/phone/src/apps/messages/hooks/useModals.ts @@ -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(messageState.activeMessageGroup) + const [ showNewMessageGroup, setShowNewMessageGroup ] = useRecoilState(messageState.showNewMessageGroup) + return { activeMessageGroup, setActiveMessageGroup, showNewMessageGroup, setShowNewMessageGroup }; +} \ No newline at end of file diff --git a/phone/src/apps/notes/modal/NoteModal.tsx b/phone/src/apps/notes/modal/NoteModal.tsx index 141d752..f5d19ba 100644 --- a/phone/src/apps/notes/modal/NoteModal.tsx +++ b/phone/src/apps/notes/modal/NoteModal.tsx @@ -61,7 +61,7 @@ export const NoteModal = () => {
{ - 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); -}); +}); \ No newline at end of file diff --git a/resources/package.json b/resources/package.json index 429463f..2ea3490 100644 --- a/resources/package.json +++ b/resources/package.json @@ -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", diff --git a/resources/server/db.ts b/resources/server/db.ts index 8fc28f1..82d5c5a 100644 --- a/resources/server/db.ts +++ b/resources/server/db.ts @@ -64,3 +64,21 @@ export function generateConnectionPool() { } export const pool = generateConnectionPool(); + + +export async function withTransaction(queries: Promise[]): Promise { + 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) + } +} \ No newline at end of file diff --git a/resources/server/sv_messages.ts b/resources/server/sv_messages.ts index c67a882..eb87b7b 100644 --- a/resources/server/sv_messages.ts +++ b/resources/server/sv_messages.ts @@ -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 { @@ -32,79 +34,153 @@ async function createMessage(userIdentifier: string, groupId: string, message: s return results; } -async function getMessages(userIdentifier: string): Promise { +async function getMessageGroups(userIdentifier: string): Promise { 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 results; +} + +async function getMessages(userIdentifier: string, groupId: string): Promise { + 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 = 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 { - const messages = await getMessages(useIdentifier); - return messages.reduce((mapping: GroupMapping, message: Message) => { - const groupId = message.group_id; +async function getConsolidatedMessageGroups(useIdentifier: string): Promise { + 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 { - const groupMapping = await groupMessagesByGroup(userIdentifier); - const groups = Object.keys(groupMapping); - return groups.map(group => { +async function getFormattedMessageGroups(userIdentifier: string): Promise { + 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 { + 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 { + const query = ` + SELECT identifier + FROM users + WHERE REGEXP_REPLACE(phone_number, '[^0-9]', '') = ? + LIMIT 1 + `; + const [results] = await pool.query(query, [ phoneNumber]); + const identifiers = results; + return identifiers[0]['identifier'] +} + +async function createMessageGroupsFromPhoneNumbers(userIdentifier: string, phoneNumbers: string[]): Promise { + 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()); + } +}); \ No newline at end of file diff --git a/resources/utils/events.ts b/resources/utils/events.ts index e3572ac..e71dd48 100644 --- a/resources/utils/events.ts +++ b/resources/utils/events.ts @@ -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', diff --git a/resources/yarn.lock b/resources/yarn.lock index 4575cff..34b037b 100644 --- a/resources/yarn.lock +++ b/resources/yarn.lock @@ -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==