Merge pull request #34 from Re-Ignited-Development/feature/messages

Feature/messages
This commit is contained in:
Christopher Gjelten authored and GitHub committed 2020-12-10 19:07:42 +01:00
commit 4655373832
53 files changed
+1540 -46

No files matched your search

+1 -2
View File
@@ -32,8 +32,7 @@
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.3",
"recoil": "^0.0.10",
"styled-components": "^5.1.1",
"uuid": "^8.3.0"
"styled-components": "^5.1.1"
},
"devDependencies": {
"@babel/cli": "^7.4.4",
+2
View File
@@ -20,6 +20,7 @@ import { useContactsService } from "./apps/contacts/hooks/useContactsService";
import { useTwitterService } from "./apps/twitter/hooks/useTwitterService";
import { useSelloutService } from "./apps/sellout/hooks/useSelloutService";
import { useBankService } from './apps/bank/hooks/useBankService';
import { useMessagesService } from "./apps/messages/hooks/useMessageService";
import { useNotesService } from "./apps/notes/hooks/useNotesService";
import Nui from "./os/nui-events/utils/Nui";
@@ -233,6 +234,7 @@ function Phone() {
useInitKeyboard();
useSelloutService();
useBankService();
useMessagesService()
useNotesService();
if (visibility === false) {
@@ -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} />
@@ -0,0 +1,71 @@
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Snackbar } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import useAlerts from "../hooks/useAlerts";
import Alert from "../../../ui/components/Alert";
const useStyles = makeStyles(() => ({
root: {
width: "100%",
bottom: "60px",
position: "absolute",
},
}));
const ALERT_TIMEOUT = 6000;
export default function AlertBar() {
const classes = useStyles();
const { t } = useTranslation();
const {
createMessageGroupResult,
clearCreateMessageGroupResult,
} = useAlerts();
const [severity, setSeverity] = useState<string | null>(null);
const [open, setOpen] = useState(false);
const [message, setMessage] = useState<string | null>(null);
const handleClose = () => {
setOpen(false);
clearCreateMessageGroupResult();
};
useEffect(() => {
if (!createMessageGroupResult) return;
const { error, phoneNumber, duplicate, mine } = createMessageGroupResult;
if (error && phoneNumber) {
const error = `${t("APPS_MESSAGES_INVALID_PHONE_NUMBER")}${phoneNumber}`;
setOpen(true);
setSeverity("error");
setMessage(error);
} else if (error && duplicate) {
setOpen(true);
setSeverity("error");
setMessage(t("APPS_MESSAGES_MESSAGE_GROUP_DUPLICATE"));
} else if (error && mine) {
setOpen(true);
setSeverity("error");
setMessage(t("APPS_MESSAGES_MESSAGE_GROUP_CREATE_MINE"));
} else if (error) {
setOpen(true);
setSeverity("error");
setMessage(t("APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED"));
}
}, [createMessageGroupResult, t]);
return (
<Snackbar
autoHideDuration={ALERT_TIMEOUT}
className={classes.root}
open={open}
onClose={handleClose}
>
<Alert onClose={handleClose} severity={severity}>
{message}
</Alert>
</Snackbar>
);
}
@@ -3,15 +3,25 @@ import { AppWrapper } from "../../../ui/components";
import { AppTitle } from "../../../ui/components/AppTitle";
import { AppContent } from "../../../ui/components/AppContent";
import { useApp } from "../../../os/apps/hooks/useApps";
import AlertBar from "./AlertBar";
import { MessageModal } from "./modal/MessageModal";
import MessageGroupModal from "./modal/MessageGroupModal";
import NewMessageGroupButton from "./buttons/NewMessageGroupButton";
import MessagesList from "./list/MessagesList";
import "./messages.css";
export const MessagesApp = () => {
const messages = useApp("MESSAGES");
return (
<AppWrapper>
<AppWrapper id="messages-app">
<AppTitle app={messages} />
<MessageModal />
<MessageGroupModal />
<AppContent>
<h1>Fuck off</h1>
<MessagesList />
<NewMessageGroupButton />
</AppContent>
<AlertBar />
</AppWrapper>
);
};
@@ -0,0 +1,30 @@
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Fab } from "@material-ui/core";
import AddIcon from "@material-ui/icons/Add";
import useModals from "../../hooks/useModals";
const useStyles = makeStyles(() => ({
root: {
position: "absolute",
bottom: "25px",
right: "15px",
},
}));
export function NewMessageGroupButton() {
const classes = useStyles();
const { setShowNewMessageGroup } = useModals();
const handleClick = () => setShowNewMessageGroup(true);
return (
<div className={classes.root}>
<Fab color="primary" onClick={handleClick}>
<AddIcon />
</Fab>
</div>
);
}
export default NewMessageGroupButton;
@@ -0,0 +1,52 @@
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";
interface IProps {
messageGroupId: string | undefined;
}
const MessageInput = ({ messageGroupId }: IProps) => {
const classes = useStyles();
const { t } = useTranslation();
const [message, setMessage] = useState("");
const handleSubmit = (event: FormEvent) => {
event.preventDefault();
if (message.trim()) {
// don't allow the user to submit white space
Nui.send("phone:sendMessage", {
groupId: messageGroupId,
message,
});
setMessage("");
}
};
if (!messageGroupId) return null;
return (
<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}
inputRef={(input) => input && input.focus()}
inputProps={{
className: classes.messagesInput,
}}
/>
<Button className={classes.sendButton} type="submit">
<SendIcon />
</Button>
</form>
</Paper>
);
};
export default MessageInput;
@@ -0,0 +1,75 @@
import React, { FormEvent, 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 [label, setLabel] = useState("");
// 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 isGroupChat = parts.length > 1;
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,
});
setParticipants("");
setShowNewMessageGroup(false); // close modal after submission
}
};
return (
<form className={classes.newGroupForm} onSubmit={handleSubmit}>
<TextField
value={participants}
onChange={(e) => setParticipants(e.target.value)}
placeholder={t("APPS_MESSAGES_NEW_MESSAGE_GROUP")}
className={classes.newGroupinput}
autoFocus
inputProps={{
className: classes.messagesInput,
}}
multiline
/>
{isGroupChat && (
<TextField
value={label}
onChange={(e) => setLabel(e.target.value)}
placeholder={t("APPS_MESSAGES_GROUP_CHAT_LABEL")}
className={classes.newGroupinput}
inputProps={{
className: classes.messagesInput,
}}
/>
)}
<Button
variant="contained"
className={classes.newGroupSubmitButton}
color="primary"
type="submit"
>
{t("APPS_MESSAGES_NEW_MESSAGE_GROUP_SUBMIT")}
</Button>
</form>
);
};
export default NewMessageGroupForm;
@@ -0,0 +1,38 @@
import { makeStyles } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
sendButton: {
float: "right",
},
paper: {
position: "absolute",
bottom: 0,
width: "100%",
},
form: {
display: "flex",
},
input: {
width: "100%",
margin: 10,
},
newGroupForm: {
position: "absolute",
top: 65,
display: "flex",
flexFlow: "column nowrap",
justifyContent: "flex-start",
width: "100%",
},
newGroupSubmitButton: {
margin: "15px 8px 0px 8px",
},
newGroupinput: {
margin: "0px 8px 15px 8px",
},
messagesInput: {
fontSize: 20,
},
}));
export default useStyles;
@@ -0,0 +1,34 @@
import React from "react";
import {
ListItem,
ListItemText,
ListItemAvatar,
Avatar as MuiAvatar,
} from "@material-ui/core";
import { MessageGroup } from "../../../../common/interfaces/messages";
interface IProps {
messageGroup: MessageGroup;
handleClick: (group: MessageGroup) => () => void;
}
const MessageGroupItem = ({ messageGroup, handleClick }: IProps): any => {
return (
<ListItem
key={messageGroup.groupId}
onClick={handleClick(messageGroup)}
divider
button
>
<ListItemAvatar>
<MuiAvatar src={messageGroup?.avatar} />
</ListItemAvatar>
<ListItemText>
{messageGroup.label || messageGroup.groupDisplay}
</ListItemText>
</ListItem>
);
};
export default MessageGroupItem;
@@ -0,0 +1,39 @@
import React from "react";
import { useTranslation } from "react-i18next";
import { InputBase, Paper } from "@material-ui/core";
import SearchIcon from "@material-ui/icons/Search";
import useStyles from "./list.styles";
interface IProps {
value: string;
handleChange: (
event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
) => void;
}
const MessageSearch = ({ value, handleChange }: IProps) => {
const { t } = useTranslation();
const classes = useStyles();
return (
<Paper elevation={24} variant="outlined" className={classes.bg}>
<div className={classes.search}>
<div className={classes.searchIcon}>
<SearchIcon />
</div>
<InputBase
value={value}
onChange={handleChange}
placeholder={t("APPS_MESSAGES_SEARCH_PLACEHOLDER")}
classes={{
root: classes.inputRoot,
input: classes.inputInput,
}}
inputProps={{ "aria-label": "search" }}
/>
</div>
</Paper>
);
};
export default MessageSearch;
@@ -0,0 +1,61 @@
import React, { useEffect, useState } from "react";
import { List } from "@material-ui/core";
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 MessageSearch from "./MessageSearch";
import MessageGroupItem from "./MessageGroupItem";
import useStyles from "./list.styles";
const MessagesList = (): any => {
const classes = useStyles();
const [searchValue, setSearchValue] = useState("");
const { messageGroups } = useMessages();
const { setActiveMessageGroup } = useModals();
useEffect(() => {
Nui.send("phone:fetchMessageGroups");
}, []);
if (!messageGroups) return null;
const handleClick = (messageGroup: MessageGroup) => () => {
setActiveMessageGroup(messageGroup);
Nui.send("phone:fetchMessages", { groupId: messageGroup.groupId });
};
const formattedSearch = searchValue.toLowerCase().trim();
const filteredGroups = formattedSearch
? messageGroups.filter((group) => {
const groupDisplay = group.groupDisplay.toLowerCase();
const displayIncludes = groupDisplay.includes(formattedSearch);
const label = group.label?.toLowerCase();
return label
? displayIncludes || label.includes(formattedSearch)
: displayIncludes;
})
: messageGroups;
return (
<>
<MessageSearch
value={searchValue}
handleChange={(e) => setSearchValue(e.target.value)}
/>
<List className={classes.root}>
{filteredGroups.map((messageGroup) => (
<MessageGroupItem
key={messageGroup.groupId}
messageGroup={messageGroup}
handleClick={handleClick}
/>
))}
</List>
</>
);
};
export default MessagesList;
@@ -0,0 +1,59 @@
import { makeStyles, fade } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
root: {
height: "100%",
overflowY: "auto",
},
bg: {
display: "flex",
height: 60,
justifyContent: "center",
alignItems: "center",
},
textFieldInput: {
fontSize: 20,
},
inputRoot: {
fontWeight: 400,
fontSize: 18,
},
inputInput: {
padding: theme.spacing(1, 4, 1, 4),
// vertical padding + font size from searchIcon
transition: theme.transitions.create("width"),
width: "100%",
[theme.breakpoints.up("sm")]: {
width: "13ch",
"&:focus": {
width: "20ch",
},
},
},
search: {
position: "relative",
borderRadius: theme.shape.borderRadius,
backgroundColor: fade(theme.palette.common.white, 0.25),
"&:hover": {
backgroundColor: fade(theme.palette.common.white, 0.25),
},
marginLeft: 0,
width: "100%",
[theme.breakpoints.up("sm")]: {
marginLeft: theme.spacing(1),
width: "auto",
},
},
searchIcon: {
padding: theme.spacing(0, 0.5),
height: "100%",
position: "absolute",
pointerEvents: "none",
display: "flex",
alignItems: "center",
justifyContent: "center",
},
}));
export default useStyles;
@@ -0,0 +1,23 @@
#messages-app {
position: relative;
}
/* override the FAB (action buttons) background when selected */
#messages-app .MuiFab-primary {
background: #ffa000 !important;
}
/* override the underlines of text fields */
#messages-app .Mui-focused:after {
border-bottom-color: #ffa000 !important;
}
/* override form submit button */
#messages-app .MuiButton-containedPrimary {
background-color: #ffa000 !important;
}
#messages-app .MuiSkeleton-text {
border-radius: 20px !important;
transform: none;
}
@@ -0,0 +1,11 @@
import { makeStyles } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
addMessageFab: {
position: "sticky",
bottom: theme.spacing(2),
left: theme.spacing(3),
},
}));
export default useStyles;
@@ -0,0 +1,42 @@
import React from "react";
import { Paper, Typography } from "@material-ui/core";
import { Message, MessageGroup } from "../../../../common/interfaces/messages";
import MessageInput from "../form/MessageInput";
import useStyles from "./modal.styles";
interface IProps {
activeMessageGroup: MessageGroup;
messages: Message[];
}
export const CONVERSATION_ELEMENT_ID = "message-modal-conversation";
const Conversation = ({ activeMessageGroup, 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"
>
<div>{message.message}</div>
<Typography variant="subtitle1" color="secondary">
{activeMessageGroup.isGroupChat && !message.isMine
? message.display || message.phone_number
: null}
</Typography>
</Paper>
</div>
))}
</div>
<MessageInput messageGroupId={activeMessageGroup.groupId} />
</>
);
};
export default Conversation;
@@ -0,0 +1,29 @@
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;
@@ -0,0 +1,101 @@
import React, { useEffect, useState } from "react";
import { Slide, Paper, Button, Typography } from "@material-ui/core";
import ArrowBackIcon from "@material-ui/icons/ArrowBack";
import useStyles from "./modal.styles";
import useMessages from "../../hooks/useMessages";
import useModals from "../../hooks/useModals";
import Conversation, { CONVERSATION_ELEMENT_ID } from "./Conversation";
import MessageSkeletonList from "./MessageSkeletonList";
import Nui from "../../../../os/nui-events/utils/Nui";
const LARGE_HEADER_CHARS = 30;
const MAX_HEADER_CHARS = 80;
const MINIMUM_LOAD_TIME = 750;
const MESSAGES_REFRESH_RATE = 5000;
export const MessageModal = () => {
const classes = useStyles();
const { messages, setMessages } = useMessages();
const [minimumLoadPassed, setMimimumLoadPassed] = useState(false);
const { activeMessageGroup, setActiveMessageGroup } = useModals();
const closeModal = () => {
setActiveMessageGroup(null);
setMessages(null);
setMimimumLoadPassed(false);
};
useEffect(() => {
if (!activeMessageGroup?.groupId) return;
const timeout = window.setTimeout(() => {
setMimimumLoadPassed(true);
}, MINIMUM_LOAD_TIME);
const interval = window.setInterval(() => {
if (!activeMessageGroup) return;
Nui.send("phone:fetchMessages", {
groupId: activeMessageGroup.groupId,
});
}, MESSAGES_REFRESH_RATE);
return () => {
window.clearInterval(interval);
window.clearTimeout(timeout);
};
}, [activeMessageGroup?.groupId]);
useEffect(() => {
// when we get a new message group we should scroll to the
// bottom to show the latest messages
if (activeMessageGroup) {
const element = document.getElementById(CONVERSATION_ELEMENT_ID);
if (element) {
element.scrollTop = element.scrollHeight;
}
}
}, [minimumLoadPassed, messages?.length]);
// we add a minimum (but short) load time here so that
// there isn't a quick flash of loading and immediately
// another flash to the tweets screen.
const hasLoaded = messages && minimumLoadPassed;
const isOpen = activeMessageGroup !== null;
// don't allow too many characters, it takes too much room
let header = activeMessageGroup ? activeMessageGroup.groupDisplay : "";
const truncatedHeader = `${header.slice(0, MAX_HEADER_CHARS).trim()}...`;
header =
header.length > MAX_HEADER_CHARS
? activeMessageGroup?.label || truncatedHeader
: header;
const headerClass =
header.length > LARGE_HEADER_CHARS
? classes.largeGroupDisplay
: classes.groupdisplay;
return (
<Slide direction="left" in={isOpen}>
<Paper className={isOpen ? classes.modalRoot : classes.modalHide}>
<Paper className={classes.topContainer}>
<Button onClick={closeModal}>
<ArrowBackIcon fontSize="large" />
</Button>
<Typography variant="h5" className={headerClass}>
{header}
</Typography>
</Paper>
{messages && hasLoaded ? (
<Conversation
messages={messages}
activeMessageGroup={activeMessageGroup}
/>
) : (
<MessageSkeletonList />
)}
</Paper>
</Slide>
);
};
@@ -0,0 +1,20 @@
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Skeleton from "@material-ui/lab/Skeleton";
const useStyles = makeStyles({
root: {
margin: "0px 0px 12px 8px",
},
});
export default function MessageSkeleton({ height, isMine = false }) {
const classes = useStyles();
const marginLeft = isMine ? "60px" : "8px";
return (
<div className={classes.root} style={{ marginLeft, height: `${height}px` }}>
<Skeleton variant="text" width={325} height={height} />
</div>
);
}
@@ -0,0 +1,21 @@
import React from "react";
import { List } from "../../../../ui/components/List";
import MessageSkeleton from "./MessageSkeleton";
export function MessageSkeletonList() {
return (
<List>
<MessageSkeleton height={75} />
<MessageSkeleton height={60} />
<MessageSkeleton height={90} isMine />
<MessageSkeleton height={60} />
<MessageSkeleton height={60} isMine />
<MessageSkeleton height={100} />
<MessageSkeleton height={75} isMine />
<MessageSkeleton height={50} />
</List>
);
}
export default MessageSkeletonList;
@@ -0,0 +1,59 @@
import { makeStyles } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
modalRoot: {
zIndex: 10,
position: "absolute",
height: "100%",
width: "100%",
},
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",
},
largeGroupDisplay: {
width: "300px",
paddingTop: "8px",
fontSize: "20px",
},
messageList: {
height: "90%",
overflowY: "auto",
paddingBottom: "40px",
},
messageContainer: {
marginTop: 25,
width: "100%",
},
sourceSms: {
float: "right",
margin: 10,
padding: "6px 12px",
width: "80%",
background: "#0288d1",
borderRadius: "20px",
},
sms: {
float: "left",
margin: 10,
padding: "6px 12px",
width: "80%",
background: "#ddd",
color: "#232323",
borderRadius: "15px",
},
}));
export default useStyles;
+24
View File
@@ -0,0 +1,24 @@
import { atom } from "recoil";
export const messageState = {
messageGroups: atom({
key: "messageGroups",
default: null,
}),
messages: atom({
key: "messages",
default: null,
}),
activeMessageGroup: atom({
key: "activeMessageGroup",
default: null,
}),
showNewMessageGroup: atom({
key: "showNewMessageGroup",
default: false,
}),
createMessageGroupResult: atom({
key: "createMessageGroupResult",
default: null,
}),
};
@@ -0,0 +1,21 @@
import { useRecoilState } from "recoil";
import { CreateMessageGroupResult } from "../../../common/interfaces/messages";
import { messageState } from "./state";
interface IUseAlerts {
createMessageGroupResult: CreateMessageGroupResult | null;
clearCreateMessageGroupResult: () => void;
}
export default (): IUseAlerts => {
const [
createMessageGroupResult,
setCreateMessageGroupResult,
] = useRecoilState<CreateMessageGroupResult | null>(
messageState.createMessageGroupResult
);
const clearCreateMessageGroupResult = () => setCreateMessageGroupResult(null);
return { createMessageGroupResult, clearCreateMessageGroupResult };
};
@@ -0,0 +1,26 @@
import { useSetRecoilState } from "recoil";
import { messageState } from "./state";
import { useNuiEvent } from "../../../os/nui-events/hooks/useNuiEvent";
const NOTIFICATION_TIMEOUT = 6000;
export const useMessagesService = () => {
const setMessageGroups = useSetRecoilState(messageState.messageGroups);
const setMessages = useSetRecoilState(messageState.messages);
const setCreateMessageGroupResult = useSetRecoilState(
messageState.createMessageGroupResult
);
useNuiEvent("MESSAGES", "phone:fetchMessageGroupsSuccess", setMessageGroups);
useNuiEvent("MESSAGES", "phone:fetchMessagesSuccess", setMessages);
useNuiEvent(
"MESSAGES",
"phone:createMessageGroupSuccess",
setCreateMessageGroupResult
);
useNuiEvent(
"MESSAGES",
"phone:createMessageGroupFailed",
setCreateMessageGroupResult
);
};
@@ -0,0 +1,19 @@
import { useRecoilState, useRecoilValue } from "recoil";
import { Message, MessageGroup } from "../../../common/interfaces/messages";
import { messageState } from "./state";
interface IUseMessages {
messages?: Message[] | null;
setMessages: (messages: Message[] | null) => void;
messageGroups?: MessageGroup[] | null;
}
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,26 @@
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,
};
};
+1 -1
View File
@@ -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
@@ -5,7 +5,7 @@ import { makeStyles } from "@material-ui/core/styles";
import { useProfile } from "../../hooks/useProfile";
import { useTweetStatus } from "../../hooks/useTweetStatus";
import Alert from "./Alert";
import Alert from "../../../../ui/components/Alert";
const useStyles = makeStyles((theme) => ({
root: {
+28
View File
@@ -0,0 +1,28 @@
export interface Message {
id: number;
message: string;
user_identifier: string;
phone_number: string;
display?: string;
avatar?: string;
isRead: boolean;
isMine: boolean;
updatedAt: string;
}
export interface MessageGroup {
groupId: string;
groupDisplay: string;
isGroupChat: boolean;
avatar?: string;
label?: string;
updatedAt: string;
}
export interface CreateMessageGroupResult {
error?: boolean;
phoneNumber?: string;
duplicate?: boolean;
groupId?: string;
mine?: boolean;
}
+10 -1
View File
@@ -51,7 +51,16 @@
"APPS_CONTACT_FORM_NAME": "Name",
"APPS_CONTACT_FORM_NUMBER": "Number",
"APPS_CONTACT_FORM_AVATAR": "Avatar URL"
"APPS_CONTACT_FORM_AVATAR": "Avatar URL",
"APPS_MESSAGES_SEARCH_PLACEHOLDER": "Search messages...",
"APPS_MESSAGES_NEW_MESSAGE": "Message...",
"APPS_MESSAGES_NEW_MESSAGE_GROUP": "Phone numbers...",
"APPS_MESSAGES_GROUP_CHAT_LABEL": "Group chat label...",
"APPS_MESSAGES_NEW_MESSAGE_GROUP_SUBMIT": "Submit",
"APPS_MESSAGES_INVALID_PHONE_NUMBER": "Invalid phone number: ",
"APPS_MESSAGES_MESSAGE_GROUP_DUPLICATE": "This message group already exists",
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED": "Failed to create message group",
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_MINE": "You cannot add yourself!"
}
}
+4 -3
View File
@@ -1,3 +1,4 @@
import { useEffect, useRef } from "react";
import { eventNameFactory } from "../utils/nuiUtils";
@@ -7,7 +8,7 @@ interface IOptions {
once?: boolean;
}
export const useNuiEvent = (app, method, handler, options: IOptions = {}) => {
export const useNuiEvent = (app: any, method: any, handler: any, options: IOptions = {}) => {
const savedHandler: any = useRef();
const { capture, passive, once } = options;
@@ -17,7 +18,7 @@ export const useNuiEvent = (app, method, handler, options: IOptions = {}) => {
useEffect(() => {
const eventName = eventNameFactory(app, method);
const eventListener = (event) => {
const eventListener = (event: any ) => {
if (savedHandler.current && savedHandler.current.call) {
const { data } = event;
console.log(eventName, data);
@@ -28,4 +29,4 @@ export const useNuiEvent = (app, method, handler, options: IOptions = {}) => {
window.addEventListener(eventName, eventListener, opts);
return () => window.removeEventListener(eventName, eventListener, opts);
}, [app, method, capture, passive, once]);
};
};
@@ -9,7 +9,7 @@ interface IOptions {
export const useNuiService = (options: IOptions = {}) => {
const { capture, passive, once } = options;
const eventListener = (event) => {
const eventListener = (event: any) => {
const { app, method, data } = event.data;
if (app && method && data !== undefined) {
window.dispatchEvent(
@@ -24,4 +24,4 @@ export const useNuiService = (options: IOptions = {}) => {
window.addEventListener("message", eventListener, opts);
return () => window.removeEventListener("message", eventListener, opts);
}, [capture, passive, once]);
};
};
+3 -7
View File
@@ -1,17 +1,13 @@
// eslint-disable-next-line
export default {
async send(event, data = {}) {
// /// #if DEBUG
//return new Promise(resolve => setTimeout(resolve, 100));
// /// #endif
async send(event: any, data = {}) {
/* eslint-disable no-unreachable */
return fetch(`http://new-phone-who-dis/${event}`, {
method: "post",
headers: {
"Content-type": "application/json; charset=UTF-8",
"Content-Type": "application/json; charset=UTF-8",
},
body: JSON.stringify(data),
});
/* eslint-enable no-unreachable */
},
};
+2 -2
View File
@@ -1,2 +1,2 @@
export const eventNameFactory = (app, method) => `${app}:${method}`;
export const eventNameMethod = (name) => name.split(":")[1] || null;
export const eventNameFactory = (app: any, method: any) => `${app}:${method}`;
export const eventNameMethod = (name: any) => name.split(":")[1] || null;
-5
View File
@@ -11820,11 +11820,6 @@ uuid@^3.3.2, uuid@^3.4.0:
resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee"
integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==
uuid@^8.3.0:
version "8.3.1"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.1.tgz#2ba2e6ca000da60fce5a196954ab241131e05a31"
integrity sha512-FOmRr+FmWEIG8uhZv6C2bTgEVXsHk08kE7mPlrBbEe+c3r9pjceVPgupIfNIhc4yx55H69OXANrUaSuu9eInKg==
v8-compile-cache@^2.0.3, v8-compile-cache@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.1.1.tgz#54bc3cdd43317bca91e35dcaf305b1a7237de745"
+77
View File
@@ -0,0 +1,77 @@
import events from '../utils/events';
import { Message, MessageGroup } from '../../phone/src/common/interfaces/messages';
import { sendMessageEvent } from '../utils/messages';
/**
* Messages get message groups
*/
RegisterNuiCallbackType(events.MESSAGES_FETCH_MESSAGE_GROUPS);
on(`__cfx_nui:${events.MESSAGES_FETCH_MESSAGE_GROUPS}`, (): void => {
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS);
});
onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS, (messageGroups: MessageGroup[]): void => {
sendMessageEvent(events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS, messageGroups);
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS);
});
onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED, () => {
sendMessageEvent(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED);
});
// fetch message groups on client launch
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS);
/**
* Messages create message group
*/
RegisterNuiCallbackType(events.MESSAGES_CREATE_MESSAGE_GROUP);
on(`__cfx_nui:${events.MESSAGES_CREATE_MESSAGE_GROUP}`, ({ phoneNumbers, label }: any): void => {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP, phoneNumbers, label);
});
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, (result: any): void => {
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, result);
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS);
});
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, (result: any): void => {
sendMessageEvent(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, result);
});
/**
* 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, (): void => {
sendMessageEvent(events.MESSAGES_FETCH_MESSAGES_FAILED);
});
/**
* Messages send message
*/
RegisterNuiCallbackType(events.MESSAGES_SEND_MESSAGE);
on(`__cfx_nui:${events.MESSAGES_SEND_MESSAGE}`, (data: any) => {
emitNet(events.MESSAGES_SEND_MESSAGE, data.groupId, data.message);
});
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);
});
+1
View File
@@ -5,6 +5,7 @@ import './cl_contacts';
import './cl_sellout';
import './cl_bank';
import './cl_notes';
import './cl_messages';
export let ESX: ESXClient = null;
+53 -7
View File
@@ -1,10 +1,13 @@
-- comment this out if your server has a different table/location for phone_number
-- or if it already exists in the users table
ALTER TABLE `users` ADD COLUMN `phone_number` VARCHAR(20) NULL DEFAULT NULL;
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);
CREATE TABLE IF NOT EXISTS npwd_phone_contacts (
id int(11) NOT NULL AUTO_INCREMENT,
identifier varchar(60) DEFAULT NULL,
avatar varchar(512) DEFAULT NULL,
number varchar(10) DEFAULT NULL,
display varchar(60) NOT NULL DEFAULT '',
PRIMARY KEY (id)
@@ -13,10 +16,7 @@ ENGINE = INNODB,
AUTO_INCREMENT = 6,
AVG_ROW_LENGTH = 4096,
CHARACTER SET utf8mb4,
COLLATE utf8mb4_general_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 ('dphone', 'Destroyed Phone', 1, 0, 1);
COLLATE utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `npwd_twitter_tweets` (
`id` int NOT NULL AUTO_INCREMENT,
@@ -28,7 +28,7 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_tweets` (
`visible` tinyint NOT NULL DEFAULT '1',
`images` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=190 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
) ENGINE=InnoDB AUTO_INCREMENT=190 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `npwd_twitter_profiles` (
@@ -43,7 +43,7 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_profiles` (
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `profile_name_UNIQUE` (`profile_name`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `npwd_twitter_likes` (
`id` int NOT NULL AUTO_INCREMENT,
@@ -71,7 +71,7 @@ AVG_ROW_LENGTH = 4096,
CHARACTER SET utf8mb4,
COLLATE utf8mb4_general_ci;
CREATE TABLE npwd_sellout_listings (
CREATE TABLE IF NOT EXISTS npwd_sellout_listings (
id int(11) NOT NULL AUTO_INCREMENT,
identifier varchar(255) DEFAULT NULL,
name varchar(50) DEFAULT NULL,
@@ -98,3 +98,49 @@ CREATE TABLE IF NOT EXISTS `npwd_twitter_reports` (
CONSTRAINT `report_profile` FOREIGN KEY (`profile_id`) REFERENCES `npwd_twitter_profiles` (`id`),
CONSTRAINT `report_tweet` FOREIGN KEY (`tweet_id`) REFERENCES `npwd_twitter_tweets` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `npwd_messages_groups` (
`id` int NOT NULL AUTO_INCREMENT,
`user_identifier` varchar(40) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`group_id` varchar(60) NOT NULL,
`participant_identifier` varchar(40) NOT NULL,
`label` varchar(60) DEFAULT '',
PRIMARY KEY (`id`),
KEY `npwd_messages_groups_group_id` (`group_id`),
KEY `npwd_messages_groups_user_identifier_idx` (`user_identifier`),
KEY `npwd_messages_groups_participant_identifier_idx` (`participant_identifier`),
CONSTRAINT `npwd_messages_groups_participant_identifier` FOREIGN KEY (`participant_identifier`) REFERENCES `users` (`identifier`),
CONSTRAINT `npwd_messages_groups_user_identifier` FOREIGN KEY (`user_identifier`) REFERENCES `users` (`identifier`)
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `npwd_messages_labels` (
`id` int NOT NULL AUTO_INCREMENT,
`user_identifier` varchar(40) NOT NULL,
`label` varchar(60) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`group_id` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
KEY `npwd_messages_labels_group_id_idx` (`group_id`),
KEY `npwd_messages_labels_group_id_idx1` (`user_identifier`),
CONSTRAINT `npwd_messages_labels_group_id` FOREIGN KEY (`group_id`) REFERENCES `npwd_messages_groups` (`group_id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE IF NOT EXISTS `npwd_messages` (
`id` int NOT NULL AUTO_INCREMENT,
`message` varchar(512) NOT NULL,
`user_identifier` varchar(40) NOT NULL,
`group_id` varchar(60) NOT NULL,
`isRead` tinyint NOT NULL DEFAULT '0',
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`visible` tinyint NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `messages_identifier_idx` (`user_identifier`),
KEY `npwd_messages_group_id_idx` (`group_id`),
CONSTRAINT `npwd_messages_group_id` FOREIGN KEY (`group_id`) REFERENCES `npwd_messages_groups` (`group_id`),
CONSTRAINT `npwd_messages_user_identifier` FOREIGN KEY (`user_identifier`) REFERENCES `users` (`identifier`)
) ENGINE=InnoDB AUTO_INCREMENT=120 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+2
View File
@@ -21,12 +21,14 @@
"connection-string-parser": "^1.0.3",
"fivem-esx-js": "^0.1.12",
"fivem-js": "^1.3.1",
"md5": "^2.3.0",
"mysql2": "^2.2.5"
},
"devDependencies": {
"@babel/preset-env": "^7.12.1",
"@babel/preset-typescript": "^7.12.1",
"@types/jest": "^26.0.14",
"@types/md5": "^2.2.1",
"@typescript-eslint/eslint-plugin": "^3.8.0",
"@typescript-eslint/parser": "^4.4.0",
"eslint": "^7.6.0",
+18
View File
@@ -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)
}
}
+4 -1
View File
@@ -1,5 +1,5 @@
import { pool } from './db';
import { ESX, getSource } from './server';
import { ESX } from "./server";
interface IPhoneNumber {
phone_number: string;
@@ -16,7 +16,10 @@ export async function usePhoneNumber(identifier: string): Promise<string> {
return phoneNumber[0].phone_number;
}
export const getSource = () => parseInt(source);
export async function useIdentifier(): Promise<string> {
return ESX.GetPlayerFromId(getSource()).getIdentifier();
const identifier = await ESX.GetPlayerFromId(getSource()).getIdentifier()
return identifier;
}
+1 -1
View File
@@ -7,9 +7,9 @@ import './sv_contacts';
import './sv_sellout';
import './sv_bank';
import './sv_notes';
import './sv_messages';
export let ESX: ESXServer = null;
emit("esx:getSharedObject", (obj: ESXServer) => (ESX = obj));
export const getSource = () => parseInt(source);
+2 -1
View File
@@ -1,5 +1,6 @@
import events from '../utils/events';
import { ESX, getSource } from './server';
import { ESX } from './server';
import { getSource } from "./functions";
import { pool } from './db';
import { Transfer, Credentials } from '../../phone/src/common/interfaces/bank';
import { useIdentifier } from './functions';
+3 -3
View File
@@ -1,7 +1,7 @@
import { ESX, getSource } from "./server";
import { ESX } from "./server";
import { pool } from "./db";
import events from "../utils/events";
import { useIdentifier } from './functions'
import { useIdentifier, getSource } from './functions'
interface Contacts {
id?: number;
@@ -31,7 +31,7 @@ async function addContact(
const query =
"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]);
}
async function updateContact(contact: Contacts, identifier: string): Promise<any> {
+379
View File
@@ -0,0 +1,379 @@
import md5 from 'md5';
import events from '../utils/events';
import { Message, MessageGroup, CreateMessageGroupResult } from '../../phone/src/common/interfaces/messages';
import { pool, withTransaction } from "./db";
import { getSource, useIdentifier } from './functions';
/**
* Used for the raw npwd_messages_groups row responses
*/
interface UnformattedMessageGroup {
group_id: string;
user_identifier: string;
participant_identifier: string;
phone_number: string;
label?: string;
avatar?: string;
display?: string;
updatedAt: string;
}
/**
* Used to help consolidate raw npwd_messages_groups rows into
* a mapping of a single message group
*/
interface MessageGroupMapping {
[groupId: string]: {
user_identifier: string;
participants: string[];
label?: string;
avatar?: string;
updatedAt: string;
}
}
/**
* Create a message in the database
* @param userIdentifier - identifier of the user creating this message
* @param groupId - the message group ID to attach this message to
* @param message - content of the message
*/
async function createMessage(userIdentifier: string, groupId: string, message: string): Promise<any> {
const query = `
INSERT INTO npwd_messages
(user_identifier, message, group_id)
VALUES (?, ?, ?)
`;
const [results] = await pool.query(query, [
userIdentifier,
message,
groupId,
]);
return results;
}
/**
* Retrieve all message groups associated with a user. This will
* populate the list of message groups on the UI
* @param userIdentifier - identifier of the user to get message groups for
*/
async function getMessageGroups(userIdentifier: string): Promise<UnformattedMessageGroup[]> {
const query = `
SELECT
npwd_messages_groups.group_id,
npwd_messages_groups.participant_identifier,
npwd_messages_groups.user_identifier,
npwd_messages_labels.label,
users.phone_number,
npwd_phone_contacts.avatar,
npwd_phone_contacts.display
FROM (
SELECT group_id
FROM npwd_messages_groups
WHERE npwd_messages_groups.participant_identifier = ?
) as t
LEFT OUTER JOIN npwd_messages_groups on npwd_messages_groups.group_id = t.group_id
LEFT OUTER JOIN users on users.identifier = npwd_messages_groups.participant_identifier
LEFT OUTER JOIN npwd_messages_labels on npwd_messages_labels.group_id = npwd_messages_groups.group_id
LEFT OUTER JOIN npwd_phone_contacts on REGEXP_REPLACE(npwd_phone_contacts.number, '[^0-9]', '') = REGEXP_REPLACE(users.phone_number, '[^0-9]', '') AND npwd_phone_contacts.identifier = ?
WHERE npwd_messages_groups.participant_identifier != ?
ORDER BY npwd_messages_groups.createdAt DESC
`
const [results] = await pool.query(query, [ userIdentifier, userIdentifier, userIdentifier ]);
return <UnformattedMessageGroup[]>results;
}
/**
* Retrieve all messages associated with a group and add a field
* "isMine" which determines if the message belongs to the user
* making the request
* @param userIdentifier - user to get messages for
* @param groupId - the group to get messages from
*/
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 npwd_messages
LEFT OUTER JOIN users on users.identifier = npwd_messages.user_identifier
LEFT OUTER JOIN npwd_phone_contacts on REGEXP_REPLACE(npwd_phone_contacts.number, '[^0-9]', '') = REGEXP_REPLACE(users.phone_number, '[^0-9]', '') AND npwd_phone_contacts.identifier = ?
WHERE npwd_messages.group_id = ?
ORDER BY createdAt ASC;
`;
const [results] = await pool.query(query, [ userIdentifier, groupId ]);
const messages = <Message[]>results;
return messages.map(message => ({
...message,
isMine: message.user_identifier === userIdentifier,
updatedAt: message.updatedAt.toString(),
}));
}
/**
* Create a message group label
* @param userIdentifier - user who is creating the message group
* @param groupId - groupId this label is attached to
* @param label - the label itself
*/
async function createLabel(userIdentifier: string, groupId: string, label: string): Promise<any> {
const query = `
INSERT INTO npwd_messages_labels
(user_identifier, group_id, label)
VALUES (?, ?, ?)
`;
await pool.query(query, [ userIdentifier, groupId, label ]);
}
/**
* Create a message group
* @param userIdentifier - the user creating the message group
* @param groupId - the unique group ID this corresponds to
* @param participantIdentifier - the participant user identifier. This identifier is what attaches
* other players to the message group
*/
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
]);
}
/**
* Find a players identifier from their phone number
* @param phoneNumber - the phone number to search for
*/
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']
}
/**
* This method checks if the input groupId already exists in
* the database. As long as the groupId is derived from the input
* identifiers this means that the user is trying to create a
* duplicate!
* @param groupId - group Id to check that it exists
*/
async function checkIfMessageGroupExists(groupId: string): Promise<boolean> {
const query = `
SELECT COUNT(*) as count
FROM npwd_messages_groups
WHERE group_id = ?;
`;
const [results] = await pool.query(query, [ groupId]);
const result = <any>results;
const count = result[0].count;
return count > 0;
}
async function getMessageCountByGroup(groupId: string): Promise<number> {
const query = `
SELECT COUNT(*) as count
FROM npwd_messages
WHERE group_id = ?;
`;
const [results] = await pool.query(query, [ groupId]);
const result = <any>results;
return result[0].count;
}
/**
* Consolidate raw message groups into a mapping that groups participants
* by the message group. The goal of this is to reduce the rows of message
* groups into a single MessageGroup object.
* @param userIdentifier - the user identifier to get message groups for
*/
async function getConsolidatedMessageGroups(userIdentifier: string): Promise<MessageGroupMapping> {
const messageGroups = await getMessageGroups(userIdentifier);
return messageGroups.reduce((mapping: MessageGroupMapping, messageGroup: UnformattedMessageGroup) => {
const groupId = messageGroup.group_id;
const displayTerm = messageGroup.display || messageGroup.phone_number || '???';
if (groupId in mapping) {
mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm)
} else {
mapping[groupId] = {
user_identifier: messageGroup.user_identifier,
avatar: messageGroup.avatar,
label: messageGroup.label,
participants: [displayTerm],
updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null
}
}
return mapping;
}, {});
}
async function getGroupIds(userIdentifier: string, groupMapping: MessageGroupMapping): Promise<string[]> {
const groupIds: string[] = [];
for (const groupId of Object.keys(groupMapping)) {
const isMine = groupMapping[groupId].user_identifier === userIdentifier
if (isMine || await getMessageCountByGroup(groupId) > 0) {
groupIds.push(groupId)
}
}
return groupIds;
}
/**
* Given the mapping of groupId: fields contents reduce it into a list
* of MessageGroup objects ready for the UI to consume
* @param userIdentifier - user to generate the MessageGroups for
*/
async function getFormattedMessageGroups(userIdentifier: string): Promise<MessageGroup[]> {
const groupMapping = await getConsolidatedMessageGroups(userIdentifier);
const groupIds = await getGroupIds(userIdentifier, groupMapping);
return groupIds.map(groupId => {
const group = groupMapping[groupId];
return {
...group,
groupId,
groupDisplay: group.participants.join(', '),
// note that 1 here references how many participants besides the user
isGroupChat: group.participants.length > 1,
}
});
}
/**
* Main method to handle creation of new message groups. First
* we retrieve identifiers for each submitted phone number and
* then rows in npwd_messages_groups are created for each of them
* bound to a unique groupId. The groupId is any unique string - we
* use hashes here.
*
* These queries are batched with a transaction so that if any of
* them fail the queries are not committed to the database. This helps
* avoid situations where some participants get added to the group but
* one fails resulting in a partial group which would be very confusing
* to the player.
* @param userIdentifier - user who is creating the group
* @param phoneNumbers - list of phone numbers to add to the grup
* @param groupLabel - optional group label to give the group
*/
async function createMessageGroupsFromPhoneNumbers(
userIdentifier: string,
phoneNumbers: string[],
groupLabel: string): Promise<CreateMessageGroupResult> {
// we check that each phoneNumber exists before we create the group
const identifiers: string[] = [];
for (const phoneNumber of phoneNumbers) {
try {
const identifier = await getIdentifierFromPhoneNumber(phoneNumber)
identifiers.push(identifier);
} catch (err) {
return { error: true, phoneNumber };
}
}
// don't allow explicitly adding yourself
if (identifiers.some(identifier => identifier === userIdentifier)) {
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);
if (await checkIfMessageGroupExists(groupId)) {
return { error: true, duplicate: true };
}
const queryPromises = [
// create a row that contains ourselves so reverse accessing from
// other players works as expected
createMessageGroup(userIdentifier, groupId, userIdentifier),
...identifiers.map(identifier => createMessageGroup(userIdentifier, groupId, identifier))
]
// we allow users to attach labels to name their group chats
if (groupLabel) {
queryPromises.push(createLabel(userIdentifier, groupId, groupLabel));
}
// 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.
try {
await withTransaction(queryPromises);
} catch (err) {
return { error: true };
}
return { error: false, groupId };
}
onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, async () => {
try {
const _identifier = await useIdentifier();
const messageGroups = await getFormattedMessageGroups(_identifier);
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS, getSource(), messageGroups);
} catch (e) {
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED, getSource());
}
});
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP, async (phoneNumbers: string[], label: string = null) => {
try {
const _identifier = await useIdentifier();
const result = await createMessageGroupsFromPhoneNumbers(_identifier, phoneNumbers, label)
if (result.error) {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, getSource(), result);
} else {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, getSource(), result);
}
} catch (e) {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_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());
}
});
onNet(events.MESSAGES_SEND_MESSAGE, async (groupId: string, message: string) => {
try {
const _identifier = await useIdentifier();
await createMessage(_identifier, groupId, message)
emitNet(events.MESSAGES_SEND_MESSAGE_SUCCESS, getSource(), groupId);
} catch (e) {
emitNet(events.MESSAGES_SEND_MESSAGE_FAILED, getSource());
}
});
+1 -2
View File
@@ -1,7 +1,6 @@
import events from "../utils/events";
import { ESX, getSource } from "./server";
import { pool } from "./db";
import { useIdentifier } from "./functions";
import { useIdentifier, getSource } from "./functions";
import { Note, NoteId } from "../../phone/src/common/interfaces/notes";
async function addNote(identifier: string, note: Note): Promise<any> {
+2 -1
View File
@@ -1,6 +1,7 @@
import events from '../utils/events';
import { ESX, getSource } from './server';
import { ESX } from './server';
import { getSource } from "./functions";
import { pool } from './db';
import { usePhoneNumber } from './functions';
+2 -1
View File
@@ -1,5 +1,6 @@
import { pool } from "./db";
import { ESX, getSource } from "./server";
import { ESX } from "./server";
import { getSource } from "./functions";
import { Tweet, Profile } from '../../phone/src/common/interfaces/twitter';
import events from "../utils/events";
import config from "../utils/config";
+1
View File
@@ -1,3 +1,4 @@
export default {
TWITTER: "TWITTER",
MESSAGES: "MESSAGES"
};
+15 -1
View File
@@ -43,7 +43,7 @@ export default {
SELLOUT_FETCH_LISTING: 'phone:fetchAllListings',
SELLOUT_SEND_LISTING: 'phone:sendAllListings',
// Bank
//
BANK_ADD_TRANSFER: 'phone:addTransfer',
BANK_ADD_TRANSFER_SUCCESS: 'phone:addTransferSuccess',
BANK_FETCH_TRANSACTIONS: 'phone:fetchAllTransactions',
@@ -53,6 +53,20 @@ export default {
BANK_SEND_CREDENTIALS: 'phone:sendBankCredentials',
BANK_GET_CREDENTIALS: 'phone:getBankCredentials',
//messages
MESSAGES_FETCH_MESSAGE_GROUPS: 'phone:fetchMessageGroups',
MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS: 'phone:fetchMessageGroupsSuccess',
MESSAGES_FETCH_MESSAGE_GROUPS_FAILED: 'phone:fetchMessageGroupsFailed',
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',
MESSAGES_FETCH_MESSAGES: 'phone:fetchMessages',
MESSAGES_FETCH_MESSAGES_SUCCESS: 'phone:fetchMessagesSuccess',
MESSAGES_FETCH_MESSAGES_FAILED: 'phone:fetchMessagesFailed',
// Notes
NOTE_ADD_NOTE: 'phone:addNote',
NOTE_FETCH_ALL_NOTES: 'phone:fetchAllNotes',
+4
View File
@@ -13,3 +13,7 @@ function sendMessage(app: string, method: string, data: any) {
export function sendTwitterMessage(method: string, data: any = {}) {
return sendMessage(apps.TWITTER, method, data);
}
export function sendMessageEvent(method: string, data: any = {}) {
return sendMessage(apps.MESSAGES, method, data);
}
+27 -1
View File
@@ -1245,6 +1245,13 @@
resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.6.tgz#f4c7ec43e81b319a9815115031709f26987891f0"
integrity sha512-3c+yGKvVP5Y9TYBEibGNR+kLtijnj7mYrXRg+WpFb2X9xm04g/DXYkfg4hmzJQosc9snFNUPkbYIhu+KAm6jJw==
"@types/md5@^2.2.1":
version "2.2.1"
resolved "https://registry.yarnpkg.com/@types/md5/-/md5-2.2.1.tgz#0e2d65d8f6cc91aafbc9be5a4c08fee9250406ce"
integrity sha512-bZB0jqBL7JETFqvRKyuDETFceFaVcLm2MBPP5LFEEL/SZuqLnyvzF37tXmMERDncC3oeEj/fOUw88ftJeMpZaw==
dependencies:
"@types/node" "*"
"@types/node@*":
version "14.11.5"
resolved "https://registry.yarnpkg.com/@types/node/-/node-14.11.5.tgz#fecad41c041cae7f2404ad4b2d0742fdb628b305"
@@ -2200,6 +2207,11 @@ char-regex@^1.0.2:
resolved "https://registry.yarnpkg.com/char-regex/-/char-regex-1.0.2.tgz#d744358226217f981ed58f479b1d6bcc29545dcf"
integrity sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==
[email protected]:
version "0.0.2"
resolved "https://registry.yarnpkg.com/charenc/-/charenc-0.0.2.tgz#c0a1d2f3a7092e03774bfa83f14c0fc5790a8667"
integrity sha1-wKHS86cJLgN3S/qD8UwPxXkKhmc=
chokidar@^2.1.8:
version "2.1.8"
resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-2.1.8.tgz#804b3a7b6a99358c3c5c61e71d8728f041cff917"
@@ -2511,6 +2523,11 @@ cross-spawn@^7.0.0, cross-spawn@^7.0.2:
shebang-command "^2.0.0"
which "^2.0.1"
[email protected]:
version "0.0.2"
resolved "https://registry.yarnpkg.com/crypt/-/crypt-0.0.2.tgz#88d7ff7ec0dfb86f713dc87bbb42d044d3e6c41b"
integrity sha1-iNf/fsDfuG9xPch7u0LQRNPmxBs=
crypto-browserify@^3.11.0:
version "3.12.0"
resolved "https://registry.yarnpkg.com/crypto-browserify/-/crypto-browserify-3.12.0.tgz#396cf9f3137f03e4b8e532c58f698254e00f80ec"
@@ -3863,7 +3880,7 @@ is-binary-path@~2.1.0:
dependencies:
binary-extensions "^2.0.0"
is-buffer@^1.1.5:
is-buffer@^1.1.5, is-buffer@~1.1.6:
version "1.1.6"
resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be"
integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==
@@ -4811,6 +4828,15 @@ md5.js@^1.3.4:
inherits "^2.0.1"
safe-buffer "^5.1.2"
md5@^2.3.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/md5/-/md5-2.3.0.tgz#c3da9a6aae3a30b46b7b0c349b87b110dc3bda4f"
integrity sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==
dependencies:
charenc "0.0.2"
crypt "0.0.2"
is-buffer "~1.1.6"
memory-fs@^0.4.1:
version "0.4.1"
resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.4.1.tgz#3a9a20b8462523e447cfbc7e8bb80ed667bfc552"