mirror of
https://github.com/darksaid98/new-phone-who-dis.git
synced 2026-12-03 14:38:45 +00:00
Still WIP :)
This commit is contained in:
1 parent
a9b824d026
commit
0ffafbc950
8 files changed
+475
-246
No files matched your search
@@ -1,14 +1,34 @@
|
||||
import React from 'react';
|
||||
import React, { useEffect, useState } 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 '../../../../../../typings/email';
|
||||
import { IEmailMessage, EmailEvents } from '../../../../../../typings/email';
|
||||
import { useEmail } from '../../hooks/useEmail';
|
||||
import { useNuiEventCallback } from '../../../../os/nui-events/hooks/useNuiEventCallback';
|
||||
import { useHistory } from 'react-router';
|
||||
|
||||
export const EmailMessage = ({ message, subject }: { message: IEmailMessage; subject: string }) => {
|
||||
const history = useHistory();
|
||||
const { t } = useTranslation();
|
||||
const { replyEmail } = useEmail();
|
||||
|
||||
const [{ phoneActions, externalActions }, setActions] = useState<
|
||||
Pick<IEmailMessage, 'phoneActions' | 'externalActions'>
|
||||
>({});
|
||||
|
||||
const [fetchEmailActions, { loading }] = useNuiEventCallback(
|
||||
'EMAIL',
|
||||
EmailEvents.FETCH_MESSAGE_ACTIONS,
|
||||
setActions,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (message.hasActions) {
|
||||
fetchEmailActions();
|
||||
}
|
||||
}, [fetchEmailActions, message.hasActions]);
|
||||
|
||||
return (
|
||||
<Box px={2}>
|
||||
<Card>
|
||||
@@ -33,6 +53,15 @@ export const EmailMessage = ({ message, subject }: { message: IEmailMessage; sub
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
{message.hasActions && phoneActions && (
|
||||
<CardActions>
|
||||
<Box textAlign="right" width="100%">
|
||||
{phoneActions.map((action) => (
|
||||
<Button onClick={() => history.push(action.href)}>{action.label}</Button>
|
||||
))}
|
||||
</Box>
|
||||
</CardActions>
|
||||
)}
|
||||
<CardActions>
|
||||
<Box textAlign="right" width="100%">
|
||||
<Button
|
||||
|
||||
@@ -49,3 +49,28 @@ onNet(EmailEvents.SEND_EMAIL_ERROR, (err: any) => {
|
||||
sendEmailEvent(EmailEvents.SEND_EMAIL_ERROR, err);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Fetch Email Message Actions
|
||||
*/
|
||||
RegisterNuiCallbackType(EmailEvents.FETCH_MESSAGE_ACTIONS);
|
||||
on(
|
||||
`__cfx_nui:${EmailEvents.FETCH_MESSAGE_ACTIONS}`,
|
||||
(data: EmailMessageInput, cb: (err: any, data?: IEmailMessage) => void) => {
|
||||
if (ClUtils.registerNuiCallback(EmailEvents.FETCH_MESSAGE_ACTIONS, cb)) {
|
||||
emitNet(EmailEvents.FETCH_MESSAGE_ACTIONS, data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
onNet(EmailEvents.FETCH_MESSAGE_ACTIONS_SUCCESS, (response: any) => {
|
||||
if (ClUtils.registerNuiCallbackSuccess(EmailEvents.FETCH_MESSAGE_ACTIONS, response)) {
|
||||
sendEmailEvent(EmailEvents.FETCH_MESSAGE_ACTIONS_SUCCESS, response);
|
||||
}
|
||||
});
|
||||
|
||||
onNet(EmailEvents.FETCH_MESSAGE_ACTIONS_ERROR, (err: any) => {
|
||||
if (ClUtils.registerNuiCallbackError(EmailEvents.FETCH_MESSAGE_ACTIONS, err)) {
|
||||
sendEmailEvent(EmailEvents.FETCH_MESSAGE_ACTIONS_ERROR, err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import { IEmailExternalAction, IEmailPhoneAction } from '../../../typings/email';
|
||||
import { pool } from './../db';
|
||||
|
||||
export interface UnformattedEmailMessage {
|
||||
message_id: number;
|
||||
parent_id?: number | null;
|
||||
email_id: number;
|
||||
read_at: number | null;
|
||||
subject: string;
|
||||
sender: string;
|
||||
sender_identifier: string;
|
||||
receiver: string;
|
||||
receiver_identifier: string;
|
||||
send_date: number;
|
||||
body: string;
|
||||
actions: boolean;
|
||||
}
|
||||
|
||||
export interface UnformattedEmailExternalAction {
|
||||
id: number;
|
||||
message_id: number;
|
||||
label: string;
|
||||
close_phone: boolean;
|
||||
delete_email: boolean;
|
||||
event_name: string;
|
||||
event_arg: string;
|
||||
}
|
||||
|
||||
export interface UnformattedEmailPhoneAction {
|
||||
id: number;
|
||||
message_id: number;
|
||||
label: string;
|
||||
close_phone: boolean;
|
||||
delete_email: boolean;
|
||||
href: string;
|
||||
}
|
||||
|
||||
export async function fetchMessageActions(
|
||||
id: number,
|
||||
): Promise<{
|
||||
phoneActions: UnformattedEmailPhoneAction[];
|
||||
externalActions: UnformattedEmailExternalAction[];
|
||||
}> {
|
||||
const queryPhoneActions = `
|
||||
SELECT
|
||||
npwd_emails_phone_actions.label as action_phone_label,
|
||||
npwd_emails_phone_actions.close_phone as action_phone_close_phone,
|
||||
npwd_emails_phone_actions.delete_email as action_phone_delete_email,
|
||||
npwd_emails_phone_actions.href as action_phone_href
|
||||
FROM npwd_emails_phone_actions
|
||||
WHERE message_id = ?;
|
||||
`;
|
||||
const queryExternalActions = `
|
||||
SELECT
|
||||
npwd_emails_external_actions.label as action_ext_label,
|
||||
npwd_emails_external_actions.close_phone as action_ext_close_phone,
|
||||
npwd_emails_external_actions.delete_email as action_ext_delete_email,
|
||||
npwd_emails_external_actions.event_name as action_ext_event_name,
|
||||
npwd_emails_external_actions.event_arg as action_ext_event_arg,
|
||||
FROM npwd_emails_external_actions
|
||||
WHERE message_id = ?;
|
||||
`;
|
||||
|
||||
const [phoneActions] = await pool.query(queryPhoneActions, [id]);
|
||||
const [externalActions] = await pool.query(queryExternalActions, [id]);
|
||||
|
||||
return {
|
||||
phoneActions: phoneActions as UnformattedEmailPhoneAction[],
|
||||
externalActions: externalActions as UnformattedEmailExternalAction[],
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchInbox(identifier: string): Promise<UnformattedEmailMessage[]> {
|
||||
const query = `
|
||||
SELECT
|
||||
npwd_emails_messages.parent_id,
|
||||
npwd_emails_messages.email_id,
|
||||
npwd_emails_messages.sender,
|
||||
npwd_emails_messages.sender_identifier,
|
||||
npwd_emails_messages.send_date,
|
||||
npwd_emails_messages.body,
|
||||
npwd_emails_messages.actions,
|
||||
npwd_emails_receivers.message_id,
|
||||
npwd_emails_receivers.receiver,
|
||||
npwd_emails_receivers.receiver_identifier,
|
||||
npwd_emails_receivers.read_at,
|
||||
subject
|
||||
FROM (
|
||||
SELECT id, subject FROM npwd_emails
|
||||
) as e
|
||||
LEFT OUTER JOIN npwd_emails_messages ON npwd_emails_messages.email_id = e.id
|
||||
LEFT OUTER JOIN npwd_emails_receivers ON npwd_emails_receivers.message_id = npwd_emails_messages.id
|
||||
WHERE npwd_emails_receivers.receiver_identifier = ? OR npwd_emails_messages.sender_identifier = ?
|
||||
ORDER BY npwd_emails_messages.send_date DESC
|
||||
`;
|
||||
|
||||
const result = await pool.query(query, [identifier, identifier]);
|
||||
|
||||
return result[0] as UnformattedEmailMessage[];
|
||||
}
|
||||
|
||||
export async function sendEmail(
|
||||
sender_identifier: string,
|
||||
sender: string,
|
||||
receivers: { email: string; identifier: string }[],
|
||||
body: string,
|
||||
email_id_or_subject: number | string,
|
||||
parent_id?: number,
|
||||
external_actions?: IEmailExternalAction[],
|
||||
phone_actions?: IEmailPhoneAction[],
|
||||
) {
|
||||
let email_id = typeof email_id_or_subject === 'number' ? email_id_or_subject : undefined;
|
||||
|
||||
const actions =
|
||||
(external_actions ? external_actions.length : 0) + (phone_actions ? phone_actions.length : 0);
|
||||
|
||||
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]);
|
||||
email_id = (emailResult as any).insertId;
|
||||
}
|
||||
|
||||
const messageQuery = `INSERT INTO npwd_emails_messages (email_id, parent_id, send_date, body, sender, sender_identifier, actions) VALUES (?, ?, ?, ?, ?, ?, ?)`;
|
||||
const [messageResult] = await pool.query(messageQuery, [
|
||||
email_id,
|
||||
parent_id || null,
|
||||
Math.floor(Date.now() / 1000),
|
||||
body,
|
||||
sender,
|
||||
sender_identifier,
|
||||
actions,
|
||||
]);
|
||||
|
||||
const message_id = (messageResult as any).insertId;
|
||||
|
||||
const receiverQuery = `INSERT INTO npwd_emails_receivers (message_id, receiver, receiver_identifier, read_at) VALUES (?, ?, ?, ?)`;
|
||||
const receiverPromises = receivers.map((r) =>
|
||||
pool.query(receiverQuery, [message_id, r.email, r.identifier, null]),
|
||||
);
|
||||
|
||||
const phoneActionQuery = `INSERT INTO npwd_emails_phone_actions (message_id, label, close_phone, delete_email, href) VALUES (?, ?, ?, ?, ?)`;
|
||||
const externalActionQuery = `INSERT INTO npwd_emails_external_actions (message_id, label, close_phone, delete_email, event_name, event_arg) VALUES (?, ?, ?, ?, ?, ?)`;
|
||||
|
||||
if (actions > 0) {
|
||||
const actionPromises = [
|
||||
...phone_actions.map((action) => {
|
||||
const label = action.label;
|
||||
const href = action.href;
|
||||
|
||||
if (!label || !href) {
|
||||
return;
|
||||
}
|
||||
|
||||
const closePhone = action.closePhone !== undefined ? action.closePhone : true;
|
||||
const deleteEmail = action.deleteEmail !== undefined ? action.deleteEmail : true;
|
||||
return pool.query(phoneActionQuery, [message_id, label, closePhone, deleteEmail, href]);
|
||||
}),
|
||||
...external_actions.map((action) => {
|
||||
const label = action.label;
|
||||
const callbackEvent = action.callbackEvent;
|
||||
|
||||
if (!label || !callbackEvent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const callbackArg = action.callbackArg || null;
|
||||
const closePhone = action.closePhone !== undefined ? action.closePhone : true;
|
||||
const deleteEmail = action.deleteEmail !== undefined ? action.deleteEmail : true;
|
||||
|
||||
return pool.query(externalActionQuery, [
|
||||
message_id,
|
||||
label,
|
||||
closePhone,
|
||||
deleteEmail,
|
||||
callbackEvent,
|
||||
callbackArg,
|
||||
]);
|
||||
}),
|
||||
];
|
||||
await Promise.all(actionPromises);
|
||||
}
|
||||
|
||||
await Promise.all(receiverPromises);
|
||||
|
||||
return messageResult;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { getEmailByIdentifier, getIdentifierByEmail, getPlayer, getSource } from './../functions';
|
||||
import {
|
||||
EmailEvents,
|
||||
EmailMessageInput,
|
||||
GlobalEmailEvents,
|
||||
SendEmailToIdentifierInput,
|
||||
} from '../../../typings/email';
|
||||
import { mainLogger } from './../sv_logger';
|
||||
import { fetchInbox, fetchMessageActions, sendEmail } from './sv_email';
|
||||
import {
|
||||
mapUnformattedEmailExternalActions,
|
||||
mapUnformattedEmailMessages,
|
||||
mapUnformattedEmailPhoneActions,
|
||||
} from './sv_email_mappers';
|
||||
|
||||
const emailLogger = mainLogger.child({ module: 'email' });
|
||||
|
||||
onNet(EmailEvents.FETCH_INBOX, async () => {
|
||||
const _source = getSource();
|
||||
try {
|
||||
const player = getPlayer(_source);
|
||||
if (!player) {
|
||||
throw new Error('Couldnt find player');
|
||||
}
|
||||
const playerEmail = player.getEmail();
|
||||
const messages = await fetchInbox(player.identifier);
|
||||
const inbox = mapUnformattedEmailMessages(messages, playerEmail);
|
||||
emitNet(EmailEvents.FETCH_INBOX_SUCCESS, _source, inbox);
|
||||
} catch (e) {
|
||||
emailLogger.error(`Failed to fetch email inbox, ${e.message}`, {
|
||||
source: _source,
|
||||
});
|
||||
emitNet(EmailEvents.SEND_EMAIL_ERROR, _source, 'APPS_EMAIL_FETCH_INBOX_ERROR');
|
||||
}
|
||||
});
|
||||
|
||||
const onSendEmail = async ({
|
||||
email_id,
|
||||
subject,
|
||||
parent_id,
|
||||
body,
|
||||
receivers,
|
||||
phoneActions,
|
||||
externalActions,
|
||||
}: 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(
|
||||
parsedReceivers.map(async (email: string) => {
|
||||
const identifier = await getIdentifierByEmail(email, true);
|
||||
return { email, identifier };
|
||||
}),
|
||||
);
|
||||
|
||||
const email = await sendEmail(
|
||||
player.identifier,
|
||||
player.getEmail(),
|
||||
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, 'GENERIC_UNEXPECTED_ERROR');
|
||||
}
|
||||
};
|
||||
|
||||
onNet(EmailEvents.FETCH_MESSAGE_ACTIONS, async ({ messageId }: { messageId: number }) => {
|
||||
const _source = getSource();
|
||||
try {
|
||||
const actions = await fetchMessageActions(messageId);
|
||||
const phoneActions = mapUnformattedEmailPhoneActions(actions.phoneActions);
|
||||
const externalActions = mapUnformattedEmailExternalActions(actions.externalActions);
|
||||
emitNet(EmailEvents.FETCH_MESSAGE_ACTIONS_SUCCESS, { phoneActions, externalActions });
|
||||
} catch (e) {
|
||||
emailLogger.error(`Failed to fetch email message actions, ${e.message}`, {
|
||||
source: _source,
|
||||
});
|
||||
emitNet(EmailEvents.FETCH_MESSAGE_ACTIONS_ERROR, _source, 'GENERIC_UNEXPECTED_ERROR');
|
||||
}
|
||||
});
|
||||
|
||||
onNet(EmailEvents.SEND_EMAIL, onSendEmail);
|
||||
|
||||
onNet(
|
||||
GlobalEmailEvents.SEND_EMAIL_TO_IDENTIFIER,
|
||||
async ({
|
||||
identifier,
|
||||
provider,
|
||||
subject = '',
|
||||
body = '',
|
||||
externalActions = [],
|
||||
phoneActions = [],
|
||||
}: SendEmailToIdentifierInput) => {
|
||||
if (!provider || !identifier) {
|
||||
throw new Error('Tried to send npwd:sendEmailToIdentifier with missing parameters!');
|
||||
}
|
||||
let receivers = '';
|
||||
try {
|
||||
receivers = await getEmailByIdentifier(identifier, true);
|
||||
} catch (e) {
|
||||
throw new Error("Tried to send npwd:sendEmailToIdentifier but identifier doesn't exist!");
|
||||
}
|
||||
onSendEmail({ subject, body, receivers, externalActions, phoneActions });
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,87 @@
|
||||
import {
|
||||
IEmail,
|
||||
IEmailExternalAction,
|
||||
IEmailMessage,
|
||||
IEmailPhoneAction,
|
||||
} from '../../../typings/email';
|
||||
import {
|
||||
UnformattedEmailExternalAction,
|
||||
UnformattedEmailMessage,
|
||||
UnformattedEmailPhoneAction,
|
||||
} from './sv_email';
|
||||
|
||||
export function formatMessage(message: UnformattedEmailMessage, myEmail: string): IEmailMessage {
|
||||
return {
|
||||
body: message.body,
|
||||
emailId: message.email_id,
|
||||
id: message.message_id,
|
||||
receivers: [message.receiver],
|
||||
sendDate: message.send_date,
|
||||
sender: message.sender,
|
||||
hasActions: message.actions,
|
||||
isMine: message.sender === myEmail,
|
||||
isRead: message.receiver === myEmail ? !!message.read_at : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function mapUnformattedEmailMessages(
|
||||
messages: UnformattedEmailMessage[],
|
||||
myEmail: string,
|
||||
): IEmail[] {
|
||||
const map = messages.reduce((emails, message) => {
|
||||
if (emails.has(message.email_id)) {
|
||||
const email = emails.get(message.email_id);
|
||||
if (email.messagesMap.has(message.message_id)) {
|
||||
const currentMessage = email.messagesMap.get(message.message_id);
|
||||
if (message.receiver === myEmail && !currentMessage.isRead) {
|
||||
currentMessage.isRead === !!message.read_at;
|
||||
}
|
||||
email.messagesMap.set(message.message_id, {
|
||||
...currentMessage,
|
||||
receivers: [...currentMessage.receivers, message.receiver_identifier],
|
||||
});
|
||||
} else {
|
||||
email.messagesMap.set(message.message_id, formatMessage(message, myEmail));
|
||||
}
|
||||
emails.set(message.email_id, {
|
||||
...email,
|
||||
messages: Array.from(email.messagesMap.values()),
|
||||
});
|
||||
return emails;
|
||||
}
|
||||
const messagesMap = new Map<number, IEmailMessage>();
|
||||
messagesMap.set(message.message_id, formatMessage(message, myEmail));
|
||||
emails.set(message.email_id, {
|
||||
id: message.email_id,
|
||||
messagesMap,
|
||||
messages: Array.from(messagesMap.values()),
|
||||
subject: message.subject,
|
||||
});
|
||||
return emails;
|
||||
}, new Map<number, IEmail & { messagesMap: Map<number, IEmailMessage> }>());
|
||||
|
||||
return Array.from(map.values()).map((m) => ({ ...m, messagesMap: undefined }));
|
||||
}
|
||||
|
||||
export function mapUnformattedEmailPhoneActions(
|
||||
actions: UnformattedEmailPhoneAction[],
|
||||
): IEmailPhoneAction[] {
|
||||
return actions.map((action) => ({
|
||||
closePhone: action.close_phone,
|
||||
deleteEmail: action.delete_email,
|
||||
href: action.href,
|
||||
label: action.label,
|
||||
}));
|
||||
}
|
||||
|
||||
export function mapUnformattedEmailExternalActions(
|
||||
actions: UnformattedEmailExternalAction[],
|
||||
): IEmailExternalAction[] {
|
||||
return actions.map((action) => ({
|
||||
closePhone: action.close_phone,
|
||||
deleteEmail: action.delete_email,
|
||||
callbackEvent: action.event_name,
|
||||
callbackArg: action.event_arg,
|
||||
label: action.label,
|
||||
}));
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import './sv_photo';
|
||||
import './sv_messages';
|
||||
import './sv_match';
|
||||
import './sv_call';
|
||||
import './sv_email';
|
||||
import './email/sv_email_events';
|
||||
import './players/sv_player_events';
|
||||
import { mainLogger } from './sv_logger';
|
||||
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
import {
|
||||
EmailEvents,
|
||||
EmailMessageInput,
|
||||
GlobalEmailEvents,
|
||||
IEmail,
|
||||
IEmailMessage,
|
||||
SendEmailToIdentifierInput,
|
||||
} from '../../typings/email';
|
||||
import { mainLogger } from './sv_logger';
|
||||
import { getIdentifierByEmail, getPlayer, getSource } from './functions';
|
||||
import { pool } from './db';
|
||||
|
||||
const emailLogger = mainLogger.child({ module: 'email' });
|
||||
|
||||
export interface UnformattedEmailMessage {
|
||||
message_id: number;
|
||||
parent_id?: number | null;
|
||||
email_id: number;
|
||||
read_at: number | null;
|
||||
subject: string;
|
||||
sender: string;
|
||||
sender_identifier: string;
|
||||
receiver: string;
|
||||
receiver_identifier: string;
|
||||
send_date: number;
|
||||
body: string;
|
||||
}
|
||||
|
||||
/***
|
||||
*
|
||||
SELECT
|
||||
npwd_emails_external_actions.label as action_ext_label,
|
||||
npwd_emails_external_actions.close_phone as action_ext_close_phone,
|
||||
npwd_emails_external_actions.delete_email as action_ext_delete_email,
|
||||
npwd_emails_external_actions.event_name as action_ext_event_name,
|
||||
npwd_emails_external_actions.event_arg as action_ext_event_arg,
|
||||
FROM npwd_emails_external_actions;
|
||||
|
||||
SELECT
|
||||
npwd_emails_phone_actions.label as action_phone_label,
|
||||
npwd_emails_phone_actions.close_phone as action_phone_close_phone,
|
||||
npwd_emails_phone_actions.delete_email as action_phone_delete_email,
|
||||
npwd_emails_phone_actions.href as action_phone_href
|
||||
FROM npwd_emails_phone_actions;
|
||||
*/
|
||||
|
||||
async function fetchInbox(identifier: string): Promise<UnformattedEmailMessage[]> {
|
||||
const query = `
|
||||
SELECT
|
||||
npwd_emails_messages.parent_id,
|
||||
npwd_emails_messages.email_id,
|
||||
npwd_emails_messages.sender,
|
||||
npwd_emails_messages.sender_identifier,
|
||||
npwd_emails_messages.send_date,
|
||||
npwd_emails_messages.body,
|
||||
npwd_emails_receivers.message_id,
|
||||
npwd_emails_receivers.receiver,
|
||||
npwd_emails_receivers.receiver_identifier,
|
||||
npwd_emails_receivers.read_at,
|
||||
subject
|
||||
FROM (
|
||||
SELECT id, subject FROM npwd_emails
|
||||
) as e
|
||||
LEFT OUTER JOIN npwd_emails_messages ON npwd_emails_messages.email_id = e.id
|
||||
LEFT OUTER JOIN npwd_emails_receivers ON npwd_emails_receivers.message_id = npwd_emails_messages.id
|
||||
WHERE npwd_emails_receivers.receiver_identifier = ? OR npwd_emails_messages.sender_identifier = ?
|
||||
ORDER BY npwd_emails_messages.send_date DESC
|
||||
`;
|
||||
|
||||
const result = await pool.query(query, [identifier, identifier]);
|
||||
|
||||
return result[0] as UnformattedEmailMessage[];
|
||||
}
|
||||
|
||||
function formatMessage(message: UnformattedEmailMessage, myEmail: string): IEmailMessage {
|
||||
return {
|
||||
body: message.body,
|
||||
emailId: message.email_id,
|
||||
id: message.message_id,
|
||||
receivers: [message.receiver],
|
||||
sendDate: message.send_date,
|
||||
sender: message.sender,
|
||||
isMine: message.sender === myEmail,
|
||||
isRead: message.receiver === myEmail ? !!message.read_at : null,
|
||||
};
|
||||
}
|
||||
|
||||
function getEmailsFromMessages(messages: UnformattedEmailMessage[], myEmail: string): IEmail[] {
|
||||
const map = messages.reduce((emails, message) => {
|
||||
if (emails.has(message.email_id)) {
|
||||
const email = emails.get(message.email_id);
|
||||
if (email.messagesMap.has(message.message_id)) {
|
||||
const currentMessage = email.messagesMap.get(message.message_id);
|
||||
if (message.receiver === myEmail && !currentMessage.isRead) {
|
||||
currentMessage.isRead === !!message.read_at;
|
||||
}
|
||||
email.messagesMap.set(message.message_id, {
|
||||
...currentMessage,
|
||||
receivers: [...currentMessage.receivers, message.receiver_identifier],
|
||||
});
|
||||
} else {
|
||||
email.messagesMap.set(message.message_id, formatMessage(message, myEmail));
|
||||
}
|
||||
emails.set(message.email_id, {
|
||||
...email,
|
||||
messages: Array.from(email.messagesMap.values()),
|
||||
});
|
||||
return emails;
|
||||
}
|
||||
const messagesMap = new Map<number, IEmailMessage>();
|
||||
messagesMap.set(message.message_id, formatMessage(message, myEmail));
|
||||
emails.set(message.email_id, {
|
||||
id: message.email_id,
|
||||
messagesMap,
|
||||
messages: Array.from(messagesMap.values()),
|
||||
subject: message.subject,
|
||||
});
|
||||
return emails;
|
||||
}, new Map<number, IEmail & { messagesMap: Map<number, IEmailMessage> }>());
|
||||
|
||||
return Array.from(map.values()).map((m) => ({ ...m, messagesMap: undefined }));
|
||||
}
|
||||
|
||||
async function sendEmail(
|
||||
sender_identifier: string,
|
||||
sender: string,
|
||||
receivers: { email: string; identifier: string }[],
|
||||
body: string,
|
||||
email_id_or_subject: number | string,
|
||||
parent_id?: number,
|
||||
) {
|
||||
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]);
|
||||
email_id = (emailResult as any).insertId;
|
||||
}
|
||||
const messageQuery = `INSERT INTO npwd_emails_messages (email_id, parent_id, send_date, body, sender, sender_identifier) VALUES (?, ?, ?, ?, ?, ?)`;
|
||||
const [messageResult] = await pool.query(messageQuery, [
|
||||
email_id,
|
||||
parent_id || null,
|
||||
Math.floor(Date.now() / 1000),
|
||||
body,
|
||||
sender,
|
||||
sender_identifier,
|
||||
]);
|
||||
|
||||
const message_id = (messageResult as any).insertId;
|
||||
|
||||
const receiverQuery = `INSERT INTO npwd_emails_receivers (message_id, receiver, receiver_identifier, read_at) VALUES (?, ?, ?, ?)`;
|
||||
const receiverPromises = receivers.map((r) =>
|
||||
pool.query(receiverQuery, [message_id, r.email, r.identifier, null]),
|
||||
);
|
||||
|
||||
await Promise.all(receiverPromises);
|
||||
|
||||
return messageResult;
|
||||
}
|
||||
|
||||
onNet(EmailEvents.FETCH_INBOX, async () => {
|
||||
const _source = getSource();
|
||||
try {
|
||||
const player = getPlayer(_source);
|
||||
if (!player) {
|
||||
throw new Error('Couldnt find player');
|
||||
}
|
||||
const playerEmail = player.getEmail();
|
||||
const messages = await fetchInbox(player.identifier);
|
||||
const inbox = getEmailsFromMessages(messages, playerEmail);
|
||||
emitNet(EmailEvents.FETCH_INBOX_SUCCESS, _source, inbox);
|
||||
} catch (e) {
|
||||
emailLogger.error(`Failed to fetch email inbox, ${e.message}`, {
|
||||
source: _source,
|
||||
});
|
||||
emitNet(EmailEvents.SEND_EMAIL_ERROR, _source, 'APPS_EMAIL_FETCH_INBOX_ERROR');
|
||||
}
|
||||
});
|
||||
|
||||
onNet(
|
||||
GlobalEmailEvents.SEND_EMAIL_TO_IDENTIFIER,
|
||||
async ({ identifier, provider, externalActions, phoneActions }: SendEmailToIdentifierInput) => {},
|
||||
);
|
||||
|
||||
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(
|
||||
parsedReceivers.map(async (email: string) => {
|
||||
const identifier = await getIdentifierByEmail(email);
|
||||
return { email, identifier };
|
||||
}),
|
||||
);
|
||||
|
||||
const email = await sendEmail(
|
||||
player.identifier,
|
||||
player.getEmail(),
|
||||
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, 'GENERIC_UNEXPECTED_ERROR');
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -23,6 +23,7 @@ export interface IEmailMessage {
|
||||
sender: string;
|
||||
sendDate: number;
|
||||
body: string;
|
||||
hasActions: boolean;
|
||||
phoneActions?: Array<IEmailPhoneAction>;
|
||||
externalActions?: Array<IEmailExternalAction>;
|
||||
}
|
||||
@@ -39,6 +40,8 @@ export interface EmailMessageInput {
|
||||
parent_id?: number;
|
||||
body: string;
|
||||
receivers: string;
|
||||
phoneActions?: IEmailPhoneAction[];
|
||||
externalActions?: IEmailExternalAction[];
|
||||
}
|
||||
|
||||
export interface SendEmailToIdentifierInput {
|
||||
@@ -61,4 +64,7 @@ export enum EmailEvents {
|
||||
SEND_EMAIL = 'npwd:sendEmail',
|
||||
SEND_EMAIL_SUCCESS = 'npwd:sendEmailSuccess',
|
||||
SEND_EMAIL_ERROR = 'npwd:sendEmailError',
|
||||
FETCH_MESSAGE_ACTIONS = 'npwd:fetchEmailMessageActions',
|
||||
FETCH_MESSAGE_ACTIONS_SUCCESS = 'npwd:fetchEmailMessageActionsSuccess',
|
||||
FETCH_MESSAGE_ACTIONS_ERROR = 'npwd:fetchEmailMessageActionsError',
|
||||
}
|
||||
Reference in new issue
Block a user