-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
GmailTrigger.node.ts
359 lines (331 loc) · 8.89 KB
/
GmailTrigger.node.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import type {
IPollFunctions,
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
INodePropertyOptions,
INodeType,
INodeTypeDescription,
} from 'n8n-workflow';
import { DateTime } from 'luxon';
import {
googleApiRequest,
googleApiRequestAllItems,
parseRawEmail,
prepareQuery,
simplifyOutput,
} from './GenericFunctions';
export class GmailTrigger implements INodeType {
description: INodeTypeDescription = {
displayName: 'Gmail Trigger',
name: 'gmailTrigger',
icon: 'file:gmail.svg',
group: ['trigger'],
version: 1,
description:
'Fetches emails from Gmail and starts the workflow on specified polling intervals.',
subtitle: '={{"Gmail Trigger"}}',
defaults: {
name: 'Gmail Trigger',
},
credentials: [
{
name: 'googleApi',
required: true,
displayOptions: {
show: {
authentication: ['serviceAccount'],
},
},
},
{
name: 'gmailOAuth2',
required: true,
displayOptions: {
show: {
authentication: ['oAuth2'],
},
},
},
],
polling: true,
inputs: [],
outputs: ['main'],
properties: [
{
displayName: 'Authentication',
name: 'authentication',
type: 'options',
options: [
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'OAuth2 (recommended)',
value: 'oAuth2',
},
{
name: 'Service Account',
value: 'serviceAccount',
},
],
default: 'oAuth2',
},
{
displayName: 'Event',
name: 'event',
type: 'options',
default: 'messageReceived',
options: [
{
name: 'Message Received',
value: 'messageReceived',
},
],
},
{
displayName: 'Simplify',
name: 'simple',
type: 'boolean',
default: true,
description:
'Whether to return a simplified version of the response instead of the raw data',
},
{
displayName: 'Filters',
name: 'filters',
type: 'collection',
placeholder: 'Add Filter',
default: {},
options: [
{
displayName: 'Include Spam and Trash',
name: 'includeSpamTrash',
type: 'boolean',
default: false,
description: 'Whether to include messages from SPAM and TRASH in the results',
},
{
displayName: 'Label Names or IDs',
name: 'labelIds',
type: 'multiOptions',
typeOptions: {
loadOptionsMethod: 'getLabels',
},
default: [],
description:
'Only return messages with labels that match all of the specified label IDs. Choose from the list, or specify IDs using an <a href="https://docs.n8n.io/code-examples/expressions/">expression</a>.',
},
{
displayName: 'Search',
name: 'q',
type: 'string',
default: '',
placeholder: 'has:attachment',
hint: 'Use the same format as in the Gmail search box. <a href="https://support.google.com/mail/answer/7190?hl=en">More info</a>.',
description: 'Only return messages matching the specified query',
},
{
displayName: 'Read Status',
name: 'readStatus',
type: 'options',
default: 'unread',
hint: 'Filter emails by whether they have been read or not',
options: [
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'Unread and read emails',
value: 'both',
},
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'Unread emails only',
value: 'unread',
},
{
// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased
name: 'Read emails only',
value: 'read',
},
],
},
{
displayName: 'Sender',
name: 'sender',
type: 'string',
default: '',
description: 'Sender name or email to filter by',
hint: 'Enter an email or part of a sender name',
},
],
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
default: {},
displayOptions: {
hide: {
simple: [true],
},
},
options: [
{
displayName: 'Attachment Prefix',
name: 'dataPropertyAttachmentsPrefixName',
type: 'string',
default: 'attachment_',
description:
"Prefix for name of the binary property to which to write the attachment. An index starting with 0 will be added. So if name is 'attachment_' the first attachment is saved to 'attachment_0'.",
},
{
displayName: 'Download Attachments',
name: 'downloadAttachments',
type: 'boolean',
default: false,
description: "Whether the email's attachments will be downloaded",
},
],
},
],
};
methods = {
loadOptions: {
// Get all the labels to display them to user so that they can
// select them easily
async getLabels(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const returnData: INodePropertyOptions[] = [];
const labels = await googleApiRequestAllItems.call(
this,
'labels',
'GET',
'/gmail/v1/users/me/labels',
);
for (const label of labels) {
returnData.push({
name: label.name,
value: label.id,
});
}
return returnData.sort((a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
},
},
};
async poll(this: IPollFunctions): Promise<INodeExecutionData[][] | null> {
const webhookData = this.getWorkflowStaticData('node');
let responseData;
const now = Math.floor(DateTime.now().toSeconds()).toString();
const startDate = (webhookData.lastTimeChecked as string) || +now;
const endDate = +now;
const options = this.getNodeParameter('options', {}) as IDataObject;
const filters = this.getNodeParameter('filters', {}) as IDataObject;
try {
const qs: IDataObject = {};
filters.receivedAfter = startDate;
if (this.getMode() === 'manual') {
qs.maxResults = 1;
delete filters.receivedAfter;
}
Object.assign(qs, prepareQuery.call(this, filters, 0), options);
responseData = await googleApiRequest.call(
this,
'GET',
'/gmail/v1/users/me/messages',
{},
qs,
);
responseData = responseData.messages;
if (!responseData?.length) {
webhookData.lastTimeChecked = endDate;
return null;
}
const simple = this.getNodeParameter('simple') as boolean;
if (simple) {
qs.format = 'metadata';
qs.metadataHeaders = ['From', 'To', 'Cc', 'Bcc', 'Subject'];
} else {
qs.format = 'raw';
}
for (let i = 0; i < responseData.length; i++) {
responseData[i] = await googleApiRequest.call(
this,
'GET',
`/gmail/v1/users/me/messages/${responseData[i].id}`,
{},
qs,
);
if (!simple) {
const dataPropertyNameDownload =
(options.dataPropertyAttachmentsPrefixName as string) || 'attachment_';
responseData[i] = await parseRawEmail.call(
this,
responseData[i],
dataPropertyNameDownload,
);
}
}
if (simple) {
responseData = this.helpers.returnJsonArray(
await simplifyOutput.call(this, responseData as IDataObject[]),
);
}
} catch (error) {
if (this.getMode() === 'manual' || !webhookData.lastTimeChecked) {
throw error;
}
const workflow = this.getWorkflow();
const node = this.getNode();
this.logger.error(
`There was a problem in '${node.name}' node in workflow '${workflow.id}': '${error.description}'`,
{
node: node.name,
workflowId: workflow.id,
error,
},
);
}
if (!responseData?.length) {
webhookData.lastTimeChecked = endDate;
return null;
}
const getEmailDateAsSeconds = (email: IDataObject) => {
const { internalDate, date } = email;
return internalDate
? +(internalDate as string) / 1000
: +DateTime.fromJSDate(new Date(date as string)).toSeconds();
};
const lastEmailDate = (responseData as IDataObject[]).reduce((lastDate, { json }) => {
const emailDate = getEmailDateAsSeconds(json as IDataObject);
return emailDate > lastDate ? emailDate : lastDate;
}, 0);
const nextPollPossibleDuplicates = (responseData as IDataObject[]).reduce(
(duplicates, { json }) => {
const emailDate = getEmailDateAsSeconds(json as IDataObject);
return emailDate === lastEmailDate
? duplicates.concat((json as IDataObject).id as string)
: duplicates;
},
[] as string[],
);
const possibleDuplicates = (webhookData.possibleDuplicates as string[]) || [];
if (possibleDuplicates.length) {
responseData = (responseData as IDataObject[]).filter(({ json }) => {
const { id } = json as IDataObject;
return !possibleDuplicates.includes(id as string);
});
}
webhookData.possibleDuplicates = nextPollPossibleDuplicates;
webhookData.lastTimeChecked = lastEmailDate || endDate;
if (Array.isArray(responseData) && responseData.length) {
return [responseData as INodeExecutionData[]];
}
return null;
}
}