@openfn/language-gmail 2.1.2 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +148 -47
- package/ast.json +67 -1
- package/dist/index.cjs +187 -42
- package/dist/index.js +185 -42
- package/package.json +2 -1
- package/types/Adaptor.d.ts +49 -2
- package/types/Utils.d.ts +9 -2
package/README.md
CHANGED
|
@@ -1,24 +1,34 @@
|
|
|
1
1
|
# Gmail adaptor
|
|
2
2
|
|
|
3
|
-
Send and receive Gmail messages with file attachments using simple, configurable
|
|
3
|
+
Send and receive Gmail messages with file attachments using simple, configurable
|
|
4
|
+
logic.
|
|
4
5
|
|
|
5
6
|
# `getContentsFromMessages`
|
|
6
7
|
|
|
7
|
-
This function is used to extract specific content from Gmail messages using
|
|
8
|
+
This function is used to extract specific content from Gmail messages using
|
|
9
|
+
custom desired "content" configurations. The sample code specifies how to query
|
|
10
|
+
Gmail for messages and identify desired attachments and metadata.
|
|
8
11
|
|
|
9
|
-
Without any parameters, the `getContentsFromMessages()` function will return an
|
|
12
|
+
Without any parameters, the `getContentsFromMessages()` function will return an
|
|
13
|
+
array containing every message in the account of the authenticated user
|
|
14
|
+
including `from`, `date` and `subject`.
|
|
10
15
|
|
|
11
|
-
A number of options are available to isolated the desired messages and to
|
|
16
|
+
A number of options are available to isolated the desired messages and to
|
|
17
|
+
customize the output.
|
|
12
18
|
|
|
13
19
|
## Parameters
|
|
14
20
|
|
|
15
|
-
An `options` object can configure the results of the function call. Optional
|
|
21
|
+
An `options` object can configure the results of the function call. Optional
|
|
22
|
+
parameters include: `contents`, `query`, `email`, `processedIds`,
|
|
23
|
+
`maxResults`, `fetchAttachments`
|
|
16
24
|
|
|
17
25
|
### options.contents
|
|
18
26
|
|
|
19
|
-
Use the `options.contents` array to specify the content to retrieve from each
|
|
27
|
+
Use the `options.contents` array to specify the content to retrieve from each
|
|
28
|
+
message. Always included are `from`, `date`, and `subject`.
|
|
20
29
|
|
|
21
|
-
Each item can be a simple string (ie, `'body'`, `'subject'`) or an
|
|
30
|
+
Each item can be a simple string (ie, `'body'`, `'subject'`) or an
|
|
31
|
+
MessageContent object offering advanced configuration.
|
|
22
32
|
|
|
23
33
|
#### Basic metadata
|
|
24
34
|
|
|
@@ -29,7 +39,8 @@ The following types of content can be extracted:
|
|
|
29
39
|
- `date`: Extracts the timestamp of the email.
|
|
30
40
|
- `from`: Extracts the sender's information.
|
|
31
41
|
|
|
32
|
-
Optionally, each of these content strings can be expanded to include additional
|
|
42
|
+
Optionally, each of these content strings can be expanded to include additional
|
|
43
|
+
specifications:
|
|
33
44
|
|
|
34
45
|
```js
|
|
35
46
|
const mySubject = {
|
|
@@ -41,13 +52,14 @@ const mySubject = {
|
|
|
41
52
|
|
|
42
53
|
- The `type` property instructs the function which content type to extract.
|
|
43
54
|
- The `name` property allows you to add a custom name to this information.
|
|
44
|
-
- The `maxLength` property allows you to limit the length of the content
|
|
55
|
+
- The `maxLength` property allows you to limit the length of the content
|
|
56
|
+
returned.
|
|
45
57
|
|
|
46
58
|
#### Attachment: basic file
|
|
47
59
|
|
|
48
60
|
Extract content from a file attachment.
|
|
49
61
|
|
|
50
|
-
`file
|
|
62
|
+
Set `file` to a string or regex to match the attached file name.
|
|
51
63
|
|
|
52
64
|
```js
|
|
53
65
|
const myMetadata = {
|
|
@@ -57,11 +69,23 @@ const myMetadata = {
|
|
|
57
69
|
};
|
|
58
70
|
```
|
|
59
71
|
|
|
72
|
+
Some file types will be parsed automatically:
|
|
73
|
+
|
|
74
|
+
- JSON files will be parsed into JSON
|
|
75
|
+
- XLSX and XLS files will be converted to a simple JSON format (arrays of
|
|
76
|
+
arrays, no headers)
|
|
77
|
+
- XML and text files will be parsed into plain text.
|
|
78
|
+
|
|
79
|
+
Other files will be returned as base64 encoded strings.
|
|
80
|
+
|
|
81
|
+
You can force attachments to be parsed into `xlsx`, `text`, `json` or `base64`
|
|
82
|
+
formats by setting `parseAs`.
|
|
83
|
+
|
|
60
84
|
```js
|
|
61
85
|
const myMetadata = {
|
|
62
86
|
type: 'file',
|
|
63
|
-
file: 'summary.
|
|
64
|
-
|
|
87
|
+
file: 'summary.text',
|
|
88
|
+
parseAs: 'json',
|
|
65
89
|
};
|
|
66
90
|
```
|
|
67
91
|
|
|
@@ -69,8 +93,10 @@ const myMetadata = {
|
|
|
69
93
|
|
|
70
94
|
Extract content from a file embedded in an archive attachment.
|
|
71
95
|
|
|
72
|
-
- `archive`: Specify the file name of the archive using either a string for an
|
|
73
|
-
|
|
96
|
+
- `archive`: Specify the file name of the archive using either a string for an
|
|
97
|
+
exact match or a regular expression to match a pattern.
|
|
98
|
+
- `file`: Identify the specific file inside the archive by providing its name as
|
|
99
|
+
a string or using a regular expression to match a pattern.
|
|
74
100
|
|
|
75
101
|
```js
|
|
76
102
|
const myArchivedFile = {
|
|
@@ -96,11 +122,14 @@ The query syntax supports the same query format as the Gmail `search` box.
|
|
|
96
122
|
options.query = 'from:ple.com rfc822msgid:<somemsgid@example.com> is:unread';
|
|
97
123
|
```
|
|
98
124
|
|
|
99
|
-
A full list of supported search operations can be found here:
|
|
125
|
+
A full list of supported search operations can be found here:
|
|
126
|
+
[Refine searches in Gmail](https://support.google.com/mail/answer/7190)
|
|
100
127
|
|
|
101
128
|
### options.email
|
|
102
129
|
|
|
103
|
-
Optionally specify the email address used for the Gmail account. This almost
|
|
130
|
+
Optionally specify the email address used for the Gmail account. This almost
|
|
131
|
+
always the same email associated with the authenticated user so this parameter
|
|
132
|
+
is optional.
|
|
104
133
|
|
|
105
134
|
```js
|
|
106
135
|
options.email = '<EMAIL>';
|
|
@@ -108,7 +137,10 @@ options.email = '<EMAIL>';
|
|
|
108
137
|
|
|
109
138
|
### options.processedIds
|
|
110
139
|
|
|
111
|
-
In some scenarios, it may be necessary to skip certain messages to prevent the
|
|
140
|
+
In some scenarios, it may be necessary to skip certain messages to prevent the
|
|
141
|
+
retrieval of duplicate data. Passing an array of messageIds will allow the
|
|
142
|
+
function to skip these messages if any of the ids are encountered in the
|
|
143
|
+
returned messages.
|
|
112
144
|
|
|
113
145
|
```js
|
|
114
146
|
options.processedIds = [
|
|
@@ -120,14 +152,44 @@ options.processedIds = [
|
|
|
120
152
|
|
|
121
153
|
### options.maxResults
|
|
122
154
|
|
|
123
|
-
To prevent inadventant massive retrieval of messages, you can limit the number
|
|
155
|
+
To prevent inadventant massive retrieval of messages, you can limit the number
|
|
156
|
+
of results returned. The default value is 1000.
|
|
124
157
|
|
|
125
158
|
This works in conjuction with the `options.processedIds` parameter. For example:
|
|
126
159
|
|
|
127
160
|
- account contains messages [1, 2, 3]
|
|
128
161
|
- `options.processedIds = [1];`
|
|
129
162
|
- `options.maxResults = 1;`
|
|
130
|
-
- this will skip message #1 and resulting dataset will contain a single message
|
|
163
|
+
- this will skip message #1 and resulting dataset will contain a single message
|
|
164
|
+
#2
|
|
165
|
+
|
|
166
|
+
### options.fetchAttachments
|
|
167
|
+
|
|
168
|
+
Set `fetchAttachments` to `false` to return message IDs and non-attachment
|
|
169
|
+
content without downloading requested file or archive attachments. The default
|
|
170
|
+
is `true`.
|
|
171
|
+
|
|
172
|
+
When downloading is disabled, matched attachments are still reported as
|
|
173
|
+
filename-only objects (without `content`), so a later job can tell which
|
|
174
|
+
messages contain the target attachment:
|
|
175
|
+
|
|
176
|
+
- matched file → `{ filename: 'report.xlsx' }`
|
|
177
|
+
- matched archive → `{ archiveFilename: 'data.zip' }`
|
|
178
|
+
- no match → `null`
|
|
179
|
+
|
|
180
|
+
Pair this with `getMessageById` in a follow-up job to download the attachment
|
|
181
|
+
for exactly the message identified here.
|
|
182
|
+
|
|
183
|
+
```js
|
|
184
|
+
getContentsFromMessages({
|
|
185
|
+
query: 'after:2026/07/01',
|
|
186
|
+
contents: [
|
|
187
|
+
'body',
|
|
188
|
+
{ type: 'file', name: 'report', file: /\.xlsx$/ },
|
|
189
|
+
],
|
|
190
|
+
fetchAttachments: false,
|
|
191
|
+
});
|
|
192
|
+
```
|
|
131
193
|
|
|
132
194
|
## Example jobs
|
|
133
195
|
|
|
@@ -165,7 +227,9 @@ getContentsFromMessages({ query, email, contents });
|
|
|
165
227
|
|
|
166
228
|
## Sample `state.data` output
|
|
167
229
|
|
|
168
|
-
For each matched message, the extracted content is returned as a message object
|
|
230
|
+
For each matched message, the extracted content is returned as a message object
|
|
231
|
+
of content properties. Here's an example `state.data` for a single matched
|
|
232
|
+
message:
|
|
169
233
|
|
|
170
234
|
```js
|
|
171
235
|
[
|
|
@@ -187,17 +251,20 @@ For each matched message, the extracted content is returned as a message object
|
|
|
187
251
|
];
|
|
188
252
|
```
|
|
189
253
|
|
|
190
|
-
Each property on the message object represents a specific piece of information
|
|
254
|
+
Each property on the message object represents a specific piece of information
|
|
255
|
+
extracted:
|
|
191
256
|
|
|
192
257
|
- **from**: Sender's email and name.
|
|
193
258
|
- **date**: The timestamp when the email was sent.
|
|
194
259
|
- **subject**: Contains the email subject.
|
|
195
260
|
- **metadata**: Metadata-named file content, with its matched file name.
|
|
196
|
-
- **data**: Data-named archive file content, with its matched archive name and
|
|
261
|
+
- **data**: Data-named archive file content, with its matched archive name and
|
|
262
|
+
file name.
|
|
197
263
|
|
|
198
264
|
# `sendMessage`
|
|
199
265
|
|
|
200
|
-
Use `sendMessage()` to send an email with optional file attachments. This
|
|
266
|
+
Use `sendMessage()` to send an email with optional file attachments. This
|
|
267
|
+
function supports plain text messages as well as attachments and archives.
|
|
201
268
|
|
|
202
269
|
## Parameters
|
|
203
270
|
|
|
@@ -213,33 +280,34 @@ Each item in the `attachments` array must include:
|
|
|
213
280
|
- `filename` (string): The name of the file.
|
|
214
281
|
- Either `content` or `archive`:
|
|
215
282
|
- `content` (string): The file content.
|
|
216
|
-
- `archive` (array): Use this to send a `.zip` file. Provide an array of
|
|
283
|
+
- `archive` (array): Use this to send a `.zip` file. Provide an array of
|
|
284
|
+
`{ filename, content }` objects.
|
|
217
285
|
|
|
218
286
|
## Example jobs
|
|
219
287
|
|
|
220
288
|
```js
|
|
221
289
|
sendMessage({
|
|
222
|
-
to:
|
|
223
|
-
subject:
|
|
224
|
-
body:
|
|
290
|
+
to: 'recipient@gmail.com',
|
|
291
|
+
subject: 'Device Summary',
|
|
292
|
+
body: 'Here is the latest device summary.',
|
|
225
293
|
attachments: [
|
|
226
294
|
{
|
|
227
|
-
filename:
|
|
228
|
-
content:
|
|
295
|
+
filename: 'summary.txt',
|
|
296
|
+
content: 'This is the summary file.',
|
|
229
297
|
},
|
|
230
298
|
{
|
|
231
|
-
filename:
|
|
299
|
+
filename: 'report.json',
|
|
232
300
|
content: '{ "status": "OK" }',
|
|
233
301
|
},
|
|
234
302
|
{
|
|
235
|
-
filename:
|
|
303
|
+
filename: 'data.zip',
|
|
236
304
|
archive: [
|
|
237
305
|
{
|
|
238
|
-
filename:
|
|
306
|
+
filename: 'one.json',
|
|
239
307
|
content: '{ "value": 1 }',
|
|
240
308
|
},
|
|
241
309
|
{
|
|
242
|
-
filename:
|
|
310
|
+
filename: 'two.json',
|
|
243
311
|
content: '{ "value": 2 }',
|
|
244
312
|
},
|
|
245
313
|
],
|
|
@@ -248,11 +316,35 @@ sendMessage({
|
|
|
248
316
|
});
|
|
249
317
|
```
|
|
250
318
|
|
|
251
|
-
This will send an email with two plain attachments and one ZIP archive
|
|
319
|
+
This will send an email with two plain attachments and one ZIP archive
|
|
320
|
+
containing two files.
|
|
321
|
+
|
|
322
|
+
# `getMessageById`
|
|
323
|
+
|
|
324
|
+
Fetch a single message by its Gmail API message id, instead of searching with
|
|
325
|
+
a query. Takes the same `contents`, `email` and `fetchAttachments` options as
|
|
326
|
+
`getContentsFromMessages`, and returns a single message object (rather than an
|
|
327
|
+
array) on `state.data`.
|
|
328
|
+
|
|
329
|
+
This is the id returned by this adaptor as `messageId` on each result. It is
|
|
330
|
+
not the RFC 822 `Message-ID` header, so it cannot be matched with the
|
|
331
|
+
`rfc822msgid:` search operator.
|
|
332
|
+
|
|
333
|
+
This pairs with `getContentsFromMessages`'s `fetchAttachments: false` for a
|
|
334
|
+
two-step pattern: one job lists messages cheaply and records which contain a
|
|
335
|
+
target attachment, and a later job downloads the attachment for one message at
|
|
336
|
+
a time:
|
|
337
|
+
|
|
338
|
+
```js
|
|
339
|
+
getMessageById($.data.find(m => m.report).messageId, {
|
|
340
|
+
contents: [{ type: 'file', name: 'report', file: /\.xlsx$/ }],
|
|
341
|
+
});
|
|
342
|
+
```
|
|
252
343
|
|
|
253
344
|
# Acquiring an access token
|
|
254
345
|
|
|
255
|
-
The Gmail adaptor implicitly uses the Gmail account of the Google account that
|
|
346
|
+
The Gmail adaptor implicitly uses the Gmail account of the Google account that
|
|
347
|
+
is used to authenticate the application.
|
|
256
348
|
|
|
257
349
|
Allowing the Gmail adaptor to access a Gmail account is a multi-step process.
|
|
258
350
|
|
|
@@ -270,34 +362,43 @@ https://support.google.com/googleapi/answer/6158849
|
|
|
270
362
|
- Select Application type "Web application"
|
|
271
363
|
- Add a uniquely-identifiable name
|
|
272
364
|
- Click "Create"
|
|
273
|
-
- On the resulting popup screen, find and click "DOWNLOAD JSON" and save this
|
|
365
|
+
- On the resulting popup screen, find and click "DOWNLOAD JSON" and save this
|
|
366
|
+
file to a secure location.
|
|
274
367
|
|
|
275
368
|
## Retrieve an access token
|
|
276
369
|
|
|
277
|
-
- Navigate to
|
|
278
|
-
|
|
279
|
-
|
|
370
|
+
- Navigate to
|
|
371
|
+
[OAuth 2.0 Playground](https://developers.google.com/oauthplayground/).
|
|
372
|
+
- Find _Step 1 Select & authorize APIs_:
|
|
373
|
+
- Find the section for _Gmail API v1_.
|
|
280
374
|
- Mark the following two scopes:
|
|
281
375
|
- https://www.googleapis.com/auth/gmail.readonly
|
|
282
376
|
- https://www.googleapis.com/auth/gmail.send
|
|
283
|
-
- In the box labeled with the watermark
|
|
377
|
+
- In the box labeled with the watermark _Input your own scopes_ add `openid`.
|
|
284
378
|
- Click on the **Authorize APIs** button.
|
|
285
379
|
- Log in to the Google account to which you want to grant access.
|
|
286
|
-
- On the
|
|
287
|
-
- On the
|
|
380
|
+
- On the _Sign in to Google OAuth 2.0 Playground_ screen, Click **Continue**.
|
|
381
|
+
- On the _Google OAuth 2.0 Playground wants access to your Google Account_
|
|
382
|
+
screen:
|
|
288
383
|
- **Select all**, including:
|
|
289
384
|
- **View your email messages and settings**.
|
|
290
385
|
- **Send email on your behalf**.
|
|
291
386
|
- Click **Continue**.
|
|
292
|
-
- Find
|
|
293
|
-
-
|
|
387
|
+
- Find _Step 2 Exchange authorization code for tokens_:
|
|
388
|
+
- _Authorization code_ will be prepopulated.
|
|
294
389
|
- Click **Exchange authorization code for tokens**.
|
|
295
|
-
-
|
|
296
|
-
|
|
390
|
+
- _Refresh token_ and _Access token_ will be populated briefly before the
|
|
391
|
+
interface automatically advances to _Step 3 Configure request to API_. To
|
|
392
|
+
view the _Access token_, return to _Step 2 Exchange authorization code for
|
|
393
|
+
tokens_.
|
|
394
|
+
- The _Access token_ is valid for 1 hour. You may enable **Auto-refresh the
|
|
395
|
+
token before it expires** or manually refresh it using the **Refresh access
|
|
396
|
+
token** button.
|
|
297
397
|
|
|
298
398
|
## Configure OpenFn CLI to find the access token
|
|
299
399
|
|
|
300
|
-
The Gmail adaptor looks for the access token in the configuration section under
|
|
400
|
+
The Gmail adaptor looks for the access token in the configuration section under
|
|
401
|
+
`access_token`.
|
|
301
402
|
|
|
302
403
|
Example configuration using a workflow:
|
|
303
404
|
|
package/ast.json
CHANGED
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
},
|
|
30
30
|
{
|
|
31
31
|
"title": "state",
|
|
32
|
-
"description": "{Array} data - The returned message objects, of the form `{ messageId, contents } `"
|
|
32
|
+
"description": "{Array} data - The returned message objects, of the form `{ messageId, ...contents } `"
|
|
33
33
|
},
|
|
34
34
|
{
|
|
35
35
|
"title": "state",
|
|
@@ -52,6 +52,11 @@
|
|
|
52
52
|
"title": "example",
|
|
53
53
|
"description": "getContentsFromMessages(\n {\n query: 'after:15/01/2025',\n contents: [\n 'subject',\n { type: 'file', name: 'metadata', file: 'report.txt'}\n ]\n }\n)",
|
|
54
54
|
"caption": "Get messages after a specific date, with subject and report.txt attachment"
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
"title": "example",
|
|
58
|
+
"description": "getContentsFromMessages(\n {\n query: 'after:2026/07/01',\n contents: [\n 'body',\n { type: 'file', name: 'report', file: /\\.xlsx$/ }\n ],\n fetchAttachments: false\n }\n)",
|
|
59
|
+
"caption": "Get metadata without downloading requested attachments"
|
|
55
60
|
}
|
|
56
61
|
]
|
|
57
62
|
},
|
|
@@ -121,6 +126,67 @@
|
|
|
121
126
|
]
|
|
122
127
|
},
|
|
123
128
|
"valid": true
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
"name": "getMessageById",
|
|
132
|
+
"params": [
|
|
133
|
+
"messageId",
|
|
134
|
+
"options"
|
|
135
|
+
],
|
|
136
|
+
"docs": {
|
|
137
|
+
"description": "Downloads contents from a single message of a Gmail account, identified by\nits Gmail API message id.",
|
|
138
|
+
"tags": [
|
|
139
|
+
{
|
|
140
|
+
"title": "public",
|
|
141
|
+
"description": null,
|
|
142
|
+
"type": null
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
"title": "function",
|
|
146
|
+
"description": null,
|
|
147
|
+
"name": null
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
"title": "param",
|
|
151
|
+
"description": "Gmail API message id to fetch.",
|
|
152
|
+
"type": {
|
|
153
|
+
"type": "NameExpression",
|
|
154
|
+
"name": "string"
|
|
155
|
+
},
|
|
156
|
+
"name": "messageId"
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
"title": "param",
|
|
160
|
+
"description": "Customized options including desired contents.",
|
|
161
|
+
"type": {
|
|
162
|
+
"type": "OptionalType",
|
|
163
|
+
"expression": {
|
|
164
|
+
"type": "NameExpression",
|
|
165
|
+
"name": "MessageIdOptions"
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
"name": "options"
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
"title": "state",
|
|
172
|
+
"description": "{Object} data - The returned message object, of the form `{ messageId, ...contents } `"
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
"title": "returns",
|
|
176
|
+
"description": null,
|
|
177
|
+
"type": {
|
|
178
|
+
"type": "NameExpression",
|
|
179
|
+
"name": "Operation"
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
{
|
|
183
|
+
"title": "example",
|
|
184
|
+
"description": "getMessageById(\n $.data.messageId,\n {\n contents: [\n { type: 'file', name: 'report', file: /\\.xlsx$/ }\n ]\n }\n)",
|
|
185
|
+
"caption": "Download attachments for a specific message identified by an earlier step"
|
|
186
|
+
}
|
|
187
|
+
]
|
|
188
|
+
},
|
|
189
|
+
"valid": true
|
|
124
190
|
}
|
|
125
191
|
],
|
|
126
192
|
"exports": [],
|
package/dist/index.cjs
CHANGED
|
@@ -38,6 +38,7 @@ __export(src_exports, {
|
|
|
38
38
|
fn: () => import_language_common2.fn,
|
|
39
39
|
fnIf: () => import_language_common2.fnIf,
|
|
40
40
|
getContentsFromMessages: () => getContentsFromMessages,
|
|
41
|
+
getMessageById: () => getMessageById,
|
|
41
42
|
lastReferenceValue: () => import_language_common2.lastReferenceValue,
|
|
42
43
|
log: () => import_language_common2.log,
|
|
43
44
|
merge: () => import_language_common2.merge,
|
|
@@ -61,6 +62,7 @@ __export(Adaptor_exports, {
|
|
|
61
62
|
fn: () => import_language_common2.fn,
|
|
62
63
|
fnIf: () => import_language_common2.fnIf,
|
|
63
64
|
getContentsFromMessages: () => getContentsFromMessages,
|
|
65
|
+
getMessageById: () => getMessageById,
|
|
64
66
|
lastReferenceValue: () => import_language_common2.lastReferenceValue,
|
|
65
67
|
log: () => import_language_common2.log,
|
|
66
68
|
merge: () => import_language_common2.merge,
|
|
@@ -72,7 +74,9 @@ var import_util = require("@openfn/language-common/util");
|
|
|
72
74
|
|
|
73
75
|
// src/Utils.js
|
|
74
76
|
var import_jszip = __toESM(require("jszip"), 1);
|
|
77
|
+
var import_xlsx = __toESM(require("xlsx"), 1);
|
|
75
78
|
var import_googleapis = require("googleapis");
|
|
79
|
+
var import_node_path = require("path");
|
|
76
80
|
var SEND_MESSAGE_BOUNDARY = "----=_Part_0_123456789.123456789";
|
|
77
81
|
var gmail;
|
|
78
82
|
async function getMessagesResult(userId, query, pageToken) {
|
|
@@ -91,19 +95,26 @@ async function getMessagesResult(userId, query, pageToken) {
|
|
|
91
95
|
throw new Error("Error fetching messages: " + error.message);
|
|
92
96
|
}
|
|
93
97
|
}
|
|
94
|
-
async function getMessageResult(userId, messageId) {
|
|
98
|
+
async function getMessageResult(userId, messageId, format = "full") {
|
|
95
99
|
var _a, _b;
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
100
|
+
try {
|
|
101
|
+
const { data } = await gmail.users.messages.get({
|
|
102
|
+
userId,
|
|
103
|
+
id: messageId,
|
|
104
|
+
format,
|
|
105
|
+
...format === "metadata" && {
|
|
106
|
+
metadataHeaders: ["From", "Date", "Subject"]
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
return {
|
|
110
|
+
userId,
|
|
111
|
+
messageId,
|
|
112
|
+
parts: (_a = data == null ? void 0 : data.payload) == null ? void 0 : _a.parts,
|
|
113
|
+
headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
|
|
114
|
+
};
|
|
115
|
+
} catch (error) {
|
|
116
|
+
throw new Error(`Error fetching message ${messageId}: ` + error.message);
|
|
117
|
+
}
|
|
107
118
|
}
|
|
108
119
|
function getContentIndicators(defaultContentRequests = [], contentRequests = []) {
|
|
109
120
|
const contentIndicators = contentRequests.map(getContentIndicator);
|
|
@@ -131,12 +142,20 @@ function getContentIndicator(contentRequest) {
|
|
|
131
142
|
}
|
|
132
143
|
return contentIndicator;
|
|
133
144
|
}
|
|
134
|
-
async function getMessageContent(message, desiredContent) {
|
|
145
|
+
async function getMessageContent(message, desiredContent, fetchAttachments = true) {
|
|
135
146
|
switch (desiredContent.type) {
|
|
136
147
|
case "archive":
|
|
137
|
-
return await getFileFromArchiveFromAttachment(
|
|
148
|
+
return await getFileFromArchiveFromAttachment(
|
|
149
|
+
message,
|
|
150
|
+
desiredContent,
|
|
151
|
+
fetchAttachments
|
|
152
|
+
);
|
|
138
153
|
case "file":
|
|
139
|
-
return await getFileFromAttachment(
|
|
154
|
+
return await getFileFromAttachment(
|
|
155
|
+
message,
|
|
156
|
+
desiredContent,
|
|
157
|
+
fetchAttachments
|
|
158
|
+
);
|
|
140
159
|
case "body":
|
|
141
160
|
return getBodyFromMessage(message, desiredContent);
|
|
142
161
|
case "from":
|
|
@@ -147,6 +166,50 @@ async function getMessageContent(message, desiredContent) {
|
|
|
147
166
|
return `Unsupported content type: ${desiredContent.type}`;
|
|
148
167
|
}
|
|
149
168
|
}
|
|
169
|
+
function resolveContentPlan(defaultContents, requestedContents, fetchAttachments) {
|
|
170
|
+
const contentIndicators = getContentIndicators(
|
|
171
|
+
defaultContents,
|
|
172
|
+
requestedContents
|
|
173
|
+
);
|
|
174
|
+
const needsFullFormat = contentIndicators.some(
|
|
175
|
+
({ type }) => type === "body" || type === "file" || type === "archive"
|
|
176
|
+
);
|
|
177
|
+
const messageFormat = needsFullFormat ? "full" : "metadata";
|
|
178
|
+
if (!fetchAttachments) {
|
|
179
|
+
const skippedNames = contentIndicators.filter(({ type }) => type === "file" || type === "archive").map(({ name }) => name);
|
|
180
|
+
if (skippedNames.length) {
|
|
181
|
+
console.log(
|
|
182
|
+
`fetchAttachments is false: skipping attachment downloads for ${skippedNames.join(
|
|
183
|
+
", "
|
|
184
|
+
)}; matched filenames will still be included in the output`
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return { contentIndicators, messageFormat };
|
|
189
|
+
}
|
|
190
|
+
async function buildMessageContent(userId, messageId, contentIndicators, messageFormat, fetchAttachments) {
|
|
191
|
+
var _a;
|
|
192
|
+
const content = { messageId };
|
|
193
|
+
const messageResult = await getMessageResult(
|
|
194
|
+
userId,
|
|
195
|
+
messageId,
|
|
196
|
+
messageFormat
|
|
197
|
+
);
|
|
198
|
+
for (const contentIndicator of contentIndicators) {
|
|
199
|
+
const messageContent = await getMessageContent(
|
|
200
|
+
messageResult,
|
|
201
|
+
contentIndicator,
|
|
202
|
+
fetchAttachments
|
|
203
|
+
);
|
|
204
|
+
if (messageContent && content[contentIndicator.name]) {
|
|
205
|
+
throw new Error(
|
|
206
|
+
`Duplicate content name detected: ${contentIndicator.name}`
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
content[_a = contentIndicator.name] ?? (content[_a] = messageContent);
|
|
210
|
+
}
|
|
211
|
+
return content;
|
|
212
|
+
}
|
|
150
213
|
async function buildAndSendMessage(message) {
|
|
151
214
|
const attachments = await parseAttachments(message.attachments);
|
|
152
215
|
const hasAttachments = attachments && attachments.length > 0;
|
|
@@ -227,7 +290,11 @@ function removeConnection(state) {
|
|
|
227
290
|
gmail = void 0;
|
|
228
291
|
return state;
|
|
229
292
|
}
|
|
230
|
-
async function getFileFromArchiveFromAttachment(message, desiredContent) {
|
|
293
|
+
async function getFileFromArchiveFromAttachment(message, desiredContent, fetchAttachments) {
|
|
294
|
+
if (!fetchAttachments) {
|
|
295
|
+
const part = findAttachmentPart(message, desiredContent.archive);
|
|
296
|
+
return part ? { archiveFilename: part.filename } : null;
|
|
297
|
+
}
|
|
231
298
|
const attachmentResult = await getAttachmentResult(
|
|
232
299
|
message,
|
|
233
300
|
desiredContent.archive
|
|
@@ -237,14 +304,18 @@ async function getFileFromArchiveFromAttachment(message, desiredContent) {
|
|
|
237
304
|
desiredContent
|
|
238
305
|
);
|
|
239
306
|
}
|
|
240
|
-
async function getFileFromAttachment(message, desiredContent) {
|
|
307
|
+
async function getFileFromAttachment(message, desiredContent, fetchAttachments) {
|
|
308
|
+
if (!fetchAttachments) {
|
|
309
|
+
const part = findAttachmentPart(message, desiredContent.file);
|
|
310
|
+
return part ? { filename: part.filename } : null;
|
|
311
|
+
}
|
|
241
312
|
const attachmentResult = await getAttachmentResult(
|
|
242
313
|
message,
|
|
243
314
|
desiredContent.file
|
|
244
315
|
);
|
|
245
316
|
return await extractFileFromAttachment(attachmentResult, desiredContent);
|
|
246
317
|
}
|
|
247
|
-
|
|
318
|
+
function findAttachmentPart(message, expression) {
|
|
248
319
|
var _a;
|
|
249
320
|
const part = (_a = message.parts) == null ? void 0 : _a.find((p) => {
|
|
250
321
|
return isExpressionMatch(p.filename, expression);
|
|
@@ -253,17 +324,60 @@ async function getAttachmentResult(message, expression) {
|
|
|
253
324
|
console.info(`Attachment not found for: ${expression}`);
|
|
254
325
|
return null;
|
|
255
326
|
}
|
|
327
|
+
return part;
|
|
328
|
+
}
|
|
329
|
+
async function getAttachmentResult(message, expression) {
|
|
330
|
+
const part = findAttachmentPart(message, expression);
|
|
331
|
+
if (!part) {
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
256
334
|
const { data } = await gmail.users.messages.attachments.get({
|
|
257
335
|
userId: message.userId,
|
|
258
336
|
messageId: message.messageId,
|
|
259
337
|
id: part.body.attachmentId
|
|
260
338
|
});
|
|
261
339
|
return {
|
|
262
|
-
data: data
|
|
340
|
+
data: data.data,
|
|
341
|
+
headers: part.headers,
|
|
263
342
|
filename: part.filename,
|
|
264
343
|
expression
|
|
265
344
|
};
|
|
266
345
|
}
|
|
346
|
+
var mimeTypeMap = {
|
|
347
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
|
|
348
|
+
"application/vnd.ms-excel": "xlsx",
|
|
349
|
+
"text/plain": "text",
|
|
350
|
+
"application/xml": "text",
|
|
351
|
+
"application/json": "json"
|
|
352
|
+
};
|
|
353
|
+
var parsers = {
|
|
354
|
+
xlsx: (data) => {
|
|
355
|
+
const workbook = import_xlsx.default.read(data, { type: "buffer" });
|
|
356
|
+
const result = {};
|
|
357
|
+
for (const sheet of workbook.SheetNames) {
|
|
358
|
+
result[sheet] = import_xlsx.default.utils.sheet_to_json(workbook.Sheets[sheet], {
|
|
359
|
+
header: 1
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
return result;
|
|
363
|
+
},
|
|
364
|
+
text: (data) => data.toString("utf-8"),
|
|
365
|
+
json: (data) => JSON.parse(data.toString("utf-8")),
|
|
366
|
+
base64: (data) => data.toString("base64")
|
|
367
|
+
};
|
|
368
|
+
function parseContent(data, headers, parseAs) {
|
|
369
|
+
var _a;
|
|
370
|
+
if (!data) {
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
const contentTypeRaw = ((_a = headers.find((h) => h.name.toLowerCase() === "content-type")) == null ? void 0 : _a.value) ?? "";
|
|
374
|
+
const contentType = contentTypeRaw.split(";")[0];
|
|
375
|
+
let type = parseAs ?? mimeTypeMap[contentType];
|
|
376
|
+
if (type in parsers) {
|
|
377
|
+
return parsers[type](data);
|
|
378
|
+
}
|
|
379
|
+
return parsers.base64(data);
|
|
380
|
+
}
|
|
267
381
|
async function extractFileFromArchiveAttachment(attachment, desiredContent) {
|
|
268
382
|
if (!attachment) {
|
|
269
383
|
return null;
|
|
@@ -301,10 +415,15 @@ async function extractFileFromAttachment(attachment, desiredContent) {
|
|
|
301
415
|
);
|
|
302
416
|
return null;
|
|
303
417
|
}
|
|
304
|
-
const fileContent = Buffer.from(attachment.data, "base64")
|
|
418
|
+
const fileContent = Buffer.from(attachment.data, "base64");
|
|
419
|
+
const content = parseContent(
|
|
420
|
+
fileContent,
|
|
421
|
+
attachment.headers,
|
|
422
|
+
desiredContent.parseAs
|
|
423
|
+
);
|
|
305
424
|
return {
|
|
306
425
|
filename: attachment.filename,
|
|
307
|
-
content: desiredContent.maxLength ?
|
|
426
|
+
content: desiredContent.maxLength ? content.substring(0, desiredContent.maxLength) : content
|
|
308
427
|
};
|
|
309
428
|
}
|
|
310
429
|
function getBodyFromMessage(message, desiredContent) {
|
|
@@ -349,7 +468,7 @@ function isExpressionMatch(text, expression) {
|
|
|
349
468
|
var import_language_common2 = require("@openfn/language-common");
|
|
350
469
|
function getContentsFromMessages(options) {
|
|
351
470
|
return async (state) => {
|
|
352
|
-
var _a
|
|
471
|
+
var _a;
|
|
353
472
|
const [resolvedOptions] = (0, import_util.expandReferences)(state, options);
|
|
354
473
|
const defaultOptions = {
|
|
355
474
|
contents: ["from", "date", "subject"],
|
|
@@ -360,11 +479,13 @@ function getContentsFromMessages(options) {
|
|
|
360
479
|
userId: resolvedOptions.email ?? defaultOptions.userId,
|
|
361
480
|
query: resolvedOptions.query,
|
|
362
481
|
processedIds: resolvedOptions.processedIds,
|
|
363
|
-
maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults
|
|
482
|
+
maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults,
|
|
483
|
+
fetchAttachments: resolvedOptions.fetchAttachments !== false
|
|
364
484
|
};
|
|
365
|
-
const contentIndicators =
|
|
485
|
+
const { contentIndicators, messageFormat } = resolveContentPlan(
|
|
366
486
|
defaultOptions.contents,
|
|
367
|
-
resolvedOptions.contents
|
|
487
|
+
resolvedOptions.contents,
|
|
488
|
+
opts.fetchAttachments
|
|
368
489
|
);
|
|
369
490
|
const contents = [];
|
|
370
491
|
const newIds = [];
|
|
@@ -387,23 +508,15 @@ function getContentsFromMessages(options) {
|
|
|
387
508
|
if (previousIds.includes(message.id)) {
|
|
388
509
|
continue;
|
|
389
510
|
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
if (messageContent && content[contentIndicator.name]) {
|
|
400
|
-
throw new Error(
|
|
401
|
-
`Duplicate content name detected: ${contentIndicator.name}`
|
|
402
|
-
);
|
|
403
|
-
}
|
|
404
|
-
content[_b = contentIndicator.name] ?? (content[_b] = messageContent);
|
|
405
|
-
}
|
|
406
|
-
contents.push(content);
|
|
511
|
+
contents.push(
|
|
512
|
+
await buildMessageContent(
|
|
513
|
+
opts.userId,
|
|
514
|
+
message.id,
|
|
515
|
+
contentIndicators,
|
|
516
|
+
messageFormat,
|
|
517
|
+
opts.fetchAttachments
|
|
518
|
+
)
|
|
519
|
+
);
|
|
407
520
|
if (contents.length >= opts.maxResults) {
|
|
408
521
|
break doNextPageToken;
|
|
409
522
|
}
|
|
@@ -429,6 +542,37 @@ function sendMessage(message) {
|
|
|
429
542
|
};
|
|
430
543
|
};
|
|
431
544
|
}
|
|
545
|
+
function getMessageById(messageId, options = {}) {
|
|
546
|
+
return async (state) => {
|
|
547
|
+
const [resolvedMessageId, resolvedOptions] = (0, import_util.expandReferences)(
|
|
548
|
+
state,
|
|
549
|
+
messageId,
|
|
550
|
+
options
|
|
551
|
+
);
|
|
552
|
+
if (typeof resolvedMessageId !== "string" || !resolvedMessageId) {
|
|
553
|
+
throw new Error("getMessageById: messageId must be a non-empty string");
|
|
554
|
+
}
|
|
555
|
+
const defaultOptions = {
|
|
556
|
+
contents: ["from", "date", "subject"],
|
|
557
|
+
userId: "me"
|
|
558
|
+
};
|
|
559
|
+
const userId = resolvedOptions.email ?? defaultOptions.userId;
|
|
560
|
+
const fetchAttachments = resolvedOptions.fetchAttachments !== false;
|
|
561
|
+
const { contentIndicators, messageFormat } = resolveContentPlan(
|
|
562
|
+
defaultOptions.contents,
|
|
563
|
+
resolvedOptions.contents,
|
|
564
|
+
fetchAttachments
|
|
565
|
+
);
|
|
566
|
+
const content = await buildMessageContent(
|
|
567
|
+
userId,
|
|
568
|
+
resolvedMessageId,
|
|
569
|
+
contentIndicators,
|
|
570
|
+
messageFormat,
|
|
571
|
+
fetchAttachments
|
|
572
|
+
);
|
|
573
|
+
return (0, import_language_common.composeNextState)(state, content);
|
|
574
|
+
};
|
|
575
|
+
}
|
|
432
576
|
function execute(...operations) {
|
|
433
577
|
const initialState = {
|
|
434
578
|
references: [],
|
|
@@ -463,6 +607,7 @@ var src_default = Adaptor_exports;
|
|
|
463
607
|
fn,
|
|
464
608
|
fnIf,
|
|
465
609
|
getContentsFromMessages,
|
|
610
|
+
getMessageById,
|
|
466
611
|
lastReferenceValue,
|
|
467
612
|
log,
|
|
468
613
|
merge,
|
package/dist/index.js
CHANGED
|
@@ -19,6 +19,7 @@ __export(Adaptor_exports, {
|
|
|
19
19
|
fn: () => fn,
|
|
20
20
|
fnIf: () => fnIf,
|
|
21
21
|
getContentsFromMessages: () => getContentsFromMessages,
|
|
22
|
+
getMessageById: () => getMessageById,
|
|
22
23
|
lastReferenceValue: () => lastReferenceValue,
|
|
23
24
|
log: () => log,
|
|
24
25
|
merge: () => merge,
|
|
@@ -36,6 +37,7 @@ import {
|
|
|
36
37
|
|
|
37
38
|
// src/Utils.js
|
|
38
39
|
import JSZip from "jszip";
|
|
40
|
+
import xlsx from "xlsx";
|
|
39
41
|
import { google } from "googleapis";
|
|
40
42
|
var SEND_MESSAGE_BOUNDARY = "----=_Part_0_123456789.123456789";
|
|
41
43
|
var gmail;
|
|
@@ -55,19 +57,26 @@ async function getMessagesResult(userId, query, pageToken) {
|
|
|
55
57
|
throw new Error("Error fetching messages: " + error.message);
|
|
56
58
|
}
|
|
57
59
|
}
|
|
58
|
-
async function getMessageResult(userId, messageId) {
|
|
60
|
+
async function getMessageResult(userId, messageId, format = "full") {
|
|
59
61
|
var _a, _b;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
62
|
+
try {
|
|
63
|
+
const { data } = await gmail.users.messages.get({
|
|
64
|
+
userId,
|
|
65
|
+
id: messageId,
|
|
66
|
+
format,
|
|
67
|
+
...format === "metadata" && {
|
|
68
|
+
metadataHeaders: ["From", "Date", "Subject"]
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
return {
|
|
72
|
+
userId,
|
|
73
|
+
messageId,
|
|
74
|
+
parts: (_a = data == null ? void 0 : data.payload) == null ? void 0 : _a.parts,
|
|
75
|
+
headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
|
|
76
|
+
};
|
|
77
|
+
} catch (error) {
|
|
78
|
+
throw new Error(`Error fetching message ${messageId}: ` + error.message);
|
|
79
|
+
}
|
|
71
80
|
}
|
|
72
81
|
function getContentIndicators(defaultContentRequests = [], contentRequests = []) {
|
|
73
82
|
const contentIndicators = contentRequests.map(getContentIndicator);
|
|
@@ -95,12 +104,20 @@ function getContentIndicator(contentRequest) {
|
|
|
95
104
|
}
|
|
96
105
|
return contentIndicator;
|
|
97
106
|
}
|
|
98
|
-
async function getMessageContent(message, desiredContent) {
|
|
107
|
+
async function getMessageContent(message, desiredContent, fetchAttachments = true) {
|
|
99
108
|
switch (desiredContent.type) {
|
|
100
109
|
case "archive":
|
|
101
|
-
return await getFileFromArchiveFromAttachment(
|
|
110
|
+
return await getFileFromArchiveFromAttachment(
|
|
111
|
+
message,
|
|
112
|
+
desiredContent,
|
|
113
|
+
fetchAttachments
|
|
114
|
+
);
|
|
102
115
|
case "file":
|
|
103
|
-
return await getFileFromAttachment(
|
|
116
|
+
return await getFileFromAttachment(
|
|
117
|
+
message,
|
|
118
|
+
desiredContent,
|
|
119
|
+
fetchAttachments
|
|
120
|
+
);
|
|
104
121
|
case "body":
|
|
105
122
|
return getBodyFromMessage(message, desiredContent);
|
|
106
123
|
case "from":
|
|
@@ -111,6 +128,50 @@ async function getMessageContent(message, desiredContent) {
|
|
|
111
128
|
return `Unsupported content type: ${desiredContent.type}`;
|
|
112
129
|
}
|
|
113
130
|
}
|
|
131
|
+
function resolveContentPlan(defaultContents, requestedContents, fetchAttachments) {
|
|
132
|
+
const contentIndicators = getContentIndicators(
|
|
133
|
+
defaultContents,
|
|
134
|
+
requestedContents
|
|
135
|
+
);
|
|
136
|
+
const needsFullFormat = contentIndicators.some(
|
|
137
|
+
({ type }) => type === "body" || type === "file" || type === "archive"
|
|
138
|
+
);
|
|
139
|
+
const messageFormat = needsFullFormat ? "full" : "metadata";
|
|
140
|
+
if (!fetchAttachments) {
|
|
141
|
+
const skippedNames = contentIndicators.filter(({ type }) => type === "file" || type === "archive").map(({ name }) => name);
|
|
142
|
+
if (skippedNames.length) {
|
|
143
|
+
console.log(
|
|
144
|
+
`fetchAttachments is false: skipping attachment downloads for ${skippedNames.join(
|
|
145
|
+
", "
|
|
146
|
+
)}; matched filenames will still be included in the output`
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return { contentIndicators, messageFormat };
|
|
151
|
+
}
|
|
152
|
+
async function buildMessageContent(userId, messageId, contentIndicators, messageFormat, fetchAttachments) {
|
|
153
|
+
var _a;
|
|
154
|
+
const content = { messageId };
|
|
155
|
+
const messageResult = await getMessageResult(
|
|
156
|
+
userId,
|
|
157
|
+
messageId,
|
|
158
|
+
messageFormat
|
|
159
|
+
);
|
|
160
|
+
for (const contentIndicator of contentIndicators) {
|
|
161
|
+
const messageContent = await getMessageContent(
|
|
162
|
+
messageResult,
|
|
163
|
+
contentIndicator,
|
|
164
|
+
fetchAttachments
|
|
165
|
+
);
|
|
166
|
+
if (messageContent && content[contentIndicator.name]) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
`Duplicate content name detected: ${contentIndicator.name}`
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
content[_a = contentIndicator.name] ?? (content[_a] = messageContent);
|
|
172
|
+
}
|
|
173
|
+
return content;
|
|
174
|
+
}
|
|
114
175
|
async function buildAndSendMessage(message) {
|
|
115
176
|
const attachments = await parseAttachments(message.attachments);
|
|
116
177
|
const hasAttachments = attachments && attachments.length > 0;
|
|
@@ -191,7 +252,11 @@ function removeConnection(state) {
|
|
|
191
252
|
gmail = void 0;
|
|
192
253
|
return state;
|
|
193
254
|
}
|
|
194
|
-
async function getFileFromArchiveFromAttachment(message, desiredContent) {
|
|
255
|
+
async function getFileFromArchiveFromAttachment(message, desiredContent, fetchAttachments) {
|
|
256
|
+
if (!fetchAttachments) {
|
|
257
|
+
const part = findAttachmentPart(message, desiredContent.archive);
|
|
258
|
+
return part ? { archiveFilename: part.filename } : null;
|
|
259
|
+
}
|
|
195
260
|
const attachmentResult = await getAttachmentResult(
|
|
196
261
|
message,
|
|
197
262
|
desiredContent.archive
|
|
@@ -201,14 +266,18 @@ async function getFileFromArchiveFromAttachment(message, desiredContent) {
|
|
|
201
266
|
desiredContent
|
|
202
267
|
);
|
|
203
268
|
}
|
|
204
|
-
async function getFileFromAttachment(message, desiredContent) {
|
|
269
|
+
async function getFileFromAttachment(message, desiredContent, fetchAttachments) {
|
|
270
|
+
if (!fetchAttachments) {
|
|
271
|
+
const part = findAttachmentPart(message, desiredContent.file);
|
|
272
|
+
return part ? { filename: part.filename } : null;
|
|
273
|
+
}
|
|
205
274
|
const attachmentResult = await getAttachmentResult(
|
|
206
275
|
message,
|
|
207
276
|
desiredContent.file
|
|
208
277
|
);
|
|
209
278
|
return await extractFileFromAttachment(attachmentResult, desiredContent);
|
|
210
279
|
}
|
|
211
|
-
|
|
280
|
+
function findAttachmentPart(message, expression) {
|
|
212
281
|
var _a;
|
|
213
282
|
const part = (_a = message.parts) == null ? void 0 : _a.find((p) => {
|
|
214
283
|
return isExpressionMatch(p.filename, expression);
|
|
@@ -217,17 +286,60 @@ async function getAttachmentResult(message, expression) {
|
|
|
217
286
|
console.info(`Attachment not found for: ${expression}`);
|
|
218
287
|
return null;
|
|
219
288
|
}
|
|
289
|
+
return part;
|
|
290
|
+
}
|
|
291
|
+
async function getAttachmentResult(message, expression) {
|
|
292
|
+
const part = findAttachmentPart(message, expression);
|
|
293
|
+
if (!part) {
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
220
296
|
const { data } = await gmail.users.messages.attachments.get({
|
|
221
297
|
userId: message.userId,
|
|
222
298
|
messageId: message.messageId,
|
|
223
299
|
id: part.body.attachmentId
|
|
224
300
|
});
|
|
225
301
|
return {
|
|
226
|
-
data: data
|
|
302
|
+
data: data.data,
|
|
303
|
+
headers: part.headers,
|
|
227
304
|
filename: part.filename,
|
|
228
305
|
expression
|
|
229
306
|
};
|
|
230
307
|
}
|
|
308
|
+
var mimeTypeMap = {
|
|
309
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
|
|
310
|
+
"application/vnd.ms-excel": "xlsx",
|
|
311
|
+
"text/plain": "text",
|
|
312
|
+
"application/xml": "text",
|
|
313
|
+
"application/json": "json"
|
|
314
|
+
};
|
|
315
|
+
var parsers = {
|
|
316
|
+
xlsx: (data) => {
|
|
317
|
+
const workbook = xlsx.read(data, { type: "buffer" });
|
|
318
|
+
const result = {};
|
|
319
|
+
for (const sheet of workbook.SheetNames) {
|
|
320
|
+
result[sheet] = xlsx.utils.sheet_to_json(workbook.Sheets[sheet], {
|
|
321
|
+
header: 1
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
return result;
|
|
325
|
+
},
|
|
326
|
+
text: (data) => data.toString("utf-8"),
|
|
327
|
+
json: (data) => JSON.parse(data.toString("utf-8")),
|
|
328
|
+
base64: (data) => data.toString("base64")
|
|
329
|
+
};
|
|
330
|
+
function parseContent(data, headers, parseAs) {
|
|
331
|
+
var _a;
|
|
332
|
+
if (!data) {
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
const contentTypeRaw = ((_a = headers.find((h) => h.name.toLowerCase() === "content-type")) == null ? void 0 : _a.value) ?? "";
|
|
336
|
+
const contentType = contentTypeRaw.split(";")[0];
|
|
337
|
+
let type = parseAs ?? mimeTypeMap[contentType];
|
|
338
|
+
if (type in parsers) {
|
|
339
|
+
return parsers[type](data);
|
|
340
|
+
}
|
|
341
|
+
return parsers.base64(data);
|
|
342
|
+
}
|
|
231
343
|
async function extractFileFromArchiveAttachment(attachment, desiredContent) {
|
|
232
344
|
if (!attachment) {
|
|
233
345
|
return null;
|
|
@@ -265,10 +377,15 @@ async function extractFileFromAttachment(attachment, desiredContent) {
|
|
|
265
377
|
);
|
|
266
378
|
return null;
|
|
267
379
|
}
|
|
268
|
-
const fileContent = Buffer.from(attachment.data, "base64")
|
|
380
|
+
const fileContent = Buffer.from(attachment.data, "base64");
|
|
381
|
+
const content = parseContent(
|
|
382
|
+
fileContent,
|
|
383
|
+
attachment.headers,
|
|
384
|
+
desiredContent.parseAs
|
|
385
|
+
);
|
|
269
386
|
return {
|
|
270
387
|
filename: attachment.filename,
|
|
271
|
-
content: desiredContent.maxLength ?
|
|
388
|
+
content: desiredContent.maxLength ? content.substring(0, desiredContent.maxLength) : content
|
|
272
389
|
};
|
|
273
390
|
}
|
|
274
391
|
function getBodyFromMessage(message, desiredContent) {
|
|
@@ -328,7 +445,7 @@ import {
|
|
|
328
445
|
} from "@openfn/language-common";
|
|
329
446
|
function getContentsFromMessages(options) {
|
|
330
447
|
return async (state) => {
|
|
331
|
-
var _a
|
|
448
|
+
var _a;
|
|
332
449
|
const [resolvedOptions] = expandReferences(state, options);
|
|
333
450
|
const defaultOptions = {
|
|
334
451
|
contents: ["from", "date", "subject"],
|
|
@@ -339,11 +456,13 @@ function getContentsFromMessages(options) {
|
|
|
339
456
|
userId: resolvedOptions.email ?? defaultOptions.userId,
|
|
340
457
|
query: resolvedOptions.query,
|
|
341
458
|
processedIds: resolvedOptions.processedIds,
|
|
342
|
-
maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults
|
|
459
|
+
maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults,
|
|
460
|
+
fetchAttachments: resolvedOptions.fetchAttachments !== false
|
|
343
461
|
};
|
|
344
|
-
const contentIndicators =
|
|
462
|
+
const { contentIndicators, messageFormat } = resolveContentPlan(
|
|
345
463
|
defaultOptions.contents,
|
|
346
|
-
resolvedOptions.contents
|
|
464
|
+
resolvedOptions.contents,
|
|
465
|
+
opts.fetchAttachments
|
|
347
466
|
);
|
|
348
467
|
const contents = [];
|
|
349
468
|
const newIds = [];
|
|
@@ -366,23 +485,15 @@ function getContentsFromMessages(options) {
|
|
|
366
485
|
if (previousIds.includes(message.id)) {
|
|
367
486
|
continue;
|
|
368
487
|
}
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
if (messageContent && content[contentIndicator.name]) {
|
|
379
|
-
throw new Error(
|
|
380
|
-
`Duplicate content name detected: ${contentIndicator.name}`
|
|
381
|
-
);
|
|
382
|
-
}
|
|
383
|
-
content[_b = contentIndicator.name] ?? (content[_b] = messageContent);
|
|
384
|
-
}
|
|
385
|
-
contents.push(content);
|
|
488
|
+
contents.push(
|
|
489
|
+
await buildMessageContent(
|
|
490
|
+
opts.userId,
|
|
491
|
+
message.id,
|
|
492
|
+
contentIndicators,
|
|
493
|
+
messageFormat,
|
|
494
|
+
opts.fetchAttachments
|
|
495
|
+
)
|
|
496
|
+
);
|
|
386
497
|
if (contents.length >= opts.maxResults) {
|
|
387
498
|
break doNextPageToken;
|
|
388
499
|
}
|
|
@@ -408,6 +519,37 @@ function sendMessage(message) {
|
|
|
408
519
|
};
|
|
409
520
|
};
|
|
410
521
|
}
|
|
522
|
+
function getMessageById(messageId, options = {}) {
|
|
523
|
+
return async (state) => {
|
|
524
|
+
const [resolvedMessageId, resolvedOptions] = expandReferences(
|
|
525
|
+
state,
|
|
526
|
+
messageId,
|
|
527
|
+
options
|
|
528
|
+
);
|
|
529
|
+
if (typeof resolvedMessageId !== "string" || !resolvedMessageId) {
|
|
530
|
+
throw new Error("getMessageById: messageId must be a non-empty string");
|
|
531
|
+
}
|
|
532
|
+
const defaultOptions = {
|
|
533
|
+
contents: ["from", "date", "subject"],
|
|
534
|
+
userId: "me"
|
|
535
|
+
};
|
|
536
|
+
const userId = resolvedOptions.email ?? defaultOptions.userId;
|
|
537
|
+
const fetchAttachments = resolvedOptions.fetchAttachments !== false;
|
|
538
|
+
const { contentIndicators, messageFormat } = resolveContentPlan(
|
|
539
|
+
defaultOptions.contents,
|
|
540
|
+
resolvedOptions.contents,
|
|
541
|
+
fetchAttachments
|
|
542
|
+
);
|
|
543
|
+
const content = await buildMessageContent(
|
|
544
|
+
userId,
|
|
545
|
+
resolvedMessageId,
|
|
546
|
+
contentIndicators,
|
|
547
|
+
messageFormat,
|
|
548
|
+
fetchAttachments
|
|
549
|
+
);
|
|
550
|
+
return composeNextState(state, content);
|
|
551
|
+
};
|
|
552
|
+
}
|
|
411
553
|
function execute(...operations) {
|
|
412
554
|
const initialState = {
|
|
413
555
|
references: [],
|
|
@@ -442,6 +584,7 @@ export {
|
|
|
442
584
|
fn,
|
|
443
585
|
fnIf,
|
|
444
586
|
getContentsFromMessages,
|
|
587
|
+
getMessageById,
|
|
445
588
|
lastReferenceValue,
|
|
446
589
|
log,
|
|
447
590
|
merge,
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openfn/language-gmail",
|
|
3
3
|
"label": "Gmail",
|
|
4
|
-
"version": "
|
|
4
|
+
"version": "3.1.0",
|
|
5
5
|
"badge": "Community",
|
|
6
6
|
"description": "OpenFn gmail adaptor",
|
|
7
7
|
"type": "module",
|
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"googleapis": "171.4.0",
|
|
26
26
|
"jszip": "^3.10.1",
|
|
27
|
+
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
|
|
27
28
|
"@openfn/language-common": "3.3.4"
|
|
28
29
|
},
|
|
29
30
|
"devDependencies": {
|
package/types/Adaptor.d.ts
CHANGED
|
@@ -15,18 +15,20 @@
|
|
|
15
15
|
* @typedef {Object} Options
|
|
16
16
|
* @public
|
|
17
17
|
* @property {string?} [query] - Gmail search query string.
|
|
18
|
-
* @property {Array<string|MessageContent>} [contents=['from', 'date', 'subject'
|
|
18
|
+
* @property {Array<string|MessageContent>} [contents=['from', 'date', 'subject']]
|
|
19
19
|
* An array of strings or MessageContent objects used to specify which parts of the message to retrieve.
|
|
20
20
|
* @property {Array<string>} [processedIds] - Ignore message ids which have already been processed.
|
|
21
21
|
* @property {string?} [email] - The user account to retrieve messages from. Defaults to the authenticated user.
|
|
22
22
|
* @property {int?} [maxResults] - Maximum number of messages to process per request. Default is 1000.
|
|
23
|
+
* @property {boolean} [fetchAttachments=true] - Whether to download file and archive attachments.
|
|
24
|
+
* When false, matched attachments are returned as filename-only objects without content.
|
|
23
25
|
*/
|
|
24
26
|
/**
|
|
25
27
|
* Downloads contents from messages of a Gmail account.
|
|
26
28
|
* @public
|
|
27
29
|
* @function
|
|
28
30
|
* @param {Options} options - Customized options including desired contents and query.
|
|
29
|
-
* @state {Array} data - The returned message objects, of the form `{ messageId, contents } `
|
|
31
|
+
* @state {Array} data - The returned message objects, of the form `{ messageId, ...contents } `
|
|
30
32
|
* @state {Array<string>} processedIds - An array of string ids processed by this request
|
|
31
33
|
* @returns {Operation}
|
|
32
34
|
* @example <caption>Get a message with a specific subject</caption>
|
|
@@ -45,6 +47,17 @@
|
|
|
45
47
|
* ]
|
|
46
48
|
* }
|
|
47
49
|
* )
|
|
50
|
+
* @example <caption>Get metadata without downloading requested attachments</caption>
|
|
51
|
+
* getContentsFromMessages(
|
|
52
|
+
* {
|
|
53
|
+
* query: 'after:2026/07/01',
|
|
54
|
+
* contents: [
|
|
55
|
+
* 'body',
|
|
56
|
+
* { type: 'file', name: 'report', file: /\.xlsx$/ }
|
|
57
|
+
* ],
|
|
58
|
+
* fetchAttachments: false
|
|
59
|
+
* }
|
|
60
|
+
* )
|
|
48
61
|
*/
|
|
49
62
|
export function getContentsFromMessages(options: Options): Operation;
|
|
50
63
|
/**
|
|
@@ -75,6 +88,36 @@ export function getContentsFromMessages(options: Options): Operation;
|
|
|
75
88
|
* })
|
|
76
89
|
*/
|
|
77
90
|
export function sendMessage(message: SendMessageOptions | SendMessageOptions[]): Operation;
|
|
91
|
+
/**
|
|
92
|
+
* Configurable options provided to getMessageById.
|
|
93
|
+
* @typedef {Object} MessageIdOptions
|
|
94
|
+
* @public
|
|
95
|
+
* @property {Array<string|MessageContent>} [contents=['from', 'date', 'subject']]
|
|
96
|
+
* An array of strings or MessageContent objects used to specify which parts of the message to retrieve.
|
|
97
|
+
* @property {string?} [email] - The user account to retrieve messages from. Defaults to the authenticated user.
|
|
98
|
+
* @property {boolean} [fetchAttachments=true] - Whether to download file and archive attachments.
|
|
99
|
+
* When false, matched attachments are returned as filename-only objects without content.
|
|
100
|
+
*/
|
|
101
|
+
/**
|
|
102
|
+
* Downloads contents from a single message of a Gmail account, identified by
|
|
103
|
+
* its Gmail API message id.
|
|
104
|
+
* @public
|
|
105
|
+
* @function
|
|
106
|
+
* @param {string} messageId - Gmail API message id to fetch.
|
|
107
|
+
* @param {MessageIdOptions} [options] - Customized options including desired contents.
|
|
108
|
+
* @state {Object} data - The returned message object, of the form `{ messageId, ...contents } `
|
|
109
|
+
* @returns {Operation}
|
|
110
|
+
* @example <caption>Download attachments for a specific message identified by an earlier step</caption>
|
|
111
|
+
* getMessageById(
|
|
112
|
+
* $.data.messageId,
|
|
113
|
+
* {
|
|
114
|
+
* contents: [
|
|
115
|
+
* { type: 'file', name: 'report', file: /\.xlsx$/ }
|
|
116
|
+
* ]
|
|
117
|
+
* }
|
|
118
|
+
* )
|
|
119
|
+
*/
|
|
120
|
+
export function getMessageById(messageId: string, options?: MessageIdOptions): Operation;
|
|
78
121
|
/**
|
|
79
122
|
* Execute a sequence of operations.
|
|
80
123
|
* Wraps `language-common/execute`, and prepends initial state for http.
|
|
@@ -115,4 +158,8 @@ export type SendMessageOptions = {
|
|
|
115
158
|
content: string | Buffer;
|
|
116
159
|
}>;
|
|
117
160
|
};
|
|
161
|
+
/**
|
|
162
|
+
* Configurable options provided to getMessageById.
|
|
163
|
+
*/
|
|
164
|
+
export type MessageIdOptions = any;
|
|
118
165
|
export { alterState, combine, cursor, dataPath, dataValue, each, field, fields, fn, fnIf, lastReferenceValue, log, merge, sourceValue } from "@openfn/language-common";
|
package/types/Utils.d.ts
CHANGED
|
@@ -2,14 +2,21 @@ export function getMessagesResult(userId: any, query: any, pageToken: any): Prom
|
|
|
2
2
|
messages: any;
|
|
3
3
|
nextPageToken: any;
|
|
4
4
|
}>;
|
|
5
|
-
export function getMessageResult(userId: any, messageId: any): Promise<{
|
|
5
|
+
export function getMessageResult(userId: any, messageId: any, format?: string): Promise<{
|
|
6
6
|
userId: any;
|
|
7
7
|
messageId: any;
|
|
8
8
|
parts: any;
|
|
9
9
|
headers: any;
|
|
10
10
|
}>;
|
|
11
11
|
export function getContentIndicators(defaultContentRequests?: any[], contentRequests?: any[]): any[];
|
|
12
|
-
export function getMessageContent(message: any, desiredContent: any): Promise<any>;
|
|
12
|
+
export function getMessageContent(message: any, desiredContent: any, fetchAttachments?: boolean): Promise<any>;
|
|
13
|
+
export function resolveContentPlan(defaultContents: any, requestedContents: any, fetchAttachments: any): {
|
|
14
|
+
contentIndicators: any[];
|
|
15
|
+
messageFormat: string;
|
|
16
|
+
};
|
|
17
|
+
export function buildMessageContent(userId: any, messageId: any, contentIndicators: any, messageFormat: any, fetchAttachments: any): Promise<{
|
|
18
|
+
messageId: any;
|
|
19
|
+
}>;
|
|
13
20
|
export function buildAndSendMessage(message: any): Promise<any>;
|
|
14
21
|
export function createConnection(state: any): any;
|
|
15
22
|
export function removeConnection(state: any): any;
|