initial working version

This commit is contained in:
erik-sn committed 2020-11-19 13:41:23 -05:00
1 parent b87baeb12e
commit 956070951a
23 files changed
+260 -107

No files matched your search

@@ -5,15 +5,18 @@ import { AppContent } from "../../../ui/components/AppContent";
import { useApp } from "../../../os/apps/hooks/useApps"; import { useApp } from "../../../os/apps/hooks/useApps";
import MessagesList from "./list/MessagesList"; import MessagesList from "./list/MessagesList";
import { MessageModal } from "./modal/MessageModal"; import { MessageModal } from "./modal/MessageModal";
import NewMessageGroupButton from "./buttons/NewMessageGroupButton";
import './messages.css'
export const MessagesApp = () => { export const MessagesApp = () => {
const messages = useApp("MESSAGES"); const messages = useApp("MESSAGES");
return ( return (
<AppWrapper> <AppWrapper id="messages-app">
<AppTitle app={messages} /> <AppTitle app={messages} />
<MessageModal /> <MessageModal />
<AppContent> <AppContent>
<MessagesList /> <MessagesList />
<NewMessageGroupButton />
</AppContent> </AppContent>
</AppWrapper> </AppWrapper>
); );
@@ -0,0 +1,27 @@
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";
const useStyles = makeStyles(() => ({
root: {
position: "absolute",
bottom: "25px",
right: "15px",
}
}));
export function NewMessageGroupButton() {
const classes = useStyles();
return (
<div className={classes.root}>
<Fab color="primary">
<AddIcon />
</Fab>
</div>
);
}
export default NewMessageGroupButton;
@@ -4,16 +4,10 @@ import useStyles from './form.styles';
import SendIcon from '@material-ui/icons/Send'; import SendIcon from '@material-ui/icons/Send';
import Nui from '../../../../os/nui-events/utils/Nui'; import Nui from '../../../../os/nui-events/utils/Nui';
export const MessageInput = ({ name }) => { export const MessageInput = ({ messageGroup }) => {
const classes = useStyles(); const classes = useStyles();
const [ message, setMessage ] = useState('') const [ message, setMessage ] = useState('')
Nui.send('phone:sendMessage', {
name,
message
})
return ( return (
<Paper <Paper
className={classes.form} className={classes.form}
@@ -1,32 +1,27 @@
import { List, ListItem, ListItemText, ListItemAvatar, Avatar as MuiAvatar } from '@material-ui/core';
import React from 'react' import React from 'react'
import { useConversation } from '../../hooks/useConversation'; import { List, ListItem, ListItemText, ListItemAvatar, Avatar as MuiAvatar } from '@material-ui/core';
import { useFilter } from '../../hooks/useFilter';
import { useMessageModal } from '../../hooks/useMessageModal';
import { useMessages } from '../../hooks/useMessages'; import { useMessages } from '../../hooks/useMessages';
import useStyles from './list.styles';
const MessagesList = (): any => { const MessagesList = (): any => {
const { setMessageModal } = useMessageModal() const classes = useStyles();
const { conversation } = useConversation(); const { messages, setActiveMessageGroupId } = useMessages();
const { setMessageFilter } = useFilter();
const handleConversation = (convo) => {
setMessageModal(true)
setMessageFilter(convo)
}
if (!conversation) return <p>loading</p>
return ( return (
<List> <List className={classes.root}>
{conversation.map((convo) => ( {messages.map((messageGroup) => (
<ListItem divider button key={convo.name} onClick={() => handleConversation(convo)}> <ListItem
key={messageGroup.channelId}
onClick={() => setActiveMessageGroupId(messageGroup.channelId)}
divider
button
>
<ListItemAvatar> <ListItemAvatar>
<MuiAvatar /> <MuiAvatar />
</ListItemAvatar> </ListItemAvatar>
<ListItemText> <ListItemText>
{convo.name} {messageGroup.channelDisplay}
</ListItemText> </ListItemText>
</ListItem> </ListItem>
))} ))}
@@ -1,6 +1,10 @@
import { makeStyles, fade } from '@material-ui/core'; import { makeStyles, fade } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({ const useStyles = makeStyles((theme) => ({
root: {
height: '100%',
overflowY: 'auto',
},
bg: { bg: {
display: "flex", display: "flex",
height: 60, height: 60,
@@ -0,0 +1,4 @@
/* override the FAB (action buttons) background when selected */
#messages-app .MuiFab-primary {
background: #ffa000 !important;
}
@@ -1,36 +1,49 @@
import React, { useState } from 'react' import React, { useEffect } from 'react'
import { Slide, Paper, Button } from '@material-ui/core' import { Slide, Paper, Button } from '@material-ui/core'
import useStyles from './modal.styles'; import useStyles from './modal.styles';
import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import { useMessages } from '../../hooks/useMessages'; import { useMessages } from '../../hooks/useMessages';
import { MessageInput } from '../form/MessageInput'; import { MessageInput } from '../form/MessageInput';
import { useMessageModal } from '../../hooks/useMessageModal';
const LIST_ID = 'message-modal-list';
export const MessageModal = () => { export const MessageModal = () => {
const classes = useStyles(); const classes = useStyles();
const {messages, setMessages} = useMessages(); const { messages, activeMessageGroupId, setActiveMessageGroupId } = useMessages();
const {messageModal, setMessageModal} = useMessageModal() 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 (element) {
element.scrollTop = element.scrollHeight;
}
}
}, [activeMessageGroupId]);
const closeModal = () => { const closeModal = () => setActiveMessageGroupId(null);
setMessageModal(false) const isOpen = activeMessageGroupId !== null;
} const activeMessageGroup = messages.find(messageGroup => messageGroup.channelId === activeMessageGroupId);
const activeMessages = activeMessageGroup ? activeMessageGroup.messages : [];
return ( return (
<Slide direction="left" in={messageModal}> <Slide direction="left" in={isOpen}>
<Paper className={messageModal ? classes.modalRoot : classes.modalHide}> <Paper className={activeMessageGroupId ? classes.modalRoot : classes.modalHide}>
<Button onClick={closeModal}><ArrowBackIcon /></Button> <Button onClick={closeModal}><ArrowBackIcon /></Button>
{messages.map((message) => ( <div id={LIST_ID} className={classes.messageList}>
<> {activeMessages.map((message) => (
<div className={classes.messageContainer}> <>
<Paper className={message.sender == 'chip' ? classes.sourceSms : classes.sms} variant="outlined"> <div className={classes.messageContainer}>
<p>{message.sms}</p> <Paper className={message.isMine ? classes.sourceSms : classes.sms} variant="outlined">
</Paper> {message.content}
</div> </Paper>
</> </div>
))} </>
<MessageInput key={messages.id} {...messages}/> ))}
</div>
<MessageInput messageGroup={activeMessageGroupId} />
</Paper> </Paper>
</Slide> </Slide>
) )
@@ -10,27 +10,31 @@ const useStyles = makeStyles((theme) => ({
modalHide: { modalHide: {
display: 'none' display: 'none'
}, },
messageList: {
height: '90%',
overflowY: 'auto',
paddingBottom: '25px',
},
messageContainer: { messageContainer: {
marginTop: 25, marginTop: 25,
width: '100%' width: '100%'
}, },
sourceSms: { sourceSms: {
float: 'right', float: 'right',
marginBottom: 20,
margin: 10, margin: 10,
width: 200, padding: '6px 12px',
width: '80%',
background: '#0288d1', background: '#0288d1',
paddingLeft: 5 borderRadius: '20px'
}, },
sms: { sms: {
float: 'left', float: 'left',
marginBottom: 20,
margin: 10, margin: 10,
minWidth: 200, padding: '6px 12px',
maxWidth: 400, width: '80%',
background: '#ddd', background: '#ddd',
color: '#232323', color: '#232323',
paddingLeft: 5 borderRadius: '15px'
} }
})) }))
+5 -9
View File
@@ -1,17 +1,13 @@
import { atom } from 'recoil'; import { atom } from 'recoil';
export const messageState = { export const messageState = {
conversation: atom({ messages: atom({
key: 'messageConversations', key: 'messages',
default: null default: null
}), }),
messageList: atom({ activeMessageGroup: atom({
key: 'messageList', key: 'activeMessageGroup',
default: [] default: null
}),
modal: atom({
key: 'messageModal',
default: true
}), }),
filter: atom({ filter: atom({
key: 'messageFilter', key: 'messageFilter',
@@ -1,7 +0,0 @@
import { useRecoilState } from 'recoil';
import { messageState } from './state';
export const useMessageModal = () => {
const [ messageModal, setMessageModal ] = useRecoilState(messageState.modal)
return { messageModal, setMessageModal }
}
@@ -1,14 +1,10 @@
import { useSetRecoilState } from 'recoil'; import { useSetRecoilState } from 'recoil';
import { messageState } from './state'; import { messageState } from './state';
import { useMessages } from './useMessages';
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent'; import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
import { useConversation } from './useConversation';
export const useMessagesService = () => { export const useMessagesService = () => {
const setMessages = useSetRecoilState(messageState.messageList); const setMessages = useSetRecoilState(messageState.messages);
const setConversation = useSetRecoilState(messageState.conversation);
useNuiEvent('MESSAGES', 'setMessages', setMessages); useNuiEvent('MESSAGES', 'phone:fetchMessagesSuccess', setMessages);
useNuiEvent('MESSAGES', 'setConversations', setConversation);
return { useMessages, useConversation };
} }
+12 -3
View File
@@ -1,7 +1,16 @@
import { useRecoilState } from 'recoil'; import { useRecoilState } from 'recoil';
import { MessageGroup } from '../../../common/interfaces/messages';
import { messageState } from './state'; import { messageState } from './state';
export const useMessages = (): any => { interface IUseMessages {
const [messages, setMessages] = useRecoilState(messageState.messageList); messages: MessageGroup[];
return { messages, setMessages }; setMessages: any;
setActiveMessageGroupId: (id: string | null) => void;
activeMessageGroupId: null | string;
}
export const useMessages = (): IUseMessages => {
const [ activeMessageGroupId, setActiveMessageGroupId ] = useRecoilState<any>(messageState.activeMessageGroup)
const [messages, setMessages] = useRecoilState<any>(messageState.messages);
return { messages, setMessages, activeMessageGroupId, setActiveMessageGroupId };
} }
+10 -13
View File
@@ -1,24 +1,21 @@
export interface Message { export interface Message {
id?: number; id?: number;
content: string; content: string;
user_id: number; user_identifier: string;
user_name?: string; channel_id: number;
conversation_id: number;
isRead: boolean; isRead: boolean;
isMine: boolean;
avatar?: string;
phone_number?: string;
display?: string;
createdAt?: string; createdAt?: string;
updatedAt?: string; updatedAt?: string;
} }
export interface ConversationParticpant { export interface MessageGroup {
id?: number; channelId: string;
user_id: number; messages: Message[];
conversation_id: number; channelDisplay: string;
createdAt?: string;
updatedAt?: string;
}
export interface Conversation {
participants: ConversationParticpant[];
createdAt?: string; createdAt?: string;
updatedAt?: string; updatedAt?: string;
} }
+21 -1
View File
@@ -1,6 +1,26 @@
import events from '../utils/events'; import events from '../utils/events';
import { Message } from '../../phone/src/common/interfaces/messages';
import { sendMessageEvent } from '../utils/messages';
RegisterNuiCallbackType(events.MESSAGES_SEND_MESSAGE); RegisterNuiCallbackType(events.MESSAGES_SEND_MESSAGE);
on(`__cfx_nui:${events.MESSAGES_SEND_MESSAGE}`, (data: any) => { on(`__cfx_nui:${events.MESSAGES_SEND_MESSAGE}`, (data: any) => {
emitNet(events.MESSAGES_SEND_MESSAGE, data); emitNet(events.MESSAGES_SEND_MESSAGE, data);
}) })
/**
* Twitter fetch messages
*/
RegisterNuiCallbackType(events.MESSAGES_FETCH_MESSAGES);
on(`__cfx_nui:${events.MESSAGES_FETCH_MESSAGES}`, () => {
emitNet(events.MESSAGES_FETCH_MESSAGES);
});
onNet(events.MESSAGES_FETCH_MESSAGES_SUCCESS, (messages: Message[]) => {
sendMessageEvent(events.MESSAGES_FETCH_MESSAGES_SUCCESS, messages);
});
onNet(events.MESSAGES_FETCH_MESSAGES_FAILED, () => {
sendMessageEvent(events.MESSAGES_FETCH_MESSAGES_FAILED);
});
emitNet(events.MESSAGES_FETCH_MESSAGES);
+1
View File
@@ -5,6 +5,7 @@ import './cl_contacts';
import './cl_sellout'; import './cl_sellout';
import './cl_bank'; import './cl_bank';
import './cl_notes'; import './cl_notes';
import './cl_messages';
export let ESX: ESXClient = null; export let ESX: ESXClient = null;
+2 -1
View File
@@ -5,6 +5,7 @@ ALTER TABLE `users` ADD COLUMN `phone_number` VARCHAR(20) NULL DEFAULT NULL;
CREATE TABLE IF NOT EXISTS npwd_phone_contacts ( CREATE TABLE IF NOT EXISTS npwd_phone_contacts (
id int(11) NOT NULL AUTO_INCREMENT, id int(11) NOT NULL AUTO_INCREMENT,
identifier varchar(60) DEFAULT NULL, identifier varchar(60) DEFAULT NULL,
avatar varchar(512) DEFAULT NULL,
number varchar(10) DEFAULT NULL, number varchar(10) DEFAULT NULL,
display varchar(60) NOT NULL DEFAULT '', display varchar(60) NOT NULL DEFAULT '',
PRIMARY KEY (id) PRIMARY KEY (id)
@@ -13,7 +14,7 @@ ENGINE = INNODB,
AUTO_INCREMENT = 6, AUTO_INCREMENT = 6,
AVG_ROW_LENGTH = 4096, AVG_ROW_LENGTH = 4096,
CHARACTER SET utf8mb4, CHARACTER SET utf8mb4,
COLLATE utf8mb4_general_ci; COLLATE utf8mb4_0900_ai_ci;
INSERT INTO `items` (`name`, `label`, `weight`, `rare`, `can_remove`) VALUES ('phone', 'Phone', 1, 0, 1); INSERT INTO `items` (`name`, `label`, `weight`, `rare`, `can_remove`) VALUES ('phone', 'Phone', 1, 0, 1);
INSERT INTO `items` (`name`, `label`, `weight`, `rare`, `can_remove`) VALUES ('dphone', 'Destroyed Phone', 1, 0, 1); INSERT INTO `items` (`name`, `label`, `weight`, `rare`, `can_remove`) VALUES ('dphone', 'Destroyed Phone', 1, 0, 1);
+1
View File
@@ -7,6 +7,7 @@ import './sv_contacts';
import './sv_sellout'; import './sv_sellout';
import './sv_bank'; import './sv_bank';
import './sv_notes'; import './sv_notes';
import './sv_messages';
export let ESX: ESXServer = null; export let ESX: ESXServer = null;
+5 -3
View File
@@ -1,7 +1,7 @@
import { ESX, getSource } from "./server"; import { ESX } from "./server";
import { pool } from "./db"; import { pool } from "./db";
import events from "../utils/events"; import events from "../utils/events";
import { useIdentifier } from './functions' import { useIdentifier, getSource } from './functions'
interface Contacts { interface Contacts {
id?: number; id?: number;
@@ -31,7 +31,8 @@ async function addContact(
const query = const query =
"INSERT INTO npwd_phone_contacts (identifier, number, display, avatar) VALUES (?, ?, ?, ?)"; "INSERT INTO npwd_phone_contacts (identifier, number, display, avatar) VALUES (?, ?, ?, ?)";
await pool.query(query, [identifier, number, display, avatar]); const [result] = await pool.query(query, [identifier, number, display, avatar]);
console.log(result);
} }
async function updateContact(contact: Contacts, identifier: string): Promise<any> { async function updateContact(contact: Contacts, identifier: string): Promise<any> {
@@ -70,6 +71,7 @@ onNet(events.CONTACTS_ADD_CONTACT, async (number: string, display: string, avata
try { try {
const _source = (global as any).source; const _source = (global as any).source;
const _identifier = await useIdentifier() const _identifier = await useIdentifier()
console.log(number, display);
addContact(_identifier, number, display, avatar); addContact(_identifier, number, display, avatar);
emitNet(events.CONTACTS_ADD_CONTACT_SUCCESS, _source) emitNet(events.CONTACTS_ADD_CONTACT_SUCCESS, _source)
+95 -8
View File
@@ -1,12 +1,99 @@
import events from '../utils/events'; import events from '../utils/events';
import { Message } from '../../phone/src/common/interfaces/messages'; import { pool } from "./db";
import { useIdentifier } from './functions'; import { Message, MessageGroup } from '../../phone/src/common/interfaces/messages';
import { getSource, useIdentifier } from './functions';
async function sendMessage(message: Message, identifier: string): Promise<any> {
interface GroupMapping {
[channelId: string]: {
messages: Message[];
updatedAt: string;
createdAt: string;
}
} }
onNet(events.MESSAGES_SEND_MESSAGE, async (message: Message) => { interface GroupMessages {
const _identifier = await useIdentifier() channelId: string;
sendMessage(message, _identifier) messages: Message[];
}) updatedAt: string;
createdAt: string;
}
async function getMessages(userIdentifier: string): Promise<Message[]> {
const query = `
SELECT
npwd_messages.*,
users.phone_number,
npwd_phone_contacts.display,
npwd_phone_contacts.avatar
FROM (
SELECT channel_id
FROM npwd_messages_groups
WHERE user_identifier = ?
) as t
LEFT OUTER JOIN npwd_messages on t.channel_id = npwd_messages.channel_id
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)
ORDER BY updatedAt ASC;
`;
const [results] = await pool.query(query, [ userIdentifier]);
const messages = <Message[]>results;
return messages.map(message => ({
...message,
isMine: message.user_identifier === userIdentifier,
createdAt: message.createdAt.toString(),
updatedAt: message.updatedAt.toString(),
}));
}
async function groupMessagesByChannel(useIdentifier: string): Promise<GroupMapping> {
const messages = await getMessages(useIdentifier);
return messages.reduce((mapping: GroupMapping, message: Message) => {
const channelId = message.channel_id;
if (channelId 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[channelId].messages = mapping[channelId].messages.concat(message);
} else {
mapping[channelId] = {
messages: [message],
updatedAt: message.updatedAt,
createdAt: message.createdAt,
}
}
return mapping;
}, {});
}
function getChannelDisplayName(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 channelMapping = await groupMessagesByChannel(userIdentifier);
const channels = Object.keys(channelMapping);
return channels.map(channel => {
console.log(getChannelDisplayName(userIdentifier, channelMapping[channel].messages))
return {
...channelMapping[channel],
channelId: channel,
channelDisplay: getChannelDisplayName(userIdentifier, channelMapping[channel].messages)
}
});
}
onNet(events.MESSAGES_FETCH_MESSAGES, async () => {
try {
const _identifier = await useIdentifier();
const messages = await getFormattedMessages(_identifier);
emitNet(events.MESSAGES_FETCH_MESSAGES_SUCCESS, getSource(), messages);
} catch (e) {
emitNet(events.MESSAGES_FETCH_MESSAGES_FAILED, getSource());
}
});
+1 -2
View File
@@ -1,7 +1,6 @@
import events from "../utils/events"; import events from "../utils/events";
import { ESX, getSource } from "./server";
import { pool } from "./db"; import { pool } from "./db";
import { useIdentifier } from "./functions"; import { useIdentifier, getSource } from "./functions";
import { Note, NoteId } from "../../phone/src/common/interfaces/notes"; import { Note, NoteId } from "../../phone/src/common/interfaces/notes";
async function addNote(identifier: string, note: Note): Promise<any> { async function addNote(identifier: string, note: Note): Promise<any> {
+1
View File
@@ -1,3 +1,4 @@
export default { export default {
TWITTER: "TWITTER", TWITTER: "TWITTER",
MESSAGES: "MESSAGES"
}; };
+3 -1
View File
@@ -55,7 +55,9 @@ export default {
//messages //messages
MESSAGES_SEND_MESSAGE: 'phone:sendMessage', MESSAGES_SEND_MESSAGE: 'phone:sendMessage',
MESSAGES_GET_MESSAGES: 'phone:getMessage', MESSAGES_FETCH_MESSAGES: 'phone:fetchMessages',
MESSAGES_FETCH_MESSAGES_SUCCESS: 'phone:fetchMessagesSuccess',
MESSAGES_FETCH_MESSAGES_FAILED: 'phone:fetchMessagesFailed',
// Notes // Notes
NOTE_ADD_NOTE: 'phone:addNote', NOTE_ADD_NOTE: 'phone:addNote',
+4
View File
@@ -13,3 +13,7 @@ function sendMessage(app: string, method: string, data: any) {
export function sendTwitterMessage(method: string, data: any = {}) { export function sendTwitterMessage(method: string, data: any = {}) {
return sendMessage(apps.TWITTER, method, data); return sendMessage(apps.TWITTER, method, data);
} }
export function sendMessageEvent(method: string, data: any = {}) {
return sendMessage(apps.MESSAGES, method, data);
}