snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
This commit is contained in:
98
apps/meteor/server/features/EmailInbox/EmailInbox.ts
Normal file
98
apps/meteor/server/features/EmailInbox/EmailInbox.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import type { IEmailInbox } from '@rocket.chat/core-typings';
|
||||
import { EmailInbox, EmailMessageHistory } from '@rocket.chat/models';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import nodemailer from 'nodemailer';
|
||||
import type Mail from 'nodemailer/lib/mailer';
|
||||
|
||||
import { onEmailReceived } from './EmailInbox_Incoming';
|
||||
import { logger } from './logger';
|
||||
import { IMAPInterceptor } from '../../email/IMAPInterceptor';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
export type Inbox = {
|
||||
imap: IMAPInterceptor;
|
||||
smtp: Mail;
|
||||
config: IEmailInbox;
|
||||
};
|
||||
|
||||
export const inboxes = new Map<string, Inbox>();
|
||||
|
||||
export async function configureEmailInboxes(): Promise<void> {
|
||||
const emailInboxesCursor = EmailInbox.findActive();
|
||||
|
||||
logger.info('Clearing old email inbox registrations');
|
||||
for (const { imap } of inboxes.values()) {
|
||||
imap.stop();
|
||||
}
|
||||
|
||||
inboxes.clear();
|
||||
|
||||
for await (const emailInboxRecord of emailInboxesCursor) {
|
||||
try {
|
||||
logger.info({ msg: 'Setting up email interceptor', email: emailInboxRecord.email });
|
||||
|
||||
const imap = new IMAPInterceptor(
|
||||
{
|
||||
password: emailInboxRecord.imap.password,
|
||||
user: emailInboxRecord.imap.username,
|
||||
host: emailInboxRecord.imap.server,
|
||||
port: emailInboxRecord.imap.port,
|
||||
...(emailInboxRecord.imap.secure
|
||||
? {
|
||||
tls: emailInboxRecord.imap.secure,
|
||||
tlsOptions: {
|
||||
rejectUnauthorized: false,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
{
|
||||
deleteAfterRead: false,
|
||||
filter: [['UNSEEN'], ['SINCE', emailInboxRecord._createdAt]],
|
||||
rejectBeforeTS: emailInboxRecord._createdAt,
|
||||
markSeen: true,
|
||||
maxRetries: emailInboxRecord.imap.maxRetries,
|
||||
},
|
||||
emailInboxRecord._id,
|
||||
);
|
||||
|
||||
imap.on('email', async (email) => {
|
||||
if (!email.messageId) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await EmailMessageHistory.create({ _id: email.messageId, email: emailInboxRecord.email });
|
||||
void onEmailReceived(email, emailInboxRecord.email, emailInboxRecord.department);
|
||||
} catch (err: any) {
|
||||
// In case the email message history has been received by other instance..
|
||||
logger.error({ err });
|
||||
}
|
||||
});
|
||||
|
||||
await imap.start();
|
||||
|
||||
const smtp = nodemailer.createTransport({
|
||||
host: emailInboxRecord.smtp.server,
|
||||
port: emailInboxRecord.smtp.port,
|
||||
secure: emailInboxRecord.smtp.secure,
|
||||
auth: {
|
||||
user: emailInboxRecord.smtp.username,
|
||||
pass: emailInboxRecord.smtp.password,
|
||||
},
|
||||
});
|
||||
|
||||
inboxes.set(emailInboxRecord.email, { imap, smtp, config: emailInboxRecord });
|
||||
} catch (err) {
|
||||
logger.error({ msg: 'Error setting up email interceptor', email: emailInboxRecord.email, err });
|
||||
}
|
||||
}
|
||||
|
||||
logger.info({ msg: 'Configured a total of inboxes', count: inboxes.size });
|
||||
}
|
||||
|
||||
Meteor.startup(() => {
|
||||
settings.watchOnce('Livechat_Routing_Method', (_) => {
|
||||
void configureEmailInboxes();
|
||||
});
|
||||
});
|
||||
254
apps/meteor/server/features/EmailInbox/EmailInbox_Incoming.ts
Normal file
254
apps/meteor/server/features/EmailInbox/EmailInbox_Incoming.ts
Normal file
@@ -0,0 +1,254 @@
|
||||
import type {
|
||||
ILivechatVisitor,
|
||||
IOmnichannelRoom,
|
||||
VideoAttachmentProps,
|
||||
ImageAttachmentProps,
|
||||
AudioAttachmentProps,
|
||||
} from '@rocket.chat/core-typings';
|
||||
import { OmnichannelSourceType } from '@rocket.chat/core-typings';
|
||||
import { LivechatVisitors, LivechatRooms, Messages } from '@rocket.chat/models';
|
||||
import { registerGuest } from '@rocket.chat/omni-core';
|
||||
import { Random } from '@rocket.chat/random';
|
||||
import type { ParsedMail, Attachment } from 'mailparser';
|
||||
import { stripHtml } from 'string-strip-html';
|
||||
|
||||
import { logger } from './logger';
|
||||
import { i18n } from '../../lib/i18n';
|
||||
import { FileUpload } from '../../lib/media/file-upload';
|
||||
import { notifyOnMessageChange } from '../../lib/notifyListener';
|
||||
import { QueueManager } from '../../lib/omnichannel/QueueManager';
|
||||
import { setDepartmentForGuest } from '../../lib/omnichannel/departmentsLib';
|
||||
import { sendMessage } from '../../lib/omnichannel/messages';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
type FileAttachment = VideoAttachmentProps & ImageAttachmentProps & AudioAttachmentProps;
|
||||
|
||||
const language = settings.get<string>('Language') || 'en';
|
||||
const t = i18n.getFixedT(language);
|
||||
|
||||
async function getGuestByEmail(email: string, name: string, department = ''): Promise<ILivechatVisitor | null> {
|
||||
const guest = await LivechatVisitors.findOneGuestByEmailAddress(email);
|
||||
|
||||
if (guest) {
|
||||
if (guest.department !== department) {
|
||||
if (!department) {
|
||||
await LivechatVisitors.removeDepartmentById(guest._id);
|
||||
delete guest.department;
|
||||
return guest;
|
||||
}
|
||||
return setDepartmentForGuest({ visitorId: guest._id, department });
|
||||
}
|
||||
return guest;
|
||||
}
|
||||
|
||||
const livechatVisitor = await registerGuest(
|
||||
{
|
||||
token: Random.id(),
|
||||
name: name || email,
|
||||
email,
|
||||
department,
|
||||
},
|
||||
{
|
||||
shouldConsiderIdleAgent: settings.get<boolean>('Livechat_enabled_when_agent_idle'),
|
||||
shouldConsiderOfflineAgent: settings.get<boolean>('Livechat_accept_chats_with_no_agents'),
|
||||
},
|
||||
);
|
||||
|
||||
if (!livechatVisitor) {
|
||||
throw new Error('Error getting guest');
|
||||
}
|
||||
|
||||
return livechatVisitor;
|
||||
}
|
||||
|
||||
async function uploadAttachment(attachmentParam: Attachment, rid: string, visitorToken: string): Promise<Partial<FileAttachment>> {
|
||||
const details = {
|
||||
name: attachmentParam.filename,
|
||||
size: attachmentParam.size,
|
||||
type: attachmentParam.contentType,
|
||||
rid,
|
||||
visitorToken,
|
||||
};
|
||||
|
||||
const fileStore = FileUpload.getStore('Uploads');
|
||||
|
||||
const file = await fileStore.insert(details, attachmentParam.content);
|
||||
|
||||
const url = FileUpload.getPath(`${file._id}/${encodeURI(file.name || '')}`);
|
||||
|
||||
const attachment: Partial<FileAttachment> = {
|
||||
title: file.name || '',
|
||||
title_link: url,
|
||||
};
|
||||
|
||||
if (file.type && /^image\/.+/.test(file.type)) {
|
||||
attachment.image_url = url;
|
||||
attachment.image_type = file.type;
|
||||
attachment.image_size = file.size;
|
||||
attachment.image_dimensions = file.identify?.size != null ? file.identify.size : undefined;
|
||||
}
|
||||
|
||||
if (file.type && /^audio\/.+/.test(file.type)) {
|
||||
attachment.audio_url = url;
|
||||
attachment.audio_type = file.type;
|
||||
attachment.audio_size = file.size;
|
||||
}
|
||||
|
||||
if (file.type && /^video\/.+/.test(file.type)) {
|
||||
attachment.video_url = url;
|
||||
attachment.video_type = file.type;
|
||||
attachment.video_size = file.size;
|
||||
}
|
||||
|
||||
return attachment;
|
||||
}
|
||||
|
||||
export async function onEmailReceived(email: ParsedMail, inbox: string, department = ''): Promise<void> {
|
||||
logger.info({ msg: 'New email conversation received on inbox. Will be assigned to department', inbox, department });
|
||||
if (!email.from?.value?.[0]?.address) {
|
||||
return;
|
||||
}
|
||||
|
||||
const references = typeof email.references === 'string' ? [email.references] : email.references;
|
||||
const initialRef = [email.messageId, email.inReplyTo].filter(Boolean) as string[];
|
||||
const thread = (references?.length ? references : []).flatMap((t: string) => t.split(',')).concat(initialRef);
|
||||
const guest = await getGuestByEmail(email.from.value[0].address, email.from.value[0].name, department);
|
||||
|
||||
if (!guest) {
|
||||
logger.error({ msg: 'No visitor found', address: email.from.value[0].address });
|
||||
return;
|
||||
}
|
||||
|
||||
let room: IOmnichannelRoom | null = await LivechatRooms.findOneByVisitorTokenAndEmailThreadAndDepartment(
|
||||
guest.token,
|
||||
thread,
|
||||
department,
|
||||
{},
|
||||
);
|
||||
|
||||
logger.debug({
|
||||
msg: 'Room found for guest',
|
||||
room,
|
||||
guest,
|
||||
});
|
||||
|
||||
if (room?.closedAt) {
|
||||
room = await QueueManager.unarchiveRoom(room);
|
||||
}
|
||||
|
||||
// TODO: html => md with turndown
|
||||
const msg = email.html
|
||||
? stripHtml(email.html, {
|
||||
dumpLinkHrefsNearby: {
|
||||
enabled: true,
|
||||
putOnNewLine: false,
|
||||
wrapHeads: '(',
|
||||
wrapTails: ')',
|
||||
},
|
||||
skipHtmlDecoding: false,
|
||||
}).result
|
||||
: email.text || '';
|
||||
|
||||
const rid = room?._id ?? Random.id();
|
||||
const msgId = Random.id();
|
||||
|
||||
sendMessage({
|
||||
guest,
|
||||
message: {
|
||||
_id: msgId,
|
||||
groupable: false,
|
||||
msg,
|
||||
token: guest.token,
|
||||
attachments: [
|
||||
{
|
||||
actions: [
|
||||
{
|
||||
type: 'button',
|
||||
text: t('Reply_via_Email'),
|
||||
msg: 'msg',
|
||||
msgId,
|
||||
msg_in_chat_window: true,
|
||||
msg_processing_type: 'respondWithQuotedMessage',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
blocks: [
|
||||
{
|
||||
type: 'context',
|
||||
elements: [
|
||||
{
|
||||
type: 'mrkdwn',
|
||||
text: `**${t('From')}:** ${email.from.text}\n**${t('Subject')}:** ${email.subject}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'section',
|
||||
text: {
|
||||
type: 'mrkdwn',
|
||||
text: msg,
|
||||
},
|
||||
},
|
||||
],
|
||||
rid,
|
||||
email: {
|
||||
thread,
|
||||
messageId: email.messageId,
|
||||
},
|
||||
},
|
||||
roomInfo: {
|
||||
email: {
|
||||
inbox,
|
||||
thread,
|
||||
replyTo: email.from.value[0].address,
|
||||
subject: email.subject,
|
||||
},
|
||||
source: {
|
||||
type: OmnichannelSourceType.EMAIL,
|
||||
id: inbox,
|
||||
alias: 'email-inbox',
|
||||
},
|
||||
},
|
||||
agent: undefined,
|
||||
})
|
||||
.then(async () => {
|
||||
if (!email.attachments.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const attachments = [];
|
||||
for await (const attachment of email.attachments) {
|
||||
if (attachment.type !== 'attachment') {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
attachments.push(await uploadAttachment(attachment, rid, guest.token));
|
||||
} catch (err) {
|
||||
logger.error({ msg: 'Error uploading attachment from email', err });
|
||||
}
|
||||
}
|
||||
|
||||
await Messages.updateOne(
|
||||
{ _id: msgId },
|
||||
{
|
||||
$addToSet: {
|
||||
attachments: {
|
||||
$each: attachments,
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
room && (await LivechatRooms.updateEmailThreadByRoomId(room._id, thread));
|
||||
void notifyOnMessageChange({
|
||||
id: msgId,
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
logger.error({
|
||||
msg: 'Error receiving email',
|
||||
err,
|
||||
});
|
||||
});
|
||||
}
|
||||
346
apps/meteor/server/features/EmailInbox/EmailInbox_Outgoing.ts
Normal file
346
apps/meteor/server/features/EmailInbox/EmailInbox_Outgoing.ts
Normal file
@@ -0,0 +1,346 @@
|
||||
import { isIMessageInbox } from '@rocket.chat/core-typings';
|
||||
import type { IEmailInbox, IUser, IOmnichannelRoom, SlashCommandCallbackParams, IUpload } from '@rocket.chat/core-typings';
|
||||
import { Messages, Uploads, LivechatRooms, Rooms, Users } from '@rocket.chat/models';
|
||||
import { isTruthy } from '@rocket.chat/tools';
|
||||
import { Match } from 'meteor/check';
|
||||
import type Mail from 'nodemailer/lib/mailer';
|
||||
|
||||
import { inboxes } from './EmailInbox';
|
||||
import type { Inbox } from './EmailInbox';
|
||||
import { logger } from './logger';
|
||||
import { callbacks } from '../../lib/callbacks';
|
||||
import { i18n } from '../../lib/i18n';
|
||||
import { FileUpload } from '../../lib/media/file-upload';
|
||||
import { sendMessage } from '../../lib/messages/sendMessage';
|
||||
import { notifyOnMessageChange } from '../../lib/notifyListener';
|
||||
import { slashCommands } from '../../lib/utils/slashCommand';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
const livechatQuoteRegExp = /^\[\s\]\(https?:\/\/.+\/live\/.+\?msg=(?<id>.+?)\)\s(?<text>.+)/s;
|
||||
|
||||
const getRocketCatUser = async (): Promise<IUser | null> => Users.findOneById('rocket.cat');
|
||||
|
||||
const language = settings.get<string>('Language') || 'en';
|
||||
const t = i18n.getFixedT(language);
|
||||
|
||||
async function buildMailAttachment(file: IUpload): Promise<Mail.Attachment | undefined> {
|
||||
const buffer = await FileUpload.getBuffer(file);
|
||||
if (!buffer) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
content: buffer,
|
||||
contentType: file.type,
|
||||
filename: file.name,
|
||||
};
|
||||
}
|
||||
|
||||
// TODO: change these messages with room notifications
|
||||
const sendErrorReplyMessage = async (error: string, options: any) => {
|
||||
if (!options?.rid || !options?.msgId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = {
|
||||
groupable: false,
|
||||
msg: `@${options.sender} something went wrong when replying email, sorry. **Error:**: ${error}`,
|
||||
_id: String(Date.now()),
|
||||
rid: options.rid,
|
||||
ts: new Date(),
|
||||
};
|
||||
|
||||
const user = await getRocketCatUser();
|
||||
if (!user) {
|
||||
return;
|
||||
}
|
||||
|
||||
return sendMessage(user, message, { _id: options.rid });
|
||||
};
|
||||
|
||||
const sendSuccessReplyMessage = async (options: { room: IOmnichannelRoom; msgId: string; sender: string }) => {
|
||||
if (!options?.room?._id || !options?.msgId) {
|
||||
return;
|
||||
}
|
||||
const message = {
|
||||
groupable: false,
|
||||
msg: `@${options.sender} Attachment was sent successfully`,
|
||||
_id: String(Date.now()),
|
||||
rid: options.room._id,
|
||||
ts: new Date(),
|
||||
};
|
||||
|
||||
const user = await getRocketCatUser();
|
||||
if (!user) {
|
||||
return;
|
||||
}
|
||||
|
||||
return sendMessage(user, message, options.room);
|
||||
};
|
||||
|
||||
async function sendEmail(inbox: Inbox, mail: Mail.Options, options?: any): Promise<{ messageId: string }> {
|
||||
return inbox.smtp
|
||||
.sendMail({
|
||||
from: inbox.config.senderInfo
|
||||
? {
|
||||
name: inbox.config.senderInfo,
|
||||
address: inbox.config.email,
|
||||
}
|
||||
: inbox.config.email,
|
||||
...mail,
|
||||
})
|
||||
.then((info) => {
|
||||
logger.info({ msg: 'Message sent', info });
|
||||
return info;
|
||||
})
|
||||
.catch(async (err) => {
|
||||
logger.error({ msg: 'Error sending Email reply', err });
|
||||
|
||||
if (!options?.msgId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await sendErrorReplyMessage(err.message, options);
|
||||
});
|
||||
}
|
||||
|
||||
slashCommands.add({
|
||||
command: 'sendEmailAttachment',
|
||||
callback: async ({ command, params }: SlashCommandCallbackParams<'sendEmailAttachment'>) => {
|
||||
if (command !== 'sendEmailAttachment' || !Match.test(params, String)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = await Messages.findOneById(params.trim());
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fileRefs = (message.files || [message.file]).filter(isTruthy);
|
||||
if (!fileRefs.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const room = await Rooms.findOneById<IOmnichannelRoom>(message.rid);
|
||||
if (!room?.email) {
|
||||
return;
|
||||
}
|
||||
|
||||
const inbox = inboxes.get(room.email.inbox);
|
||||
|
||||
if (!inbox) {
|
||||
return sendErrorReplyMessage(`Email inbox ${room.email.inbox} not found or disabled.`, {
|
||||
msgId: message._id,
|
||||
sender: message.u.username,
|
||||
rid: room._id,
|
||||
});
|
||||
}
|
||||
|
||||
const files = await Uploads.find({ _id: { $in: fileRefs.map((f) => f._id) } }).toArray();
|
||||
const emailAttachments = await Promise.all(files.map(buildMailAttachment));
|
||||
const validAttachments = emailAttachments.filter((a): a is Mail.Attachment => Boolean(a));
|
||||
if (validAttachments.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const emailText =
|
||||
message?.attachments
|
||||
?.map((a) => a.description)
|
||||
.filter(Boolean)
|
||||
.join('\n\n') || '';
|
||||
|
||||
void sendEmail(
|
||||
inbox,
|
||||
{
|
||||
to: room.email?.replyTo,
|
||||
subject: room.email?.subject,
|
||||
text: emailText,
|
||||
attachments: validAttachments,
|
||||
inReplyTo: Array.isArray(room.email?.thread) ? room.email?.thread[0] : room.email?.thread,
|
||||
references: ([] as string[]).concat(room.email?.thread || []),
|
||||
},
|
||||
{
|
||||
msgId: message._id,
|
||||
sender: message.u.username,
|
||||
rid: message.rid,
|
||||
},
|
||||
).then((info) => LivechatRooms.updateEmailThreadByRoomId(room._id, info.messageId));
|
||||
|
||||
await Messages.updateOne(
|
||||
{ _id: message._id },
|
||||
{
|
||||
$set: {
|
||||
blocks: [
|
||||
{
|
||||
type: 'context',
|
||||
elements: [
|
||||
{
|
||||
type: 'mrkdwn',
|
||||
text: `**${t('To')}:** ${room.email.replyTo}\n**${t('Subject')}:** ${room.email.subject}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
$pull: {
|
||||
attachments: { 'actions.0.type': 'button' },
|
||||
},
|
||||
},
|
||||
);
|
||||
void notifyOnMessageChange({
|
||||
id: message._id,
|
||||
});
|
||||
|
||||
return sendSuccessReplyMessage({
|
||||
msgId: message._id,
|
||||
sender: message.u.username,
|
||||
room,
|
||||
});
|
||||
},
|
||||
options: {
|
||||
description: 'Send attachment as email',
|
||||
params: 'msg_id',
|
||||
},
|
||||
providesPreview: false,
|
||||
});
|
||||
|
||||
callbacks.add(
|
||||
'afterSaveMessage',
|
||||
async (message, { room: omnichannelRoom }) => {
|
||||
const room = omnichannelRoom as IOmnichannelRoom;
|
||||
|
||||
if (!room?.email?.inbox) {
|
||||
return message;
|
||||
}
|
||||
|
||||
const user = await getRocketCatUser();
|
||||
if (!user) {
|
||||
return message;
|
||||
}
|
||||
|
||||
if (message.files?.length && message.u.username !== 'rocket.cat') {
|
||||
await sendMessage(
|
||||
user,
|
||||
{
|
||||
msg: '',
|
||||
attachments: [
|
||||
{
|
||||
actions: [
|
||||
{
|
||||
type: 'button',
|
||||
text: t('Send_via_Email_as_attachment'),
|
||||
msg: `/sendEmailAttachment ${message._id}`,
|
||||
msg_in_chat_window: true,
|
||||
msg_processing_type: 'sendMessage',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
room,
|
||||
{ upsert: true },
|
||||
);
|
||||
return message;
|
||||
}
|
||||
|
||||
const { msg } = message;
|
||||
|
||||
// Try to identify a quote in a livechat room
|
||||
const match = msg.match(livechatQuoteRegExp);
|
||||
if (!match?.groups) {
|
||||
return message;
|
||||
}
|
||||
|
||||
const inbox = inboxes.get(room.email.inbox);
|
||||
|
||||
if (!inbox) {
|
||||
await sendErrorReplyMessage(`Email inbox ${room.email.inbox} not found or disabled.`, {
|
||||
msgId: message._id,
|
||||
sender: message.u.username,
|
||||
rid: room._id,
|
||||
});
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
if (!inbox) {
|
||||
return message;
|
||||
}
|
||||
|
||||
const replyToMessage = await Messages.findOneById(match.groups.id);
|
||||
if (!replyToMessage || !isIMessageInbox(replyToMessage) || !replyToMessage.email?.messageId) {
|
||||
return message;
|
||||
}
|
||||
|
||||
void sendEmail(
|
||||
inbox,
|
||||
{
|
||||
text: match.groups.text,
|
||||
inReplyTo: replyToMessage.email.messageId,
|
||||
references: [...(replyToMessage.email.references ?? []), replyToMessage.email.messageId],
|
||||
to: room.email.replyTo,
|
||||
subject: room.email.subject,
|
||||
},
|
||||
{
|
||||
msgId: message._id,
|
||||
sender: message.u.username,
|
||||
rid: room._id,
|
||||
},
|
||||
).then((info) => LivechatRooms.updateEmailThreadByRoomId(room._id, info.messageId));
|
||||
|
||||
message.msg = match.groups.text;
|
||||
|
||||
message.groupable = false;
|
||||
|
||||
message.blocks = [
|
||||
{
|
||||
type: 'context',
|
||||
elements: [
|
||||
{
|
||||
type: 'mrkdwn',
|
||||
text: `**${t('To')}:** ${room.email.replyTo}\n**${t('Subject')}:** ${room.email.subject}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'section',
|
||||
text: {
|
||||
type: 'mrkdwn',
|
||||
text: message.msg,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'section',
|
||||
text: {
|
||||
type: 'mrkdwn',
|
||||
text: `> ---\n${replyToMessage.msg.replace(/^/gm, '> ')}`,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
delete message.urls;
|
||||
|
||||
return message;
|
||||
},
|
||||
callbacks.priority.LOW,
|
||||
'ReplyEmail',
|
||||
);
|
||||
|
||||
export async function sendTestEmailToInbox(emailInboxRecord: IEmailInbox, user: IUser): Promise<void> {
|
||||
const inbox = inboxes.get(emailInboxRecord.email);
|
||||
|
||||
if (!inbox) {
|
||||
throw new Error('inbox-not-found');
|
||||
}
|
||||
|
||||
const address = user.emails?.find((email) => email.verified)?.address;
|
||||
|
||||
if (!address) {
|
||||
throw new Error('user-without-verified-email');
|
||||
}
|
||||
|
||||
void sendEmail(inbox, {
|
||||
to: address,
|
||||
subject: 'Test of inbox configuration',
|
||||
text: 'Test of inbox configuration successful',
|
||||
});
|
||||
}
|
||||
2
apps/meteor/server/features/EmailInbox/index.ts
Normal file
2
apps/meteor/server/features/EmailInbox/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
import './EmailInbox_Incoming';
|
||||
import './EmailInbox_Outgoing';
|
||||
3
apps/meteor/server/features/EmailInbox/logger.ts
Normal file
3
apps/meteor/server/features/EmailInbox/logger.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { Logger } from '@rocket.chat/logger';
|
||||
|
||||
export const logger = new Logger('EmailInbox');
|
||||
Reference in New Issue
Block a user