2020-08-18 03:40:19 -07:00
|
|
|
import {
|
|
|
|
OptionsWithUri,
|
|
|
|
} from 'request';
|
|
|
|
|
|
|
|
import {
|
|
|
|
simpleParser,
|
|
|
|
} from 'mailparser';
|
|
|
|
|
|
|
|
import {
|
|
|
|
IExecuteFunctions,
|
|
|
|
IExecuteSingleFunctions,
|
|
|
|
ILoadOptionsFunctions,
|
|
|
|
} from 'n8n-core';
|
|
|
|
|
|
|
|
import {
|
|
|
|
IBinaryKeyData,
|
|
|
|
IDataObject,
|
|
|
|
INodeExecutionData,
|
2021-04-16 09:33:36 -07:00
|
|
|
NodeApiError,
|
|
|
|
NodeOperationError,
|
2020-08-18 03:40:19 -07:00
|
|
|
} from 'n8n-workflow';
|
|
|
|
|
|
|
|
import {
|
|
|
|
IEmail,
|
|
|
|
} from './Gmail.node';
|
|
|
|
|
2021-01-10 11:49:47 -08:00
|
|
|
import * as moment from 'moment-timezone';
|
|
|
|
|
|
|
|
import * as jwt from 'jsonwebtoken';
|
|
|
|
|
2021-12-24 07:12:18 -08:00
|
|
|
interface IGoogleAuthCredentials {
|
|
|
|
delegatedEmail?: string;
|
|
|
|
email: string;
|
|
|
|
inpersonate: boolean;
|
|
|
|
privateKey: string;
|
|
|
|
}
|
|
|
|
|
2020-11-02 23:17:54 -08:00
|
|
|
const mailComposer = require('nodemailer/lib/mail-composer');
|
2020-11-02 13:47:47 -08:00
|
|
|
|
2020-08-18 03:40:19 -07:00
|
|
|
export async function googleApiRequest(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, method: string,
|
|
|
|
endpoint: string, body: any = {}, qs: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
|
2021-01-10 11:49:47 -08:00
|
|
|
const authenticationMethod = this.getNodeParameter('authentication', 0, 'serviceAccount') as string;
|
2020-08-18 03:40:19 -07:00
|
|
|
let options: OptionsWithUri = {
|
|
|
|
headers: {
|
|
|
|
'Accept': 'application/json',
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
method,
|
|
|
|
body,
|
|
|
|
qs,
|
|
|
|
uri: uri || `https://www.googleapis.com${endpoint}`,
|
2022-01-27 12:25:32 -08:00
|
|
|
qsStringifyOptions: {
|
2021-03-02 03:47:53 -08:00
|
|
|
arrayFormat: 'repeat',
|
|
|
|
},
|
2020-08-18 03:40:19 -07:00
|
|
|
json: true,
|
|
|
|
};
|
|
|
|
|
|
|
|
options = Object.assign({}, options, option);
|
|
|
|
|
|
|
|
try {
|
|
|
|
if (Object.keys(body).length === 0) {
|
|
|
|
delete options.body;
|
|
|
|
}
|
|
|
|
|
2021-01-10 11:49:47 -08:00
|
|
|
if (authenticationMethod === 'serviceAccount') {
|
2021-08-20 09:57:30 -07:00
|
|
|
const credentials = await this.getCredentials('googleApi');
|
2021-01-10 11:49:47 -08:00
|
|
|
|
|
|
|
if (credentials === undefined) {
|
2021-04-16 09:33:36 -07:00
|
|
|
throw new NodeOperationError(this.getNode(), 'No credentials got returned!');
|
2021-01-10 11:49:47 -08:00
|
|
|
}
|
|
|
|
|
2021-12-24 07:12:18 -08:00
|
|
|
const { access_token } = await getAccessToken.call(this, credentials as unknown as IGoogleAuthCredentials);
|
2021-01-10 11:49:47 -08:00
|
|
|
|
|
|
|
options.headers!.Authorization = `Bearer ${access_token}`;
|
|
|
|
//@ts-ignore
|
|
|
|
return await this.helpers.request(options);
|
|
|
|
} else {
|
|
|
|
//@ts-ignore
|
|
|
|
return await this.helpers.requestOAuth2.call(this, 'gmailOAuth2', options);
|
|
|
|
}
|
2020-08-18 03:40:19 -07:00
|
|
|
|
|
|
|
} catch (error) {
|
2021-06-22 10:59:27 -07:00
|
|
|
if (error.code === 'ERR_OSSL_PEM_NO_START_LINE') {
|
|
|
|
error.statusCode = '401';
|
|
|
|
}
|
|
|
|
|
2021-04-16 09:33:36 -07:00
|
|
|
throw new NodeApiError(this.getNode(), error);
|
2020-08-18 03:40:19 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2020-10-15 01:41:47 -07:00
|
|
|
export async function parseRawEmail(this: IExecuteFunctions, messageData: any, dataPropertyNameDownload: string): Promise<INodeExecutionData> { // tslint:disable-line:no-any
|
2020-08-18 03:40:19 -07:00
|
|
|
|
2020-10-15 01:41:47 -07:00
|
|
|
const messageEncoded = Buffer.from(messageData.raw, 'base64').toString('utf8');
|
|
|
|
let responseData = await simpleParser(messageEncoded);
|
2020-08-18 03:40:19 -07:00
|
|
|
|
|
|
|
const headers: IDataObject = {};
|
2020-10-15 01:41:47 -07:00
|
|
|
// @ts-ignore
|
2020-08-18 03:40:19 -07:00
|
|
|
for (const header of responseData.headerLines) {
|
|
|
|
headers[header.key] = header.line;
|
|
|
|
}
|
|
|
|
|
|
|
|
// @ts-ignore
|
|
|
|
responseData.headers = headers;
|
|
|
|
// @ts-ignore
|
|
|
|
responseData.headerLines = undefined;
|
|
|
|
|
|
|
|
const binaryData: IBinaryKeyData = {};
|
|
|
|
if (responseData.attachments) {
|
|
|
|
|
|
|
|
for (let i = 0; i < responseData.attachments.length; i++) {
|
|
|
|
const attachment = responseData.attachments[i];
|
|
|
|
binaryData[`${dataPropertyNameDownload}${i}`] = await this.helpers.prepareBinaryData(attachment.content, attachment.filename, attachment.contentType);
|
|
|
|
}
|
|
|
|
// @ts-ignore
|
|
|
|
responseData.attachments = undefined;
|
|
|
|
}
|
|
|
|
|
2020-10-15 01:41:47 -07:00
|
|
|
const mailBaseData: IDataObject = {};
|
|
|
|
|
|
|
|
const resolvedModeAddProperties = [
|
|
|
|
'id',
|
|
|
|
'threadId',
|
|
|
|
'labelIds',
|
|
|
|
'sizeEstimate',
|
|
|
|
];
|
|
|
|
|
|
|
|
for (const key of resolvedModeAddProperties) {
|
|
|
|
// @ts-ignore
|
|
|
|
mailBaseData[key] = messageData[key];
|
|
|
|
}
|
|
|
|
|
|
|
|
responseData = Object.assign(mailBaseData, responseData);
|
|
|
|
|
2020-08-18 03:40:19 -07:00
|
|
|
return {
|
|
|
|
json: responseData as unknown as IDataObject,
|
|
|
|
binary: Object.keys(binaryData).length ? binaryData : undefined,
|
|
|
|
} as INodeExecutionData;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
//------------------------------------------------------------------------------------------------------------------------------------------
|
|
|
|
// This function converts an email object into a MIME encoded email and then converts that string into base64 encoding
|
|
|
|
// for more info on MIME, https://docs.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/aa494197(v%3Dexchg.140)
|
|
|
|
//------------------------------------------------------------------------------------------------------------------------------------------
|
|
|
|
|
2020-11-02 13:47:47 -08:00
|
|
|
export async function encodeEmail(email: IEmail) {
|
|
|
|
let mailBody: Buffer;
|
|
|
|
|
|
|
|
const mailOptions = {
|
2021-07-30 07:26:57 -07:00
|
|
|
from: email.from,
|
2020-11-02 13:47:47 -08:00
|
|
|
to: email.to,
|
2021-01-07 02:58:28 -08:00
|
|
|
cc: email.cc,
|
2020-11-02 13:47:47 -08:00
|
|
|
bcc: email.bcc,
|
|
|
|
replyTo: email.inReplyTo,
|
|
|
|
references: email.reference,
|
|
|
|
subject: email.subject,
|
|
|
|
text: email.body,
|
2022-01-27 12:25:32 -08:00
|
|
|
keepBcc: true,
|
2020-11-02 13:47:47 -08:00
|
|
|
} as IDataObject;
|
2021-01-07 02:58:28 -08:00
|
|
|
if (email.htmlBody) {
|
|
|
|
mailOptions.html = email.htmlBody;
|
|
|
|
}
|
2020-11-02 13:47:47 -08:00
|
|
|
|
|
|
|
if (email.attachments !== undefined && Array.isArray(email.attachments) && email.attachments.length > 0) {
|
|
|
|
const attachments = email.attachments.map((attachment) => ({
|
|
|
|
filename: attachment.name,
|
|
|
|
content: attachment.content,
|
|
|
|
contentType: attachment.type,
|
2021-01-07 02:58:28 -08:00
|
|
|
encoding: 'base64',
|
2020-11-02 13:47:47 -08:00
|
|
|
}));
|
|
|
|
|
|
|
|
mailOptions.attachments = attachments;
|
|
|
|
}
|
2020-08-18 03:40:19 -07:00
|
|
|
|
2022-01-27 12:25:32 -08:00
|
|
|
const mail = new mailComposer(mailOptions).compile();
|
2020-11-02 23:17:54 -08:00
|
|
|
|
2022-01-27 12:25:32 -08:00
|
|
|
// by default the bcc headers are deleted when the mail is built.
|
|
|
|
// So add keepBcc flag to averride such behaviour. Only works when
|
|
|
|
// the flag is set after the compilation.
|
|
|
|
//https://nodemailer.com/extras/mailcomposer/#bcc
|
|
|
|
mail.keepBcc = true;
|
2020-08-18 03:40:19 -07:00
|
|
|
|
2022-01-27 12:25:32 -08:00
|
|
|
mailBody = await mail.build();
|
2020-08-18 03:40:19 -07:00
|
|
|
|
2020-11-02 23:17:54 -08:00
|
|
|
return mailBody.toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
|
2020-08-18 03:40:19 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function googleApiRequestAllItems(this: IExecuteFunctions | ILoadOptionsFunctions, propertyName: string, method: string, endpoint: string, body: any = {}, query: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
|
|
|
|
|
|
|
|
const returnData: IDataObject[] = [];
|
|
|
|
|
|
|
|
let responseData;
|
|
|
|
query.maxResults = 100;
|
|
|
|
|
|
|
|
do {
|
|
|
|
responseData = await googleApiRequest.call(this, method, endpoint, body, query);
|
|
|
|
query.pageToken = responseData['nextPageToken'];
|
|
|
|
returnData.push.apply(returnData, responseData[propertyName]);
|
|
|
|
} while (
|
|
|
|
responseData['nextPageToken'] !== undefined &&
|
|
|
|
responseData['nextPageToken'] !== ''
|
|
|
|
);
|
|
|
|
|
|
|
|
return returnData;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function extractEmail(s: string) {
|
|
|
|
const data = s.split('<')[1];
|
|
|
|
return data.substring(0, data.length - 1);
|
|
|
|
}
|
2021-01-10 11:49:47 -08:00
|
|
|
|
2021-12-24 07:12:18 -08:00
|
|
|
function getAccessToken(this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions, credentials: IGoogleAuthCredentials): Promise<IDataObject> {
|
2021-01-10 11:49:47 -08:00
|
|
|
//https://developers.google.com/identity/protocols/oauth2/service-account#httprest
|
|
|
|
|
|
|
|
const scopes = [
|
2021-02-28 08:27:52 -08:00
|
|
|
'https://www.googleapis.com/auth/gmail.labels',
|
|
|
|
'https://www.googleapis.com/auth/gmail.addons.current.action.compose',
|
|
|
|
'https://www.googleapis.com/auth/gmail.addons.current.message.action',
|
|
|
|
'https://mail.google.com/',
|
|
|
|
'https://www.googleapis.com/auth/gmail.modify',
|
|
|
|
'https://www.googleapis.com/auth/gmail.compose',
|
2021-01-10 11:49:47 -08:00
|
|
|
];
|
|
|
|
|
|
|
|
const now = moment().unix();
|
|
|
|
|
2021-12-24 07:12:18 -08:00
|
|
|
credentials.email = credentials.email.trim();
|
|
|
|
const privateKey = (credentials.privateKey as string).replace(/\\n/g, '\n').trim();
|
2021-12-24 01:48:23 -08:00
|
|
|
|
2021-01-10 11:49:47 -08:00
|
|
|
const signature = jwt.sign(
|
|
|
|
{
|
|
|
|
'iss': credentials.email as string,
|
|
|
|
'sub': credentials.delegatedEmail || credentials.email as string,
|
|
|
|
'scope': scopes.join(' '),
|
|
|
|
'aud': `https://oauth2.googleapis.com/token`,
|
|
|
|
'iat': now,
|
|
|
|
'exp': now + 3600,
|
|
|
|
},
|
2021-12-24 01:48:23 -08:00
|
|
|
privateKey,
|
2021-01-10 11:49:47 -08:00
|
|
|
{
|
|
|
|
algorithm: 'RS256',
|
|
|
|
header: {
|
2021-12-24 01:48:23 -08:00
|
|
|
'kid': privateKey,
|
2021-01-10 11:49:47 -08:00
|
|
|
'typ': 'JWT',
|
|
|
|
'alg': 'RS256',
|
|
|
|
},
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
const options: OptionsWithUri = {
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
|
|
},
|
|
|
|
method: 'POST',
|
|
|
|
form: {
|
|
|
|
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
|
|
|
|
assertion: signature,
|
|
|
|
},
|
|
|
|
uri: 'https://oauth2.googleapis.com/token',
|
|
|
|
json: true,
|
|
|
|
};
|
|
|
|
|
|
|
|
//@ts-ignore
|
|
|
|
return this.helpers.request(options);
|
|
|
|
}
|