mirror of
https://github.com/darksaid98/new-phone-who-dis.git
synced 2026-12-04 22:16:40 +00:00
Create email and Reply functionality
This commit is contained in:
1 parent
15a8db1293
commit
b83a890f48
18 files changed
+229
-179
No files matched your search
@@ -7,8 +7,7 @@ import { Route, Switch } from 'react-router-dom';
|
|||||||
import { InboxPage } from './pages/InboxPage';
|
import { InboxPage } from './pages/InboxPage';
|
||||||
import { EmailAppHeader } from './EmailAppHeader';
|
import { EmailAppHeader } from './EmailAppHeader';
|
||||||
import { NewEmailPage } from './pages/NewEmailPage';
|
import { NewEmailPage } from './pages/NewEmailPage';
|
||||||
import { SentPage } from './pages/SentPage';
|
import { EmailDetailsPage } from './pages/EmailDetailsPage'; // <--- What the hell is going on
|
||||||
import { EmailDetailsPage } from './pages/EmailDetailsPage';
|
|
||||||
|
|
||||||
export const EmailApp = () => {
|
export const EmailApp = () => {
|
||||||
return (
|
return (
|
||||||
@@ -20,9 +19,6 @@ export const EmailApp = () => {
|
|||||||
<Route path="/email" exact>
|
<Route path="/email" exact>
|
||||||
<InboxPage />
|
<InboxPage />
|
||||||
</Route>
|
</Route>
|
||||||
<Route path="/email/sent" exact>
|
|
||||||
<SentPage />
|
|
||||||
</Route>
|
|
||||||
<Route path="/email/new" exact>
|
<Route path="/email/new" exact>
|
||||||
<NewEmailPage />
|
<NewEmailPage />
|
||||||
</Route>
|
</Route>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import LeftIcon from '@material-ui/icons/ChevronLeft';
|
|||||||
import RightIcon from '@material-ui/icons/ChevronRight';
|
import RightIcon from '@material-ui/icons/ChevronRight';
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { useParams } from 'react-router';
|
import { useParams } from 'react-router';
|
||||||
import { IEmailMessage } from '../../../../common/typings/email';
|
import { IEmailMessage } from '../../../../../../typings/email'; // :)
|
||||||
import { useEmail } from '../../hooks/useEmail';
|
import { useEmail } from '../../hooks/useEmail';
|
||||||
import { EmailMessage } from '../shared/EmailMessage';
|
import { EmailMessage } from '../shared/EmailMessage';
|
||||||
|
|
||||||
@@ -71,7 +71,7 @@ export const EmailDetailsPage = () => {
|
|||||||
<CircularProgress color="primary" />
|
<CircularProgress color="primary" />
|
||||||
</Box>
|
</Box>
|
||||||
) : (
|
) : (
|
||||||
<EmailMessage message={message} />
|
<EmailMessage message={message} subject={email.subject} />
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import SendIcon from '@material-ui/icons/Send';
|
import SendIcon from '@material-ui/icons/Send';
|
||||||
import { Box, Fab, makeStyles, TextField } from '@material-ui/core';
|
import { Box, CircularProgress, Fab, makeStyles, TextField } from '@material-ui/core';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { useEmail } from '../../hooks/useEmail';
|
||||||
|
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
|
||||||
|
|
||||||
const useStyles = makeStyles((theme) => ({
|
const useStyles = makeStyles((theme) => ({
|
||||||
search: {
|
search: {
|
||||||
@@ -21,10 +23,33 @@ const useStyles = makeStyles((theme) => ({
|
|||||||
export const NewEmailPage = () => {
|
export const NewEmailPage = () => {
|
||||||
const classes = useStyles();
|
const classes = useStyles();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { sendEmail, loading } = useEmail();
|
||||||
const [subject, setSubject] = useState<string>('');
|
const [subject, setSubject] = useState<string>('');
|
||||||
const [receivers, setReceivers] = useState<string>('');
|
const [receivers, setReceivers] = useState<string>('');
|
||||||
const [body, setBody] = useState<string>('');
|
const [body, setBody] = useState<string>('');
|
||||||
|
|
||||||
|
const {
|
||||||
|
messageId: queryMessageId,
|
||||||
|
subject: querySubject,
|
||||||
|
emailId: queryEmailId,
|
||||||
|
receivers: queryReceivers,
|
||||||
|
body: queryBody,
|
||||||
|
} = useQueryParams({
|
||||||
|
subject: '',
|
||||||
|
emailId: null,
|
||||||
|
receivers: '',
|
||||||
|
messageId: null,
|
||||||
|
body: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (queryEmailId) {
|
||||||
|
setSubject(querySubject);
|
||||||
|
setReceivers(queryReceivers);
|
||||||
|
setBody(queryBody);
|
||||||
|
}
|
||||||
|
}, [queryEmailId, querySubject, queryReceivers, queryBody]);
|
||||||
|
|
||||||
const handleSubject = (e) => {
|
const handleSubject = (e) => {
|
||||||
setSubject(e.target.value || '');
|
setSubject(e.target.value || '');
|
||||||
};
|
};
|
||||||
@@ -37,6 +62,16 @@ export const NewEmailPage = () => {
|
|||||||
setBody(e.target.value || '');
|
setBody(e.target.value || '');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
sendEmail({
|
||||||
|
subject,
|
||||||
|
receivers,
|
||||||
|
body,
|
||||||
|
email_id: Number(queryEmailId) || undefined,
|
||||||
|
parent_id: Number(queryMessageId) || undefined,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box height="100%" pt="180px">
|
<Box height="100%" pt="180px">
|
||||||
<Box p={2} className={classes.search}>
|
<Box p={2} className={classes.search}>
|
||||||
@@ -50,6 +85,7 @@ export const NewEmailPage = () => {
|
|||||||
onChange={handleReceiver}
|
onChange={handleReceiver}
|
||||||
/>
|
/>
|
||||||
<TextField
|
<TextField
|
||||||
|
disabled={!!queryEmailId}
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
placeholder="Subject"
|
placeholder="Subject"
|
||||||
color="primary"
|
color="primary"
|
||||||
@@ -68,8 +104,13 @@ export const NewEmailPage = () => {
|
|||||||
value={body}
|
value={body}
|
||||||
onChange={handleBody}
|
onChange={handleBody}
|
||||||
/>
|
/>
|
||||||
<Fab disabled={!body || !receivers} className={classes.sendBtn} color="primary">
|
<Fab
|
||||||
<SendIcon />
|
onClick={handleSubmit}
|
||||||
|
disabled={!body || !receivers}
|
||||||
|
className={classes.sendBtn}
|
||||||
|
color="primary"
|
||||||
|
>
|
||||||
|
{loading ? <CircularProgress color="secondary" size={1} /> : <SendIcon />}
|
||||||
</Fab>
|
</Fab>
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
import React from 'react';
|
|
||||||
import { Box } from '@material-ui/core';
|
|
||||||
import { useEmail } from '../../hooks/useEmail';
|
|
||||||
import { EmailList } from '../shared/EmailList';
|
|
||||||
|
|
||||||
export const SentPage = () => {
|
|
||||||
const { sent } = useEmail();
|
|
||||||
return (
|
|
||||||
<Box height="100%">
|
|
||||||
<Box overflow="auto" maxHeight="100%">
|
|
||||||
<EmailList emails={sent} />
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { IEmail } from '../../../../common/typings/email';
|
import { IEmail } from '../../../../../../typings/email';
|
||||||
import { EmailListItem } from './EmailListItem';
|
import { EmailListItem } from './EmailListItem';
|
||||||
import { List } from '@material-ui/core';
|
import { List } from '@material-ui/core';
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import dayjs from 'dayjs';
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import MarkRead from '@material-ui/icons/Markunread';
|
import MarkRead from '@material-ui/icons/Markunread';
|
||||||
import MarkUnread from '@material-ui/icons/MarkunreadMailbox';
|
import MarkUnread from '@material-ui/icons/MarkunreadMailbox';
|
||||||
import { IEmail } from '../../../../common/typings/email';
|
import { IEmail } from '../../../../../../typings/email';
|
||||||
import { useHistory } from 'react-router';
|
import { useHistory } from 'react-router';
|
||||||
import { useEmail } from '../../hooks/useEmail';
|
import { useEmail } from '../../hooks/useEmail';
|
||||||
|
|
||||||
@@ -37,11 +37,7 @@ export const EmailListItem = ({ email }: { email: IEmail }) => {
|
|||||||
<Avatar>{latestMessage.sender.charAt(0).toUpperCase()}</Avatar>
|
<Avatar>{latestMessage.sender.charAt(0).toUpperCase()}</Avatar>
|
||||||
</ListItemAvatar>
|
</ListItemAvatar>
|
||||||
<ListItemText secondary={highlight ? <strong>{sendDate}</strong> : <span>{sendDate}</span>}>
|
<ListItemText secondary={highlight ? <strong>{sendDate}</strong> : <span>{sendDate}</span>}>
|
||||||
{highlight ? (
|
{highlight ? <strong>{email.subject}</strong> : <span>{email.subject}</span>}
|
||||||
<strong>{latestMessage.subject}</strong>
|
|
||||||
) : (
|
|
||||||
<span>{latestMessage.subject}</span>
|
|
||||||
)}
|
|
||||||
</ListItemText>
|
</ListItemText>
|
||||||
<ListItemSecondaryAction>
|
<ListItemSecondaryAction>
|
||||||
{!mine && (
|
{!mine && (
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
import { Box, Card, CardContent } from '@material-ui/core';
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
import ReplyAllIcon from '@material-ui/icons/ReplyAll';
|
||||||
|
import ReplyIcon from '@material-ui/icons/Reply';
|
||||||
|
import { Box, Button, Card, CardActions, CardContent, Typography } from '@material-ui/core';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { IEmailMessage } from '../../../../common/typings/email';
|
import { IEmailMessage } from '../../../../../../typings/email';
|
||||||
|
import { useEmail } from '../../hooks/useEmail';
|
||||||
|
|
||||||
export const EmailMessage = ({ message }: { message: IEmailMessage }) => {
|
export const EmailMessage = ({ message, subject }: { message: IEmailMessage; subject: string }) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { replyEmail } = useEmail();
|
||||||
return (
|
return (
|
||||||
<Box px={2}>
|
<Box px={2}>
|
||||||
<Card>
|
<Card>
|
||||||
@@ -16,13 +20,37 @@ export const EmailMessage = ({ message }: { message: IEmailMessage }) => {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
|
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{t('APPS_EMAIL_SUBJECT')}: <i>{message.subject || '( - )'}</i>
|
{t('APPS_EMAIL_SUBJECT')}: <i>{subject || '( - )'}</i>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
<Box mt={2}>
|
<Box mt={2}>
|
||||||
<Card>
|
<Card>
|
||||||
<CardContent>{message.body}</CardContent>
|
<CardContent>
|
||||||
|
{message.body.split('\n').map((paragraph) => (
|
||||||
|
<Typography variant="caption" paragraph>
|
||||||
|
{paragraph}
|
||||||
|
</Typography>
|
||||||
|
))}
|
||||||
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
<CardActions>
|
||||||
|
<Box textAlign="right" width="100%">
|
||||||
|
<Button
|
||||||
|
onClick={() => replyEmail({ ...message, subject })}
|
||||||
|
color="primary"
|
||||||
|
startIcon={<ReplyAllIcon />}
|
||||||
|
>
|
||||||
|
{t('GENERIC_REPLY_ALL')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => replyEmail({ ...message, subject, receivers: [message.sender] })}
|
||||||
|
color="primary"
|
||||||
|
startIcon={<ReplyIcon />}
|
||||||
|
>
|
||||||
|
{t('GENERIC_REPLY')}
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</CardActions>
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { atom } from 'recoil';
|
import { atom } from 'recoil';
|
||||||
import { IEmail } from '../../../common/typings/email';
|
import { IEmail } from '../../../../../typings/email';
|
||||||
|
|
||||||
export const emailState = {
|
export const emailState = {
|
||||||
search: atom<IEmail[]>({
|
search: atom<IEmail[]>({
|
||||||
|
|||||||
@@ -1,32 +1,66 @@
|
|||||||
|
import dayjs from 'dayjs';
|
||||||
|
import qs from 'qs';
|
||||||
import { useCallback, useMemo } from 'react';
|
import { useCallback, useMemo } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { useHistory } from 'react-router';
|
||||||
import { useRecoilState, useRecoilValue } from 'recoil';
|
import { useRecoilState, useRecoilValue } from 'recoil';
|
||||||
import { IEmailMessage } from '../../../common/typings/email';
|
import { EmailEvents, EmailMessageInput, IEmailMessage } from '../../../../../typings/email';
|
||||||
import { useNuiEventCallback } from '../../../os/nui-events/hooks/useNuiEventCallback';
|
import { useNuiEventCallback } from '../../../os/nui-events/hooks/useNuiEventCallback';
|
||||||
|
import { useSnackbar } from '../../../ui/hooks/useSnackbar';
|
||||||
import { emailState } from './state';
|
import { emailState } from './state';
|
||||||
|
|
||||||
export const useEmail = () => {
|
export const useEmail = () => {
|
||||||
|
const history = useHistory();
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { addAlert } = useSnackbar();
|
||||||
const [inbox, setInbox] = useRecoilState(emailState.inbox);
|
const [inbox, setInbox] = useRecoilState(emailState.inbox);
|
||||||
const [sent, setSent] = useRecoilState(emailState.sent);
|
|
||||||
const myEmail = useRecoilValue(emailState.myEmail);
|
const myEmail = useRecoilValue(emailState.myEmail);
|
||||||
|
|
||||||
|
const onError = useCallback((error) => addAlert({ message: t(error), type: 'error' }), [
|
||||||
|
addAlert,
|
||||||
|
t,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const onSendSuccess = useCallback(() => {
|
||||||
|
addAlert({ message: t('APPS_EMAIL_SEND_EMAIL_SUCCESS'), type: 'success' });
|
||||||
|
history.push('/email');
|
||||||
|
}, [addAlert, history, t]);
|
||||||
|
|
||||||
|
const [sendEmail, { loading: sendLoading }] = useNuiEventCallback<EmailMessageInput>(
|
||||||
|
'EMAIL',
|
||||||
|
EmailEvents.SEND_EMAIL,
|
||||||
|
onSendSuccess,
|
||||||
|
onError,
|
||||||
|
);
|
||||||
|
|
||||||
const [fetchInbox, { loading: inboxLoading }] = useNuiEventCallback(
|
const [fetchInbox, { loading: inboxLoading }] = useNuiEventCallback(
|
||||||
'EMAIL',
|
'EMAIL',
|
||||||
'phone:fetchInbox',
|
EmailEvents.FETCH_INBOX,
|
||||||
setInbox,
|
setInbox,
|
||||||
);
|
onError,
|
||||||
const [fetchSent, { loading: sentLoading }] = useNuiEventCallback(
|
|
||||||
'EMAIL',
|
|
||||||
'phone:fetchSentEmails',
|
|
||||||
setSent,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const loading = inboxLoading || sentLoading;
|
const loading = inboxLoading || sendLoading;
|
||||||
const allEmails = useMemo(() => [...(sent || []), ...(inbox || [])], [inbox, sent]);
|
const allEmails = useMemo(() => [...(inbox || [])], [inbox]);
|
||||||
|
|
||||||
const head = useCallback((arr: IEmailMessage[]): IEmailMessage => arr && arr[0], []);
|
const head = useCallback((arr: IEmailMessage[]): IEmailMessage => arr && arr[0], []);
|
||||||
const getEmailById = useCallback((id: number) => allEmails.find((e) => e.id === id) || null, [
|
const getEmailById = useCallback((id: number) => allEmails.find((e) => e.id === id) || null, [
|
||||||
allEmails,
|
allEmails,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return { inbox, sent, myEmail, getEmailById, head, fetchSent, fetchInbox, loading };
|
const replyEmail = (message: IEmailMessage & { subject: string }) => {
|
||||||
|
const sendDate = dayjs.unix(message.sendDate).format(t('DATE_FORMAT'));
|
||||||
|
const receivers = message.receivers.join(',');
|
||||||
|
const query = qs.stringify(
|
||||||
|
{
|
||||||
|
...message,
|
||||||
|
receivers,
|
||||||
|
body: ` \n\n ----- On ${sendDate} ${message.sender} wrote: ----- \n\n ${message.body}`,
|
||||||
|
},
|
||||||
|
{ addQueryPrefix: true },
|
||||||
|
);
|
||||||
|
history.push(`/email/new/${query}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
return { inbox, myEmail, getEmailById, head, fetchInbox, sendEmail, replyEmail, loading };
|
||||||
};
|
};
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useSetRecoilState } from 'recoil';
|
import { useSetRecoilState } from 'recoil';
|
||||||
import { IEmail } from '../../../common/typings/email';
|
import { EmailEvents, IEmail } from '../../../../../typings/email';
|
||||||
import InjectDebugData from '../../../os/debug/InjectDebugData';
|
import InjectDebugData from '../../../os/debug/InjectDebugData';
|
||||||
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
|
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
|
||||||
import { emailState } from './state';
|
import { emailState } from './state';
|
||||||
@@ -22,7 +22,7 @@ InjectDebugData<IEmail[]>(
|
|||||||
[
|
[
|
||||||
{
|
{
|
||||||
app: 'EMAIL',
|
app: 'EMAIL',
|
||||||
method: 'phone:fetchSentEmailsSuccess',
|
method: EmailEvents.FETCH_INBOX_SUCCESS,
|
||||||
data: [
|
data: [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
@@ -56,7 +56,7 @@ InjectDebugData<IEmail[]>(
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
app: 'EMAIL',
|
app: 'EMAIL',
|
||||||
method: 'phone:fetchEmailsSuccess',
|
method: EmailEvents.FETCH_INBOX_SUCCESS,
|
||||||
data: [
|
data: [
|
||||||
{
|
{
|
||||||
id: 3,
|
id: 3,
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Box, List } from '@material-ui/core';
|
import { Box, List } from '@material-ui/core';
|
||||||
import { MessageEvents, MessageGroup } from '../../../../../../typings/messages';
|
import { MessageGroup } from '../../../../../../typings/messages';
|
||||||
import Nui from '../../../../os/nui-events/utils/Nui';
|
|
||||||
import useMessages from '../../hooks/useMessages';
|
import useMessages from '../../hooks/useMessages';
|
||||||
import MessageGroupItem from './MessageGroupItem';
|
import MessageGroupItem from './MessageGroupItem';
|
||||||
import useStyles from './list.styles';
|
import useStyles from './list.styles';
|
||||||
|
|||||||
@@ -31,6 +31,9 @@
|
|||||||
"generateProfileNameFromUsers": true,
|
"generateProfileNameFromUsers": true,
|
||||||
"allowEdtiableProfileName": true
|
"allowEdtiableProfileName": true
|
||||||
},
|
},
|
||||||
|
"email": {
|
||||||
|
"provider": "project-error.dev"
|
||||||
|
},
|
||||||
"bank": {
|
"bank": {
|
||||||
"showNotifications": true
|
"showNotifications": true
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -206,8 +206,16 @@
|
|||||||
"APPS_EMAIL_INBOX": "Inbox",
|
"APPS_EMAIL_INBOX": "Inbox",
|
||||||
"APPS_EMAIL_SENT": "Sent",
|
"APPS_EMAIL_SENT": "Sent",
|
||||||
"APPS_EMAIL_SUBJECT": "Subject",
|
"APPS_EMAIL_SUBJECT": "Subject",
|
||||||
|
"APPS_EMAIL_SEND_EMAIL_SUCCESS": "Email was sent succesfully",
|
||||||
|
"APPS_EMAIL_SEND_EMAIL_ERROR_NOT_FOUND": "None of the receivers were found!",
|
||||||
|
"APPS_EMAIL_SEND_EMAIL_BAD_INPUT": "Please input a message and a receiver",
|
||||||
|
"APPS_EMAIL_FETCH_INBOX_ERROR": "Failed to fetch inbox, an unexpected error occurred",
|
||||||
|
|
||||||
|
"GENERIC_UNEXPECTED_ERROR": "An unexpected error occurred, please check the logs.",
|
||||||
"GENERIC_CLICK_TO_REVEAL": "Click to reveal",
|
"GENERIC_CLICK_TO_REVEAL": "Click to reveal",
|
||||||
|
"GENERIC_REPLY": "Reply",
|
||||||
|
"GENERIC_REPLY_ALL": "Reply All",
|
||||||
|
"GENERIC_ALL": "All",
|
||||||
"GENERIC_NEW": "New",
|
"GENERIC_NEW": "New",
|
||||||
"GENERIC_FROM": "From",
|
"GENERIC_FROM": "From",
|
||||||
"GENERIC_TO": "To",
|
"GENERIC_TO": "To",
|
||||||
|
|||||||
@@ -1,59 +1,26 @@
|
|||||||
import { uuidv4 } from 'fivem-js';
|
import { uuidv4 } from 'fivem-js';
|
||||||
import { sendEmailEvent } from '../utils/messages';
|
import { sendEmailEvent } from '../utils/messages';
|
||||||
import { EmailEvents, EmailMessageInput, IEmailMessage } from '../../typings/email';
|
import { EmailEvents, EmailMessageInput, IEmailMessage } from '../../typings/email';
|
||||||
|
import { ClUtils } from './client';
|
||||||
interface ICallback {
|
|
||||||
cb: (err: any, data?: unknown) => void;
|
|
||||||
timeout: NodeJS.Timeout;
|
|
||||||
}
|
|
||||||
|
|
||||||
const _timeout = 10000;
|
|
||||||
const _callbacks = new Map<string, ICallback>();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch Inbox
|
* Fetch Inbox
|
||||||
*/
|
*/
|
||||||
RegisterNuiCallbackType(EmailEvents.FETCH_INBOX);
|
RegisterNuiCallbackType(EmailEvents.FETCH_INBOX);
|
||||||
on(`__cfx_nui:${EmailEvents.FETCH_INBOX}`, (data: any, cb: (err: any, data?: any) => void) => {
|
on(`__cfx_nui:${EmailEvents.FETCH_INBOX}`, (data: any, cb: (err: any, data?: any) => void) => {
|
||||||
if (_callbacks.has(EmailEvents.FETCH_INBOX)) {
|
if (ClUtils.registerNuiCallback(EmailEvents.FETCH_INBOX, cb)) {
|
||||||
cb(
|
emitNet(EmailEvents.FETCH_INBOX, data);
|
||||||
new Error(
|
|
||||||
`Nui Server Callback with name "${EmailEvents.FETCH_INBOX}" is already waiting for server!`,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
emitNet(EmailEvents.FETCH_INBOX, data);
|
|
||||||
|
|
||||||
_callbacks.set(EmailEvents.FETCH_INBOX, {
|
|
||||||
cb,
|
|
||||||
timeout: setTimeout(() => {
|
|
||||||
if (_callbacks.has(EmailEvents.FETCH_INBOX)) {
|
|
||||||
_callbacks
|
|
||||||
.get(EmailEvents.FETCH_INBOX)
|
|
||||||
.cb(new Error(`Nui Server Callback with name "${EmailEvents.FETCH_INBOX}" timed out`));
|
|
||||||
_callbacks.delete(EmailEvents.FETCH_INBOX);
|
|
||||||
}
|
|
||||||
}, _timeout),
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
onNet(EmailEvents.FETCH_INBOX_SUCCESS, (response: any) => {
|
onNet(EmailEvents.FETCH_INBOX_SUCCESS, (response: any) => {
|
||||||
if (_callbacks.has(EmailEvents.FETCH_INBOX)) {
|
if (ClUtils.registerNuiCallbackSuccess(EmailEvents.FETCH_INBOX, response)) {
|
||||||
const callback = _callbacks.get(EmailEvents.FETCH_INBOX);
|
|
||||||
clearTimeout(callback.timeout);
|
|
||||||
callback.cb(null, response);
|
|
||||||
_callbacks.delete(EmailEvents.FETCH_INBOX);
|
|
||||||
sendEmailEvent(EmailEvents.FETCH_INBOX_SUCCESS, response);
|
sendEmailEvent(EmailEvents.FETCH_INBOX_SUCCESS, response);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
onNet(EmailEvents.FETCH_INBOX_ERROR, (err: any) => {
|
onNet(EmailEvents.FETCH_INBOX_ERROR, (err: any) => {
|
||||||
if (_callbacks.has(EmailEvents.FETCH_INBOX)) {
|
if (ClUtils.registerNuiCallbackError(EmailEvents.FETCH_INBOX, err)) {
|
||||||
const callback = _callbacks.get(EmailEvents.FETCH_INBOX);
|
|
||||||
clearTimeout(callback.timeout);
|
|
||||||
callback.cb(err);
|
|
||||||
_callbacks.delete(EmailEvents.FETCH_INBOX);
|
|
||||||
sendEmailEvent(EmailEvents.FETCH_INBOX_ERROR, err);
|
sendEmailEvent(EmailEvents.FETCH_INBOX_ERROR, err);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -65,46 +32,20 @@ RegisterNuiCallbackType(EmailEvents.SEND_EMAIL);
|
|||||||
on(
|
on(
|
||||||
`__cfx_nui:${EmailEvents.SEND_EMAIL}`,
|
`__cfx_nui:${EmailEvents.SEND_EMAIL}`,
|
||||||
(data: EmailMessageInput, cb: (err: any, data?: IEmailMessage) => void) => {
|
(data: EmailMessageInput, cb: (err: any, data?: IEmailMessage) => void) => {
|
||||||
if (_callbacks.has(EmailEvents.SEND_EMAIL)) {
|
if (ClUtils.registerNuiCallback(EmailEvents.SEND_EMAIL, cb)) {
|
||||||
cb(
|
emitNet(EmailEvents.SEND_EMAIL, data);
|
||||||
new Error(
|
|
||||||
`Nui Server Callback with name "${EmailEvents.SEND_EMAIL}" is already waiting for server!`,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
emitNet(EmailEvents.SEND_EMAIL, data);
|
|
||||||
|
|
||||||
_callbacks.set(EmailEvents.SEND_EMAIL, {
|
|
||||||
cb,
|
|
||||||
timeout: setTimeout(() => {
|
|
||||||
if (_callbacks.has(EmailEvents.SEND_EMAIL)) {
|
|
||||||
_callbacks
|
|
||||||
.get(EmailEvents.SEND_EMAIL)
|
|
||||||
.cb(new Error(`Nui Server Callback with name "${EmailEvents.SEND_EMAIL}" timed out`));
|
|
||||||
_callbacks.delete(EmailEvents.SEND_EMAIL);
|
|
||||||
}
|
|
||||||
}, _timeout),
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
onNet(EmailEvents.SEND_EMAIL_SUCCESS, (response: any) => {
|
onNet(EmailEvents.SEND_EMAIL_SUCCESS, (response: any) => {
|
||||||
if (_callbacks.has(EmailEvents.SEND_EMAIL)) {
|
if (ClUtils.registerNuiCallbackSuccess(EmailEvents.SEND_EMAIL, response)) {
|
||||||
const callback = _callbacks.get(EmailEvents.SEND_EMAIL);
|
|
||||||
clearTimeout(callback.timeout);
|
|
||||||
callback.cb(null, response);
|
|
||||||
_callbacks.delete(EmailEvents.SEND_EMAIL);
|
|
||||||
sendEmailEvent(EmailEvents.SEND_EMAIL_SUCCESS, response);
|
sendEmailEvent(EmailEvents.SEND_EMAIL_SUCCESS, response);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
onNet(EmailEvents.SEND_EMAIL_ERROR, (err: any) => {
|
onNet(EmailEvents.SEND_EMAIL_ERROR, (err: any) => {
|
||||||
if (_callbacks.has(EmailEvents.SEND_EMAIL)) {
|
if (ClUtils.registerNuiCallbackError(EmailEvents.SEND_EMAIL, err)) {
|
||||||
const callback = _callbacks.get(EmailEvents.SEND_EMAIL);
|
|
||||||
clearTimeout(callback.timeout);
|
|
||||||
callback.cb(err);
|
|
||||||
_callbacks.delete(EmailEvents.SEND_EMAIL);
|
|
||||||
sendEmailEvent(EmailEvents.SEND_EMAIL_ERROR, err);
|
sendEmailEvent(EmailEvents.SEND_EMAIL_ERROR, err);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -60,45 +60,45 @@ export default class ClientUtils {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public registerNuiServerCallback<I = any, R = any>(
|
registerNuiCallback<D = unknown>(event: string, cb: (error: any, result?: D) => void): boolean {
|
||||||
app: string,
|
if (this._callbacks.has(event)) {
|
||||||
event: string,
|
cb(new Error(`Nui Server Callback with name "${event}" is already waiting for server!`));
|
||||||
successEvent?: string,
|
return false;
|
||||||
errorEvent?: string,
|
}
|
||||||
) {
|
this._callbacks.set(event, {
|
||||||
const uid = uuidv4();
|
cb,
|
||||||
const callbackId = `${event}:${uid}`;
|
timeout: setTimeout(() => {
|
||||||
|
if (this._callbacks.has(event)) {
|
||||||
RegisterNuiCallbackType(event);
|
this._callbacks
|
||||||
on(`__cfx_nui:${event}`, (data: I, cb: (err: any, data?: R) => void) => {
|
.get(event)
|
||||||
if (this._callbacks.has(callbackId)) {
|
.cb(new Error(`Nui Server Callback with name "${event}" timed out`));
|
||||||
cb(new Error(`Nui Server Callback with name "${event}" is already waiting for server!`));
|
this._callbacks.delete(event);
|
||||||
return;
|
}
|
||||||
}
|
}, this._settings.promiseTimeout),
|
||||||
emitNet(event, data);
|
|
||||||
});
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
const _success = successEvent || `${event}Success`;
|
registerNuiCallbackSuccess<R = unknown>(event: string, response?: R) {
|
||||||
onNet(_success, (response: R) => {
|
if (this._callbacks.has(event)) {
|
||||||
if (this._callbacks.has(callbackId)) {
|
const callback = this._callbacks.get(event);
|
||||||
const callback = this._callbacks.get(callbackId);
|
clearTimeout(callback.timeout);
|
||||||
clearTimeout(callback.timeout);
|
callback.cb(null, response);
|
||||||
callback.cb(null, response);
|
this._callbacks.delete(event);
|
||||||
this._callbacks.delete(callbackId);
|
return true;
|
||||||
sendMessage(app, _success, response);
|
}
|
||||||
}
|
return false;
|
||||||
});
|
}
|
||||||
|
|
||||||
const _error = errorEvent || `${event}Error`;
|
registerNuiCallbackError(event: string, error?: any) {
|
||||||
onNet(_error, (err: any) => {
|
if (this._callbacks.has(event)) {
|
||||||
if (this._callbacks.has(callbackId)) {
|
const callback = this._callbacks.get(event);
|
||||||
const callback = this._callbacks.get(callbackId);
|
clearTimeout(callback.timeout);
|
||||||
clearTimeout(callback.timeout);
|
callback.cb(error);
|
||||||
callback.cb(err);
|
this._callbacks.delete(event);
|
||||||
this._callbacks.delete(callbackId);
|
return true;
|
||||||
sendMessage(app, _error, err);
|
}
|
||||||
}
|
return false;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -121,15 +121,15 @@ export async function generateEmail(identifier: string): Promise<string> {
|
|||||||
const email = result[0]?.phone_email;
|
const email = result[0]?.phone_email;
|
||||||
|
|
||||||
if (!email) {
|
if (!email) {
|
||||||
const emailUser = await getDefaultProfileNames(identifier);
|
const userProfileNames = await getDefaultProfileNames(identifier);
|
||||||
|
|
||||||
if (!emailUser) {
|
if (!userProfileNames) {
|
||||||
throw new Error('Must provide a fullName or phoneNumber option to create an email');
|
throw new Error('Must provide a fullName or phoneNumber option to create an email');
|
||||||
}
|
}
|
||||||
|
|
||||||
const emailProvider = config.email.provider || 'project-error.dev';
|
const emailProvider = config.email.provider || 'project-error.dev';
|
||||||
|
|
||||||
const newEmail = `${emailUser}@${emailProvider}`;
|
const newEmail = `${userProfileNames[0]}@${emailProvider}`.trim().toLowerCase();
|
||||||
const query = 'UPDATE users SET phone_email = ? WHERE identifier = ?';
|
const query = 'UPDATE users SET phone_email = ? WHERE identifier = ?';
|
||||||
await pool.query(query, [newEmail, identifier]);
|
await pool.query(query, [newEmail, identifier]);
|
||||||
mainLogger.debug(`Inserting email into Database: ${newEmail}`);
|
mainLogger.debug(`Inserting email into Database: ${newEmail}`);
|
||||||
|
|||||||
@@ -240,7 +240,7 @@ export class Player {
|
|||||||
* Set the stored phone email for a user
|
* Set the stored phone email for a user
|
||||||
**/
|
**/
|
||||||
public setEmail(email: string): void {
|
public setEmail(email: string): void {
|
||||||
this._email = email;
|
this._email = email.trim().toLowerCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,12 +1,9 @@
|
|||||||
import { EmailEvents, EmailMessageInput } from '../../typings/email';
|
import { EmailEvents, EmailMessageInput, IEmail, IEmailMessage } from '../../typings/email';
|
||||||
import { mainLogger } from './sv_logger';
|
import { mainLogger } from './sv_logger';
|
||||||
import { getIdentifierByEmail, getPlayer, getSource } from './functions';
|
import { getIdentifierByEmail, getPlayer, getSource } from './functions';
|
||||||
import { IEmail, IEmailMessage } from '../../phone/src/common/typings/email';
|
|
||||||
import { pool } from './db';
|
import { pool } from './db';
|
||||||
import config from '../utils/config';
|
|
||||||
import { getPlayerInfo } from './players/sv_players';
|
|
||||||
|
|
||||||
const emailLogger = mainLogger.child({ module: 'contact' });
|
const emailLogger = mainLogger.child({ module: 'email' });
|
||||||
|
|
||||||
export interface UnformattedEmailMessage {
|
export interface UnformattedEmailMessage {
|
||||||
message_id: number;
|
message_id: number;
|
||||||
@@ -125,7 +122,7 @@ async function sendEmail(
|
|||||||
email_id_or_subject: number | string,
|
email_id_or_subject: number | string,
|
||||||
parent_id?: number,
|
parent_id?: number,
|
||||||
) {
|
) {
|
||||||
let email_id = email_id_or_subject === 'number' ? email_id_or_subject : undefined;
|
let email_id = typeof email_id_or_subject === 'number' ? email_id_or_subject : undefined;
|
||||||
if (typeof email_id_or_subject === 'string') {
|
if (typeof email_id_or_subject === 'string') {
|
||||||
const emailQuery = `INSERT INTO npwd_emails (subject) VALUES (?)`;
|
const emailQuery = `INSERT INTO npwd_emails (subject) VALUES (?)`;
|
||||||
const [emailResult] = await pool.query(emailQuery, [email_id_or_subject]);
|
const [emailResult] = await pool.query(emailQuery, [email_id_or_subject]);
|
||||||
@@ -168,7 +165,7 @@ onNet(EmailEvents.FETCH_INBOX, async () => {
|
|||||||
emailLogger.error(`Failed to fetch email inbox, ${e.message}`, {
|
emailLogger.error(`Failed to fetch email inbox, ${e.message}`, {
|
||||||
source: _source,
|
source: _source,
|
||||||
});
|
});
|
||||||
emitNet(EmailEvents.FETCH_INBOX_ERROR, _source, e);
|
emitNet(EmailEvents.SEND_EMAIL_ERROR, _source, 'APPS_EMAIL_FETCH_INBOX_ERROR');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -176,37 +173,59 @@ onNet(
|
|||||||
EmailEvents.SEND_EMAIL,
|
EmailEvents.SEND_EMAIL,
|
||||||
async ({ email_id, subject, parent_id, body, receivers }: EmailMessageInput) => {
|
async ({ email_id, subject, parent_id, body, receivers }: EmailMessageInput) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
|
|
||||||
|
if (!body || !receivers) {
|
||||||
|
emitNet(EmailEvents.SEND_EMAIL_ERROR, _source, 'APPS_EMAIL_SEND_EMAIL_BAD_INPUT');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const player = getPlayer(_source);
|
const player = getPlayer(_source);
|
||||||
if (!player) {
|
if (!player) {
|
||||||
throw new Error('Couldnt find player');
|
throw new Error('Couldnt find player');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const parsedReceivers = receivers
|
||||||
|
.split(',')
|
||||||
|
.map((email: string) => email.trim().toLowerCase());
|
||||||
|
|
||||||
const mappedReceivers = await Promise.all(
|
const mappedReceivers = await Promise.all(
|
||||||
receivers
|
parsedReceivers.map(async (email: string) => {
|
||||||
.split(',')
|
const identifier = await getIdentifierByEmail(email);
|
||||||
.map((s: string) => s.trim())
|
return { email, identifier };
|
||||||
.map(async (email: string) => {
|
}),
|
||||||
const identifier = await getIdentifierByEmail(email);
|
|
||||||
return { email, identifier };
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const email = await sendEmail(
|
const email = await sendEmail(
|
||||||
player.identifier,
|
player.identifier,
|
||||||
player.getEmail(),
|
player.getEmail(),
|
||||||
mappedReceivers,
|
mappedReceivers.filter((r) => !!r.identifier),
|
||||||
body,
|
body,
|
||||||
email_id || subject,
|
email_id || subject,
|
||||||
parent_id || null,
|
parent_id || null,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const failedReceivers = mappedReceivers.filter((r) => !r.identifier);
|
||||||
|
|
||||||
|
if (failedReceivers.length) {
|
||||||
|
failedReceivers.map((r) =>
|
||||||
|
emailLogger.debug(`Email receiver not found in DB: "${r.email}"`, {
|
||||||
|
source: _source,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (failedReceivers.length === mappedReceivers.length) {
|
||||||
|
emitNet(EmailEvents.SEND_EMAIL_ERROR, _source, 'APPS_EMAIL_SEND_EMAIL_ERROR_NOT_FOUND');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
emitNet(EmailEvents.SEND_EMAIL_SUCCESS, _source, email);
|
emitNet(EmailEvents.SEND_EMAIL_SUCCESS, _source, email);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
emailLogger.error(`Failed to send email, ${e.message}`, {
|
emailLogger.error(`Failed to send email, ${e.message}`, {
|
||||||
source: _source,
|
source: _source,
|
||||||
});
|
});
|
||||||
emitNet(EmailEvents.SEND_EMAIL_ERROR, _source, e);
|
emitNet(EmailEvents.SEND_EMAIL_ERROR, _source, 'GENERIC_UNEXPECTED_ERROR');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
Reference in new issue
Block a user