mirror of
https://github.com/darksaid98/new-phone-who-dis.git
synced 2026-12-04 06:28:51 +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 { EmailAppHeader } from './EmailAppHeader';
|
||||
import { NewEmailPage } from './pages/NewEmailPage';
|
||||
import { SentPage } from './pages/SentPage';
|
||||
import { EmailDetailsPage } from './pages/EmailDetailsPage';
|
||||
import { EmailDetailsPage } from './pages/EmailDetailsPage'; // <--- What the hell is going on
|
||||
|
||||
export const EmailApp = () => {
|
||||
return (
|
||||
@@ -20,9 +19,6 @@ export const EmailApp = () => {
|
||||
<Route path="/email" exact>
|
||||
<InboxPage />
|
||||
</Route>
|
||||
<Route path="/email/sent" exact>
|
||||
<SentPage />
|
||||
</Route>
|
||||
<Route path="/email/new" exact>
|
||||
<NewEmailPage />
|
||||
</Route>
|
||||
|
||||
@@ -3,7 +3,7 @@ import LeftIcon from '@material-ui/icons/ChevronLeft';
|
||||
import RightIcon from '@material-ui/icons/ChevronRight';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useParams } from 'react-router';
|
||||
import { IEmailMessage } from '../../../../common/typings/email';
|
||||
import { IEmailMessage } from '../../../../../../typings/email'; // :)
|
||||
import { useEmail } from '../../hooks/useEmail';
|
||||
import { EmailMessage } from '../shared/EmailMessage';
|
||||
|
||||
@@ -71,7 +71,7 @@ export const EmailDetailsPage = () => {
|
||||
<CircularProgress color="primary" />
|
||||
</Box>
|
||||
) : (
|
||||
<EmailMessage message={message} />
|
||||
<EmailMessage message={message} subject={email.subject} />
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
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 { useEmail } from '../../hooks/useEmail';
|
||||
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
|
||||
|
||||
const useStyles = makeStyles((theme) => ({
|
||||
search: {
|
||||
@@ -21,10 +23,33 @@ const useStyles = makeStyles((theme) => ({
|
||||
export const NewEmailPage = () => {
|
||||
const classes = useStyles();
|
||||
const { t } = useTranslation();
|
||||
const { sendEmail, loading } = useEmail();
|
||||
const [subject, setSubject] = useState<string>('');
|
||||
const [receivers, setReceivers] = 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) => {
|
||||
setSubject(e.target.value || '');
|
||||
};
|
||||
@@ -37,6 +62,16 @@ export const NewEmailPage = () => {
|
||||
setBody(e.target.value || '');
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
sendEmail({
|
||||
subject,
|
||||
receivers,
|
||||
body,
|
||||
email_id: Number(queryEmailId) || undefined,
|
||||
parent_id: Number(queryMessageId) || undefined,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Box height="100%" pt="180px">
|
||||
<Box p={2} className={classes.search}>
|
||||
@@ -50,6 +85,7 @@ export const NewEmailPage = () => {
|
||||
onChange={handleReceiver}
|
||||
/>
|
||||
<TextField
|
||||
disabled={!!queryEmailId}
|
||||
variant="outlined"
|
||||
placeholder="Subject"
|
||||
color="primary"
|
||||
@@ -68,8 +104,13 @@ export const NewEmailPage = () => {
|
||||
value={body}
|
||||
onChange={handleBody}
|
||||
/>
|
||||
<Fab disabled={!body || !receivers} className={classes.sendBtn} color="primary">
|
||||
<SendIcon />
|
||||
<Fab
|
||||
onClick={handleSubmit}
|
||||
disabled={!body || !receivers}
|
||||
className={classes.sendBtn}
|
||||
color="primary"
|
||||
>
|
||||
{loading ? <CircularProgress color="secondary" size={1} /> : <SendIcon />}
|
||||
</Fab>
|
||||
</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 { IEmail } from '../../../../common/typings/email';
|
||||
import { IEmail } from '../../../../../../typings/email';
|
||||
import { EmailListItem } from './EmailListItem';
|
||||
import { List } from '@material-ui/core';
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import dayjs from 'dayjs';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import MarkRead from '@material-ui/icons/Markunread';
|
||||
import MarkUnread from '@material-ui/icons/MarkunreadMailbox';
|
||||
import { IEmail } from '../../../../common/typings/email';
|
||||
import { IEmail } from '../../../../../../typings/email';
|
||||
import { useHistory } from 'react-router';
|
||||
import { useEmail } from '../../hooks/useEmail';
|
||||
|
||||
@@ -37,11 +37,7 @@ export const EmailListItem = ({ email }: { email: IEmail }) => {
|
||||
<Avatar>{latestMessage.sender.charAt(0).toUpperCase()}</Avatar>
|
||||
</ListItemAvatar>
|
||||
<ListItemText secondary={highlight ? <strong>{sendDate}</strong> : <span>{sendDate}</span>}>
|
||||
{highlight ? (
|
||||
<strong>{latestMessage.subject}</strong>
|
||||
) : (
|
||||
<span>{latestMessage.subject}</span>
|
||||
)}
|
||||
{highlight ? <strong>{email.subject}</strong> : <span>{email.subject}</span>}
|
||||
</ListItemText>
|
||||
<ListItemSecondaryAction>
|
||||
{!mine && (
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { Box, Card, CardContent } from '@material-ui/core';
|
||||
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 { 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 { replyEmail } = useEmail();
|
||||
return (
|
||||
<Box px={2}>
|
||||
<Card>
|
||||
@@ -16,13 +20,37 @@ export const EmailMessage = ({ message }: { message: IEmailMessage }) => {
|
||||
</CardContent>
|
||||
|
||||
<CardContent>
|
||||
{t('APPS_EMAIL_SUBJECT')}: <i>{message.subject || '( - )'}</i>
|
||||
{t('APPS_EMAIL_SUBJECT')}: <i>{subject || '( - )'}</i>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Box mt={2}>
|
||||
<Card>
|
||||
<CardContent>{message.body}</CardContent>
|
||||
<CardContent>
|
||||
{message.body.split('\n').map((paragraph) => (
|
||||
<Typography variant="caption" paragraph>
|
||||
{paragraph}
|
||||
</Typography>
|
||||
))}
|
||||
</CardContent>
|
||||
</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>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { atom } from 'recoil';
|
||||
import { IEmail } from '../../../common/typings/email';
|
||||
import { IEmail } from '../../../../../typings/email';
|
||||
|
||||
export const emailState = {
|
||||
search: atom<IEmail[]>({
|
||||
|
||||
@@ -1,32 +1,66 @@
|
||||
import dayjs from 'dayjs';
|
||||
import qs from 'qs';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useHistory } from 'react-router';
|
||||
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 { useSnackbar } from '../../../ui/hooks/useSnackbar';
|
||||
import { emailState } from './state';
|
||||
|
||||
export const useEmail = () => {
|
||||
const history = useHistory();
|
||||
const { t } = useTranslation();
|
||||
const { addAlert } = useSnackbar();
|
||||
const [inbox, setInbox] = useRecoilState(emailState.inbox);
|
||||
const [sent, setSent] = useRecoilState(emailState.sent);
|
||||
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(
|
||||
'EMAIL',
|
||||
'phone:fetchInbox',
|
||||
EmailEvents.FETCH_INBOX,
|
||||
setInbox,
|
||||
);
|
||||
const [fetchSent, { loading: sentLoading }] = useNuiEventCallback(
|
||||
'EMAIL',
|
||||
'phone:fetchSentEmails',
|
||||
setSent,
|
||||
onError,
|
||||
);
|
||||
|
||||
const loading = inboxLoading || sentLoading;
|
||||
const allEmails = useMemo(() => [...(sent || []), ...(inbox || [])], [inbox, sent]);
|
||||
const loading = inboxLoading || sendLoading;
|
||||
const allEmails = useMemo(() => [...(inbox || [])], [inbox]);
|
||||
|
||||
const head = useCallback((arr: IEmailMessage[]): IEmailMessage => arr && arr[0], []);
|
||||
const getEmailById = useCallback((id: number) => allEmails.find((e) => e.id === id) || null, [
|
||||
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 { IEmail } from '../../../common/typings/email';
|
||||
import { EmailEvents, IEmail } from '../../../../../typings/email';
|
||||
import InjectDebugData from '../../../os/debug/InjectDebugData';
|
||||
import { useNuiEvent } from '../../../os/nui-events/hooks/useNuiEvent';
|
||||
import { emailState } from './state';
|
||||
@@ -22,7 +22,7 @@ InjectDebugData<IEmail[]>(
|
||||
[
|
||||
{
|
||||
app: 'EMAIL',
|
||||
method: 'phone:fetchSentEmailsSuccess',
|
||||
method: EmailEvents.FETCH_INBOX_SUCCESS,
|
||||
data: [
|
||||
{
|
||||
id: 1,
|
||||
@@ -56,7 +56,7 @@ InjectDebugData<IEmail[]>(
|
||||
},
|
||||
{
|
||||
app: 'EMAIL',
|
||||
method: 'phone:fetchEmailsSuccess',
|
||||
method: EmailEvents.FETCH_INBOX_SUCCESS,
|
||||
data: [
|
||||
{
|
||||
id: 3,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Box, List } from '@material-ui/core';
|
||||
import { MessageEvents, MessageGroup } from '../../../../../../typings/messages';
|
||||
import Nui from '../../../../os/nui-events/utils/Nui';
|
||||
import { MessageGroup } from '../../../../../../typings/messages';
|
||||
import useMessages from '../../hooks/useMessages';
|
||||
import MessageGroupItem from './MessageGroupItem';
|
||||
import useStyles from './list.styles';
|
||||
|
||||
@@ -31,6 +31,9 @@
|
||||
"generateProfileNameFromUsers": true,
|
||||
"allowEdtiableProfileName": true
|
||||
},
|
||||
"email": {
|
||||
"provider": "project-error.dev"
|
||||
},
|
||||
"bank": {
|
||||
"showNotifications": true
|
||||
},
|
||||
|
||||
@@ -206,8 +206,16 @@
|
||||
"APPS_EMAIL_INBOX": "Inbox",
|
||||
"APPS_EMAIL_SENT": "Sent",
|
||||
"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_REPLY": "Reply",
|
||||
"GENERIC_REPLY_ALL": "Reply All",
|
||||
"GENERIC_ALL": "All",
|
||||
"GENERIC_NEW": "New",
|
||||
"GENERIC_FROM": "From",
|
||||
"GENERIC_TO": "To",
|
||||
|
||||
@@ -1,59 +1,26 @@
|
||||
import { uuidv4 } from 'fivem-js';
|
||||
import { sendEmailEvent } from '../utils/messages';
|
||||
import { EmailEvents, EmailMessageInput, IEmailMessage } from '../../typings/email';
|
||||
|
||||
interface ICallback {
|
||||
cb: (err: any, data?: unknown) => void;
|
||||
timeout: NodeJS.Timeout;
|
||||
}
|
||||
|
||||
const _timeout = 10000;
|
||||
const _callbacks = new Map<string, ICallback>();
|
||||
import { ClUtils } from './client';
|
||||
|
||||
/**
|
||||
* Fetch Inbox
|
||||
*/
|
||||
RegisterNuiCallbackType(EmailEvents.FETCH_INBOX);
|
||||
on(`__cfx_nui:${EmailEvents.FETCH_INBOX}`, (data: any, cb: (err: any, data?: any) => void) => {
|
||||
if (_callbacks.has(EmailEvents.FETCH_INBOX)) {
|
||||
cb(
|
||||
new Error(
|
||||
`Nui Server Callback with name "${EmailEvents.FETCH_INBOX}" is already waiting for server!`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
if (ClUtils.registerNuiCallback(EmailEvents.FETCH_INBOX, cb)) {
|
||||
emitNet(EmailEvents.FETCH_INBOX, data);
|
||||
}
|
||||
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) => {
|
||||
if (_callbacks.has(EmailEvents.FETCH_INBOX)) {
|
||||
const callback = _callbacks.get(EmailEvents.FETCH_INBOX);
|
||||
clearTimeout(callback.timeout);
|
||||
callback.cb(null, response);
|
||||
_callbacks.delete(EmailEvents.FETCH_INBOX);
|
||||
if (ClUtils.registerNuiCallbackSuccess(EmailEvents.FETCH_INBOX, response)) {
|
||||
sendEmailEvent(EmailEvents.FETCH_INBOX_SUCCESS, response);
|
||||
}
|
||||
});
|
||||
|
||||
onNet(EmailEvents.FETCH_INBOX_ERROR, (err: any) => {
|
||||
if (_callbacks.has(EmailEvents.FETCH_INBOX)) {
|
||||
const callback = _callbacks.get(EmailEvents.FETCH_INBOX);
|
||||
clearTimeout(callback.timeout);
|
||||
callback.cb(err);
|
||||
_callbacks.delete(EmailEvents.FETCH_INBOX);
|
||||
if (ClUtils.registerNuiCallbackError(EmailEvents.FETCH_INBOX, err)) {
|
||||
sendEmailEvent(EmailEvents.FETCH_INBOX_ERROR, err);
|
||||
}
|
||||
});
|
||||
@@ -65,46 +32,20 @@ RegisterNuiCallbackType(EmailEvents.SEND_EMAIL);
|
||||
on(
|
||||
`__cfx_nui:${EmailEvents.SEND_EMAIL}`,
|
||||
(data: EmailMessageInput, cb: (err: any, data?: IEmailMessage) => void) => {
|
||||
if (_callbacks.has(EmailEvents.SEND_EMAIL)) {
|
||||
cb(
|
||||
new Error(
|
||||
`Nui Server Callback with name "${EmailEvents.SEND_EMAIL}" is already waiting for server!`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
if (ClUtils.registerNuiCallback(EmailEvents.SEND_EMAIL, cb)) {
|
||||
emitNet(EmailEvents.SEND_EMAIL, data);
|
||||
}
|
||||
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) => {
|
||||
if (_callbacks.has(EmailEvents.SEND_EMAIL)) {
|
||||
const callback = _callbacks.get(EmailEvents.SEND_EMAIL);
|
||||
clearTimeout(callback.timeout);
|
||||
callback.cb(null, response);
|
||||
_callbacks.delete(EmailEvents.SEND_EMAIL);
|
||||
if (ClUtils.registerNuiCallbackSuccess(EmailEvents.SEND_EMAIL, response)) {
|
||||
sendEmailEvent(EmailEvents.SEND_EMAIL_SUCCESS, response);
|
||||
}
|
||||
});
|
||||
|
||||
onNet(EmailEvents.SEND_EMAIL_ERROR, (err: any) => {
|
||||
if (_callbacks.has(EmailEvents.SEND_EMAIL)) {
|
||||
const callback = _callbacks.get(EmailEvents.SEND_EMAIL);
|
||||
clearTimeout(callback.timeout);
|
||||
callback.cb(err);
|
||||
_callbacks.delete(EmailEvents.SEND_EMAIL);
|
||||
if (ClUtils.registerNuiCallbackError(EmailEvents.SEND_EMAIL, err)) {
|
||||
sendEmailEvent(EmailEvents.SEND_EMAIL_ERROR, err);
|
||||
}
|
||||
});
|
||||
@@ -60,45 +60,45 @@ export default class ClientUtils {
|
||||
});
|
||||
}
|
||||
|
||||
public registerNuiServerCallback<I = any, R = any>(
|
||||
app: string,
|
||||
event: string,
|
||||
successEvent?: string,
|
||||
errorEvent?: string,
|
||||
) {
|
||||
const uid = uuidv4();
|
||||
const callbackId = `${event}:${uid}`;
|
||||
|
||||
RegisterNuiCallbackType(event);
|
||||
on(`__cfx_nui:${event}`, (data: I, cb: (err: any, data?: R) => void) => {
|
||||
if (this._callbacks.has(callbackId)) {
|
||||
cb(new Error(`Nui Server Callback with name "${event}" is already waiting for server!`));
|
||||
return;
|
||||
}
|
||||
emitNet(event, data);
|
||||
registerNuiCallback<D = unknown>(event: string, cb: (error: any, result?: D) => void): boolean {
|
||||
if (this._callbacks.has(event)) {
|
||||
cb(new Error(`Nui Server Callback with name "${event}" is already waiting for server!`));
|
||||
return false;
|
||||
}
|
||||
this._callbacks.set(event, {
|
||||
cb,
|
||||
timeout: setTimeout(() => {
|
||||
if (this._callbacks.has(event)) {
|
||||
this._callbacks
|
||||
.get(event)
|
||||
.cb(new Error(`Nui Server Callback with name "${event}" timed out`));
|
||||
this._callbacks.delete(event);
|
||||
}
|
||||
}, this._settings.promiseTimeout),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
const _success = successEvent || `${event}Success`;
|
||||
onNet(_success, (response: R) => {
|
||||
if (this._callbacks.has(callbackId)) {
|
||||
const callback = this._callbacks.get(callbackId);
|
||||
clearTimeout(callback.timeout);
|
||||
callback.cb(null, response);
|
||||
this._callbacks.delete(callbackId);
|
||||
sendMessage(app, _success, response);
|
||||
}
|
||||
});
|
||||
registerNuiCallbackSuccess<R = unknown>(event: string, response?: R) {
|
||||
if (this._callbacks.has(event)) {
|
||||
const callback = this._callbacks.get(event);
|
||||
clearTimeout(callback.timeout);
|
||||
callback.cb(null, response);
|
||||
this._callbacks.delete(event);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const _error = errorEvent || `${event}Error`;
|
||||
onNet(_error, (err: any) => {
|
||||
if (this._callbacks.has(callbackId)) {
|
||||
const callback = this._callbacks.get(callbackId);
|
||||
clearTimeout(callback.timeout);
|
||||
callback.cb(err);
|
||||
this._callbacks.delete(callbackId);
|
||||
sendMessage(app, _error, err);
|
||||
}
|
||||
});
|
||||
registerNuiCallbackError(event: string, error?: any) {
|
||||
if (this._callbacks.has(event)) {
|
||||
const callback = this._callbacks.get(event);
|
||||
clearTimeout(callback.timeout);
|
||||
callback.cb(error);
|
||||
this._callbacks.delete(event);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -121,15 +121,15 @@ export async function generateEmail(identifier: string): Promise<string> {
|
||||
const email = result[0]?.phone_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');
|
||||
}
|
||||
|
||||
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 = ?';
|
||||
await pool.query(query, [newEmail, identifier]);
|
||||
mainLogger.debug(`Inserting email into Database: ${newEmail}`);
|
||||
|
||||
@@ -240,7 +240,7 @@ export class Player {
|
||||
* Set the stored phone email for a user
|
||||
**/
|
||||
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 { getIdentifierByEmail, getPlayer, getSource } from './functions';
|
||||
import { IEmail, IEmailMessage } from '../../phone/src/common/typings/email';
|
||||
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 {
|
||||
message_id: number;
|
||||
@@ -125,7 +122,7 @@ async function sendEmail(
|
||||
email_id_or_subject: number | string,
|
||||
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') {
|
||||
const emailQuery = `INSERT INTO npwd_emails (subject) VALUES (?)`;
|
||||
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}`, {
|
||||
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,
|
||||
async ({ email_id, subject, parent_id, body, receivers }: EmailMessageInput) => {
|
||||
const _source = getSource();
|
||||
|
||||
if (!body || !receivers) {
|
||||
emitNet(EmailEvents.SEND_EMAIL_ERROR, _source, 'APPS_EMAIL_SEND_EMAIL_BAD_INPUT');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const player = getPlayer(_source);
|
||||
if (!player) {
|
||||
throw new Error('Couldnt find player');
|
||||
}
|
||||
|
||||
const parsedReceivers = receivers
|
||||
.split(',')
|
||||
.map((email: string) => email.trim().toLowerCase());
|
||||
|
||||
const mappedReceivers = await Promise.all(
|
||||
receivers
|
||||
.split(',')
|
||||
.map((s: string) => s.trim())
|
||||
.map(async (email: string) => {
|
||||
const identifier = await getIdentifierByEmail(email);
|
||||
return { email, identifier };
|
||||
}),
|
||||
parsedReceivers.map(async (email: string) => {
|
||||
const identifier = await getIdentifierByEmail(email);
|
||||
return { email, identifier };
|
||||
}),
|
||||
);
|
||||
|
||||
const email = await sendEmail(
|
||||
player.identifier,
|
||||
player.getEmail(),
|
||||
mappedReceivers,
|
||||
mappedReceivers.filter((r) => !!r.identifier),
|
||||
body,
|
||||
email_id || subject,
|
||||
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);
|
||||
} catch (e) {
|
||||
emailLogger.error(`Failed to send email, ${e.message}`, {
|
||||
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