feat: provide send mail through user gmail

This commit is contained in:
prafull-opensignlabs
2024-04-19 20:56:43 +05:30
parent 9890d568fd
commit f14c98505a
7 changed files with 395 additions and 100 deletions
+72 -65
View File
@@ -94,7 +94,7 @@ async function sendCompletedMail(e) {
} catch (e) {
console.log('error in fetch tenant in signpdf', e.message);
}
e = {
g = {
extUserId: s.objectId,
url: a,
from: 'OpenSign™',
@@ -102,8 +102,9 @@ async function sendCompletedMail(e) {
subject: o,
pdfName: r,
html: n,
isMailProvider: e.isMailProvider,
};
await axios.post(serverUrl + '/functions/sendmailv3', e, {
await axios.post(serverUrl + '/functions/sendmailv3', g, {
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': APPID,
@@ -173,8 +174,9 @@ async function PDF(o) {
try {
var n = o.params.docId,
e = o.params.userId,
l = o.params.isCustomCompletionMail,
d = await axios.get(
l = o.params.isCustomCompletionMail || !1,
d = o.params.isMailProvider || !1,
c = await axios.get(
serverUrl + '/classes/contracts_Document/' + n + '?include=ExtUserPtr,Signers',
{
headers: {
@@ -184,33 +186,33 @@ async function PDF(o) {
},
}
),
c = await axios.get(serverUrl + '/users/me', {
p = await axios.get(serverUrl + '/users/me', {
headers: {
'X-Parse-Application-Id': APPID,
'X-Parse-Session-Token': o.headers.sessiontoken,
},
});
if (!c.data || !c.data.objectId) return { status: 'error', message: 'This user not allowed!' };
if (!p.data || !p.data.objectId) return { status: 'error', message: 'This user not allowed!' };
{
var a,
t,
s,
p = JSON.stringify({ objectId: e });
m = JSON.stringify({ objectId: e });
let r, i;
i = e
? (a = await axios.get(serverUrl + '/classes/contracts_Contactbook?where=' + p, {
? (a = await axios.get(serverUrl + '/classes/contracts_Contactbook?where=' + m, {
headers: {
'X-Parse-Application-Id': APPID,
'X-Parse-Session-Token': o.headers.sessiontoken,
},
})).data && 0 < a.data.results.length
? ((r = a), 'contracts_Contactbook')
: ((r = await axios.get(serverUrl + '/classes/contracts_Users?where=' + p, {
: ((r = await axios.get(serverUrl + '/classes/contracts_Users?where=' + m, {
headers: { 'X-Parse-Application-Id': APPID, 'X-Parse-Master-Key': masterKEY },
})),
'contracts_Users')
: ((t = JSON.stringify({
UserId: { __type: 'Pointer', className: '_User', objectId: c.data.objectId },
UserId: { __type: 'Pointer', className: '_User', objectId: p.data.objectId },
})),
(s = await axios.get(serverUrl + '/classes/contracts_Users?where=' + t, {
headers: { 'X-Parse-Application-Id': APPID, 'X-Parse-Master-Key': masterKEY },
@@ -223,68 +225,67 @@ async function PDF(o) {
},
})),
'contracts_Contactbook'));
var m = r.data.results[0].Name,
g = r.data.results[0].Email;
var g = r.data.results[0].Name,
u = r.data.results[0].Email;
if (!o.params.pdfFile) return { status: 'error', message: 'Pdf file not present!' };
{
let e = Buffer.from(o.params.pdfFile, 'base64');
var u = process.env.PFX_BASE64,
h = Buffer.from(u, 'base64'),
f = {
var h = process.env.PFX_BASE64,
f = Buffer.from(h, 'base64'),
P = {
UserPtr: { __type: 'Pointer', className: i, objectId: r.data.results[0].objectId },
SignedUrl: '',
Activity: 'Signed',
ipAddress: o.headers['x-real-ip'],
};
let a;
var P = (a =
d.data.AuditTrail && 0 < d.data.AuditTrail.length
? [...d.data.AuditTrail, f]
: [f]).filter(e => 'Signed' === e.Activity);
var y = (a =
c.data.AuditTrail && 0 < c.data.AuditTrail.length
? [...c.data.AuditTrail, P]
: [P]).filter(e => 'Signed' === e.Activity);
let t = !1;
!(
(d.data.Signers && 0 < d.data.Signers.length && P.length !== d.data.Signers.length) ||
(c.data.Signers && 0 < c.data.Signers.length && y.length !== c.data.Signers.length) ||
!(t = !0)
);
var y,
var v,
b,
v,
U,
I,
w,
D = `exported_file_${Math.floor(5e3 * Math.random())}.pdf`,
S = './exports/' + D;
D,
S = `exported_file_${Math.floor(5e3 * Math.random())}.pdf`,
_ = './exports/' + S;
let s = e.length;
s = (
t
? ((y = d.data.Signers?.map(e => e.Name + ' <' + e.Email + '>')),
? ((v = c.data.Signers?.map(e => e.Name + ' <' + e.Email + '>')),
(e =
y && 0 < y.length
v && 0 < v.length
? ((b = await PDFDocument.load(e)),
pdflibAddPlaceholder({
pdfDoc: b,
reason: 'Digitally signed by OpenSign for ' + y?.join(', '),
reason: 'Digitally signed by OpenSign for ' + v?.join(', '),
location: 'n/a',
signatureLength: 15e3,
}),
(v = await b.save()),
Buffer.from(v))
: ((U = await PDFDocument.load(e)),
(U = await b.save()),
Buffer.from(U))
: ((I = await PDFDocument.load(e)),
pdflibAddPlaceholder({
pdfDoc: U,
reason: 'Digitally signed by OpenSign for ' + m + ' <' + g + '>',
pdfDoc: I,
reason: 'Digitally signed by OpenSign for ' + g + ' <' + u + '>',
location: 'n/a',
signatureLength: 15e3,
}),
(I = await U.save()),
Buffer.from(I))),
(w = await new SignPDF(e, h).signPDF()),
fs.writeFileSync(S, w),
w)
: (fs.writeFileSync(S, e), e)
(w = await I.save()),
Buffer.from(w))),
(D = await new SignPDF(e, f).signPDF()),
fs.writeFileSync(_, D),
D)
: (fs.writeFileSync(_, e), e)
).length;
var _,
A,
var A,
x,
E,
j,
@@ -292,55 +293,61 @@ async function PDF(o) {
F,
C,
T,
N = await uploadFile(D, S);
M,
N = await uploadFile(S, _);
if (N && N.imageUrl)
return (
(_ = await updateDoc(
(A = await updateDoc(
o.params.docId,
N.imageUrl,
r.data.results[0].objectId,
o.headers['x-real-ip'],
d.data,
c.data,
i
)),
sendDoctoWebhook(d, N.imageUrl, 'signed', r?.data.results?.[0]),
saveFileUsage(s, N.imageUrl, c.data.objectId),
_ &&
_.isCompleted &&
((A = { ...d.data, AuditTrail: _.AuditTrail }),
(x = await GenerateCertificate(A)),
(E = await PDFDocument.load(x)),
sendDoctoWebhook(c, N.imageUrl, 'signed', r?.data.results?.[0]),
saveFileUsage(s, N.imageUrl, p.data.objectId),
A &&
A.isCompleted &&
((x = { ...c.data, AuditTrail: A.AuditTrail }),
(E = await GenerateCertificate(x)),
(j = await PDFDocument.load(E)),
pdflibAddPlaceholder({
pdfDoc: E,
pdfDoc: j,
reason: 'Digitally signed by OpenSign.',
location: 'n/a',
signatureLength: 15e3,
}),
(j = await E.save()),
(k = Buffer.from(j)),
(F = await new SignPDF(k, h).signPDF()),
fs.writeFileSync('./exports/certificate.pdf', F),
(T = {
CertificateUrl: (C = await uploadFile(
(k = await j.save()),
(F = Buffer.from(k)),
(C = await new SignPDF(F, f).signPDF()),
fs.writeFileSync('./exports/certificate.pdf', C),
(M = {
CertificateUrl: (T = await uploadFile(
'certificate.pdf',
'./exports/certificate.pdf'
)).imageUrl,
}),
await axios.put(serverUrl + '/classes/contracts_Document/' + n, T, {
await axios.put(serverUrl + '/classes/contracts_Document/' + n, M, {
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': APPID,
'X-Parse-Master-Key': masterKEY,
},
}),
d.data.IsSendMail && !1 === d.data.IsSendMail
c.data.IsSendMail && !1 === c.data.IsSendMail
? console.log("don't send mail")
: sendCompletedMail({ url: N.imageUrl, isCustomMail: l, doc: d.data }),
saveFileUsage(k.length, C.imageUrl, c.data.objectId),
sendDoctoWebhook(d, N.imageUrl, 'completed')),
fs.unlinkSync(S),
console.log('New Signed PDF created called: ' + S),
'success' === _.message
: sendCompletedMail({
url: N.imageUrl,
isCustomMail: l,
doc: c.data,
isMailProvider: d,
}),
saveFileUsage(F.length, T.imageUrl, p.data.objectId),
sendDoctoWebhook(c, N.imageUrl, 'completed')),
fs.unlinkSync(_),
console.log('New Signed PDF created called: ' + _),
'success' === A.message
? { status: 'success', data: N.imageUrl }
: { status: 'error', message: 'Please provide required parameters!' }
);
@@ -0,0 +1,141 @@
import axios from 'axios';
import { google } from 'googleapis';
import fs from 'node:fs';
import https from 'https';
const clientId = process.env.GOOGLE_CLIENT_ID;
const clientSecret = process.env.GOOGLE_CLIENT_SECRET;
// Function to create a Gmail client
const createGmailClient = accessToken => {
const oauth2Client = new google.auth.OAuth2();
oauth2Client.setCredentials({ access_token: accessToken });
return google.gmail({ version: 'v1', auth: oauth2Client });
};
// Function to exchange refresh token for new access token
const refreshAccessToken = async refreshToken => {
const tokenEndpoint = 'https://oauth2.googleapis.com/token';
const params = new URLSearchParams();
params.append('refresh_token', refreshToken);
params.append('client_id', clientId);
params.append('client_secret', clientSecret);
params.append('grant_type', 'refresh_token');
const response = await axios.post(tokenEndpoint, params);
return response.data.access_token;
};
// Function to create a raw email message
const makeEmail = async (to, from, subject, html, url, pdfName) => {
const htmlContent = html;
const boundary = 'boundary_' + Date.now().toString(16);
let str;
if (url) {
let attachments;
let Pdf = fs.createWriteStream('test.pdf');
const writeToLocalDisk = () => {
return new Promise((resolve, reject) => {
https.get(url, async function (response) {
response.pipe(Pdf);
response.on('end', () => resolve('success'));
});
});
};
// `writeToLocalDisk` is used to create pdf file from doc url
const ress = await writeToLocalDisk();
if (ress) {
const file = {
filename: `${pdfName}.pdf` || 'exported.pdf',
type: 'application/pdf',
path: Pdf.path,
};
// `certificateBuffer` used to create buffer from pdf file
try {
const certificate = {
filename: 'certificate.pdf',
type: 'application/pdf',
path: './exports/certificate.pdf',
};
attachments = [file, certificate];
} catch (err) {
attachments = [file];
console.log('Err in read certificate sendmailv3', err);
}
}
const attachmentParts = attachments.map(attachment => {
const content = fs.readFileSync(attachment.path);
const encodedContent = content.toString('base64');
return [
`Content-Type: ${attachment.type}\n`,
'MIME-Version: 1.0\n',
`Content-Disposition: attachment; filename="${attachment.filename}"\n`,
`Content-Transfer-Encoding: base64\n\n`,
`${encodedContent}\n`,
].join('');
});
const attachmentBody = attachmentParts.join(`\n--${boundary}\n`);
str = [
'Content-Type: multipart/mixed; boundary="' + boundary + '"\n',
'MIME-Version: 1.0\n',
`To: ${to}\n`,
`From: ${from}\n`,
`Subject: ${subject}\n\n`,
'--' + boundary + '\n',
'Content-Type: text/html; charset="UTF-8"\n',
'MIME-Version: 1.0\n\n',
`${htmlContent}\n\n`,
`\n--${boundary}\n`,
attachmentBody,
'--' + boundary + '--',
].join('');
} else {
str = [
'Content-Type: multipart/mixed; boundary="' + boundary + '"\n',
'MIME-Version: 1.0\n',
`To: ${to}\n`,
`From: ${from}\n`,
`Subject: ${subject}\n\n`,
'--' + boundary + '\n',
'Content-Type: text/html; charset="UTF-8"\n',
'MIME-Version: 1.0\n\n',
`${htmlContent}\n\n`,
'--' + boundary + '--',
].join('');
}
const encodedMail = Buffer.from(str).toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
return encodedMail;
};
export default async function sendMailGmailProvider(_extRes, template) {
const { sender, receiver, subject, html, url, pdfName } = template;
if (_extRes) {
const refresh_token = _extRes.google_refresh_token;
// generate access token
const access_token = await refreshAccessToken(refresh_token);
try {
// Construct email message
const from = sender || _extRes.Email || 'me';
const to = receiver;
const email = await makeEmail(to, from, subject, html, url, pdfName);
// Update Gmail client with new access token
const newGmail = createGmailClient(access_token);
// sending email with new client
const response = await newGmail.users.messages.send({
userId: 'me',
requestBody: {
raw: email,
},
});
// console.log('response ', response);
return { code: 200, message: 'Email sent successfully' };
} catch (error) {
console.error('Error sending email:', error);
return { code: 500, message: 'Failed to send email ' + error };
}
}
}
@@ -2,10 +2,9 @@ import fs from 'node:fs';
import https from 'https';
import formData from 'form-data';
import Mailgun from 'mailgun.js';
import { createTransport } from 'nodemailer';
import { updateMailCount } from '../../Utils.js';
async function sendmailv3(req) {
import sendMailGmailProvider from './sendMailGmailProvider.js';
async function sendMailProvider(req) {
try {
let transporterSMTP;
let mailgunClient;
@@ -98,9 +97,7 @@ async function sendmailv3(req) {
} catch (err) {
console.log('Err in unlink certificate sendmailv3');
}
return {
status: 'success',
};
return { status: 'success' };
}
} else {
const res = await mailgunClient.messages.create(mailgunDomain, messageParams);
@@ -141,9 +138,7 @@ async function sendmailv3(req) {
if (req.params?.extUserId) {
await updateMailCount(req.params.extUserId);
}
return {
status: 'success',
};
return { status: 'success' };
}
} else {
const res = await mailgunClient.messages.create(mailgunDomain, messageParams);
@@ -152,9 +147,7 @@ async function sendmailv3(req) {
if (req.params?.extUserId) {
await updateMailCount(req.params.extUserId);
}
return {
status: 'success',
};
return { status: 'success' };
}
}
}
@@ -165,5 +158,45 @@ async function sendmailv3(req) {
}
}
}
async function sendmailv3(req) {
const isMailProvider = req.params.isMailProvider || false;
if (isMailProvider) {
try {
const extUserId = req.params.extUserId || '';
const pdfName = req.params.pdfName || '';
const template = {
sender: req.params.from || '',
receiver: req.params.recipient,
subject: req.params.subject,
html: req.params.html || '',
url: req.params.url ? req.params.url : '',
pdfName: pdfName,
};
const extUserQuery = new Parse.Query('contracts_Users');
const extRes = await extUserQuery.get(extUserId, { useMasterKey: true });
if (extRes) {
const _extRes = JSON.parse(JSON.stringify(extRes));
if (_extRes.google_refresh_token) {
const res = await sendMailGmailProvider(_extRes, template);
if (res.code === 200) {
await updateMailCount(req.params.extUserId);
return { status: 'success' };
} else {
return { status: 'error' };
}
} else {
const nonCustomMail = await sendMailProvider(req);
return nonCustomMail;
}
}
} catch (err) {
console.log('err in send custom mail', err);
return { status: 'error' };
}
} else {
const nonCustomMail = await sendMailProvider(req);
return nonCustomMail;
}
}
export default sendmailv3;