Skip to content

Commit

Permalink
βœ” Fix E-Mail (?) πŸ€”
Browse files Browse the repository at this point in the history
  • Loading branch information
bifeldy committed Jul 15, 2023
1 parent c0b8c0c commit 59621ae
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 50 deletions.
2 changes: 1 addition & 1 deletion dist/fansubid/browser/ngsw.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"configVersion": 1,
"timestamp": 1689408455246,
"timestamp": 1689420147217,
"index": "/index.html",
"assetGroups": [
{
Expand Down
2 changes: 1 addition & 1 deletion dist/fansubid/server/main.js

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion src/api/controllers/mail-/mail-inbox.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,11 @@ export class MailInboxController {
}
delete m.html;
delete m.text;
(m as any).attachment_count = m.attachment_.length;
if ('attachment_' in m && m.attachment_) {
(m as any).attachment_count = m.attachment_.length;
} else {
(m as any).attachment_count = 0;
}
delete m.attachment_;
}
return {
Expand Down
6 changes: 5 additions & 1 deletion src/api/controllers/mail-/mail-outbox.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,11 @@ export class MailOutboxController {
for (const m of mailboxs) {
delete m.html;
delete m.text;
(m as any).attachment_count = m.attachment_.length;
if ('attachment_' in m && m.attachment_) {
(m as any).attachment_count = m.attachment_.length;
} else {
(m as any).attachment_count = 0;
}
delete m.attachment_;
}
return {
Expand Down
99 changes: 59 additions & 40 deletions src/api/controllers/mail-/mail-webhook.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Controller, HttpCode, HttpException, HttpStatus, Post, Req, Res, UseInt
import { ApiExcludeController } from '@nestjs/swagger';
import { AnyFilesInterceptor, } from '@nestjs/platform-express';
import { Request, Response } from 'express';
import { In } from 'typeorm';
import { ILike, In } from 'typeorm';

import { CONSTANTS } from '../../../constants';

Expand Down Expand Up @@ -50,14 +50,26 @@ export class MailWebhookController {
async mailHook(@Req() req: Request, @Res({ passthrough: true }) res: Response): Promise<any> {
try {
if ('From' in req.body) {
const userTarget = [];
let stringRecipient = req.body.To;
let stringRecipient = '';
if (req.body.To) {
if (stringRecipient !== '') {
stringRecipient += ', ';
}
stringRecipient += req.body.To.split(',').map(v => v.trim()).join(', ');
}
if (req.body.Cc) {
stringRecipient += `, ${req.body.Cc}`;
if (stringRecipient !== '') {
stringRecipient += ', ';
}
stringRecipient += req.body.Cc.split(',').map(v => v.trim()).join(', ');
}
if (req.body.Bcc) {
stringRecipient += `, ${req.body.Bcc}`;
if (stringRecipient !== '') {
stringRecipient += ', ';
}
stringRecipient += req.body.Bcc.split(',').map(v => v.trim()).join(', ');
}
const userTarget = [];
for (const recipient of stringRecipient.split(', ')) {
if (recipient.includes(`@${environment.mailTrap.domain}`)) {
let email = recipient;
Expand All @@ -67,23 +79,40 @@ export class MailWebhookController {
userTarget.push(email.split('@')[0]);
}
}
const usersCount = await this.userRepo.count({
const userTargetSorted = userTarget.sort();
const users = await this.userRepo.find({
where: [
{
username: In(userTarget),
verified: true
}
{ username: In(userTargetSorted) }
]
});
if (usersCount === 0) {
if (users.length === 0) {
throw new HttpException({
info: `πŸ™„ 404 - Mail Webhook API :: Gagal Menyimpan Email πŸ˜ͺ`,
result: {
message: 'Pengguna Tidak Terdaftar!'
}
}, HttpStatus.NOT_FOUND);
}
const mailbox = this.mailboxRepo.new();
const mailboxs = await this.mailboxRepo.find({
where: [
{ mail: ILike(`%${req.body['Message-Id']}%`) },
{
from: ILike(req.body.From),
subject: ILike(req.body.Subject),
html: ILike(req.body['body-html']),
text: ILike(req.body['body-plain']),
date: new Date(req.body.Date)
}
]
});
let mailbox = null;
if (mailboxs.length <= 0) {
mailbox = this.mailboxRepo.new();
} else if (mailboxs.length === 1) {
mailbox = mailboxs[0];
} else {
throw new Error('Data Duplikat');
}
mailbox.mail = req.body['Message-Id'];
mailbox.from = req.body.From;
mailbox.to = req.body.To;
Expand All @@ -93,18 +122,21 @@ export class MailWebhookController {
mailbox.html = req.body['body-html'];
mailbox.text = req.body['body-plain'];
mailbox.date = new Date(req.body.Date);
let mailboxSave = await this.mailboxRepo.save(mailbox);
if (req.files?.length > 0) {
let attachments = [];
for (const file of req.files as any) {
const attachment = this.attachmentRepo.new();
attachment.name = file.filename;
attachment.ext = file.originalname.split('.').pop().toLowerCase();
attachment.size = file.size;
attachment.mime = file.mimetype;
const resAttachmentSave = await this.attachmentRepo.save(attachment);
const fileExt = file.originalname.split('.').pop().toLowerCase();
const files = readdirSync(`${environment.uploadFolder}`, { withFileTypes: true });
const fIdx = files.findIndex(f => f.name === attachment.name || f.name === `${attachment.name}.${attachment.ext}`);
const fIdx = files.findIndex(f => f.name === file.filename || f.name === `${file.filename}.${fileExt}`);
if (fIdx >= 0) {
const attachment = this.attachmentRepo.new();
attachment.pending = true;
attachment.name = file.filename;
attachment.ext = fileExt;
attachment.size = file.size;
attachment.mime = file.mimetype;
const resAttachmentSave = await this.attachmentRepo.save(attachment);
attachments.push(resAttachmentSave);
// Upload Attachment -- Jpg, Png, etc
if (environment.production) {
Expand All @@ -121,34 +153,21 @@ export class MailWebhookController {
},
fields: 'id'
}, { signal: null });
resAttachmentSave.mime = dfile.data.mimeType;
resAttachmentSave.google_drive = dfile.data.id;
resAttachmentSave.pending = false;
await this.attachmentRepo.save(resAttachmentSave);
this.gs.deleteAttachment(files[fIdx].name);
}).catch(e => this.gs.log('[GDRIVE-ERROR] πŸ’½', e, 'error'));
}
} else {
await this.attachmentRepo.remove(resAttachmentSave);
for (const a of attachments) {
if (a.google_drive) {
this.gdrive.gDrive(true).then(async (gdrive) => {
await gdrive.files.delete({ fileId: a.google_drive }, { signal: null });
}).catch(e => this.gs.log('[GDRIVE-ERROR] πŸ’½', e, 'error'));
}
await this.attachmentRepo.remove(a);
}).catch(async (e) => {
this.gs.log('[GDRIVE-ERROR] πŸ’½', e, 'error');
resAttachmentSave.pending = false;
await this.attachmentRepo.save(resAttachmentSave);
});
}
attachments = [];
throw new HttpException({
info: `πŸ™„ 404 - Mail Webhook API :: Gagal Mencari Lampiran πŸ˜ͺ`,
result: {
message: 'Lampiran Tidak Ditemukan!'
}
}, HttpStatus.NOT_FOUND);
}
}
mailbox.attachment_ = attachments;
mailboxSave.attachment_ = attachments;
}
const mailboxSave = await this.mailboxRepo.save(mailbox);
mailboxSave = await this.mailboxRepo.save(mailboxSave);
return {
info: '😍 201 - Mail Webhook API :: Receive New Email πŸ₯°',
header: req.headers,
Expand Down
22 changes: 16 additions & 6 deletions src/api/controllers/mail.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,11 @@ export class MailController {
for (const m of mailboxs) {
delete m.html;
delete m.text;
(m as any).attachment_count = m.attachment_.length;
if ('attachment_' in m && m.attachment_) {
(m as any).attachment_count = m.attachment_.length;
} else {
(m as any).attachment_count = 0;
}
delete m.attachment_;
}
return {
Expand Down Expand Up @@ -205,6 +209,12 @@ export class MailController {
mailbox.mail = mailSend.message_ids[0];
mailbox.date = new Date();
const mailboxSave = await this.mailboxRepo.save(mailbox);
if ('attachment_' in mailboxSave && mailboxSave.attachment_) {
for (const a of mailboxSave.attachment_) {
delete a.created_at;
delete a.updated_at;
}
}
return {
info: 'πŸ™‚ 201 - Mail API :: Email Terkirim! πŸ₯°',
result: mailboxSave
Expand Down Expand Up @@ -252,17 +262,17 @@ export class MailController {
}
}, HttpStatus.FORBIDDEN);
}
if (user.role !== RoleModel.ADMIN && user.role !== RoleModel.MODERATOR) {
if (mailbox.bcc?.includes(`${user.username}@${environment.mailTrap.domain}`)) {
mailbox.bcc = `${user.username}@${environment.mailTrap.domain}`;
}
}
if ('attachment_' in mailbox && mailbox.attachment_) {
for (const a of mailbox.attachment_) {
delete a.created_at;
delete a.updated_at;
}
}
if (user.role !== RoleModel.ADMIN && user.role !== RoleModel.MODERATOR) {
if (mailbox.bcc?.includes(`${user.username}@${environment.mailTrap.domain}`)) {
mailbox.bcc = `${user.username}@${environment.mailTrap.domain}`;
}
}
return {
info: `πŸ˜… 200 - Mail API :: Detail ${req.params['id']} 🀣`,
result: mailbox
Expand Down

0 comments on commit 59621ae

Please sign in to comment.