@openfn/language-gmail 1.0.0 → 1.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 CHANGED
@@ -1,103 +1,152 @@
1
- # Gmail Message Content Extraction
1
+ # Gmail Adaptor
2
2
 
3
- This adaptor is used to extract specific content from Gmail messages using
4
- custom "desiredContent" configurations. The sample code specifies how to query
5
- Gmail for messages and identify desired attachments and metadata.
3
+ ## What it does
6
4
 
7
- ## How It Works
5
+ This adaptor is used to extract specific content from Gmail messages using custom desired "content" configurations. The sample code specifies how to query Gmail for messages and identify desired attachments and metadata.
8
6
 
9
- 1. Gmail Query: Constructs a Gmail query string to filter relevant messages.
10
- 2. Desired Content Matching: Uses the desiredContents array to identify and
11
- extract:
12
- - Metadata files
13
- - Archive files and their contents
14
- - Message metadata (subject, date, from, body)
15
- 3. Output: Returns a structured collection of matched content.
7
+ Without any parameters, the `getContentsFromMessages()` function will return an array containing every message in the account of the authenticated user including `from`, `date` and `subject`.
16
8
 
17
- ## Usage
9
+ A number of options are available to isolated the desired messages and to customize the output.
18
10
 
19
- The adaptor's primary function is `getContentsFromMessages`
11
+ ## Options
20
12
 
21
- ```js
22
- getContentsFromMessages(userId, query, desiredContents, callback);
23
- ```
13
+ Optional parameters include: `contents`, `query`, `email`, `processedIds`, `maxResults`
24
14
 
25
- 1. Set userId with the Gmail account to query.
26
- 2. Customize the query to contain filters as needed. This is the same format a
27
- the query in the Gmail UI.
28
- 3. Specify what content to retrieve from messages (body, subject, attachments,
29
- etc)
15
+ ### options.contents
30
16
 
31
- ## Extracting Message Contents
17
+ Use the `options.contents` array to specify the content to retrieve from each message. Always included are `from`, `date`, and `subject`.
32
18
 
33
- The `desiredContents` array should list what content to retrieve from each
34
- message. Each item should be a string (ie, `"body"` or an object describing an
35
- attachment)
19
+ Each item can be a simple string (ie, `'body'`, `'subject'`) or an MessageContent object offering advanced configuration.
36
20
 
37
- ### Metadata
21
+ #### Basic metadata
38
22
 
39
- The following strings can be extracted:
23
+ The following types of content can be extracted:
40
24
 
41
25
  - `body`: Extracts the message body.
42
26
  - `subject`: Extracts the email subject.
43
27
  - `date`: Extracts the timestamp of the email.
44
28
  - `from`: Extracts the sender's information.
45
29
 
46
- ### Attachment: basic file
30
+ Optionally, each of these content strings can be expanded to include additional specifications:
31
+
32
+ ```js
33
+ const mySubject = {
34
+ type: 'subject',
35
+ name: 'email-title',
36
+ maxLength: 25,
37
+ };
38
+ ```
39
+
40
+ - The `type` property instructs the function which content type to extract.
41
+ - The `name` property allows you to add a custom name to this information.
42
+ - The `maxLength` property allows you to limit the length of the content returned.
43
+
44
+ #### Attachment: basic file
45
+
46
+ Extract content from a file attachment.
47
47
 
48
- Extract the content from a file attachment. Specify the file name with a regular
49
- expression on the `file` key.
48
+ `file`: Identify the specific file inside the archive by providing its name as a string or using a regular expression to matching a pattern.
50
49
 
51
50
  ```js
52
- {
53
- type: "file",
54
- name: "metadata",
51
+ const myMetadata = {
52
+ type: 'file',
53
+ name: 'metadata',
55
54
  file: /^summary\.txt$/,
56
- }
55
+ };
56
+ ```
57
+
58
+ ```js
59
+ const myMetadata = {
60
+ type: 'file',
61
+ file: 'summary.txt',
62
+ maxLength: 500,
63
+ };
57
64
  ```
58
65
 
59
- ### Attachment: archived file
66
+ #### Attachment: archived file
60
67
 
61
- Extract the content from a file embedded in an archive attachment.
68
+ Extract content from a file embedded in an archive attachment.
62
69
 
63
- Specify the archive with a regular expression on the `archive` key. Extract a
64
- file within the archive with the `file` key.
70
+ - `archive`: Specify the file name of the archive using either a string for an exact match or a regular expression to match a pattern.
71
+ - `file`: Identify the specific file inside the archive by providing its name as a string or using a regular expression to match a pattern.
65
72
 
66
73
  ```js
67
- {
68
- type: "archive",
69
- name: "data",
70
- archive: /_device_data\.zip$/,
74
+ const myArchivedFile = {
75
+ type: 'archive',
76
+ name: 'data',
77
+ archive: 'devicedata.zip',
71
78
  file: /_CURRENT_DATA_\w*?\.json$/,
72
- }
79
+ maxLength: 5000,
80
+ };
73
81
  ```
74
82
 
75
- ## Query Setup
83
+ ```js
84
+ options.contents = [mySubject, 'body', myMetadata, myArchivedFile];
85
+ ```
76
86
 
77
- The query variable is constructed to filter Gmail messages:
87
+ ### options.query
78
88
 
79
- - Inbox messages with the subject containing "30DTR Data".
80
- - Messages sent within the last 31 days.
89
+ Use a `query` parameter to filter the messages returned.
81
90
 
82
- ## Example
91
+ The query syntax supports the same query format as the Gmail `search` box.
83
92
 
84
- ```js
85
- const userId = 'tester@gmail.com';
93
+ ```
94
+ options.query = 'from:someuser@example.com rfc822msgid:<somemsgid@example.com> is:unread';
95
+ ```
96
+
97
+ A full list of supported search operations can be found here: [Refine searches in Gmail](https://support.google.com/mail/answer/7190)
98
+
99
+ ### options.email
100
+
101
+ Optionally specify the email address used for the Gmail account. This almost always the same email associated with the authenticated user so this parameter is optional.
102
+
103
+ ```
104
+ options.email = '<EMAIL>';
105
+ ```
106
+
107
+ ### options.processedIds
108
+
109
+ In some scenarios, it may be necessary to skip certain messages to prevent the retrieval of duplicate data. Passing an array of messageIds will allow the function to skip these messages if any of the ids are encountered in the returned messages.
86
110
 
87
- const querySubject = encodeURIComponent('device data summary');
111
+ ```
112
+ options.processedIds = [
113
+ '194e3cf1ca0ccd66',
114
+ '283e2df2ca0ecd75',
115
+ '572e1af3ca0bcd84',
116
+ ];
117
+ ```
118
+
119
+ ### options.maxResults
120
+
121
+ To prevent inadventant massive retrieval of messages, you can limit the number of results returned. The default value is 1000.
122
+
123
+ This works in conjuction with the `options.processedIds` parameter. For example:
124
+
125
+ - account contains messages [1, 2, 3]
126
+ - `options.processedIds = [1];`
127
+ - `options.maxResults = 1;`
128
+ - this will skip message #1 and resulting dataset will contain a single message #2
129
+
130
+ ## Example jobs
131
+
132
+ ```js
133
+ const query = 'in:inbox newer_than:2d';
134
+ const contents = ['body'];
135
+ const maxResults = 200;
136
+ getContentsFromMessages({ query, contents, maxResults });
137
+ ```
88
138
 
89
- // All messages newer than 30 days ago
90
- const MILLISECONDS_PER_DAY = 1000 * 60 * 60 * 24;
91
- const queryAfterDate = new Date(Date.now() - 30 * MILLISECONDS_PER_DAY)
92
- .toISOString()
93
- .split('T')[0];
139
+ ```js
140
+ const subject = 'device data summary'.replace(' ', '+');
141
+ const query = `in:inbox subject:${subject} newer_than:1m`;
94
142
 
95
- const query = `in:inbox subject:${querySubject} after:${queryAfterDate}`;
143
+ const email = 'special_assigned_delegate@gmail.com';
96
144
 
97
145
  const metadataFile = {
98
146
  type: 'file',
99
147
  name: 'metadata',
100
- file: /^summary\.txt$/,
148
+ file: /summary\.txt$/,
149
+ maxLength: 500,
101
150
  };
102
151
 
103
152
  const dataFile = {
@@ -107,63 +156,114 @@ const dataFile = {
107
156
  file: /_CURRENT_DATA_\w*?\.json$/,
108
157
  };
109
158
 
110
- const desiredContents = [
111
- 'body',
112
- 'subject',
113
- 'date',
114
- 'from',
115
- metadataFile,
116
- dataFile,
117
- ];
159
+ const contents = [metadataFile, dataFile];
118
160
 
119
- getContentsFromMessages(userId, query, desiredContents, state =>
120
- console.log(state.data)
121
- );
161
+ getContentsFromMessages({ query, email, contents });
122
162
  ```
123
163
 
124
- ## Sample Output
164
+ ## Sample `state.data` Output
125
165
 
126
- For each matched message, the extracted content is returned in a collection of
127
- content blocks. Here's an example for a single match message:
166
+ For each matched message, the extracted content is returned as a message object of content properties. Here's an example `state.data` for a single matched message:
128
167
 
129
168
  ```js
130
169
  [
131
170
  {
132
171
  messageId: '1934c017c1752c01',
133
- contents: [
134
- {
135
- name: 'subject',
136
- value: 'Fwd: FW: Facility Temperature Report (Summary Data)',
137
- },
138
- {
139
- name: 'date',
140
- value: '2024-11-20T23:56:08.000Z',
141
- },
142
- {
143
- name: 'from',
144
- value: 'Friendly Sender <sender@gmail.com>',
145
- },
146
- {
147
- name: 'metadata',
148
- value:
149
- '{\n "appInfo": {\n "isAutomaticTime": true,\n "isTrueTime": true,\n "os": "Android",\n "osVe" }',
150
- path: '004800123457501820383131_20241115T102926Z.json',
151
- },
152
- {
153
- name: 'data',
154
- value:
155
- '{\n "AMOD": "VL45",\n "AMFR": "ICECO",\n "ASER": "BJBC 08 30",\n "ADOP": "2024-04-01",\n "APQS": "E003/XX" }',
156
- path: '004800123457501820383131_CURRENT_DATA_P100DT9H45M46S_20241115T102926Z.json',
157
- },
158
- ],
172
+ from: 'Friendly Sender <sender@gmail.com>',
173
+ date: '2024-11-20T23:56:08.000Z',
174
+ subject: 'Fwd: FW: Facility Anomaly Report (Summary Data)',
175
+ metadata: {
176
+ filename: 'daily_summary.txt',
177
+ content: '{ "appInfo": { "isAutomaticTime": true }',
178
+ },
179
+ data: {
180
+ archiveFilename: '0031_device_data.zip',
181
+ filename: '0031_CURRENT_DATA_P100DT9H45M46S_20241115T102926Z.json',
182
+ content: '{ "AMOD": "VL45", "AMFR": "ICECO" }',
183
+ },
159
184
  },
160
185
  ];
161
186
  ```
162
187
 
163
- Each content block represents a specific piece of information extracted:
188
+ Each property on the message object represents a specific piece of information extracted:
164
189
 
165
- - **subject**: Contains the email subject.
166
- - **date**: The timestamp when the email was sent.
167
190
  - **from**: Sender's email and name.
168
- - **metadata**: Metadata file content, with its file path.
169
- - **data**: Data file content, with its file path.
191
+ - **date**: The timestamp when the email was sent.
192
+ - **subject**: Contains the email subject.
193
+ - **metadata**: Metadata-named file content, with its matched file name.
194
+ - **data**: Data-named archive file content, with its matched archive name and file name.
195
+
196
+ ## Acquiring an access token
197
+
198
+ The Gmail adaptor implicitly uses the Gmail account of the Google account that is used to authenticate the application.
199
+
200
+ Allowing the Gmail adaptor to access a Gmail account is a multi-step process.
201
+
202
+ ### Create an OAuth 2.0 client ID
203
+
204
+ Follow the instructions are found here:
205
+ https://support.google.com/googleapi/answer/6158849
206
+
207
+ - Go to [Google Cloud Platform Console](https://console.cloud.google.com/)
208
+ - Go to "APIs & Services"
209
+ - Click "Credentials"
210
+ - Click "Create Credentials"
211
+ - Select "OAuth client ID"
212
+ - Select "Create OAuth client ID"
213
+ - Select Application type "Web application"
214
+ - Add a uniquely-identifiable name
215
+ - Click "Create"
216
+ - On the resulting popup screen, find and click "DOWNLOAD JSON" and save this file to a secure location.
217
+
218
+ ### Use the Postman application to query the OAuth enpoint and retrieve an access token
219
+
220
+ Initially, you'll need to configure an authentication request using Postman's built-in OAuth 2.0 implementation:
221
+
222
+ - Open Postman
223
+ - Create a new request
224
+ - Switch to the "Authorization" tab
225
+ - On the left side, select Type OAuth 2.0
226
+ - On the right side, scroll down to the "Configure New Token" section
227
+ - Fill out the form using information from the downloaded json file from the
228
+ previous section
229
+ - Token Name: Google Oauth
230
+ - Grant Type: Authorization Code
231
+ - Auth URL: (found in the json file as auth_url)
232
+ - Access Token URL: (found in the json file as token_url)
233
+ - Client ID: (found in the json file as client_id)
234
+ - Client Secret: (found in the json file as client_secret)
235
+ - Scope: https://www.googleapis.com/auth/gmail.readonly
236
+ - State: (any random string is fine)
237
+ - Client Authentication: Send as Basic Auth header
238
+
239
+ Once the form is filled out, repeat these steps each hour to retrieve a new
240
+ access token:
241
+
242
+ - Click on "Get New Access Token"
243
+ - A browser will open and you'll be asked to authenticate with your Google Account
244
+ - Accept the request to allow this OAuth session to access your Google Account.
245
+ - In the MANAGE ACCESS TOKENS popup, find and copy the new Access Token
246
+ - This access token will be valid for 1 hour.
247
+
248
+ ### Configure OpenFn CLI to find the access token
249
+
250
+ The Gmail adaptor looks for the access token in the configuration section under `access_token`.
251
+
252
+ Example configuration using a workflow:
253
+
254
+ ```
255
+ "workflow": {
256
+ "steps": [
257
+ {
258
+ "id": "getGmailContent",
259
+ "adaptors": [
260
+ "gmail"
261
+ ],
262
+ "expression": "path/to/gmail.js",
263
+ "configuration": {
264
+ "access_token": "(access token acquired from Postman)"
265
+ }
266
+ }
267
+ ]
268
+ }
269
+ ```
package/ast.json CHANGED
@@ -3,8 +3,7 @@
3
3
  {
4
4
  "name": "getContentsFromMessages",
5
5
  "params": [
6
- "userId",
7
- "userOptions"
6
+ "options"
8
7
  ],
9
8
  "docs": {
10
9
  "description": "Used to isolate the type of content to retrieve from the message.",
@@ -16,7 +15,7 @@
16
15
  "type": "NameExpression",
17
16
  "name": "Object"
18
17
  },
19
- "name": "DesiredContent"
18
+ "name": "MessageContent"
20
19
  },
21
20
  {
22
21
  "title": "public",
@@ -27,27 +26,25 @@
27
26
  "title": "property",
28
27
  "description": "Message content type. Valid types: from, date, subject, body, archive, file.",
29
28
  "type": {
30
- "type": "NameExpression",
31
- "name": "string"
29
+ "type": "OptionalType",
30
+ "expression": {
31
+ "type": "NameExpression",
32
+ "name": "string"
33
+ }
32
34
  },
33
35
  "name": "type"
34
36
  },
35
37
  {
36
38
  "title": "property",
37
- "description": "A custom description for the content type. Optional.",
39
+ "description": "A custom description for the content type.",
38
40
  "type": {
39
41
  "type": "OptionalType",
40
42
  "expression": {
41
- "type": "NullableType",
42
- "expression": {
43
- "type": "NameExpression",
44
- "name": "string"
45
- },
46
- "prefix": false
43
+ "type": "NameExpression",
44
+ "name": "string"
47
45
  }
48
46
  },
49
- "name": "name",
50
- "default": "null"
47
+ "name": "name"
51
48
  },
52
49
  {
53
50
  "title": "property",
@@ -93,7 +90,7 @@
93
90
  },
94
91
  {
95
92
  "title": "property",
96
- "description": "Maximum number of characters to retrieve from the content. Optional.",
93
+ "description": "Maximum number of characters to retrieve from the content.",
97
94
  "type": {
98
95
  "type": "OptionalType",
99
96
  "expression": {
@@ -105,8 +102,7 @@
105
102
  "prefix": false
106
103
  }
107
104
  },
108
- "name": "maxLength",
109
- "default": "null"
105
+ "name": "maxLength"
110
106
  }
111
107
  ]
112
108
  },
package/dist/index.cjs CHANGED
@@ -72,13 +72,13 @@ var import_util = require("@openfn/language-common/util");
72
72
  var import_unzipper = __toESM(require("unzipper"), 1);
73
73
  var import_googleapis = require("googleapis");
74
74
  var gmail;
75
- async function getMessagesResult(userId, query, lastPageToken) {
75
+ async function getMessagesResult(userId, query, pageToken) {
76
76
  try {
77
77
  const { data } = await gmail.users.messages.list({
78
78
  userId,
79
79
  q: query,
80
- maxResults: 3,
81
- pageToken: lastPageToken
80
+ maxResults: 20,
81
+ pageToken
82
82
  });
83
83
  return {
84
84
  messages: data.messages,
@@ -102,23 +102,37 @@ async function getMessageResult(userId, messageId) {
102
102
  headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
103
103
  };
104
104
  }
105
- function getDesiredContent(hint) {
106
- const desiredContent = typeof hint === "string" ? { type: hint } : hint;
107
- if (!desiredContent.type) {
108
- if (desiredContent.archive) {
109
- desiredContent.type = "archive";
110
- } else if (desiredContent.file) {
111
- desiredContent.type = "file";
105
+ function getContentIndicators(defaultContentRequests, contentRequests) {
106
+ const indicators = /* @__PURE__ */ new Map();
107
+ const requests = [
108
+ ...defaultContentRequests || [],
109
+ ...contentRequests || []
110
+ ];
111
+ for (const request of requests) {
112
+ const indicator = getContentIndicator(request);
113
+ indicators.set(indicator.type, indicator);
114
+ }
115
+ return Array.from(indicators.values());
116
+ }
117
+ function getContentIndicator(contentRequest) {
118
+ const contentIndicator = typeof contentRequest === "string" ? { type: contentRequest } : { ...contentRequest };
119
+ if (!contentIndicator.type) {
120
+ if (contentIndicator.archive) {
121
+ contentIndicator.type = "archive";
122
+ } else if (contentIndicator.file) {
123
+ contentIndicator.type = "file";
112
124
  }
113
125
  }
114
- if (!desiredContent.type) {
115
- console.error(`Unable to determine desired content type: ${hint}`);
126
+ if (!contentIndicator.type) {
127
+ console.error(
128
+ `Unable to determine desired content type: ${contentRequest}`
129
+ );
116
130
  throw new Error("No desired content type provided.");
117
131
  }
118
- if (!desiredContent.name) {
119
- desiredContent.name = desiredContent.type;
132
+ if (!contentIndicator.name) {
133
+ contentIndicator.name = contentIndicator.type;
120
134
  }
121
- return desiredContent;
135
+ return contentIndicator;
122
136
  }
123
137
  async function getMessageContent(message, desiredContent) {
124
138
  switch (desiredContent.type) {
@@ -128,9 +142,9 @@ async function getMessageContent(message, desiredContent) {
128
142
  return await getFileFromAttachment(message, desiredContent);
129
143
  case "body":
130
144
  return getBodyFromMessage(message, desiredContent);
131
- case "subject":
132
145
  case "from":
133
146
  case "date":
147
+ case "subject":
134
148
  return getValueFromMessageHeader(message, desiredContent);
135
149
  default:
136
150
  return `Unsupported content type: ${desiredContent.type}`;
@@ -268,62 +282,71 @@ function isExpressionMatch(text, expression) {
268
282
 
269
283
  // src/Adaptor.js
270
284
  var import_language_common2 = require("@openfn/language-common");
271
- function getContentsFromMessages(userId, userOptions) {
285
+ function getContentsFromMessages(options) {
272
286
  return async (state) => {
273
287
  var _a, _b;
274
- const [resolvedUserId, resolvedUserOptions] = (0, import_util.expandReferences)(
275
- state,
276
- userId,
277
- userOptions
278
- );
288
+ const [resolvedOptions] = (0, import_util.expandReferences)(state, options);
279
289
  const defaultOptions = {
280
- desiredContents: ["from", "date", "subject", "body"]
290
+ contents: ["from", "date", "subject"],
291
+ userId: "me",
292
+ maxResults: 1e3
293
+ };
294
+ const opts = {
295
+ userId: resolvedOptions.email ?? defaultOptions.userId,
296
+ query: resolvedOptions.query,
297
+ processedIds: resolvedOptions.processedIds,
298
+ maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults
281
299
  };
282
- const options = { ...defaultOptions, ...resolvedUserOptions || {} };
300
+ const contentIndicators = getContentIndicators(
301
+ defaultOptions.contents,
302
+ resolvedOptions.contents
303
+ );
283
304
  const contents = [];
284
- const currentIds = [];
285
- const previousIds = Array.isArray(options.processedIds) ? options.processedIds : [];
305
+ const newIds = [];
306
+ const previousIds = Array.isArray(opts.processedIds) ? opts.processedIds : [];
286
307
  let nextPageToken = null;
287
- do {
288
- const messagesResult = await getMessagesResult(
289
- resolvedUserId,
290
- options.query,
291
- nextPageToken
292
- );
293
- if (!((_a = messagesResult.messages) == null ? void 0 : _a.length)) {
294
- console.log("No messages found.");
295
- break;
296
- }
297
- nextPageToken = messagesResult.nextPageToken;
298
- const currentPageIds = messagesResult.messages.map((message) => message.id);
299
- const unprocessedIds = currentPageIds.filter(
300
- (id) => !previousIds.includes(id)
301
- );
302
- for (const messageId of unprocessedIds) {
303
- const content = {
304
- messageId
305
- };
306
- const messageResult = await getMessageResult(userId, messageId);
307
- for (const desiredContentHint of options.desiredContents) {
308
- const desiredContent = getDesiredContent(desiredContentHint);
309
- const messageContent = await getMessageContent(
310
- messageResult,
311
- desiredContent
312
- );
313
- if (messageContent && content[desiredContent.name]) {
314
- throw new Error(
315
- `Duplicate content name detected: ${desiredContent.name}`
308
+ doNextPageToken:
309
+ do {
310
+ const messagesResult = await getMessagesResult(
311
+ opts.userId,
312
+ opts.query,
313
+ nextPageToken
314
+ );
315
+ if (!((_a = messagesResult.messages) == null ? void 0 : _a.length)) {
316
+ console.log("No messages found.");
317
+ break;
318
+ }
319
+ nextPageToken = messagesResult.nextPageToken;
320
+ for (const message of messagesResult.messages) {
321
+ newIds.push(message.id);
322
+ if (previousIds.includes(message.id)) {
323
+ continue;
324
+ }
325
+ const content = {
326
+ messageId: message.id
327
+ };
328
+ const messageResult = await getMessageResult(opts.userId, message.id);
329
+ for (const contentIndicator of contentIndicators) {
330
+ const messageContent = await getMessageContent(
331
+ messageResult,
332
+ contentIndicator
316
333
  );
334
+ if (messageContent && content[contentIndicator.name]) {
335
+ throw new Error(
336
+ `Duplicate content name detected: ${contentIndicator.name}`
337
+ );
338
+ }
339
+ content[_b = contentIndicator.name] ?? (content[_b] = messageContent);
340
+ }
341
+ contents.push(content);
342
+ if (contents.length >= opts.maxResults) {
343
+ break doNextPageToken;
317
344
  }
318
- content[_b = desiredContent.name] ?? (content[_b] = messageContent);
319
345
  }
320
- contents.push(content);
321
- }
322
- currentIds.push(...currentPageIds);
323
- } while (nextPageToken);
346
+ } while (nextPageToken);
324
347
  const nextState = {
325
348
  ...(0, import_language_common.composeNextState)(state, contents),
326
- processedIds: currentIds
349
+ processedIds: newIds
327
350
  };
328
351
  return nextState;
329
352
  };
package/dist/index.js CHANGED
@@ -37,13 +37,13 @@ import {
37
37
  import unzipper from "unzipper";
38
38
  import { google } from "googleapis";
39
39
  var gmail;
40
- async function getMessagesResult(userId, query, lastPageToken) {
40
+ async function getMessagesResult(userId, query, pageToken) {
41
41
  try {
42
42
  const { data } = await gmail.users.messages.list({
43
43
  userId,
44
44
  q: query,
45
- maxResults: 3,
46
- pageToken: lastPageToken
45
+ maxResults: 20,
46
+ pageToken
47
47
  });
48
48
  return {
49
49
  messages: data.messages,
@@ -67,23 +67,37 @@ async function getMessageResult(userId, messageId) {
67
67
  headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
68
68
  };
69
69
  }
70
- function getDesiredContent(hint) {
71
- const desiredContent = typeof hint === "string" ? { type: hint } : hint;
72
- if (!desiredContent.type) {
73
- if (desiredContent.archive) {
74
- desiredContent.type = "archive";
75
- } else if (desiredContent.file) {
76
- desiredContent.type = "file";
70
+ function getContentIndicators(defaultContentRequests, contentRequests) {
71
+ const indicators = /* @__PURE__ */ new Map();
72
+ const requests = [
73
+ ...defaultContentRequests || [],
74
+ ...contentRequests || []
75
+ ];
76
+ for (const request of requests) {
77
+ const indicator = getContentIndicator(request);
78
+ indicators.set(indicator.type, indicator);
79
+ }
80
+ return Array.from(indicators.values());
81
+ }
82
+ function getContentIndicator(contentRequest) {
83
+ const contentIndicator = typeof contentRequest === "string" ? { type: contentRequest } : { ...contentRequest };
84
+ if (!contentIndicator.type) {
85
+ if (contentIndicator.archive) {
86
+ contentIndicator.type = "archive";
87
+ } else if (contentIndicator.file) {
88
+ contentIndicator.type = "file";
77
89
  }
78
90
  }
79
- if (!desiredContent.type) {
80
- console.error(`Unable to determine desired content type: ${hint}`);
91
+ if (!contentIndicator.type) {
92
+ console.error(
93
+ `Unable to determine desired content type: ${contentRequest}`
94
+ );
81
95
  throw new Error("No desired content type provided.");
82
96
  }
83
- if (!desiredContent.name) {
84
- desiredContent.name = desiredContent.type;
97
+ if (!contentIndicator.name) {
98
+ contentIndicator.name = contentIndicator.type;
85
99
  }
86
- return desiredContent;
100
+ return contentIndicator;
87
101
  }
88
102
  async function getMessageContent(message, desiredContent) {
89
103
  switch (desiredContent.type) {
@@ -93,9 +107,9 @@ async function getMessageContent(message, desiredContent) {
93
107
  return await getFileFromAttachment(message, desiredContent);
94
108
  case "body":
95
109
  return getBodyFromMessage(message, desiredContent);
96
- case "subject":
97
110
  case "from":
98
111
  case "date":
112
+ case "subject":
99
113
  return getValueFromMessageHeader(message, desiredContent);
100
114
  default:
101
115
  return `Unsupported content type: ${desiredContent.type}`;
@@ -248,62 +262,71 @@ import {
248
262
  merge,
249
263
  sourceValue
250
264
  } from "@openfn/language-common";
251
- function getContentsFromMessages(userId, userOptions) {
265
+ function getContentsFromMessages(options) {
252
266
  return async (state) => {
253
267
  var _a, _b;
254
- const [resolvedUserId, resolvedUserOptions] = expandReferences(
255
- state,
256
- userId,
257
- userOptions
258
- );
268
+ const [resolvedOptions] = expandReferences(state, options);
259
269
  const defaultOptions = {
260
- desiredContents: ["from", "date", "subject", "body"]
270
+ contents: ["from", "date", "subject"],
271
+ userId: "me",
272
+ maxResults: 1e3
273
+ };
274
+ const opts = {
275
+ userId: resolvedOptions.email ?? defaultOptions.userId,
276
+ query: resolvedOptions.query,
277
+ processedIds: resolvedOptions.processedIds,
278
+ maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults
261
279
  };
262
- const options = { ...defaultOptions, ...resolvedUserOptions || {} };
280
+ const contentIndicators = getContentIndicators(
281
+ defaultOptions.contents,
282
+ resolvedOptions.contents
283
+ );
263
284
  const contents = [];
264
- const currentIds = [];
265
- const previousIds = Array.isArray(options.processedIds) ? options.processedIds : [];
285
+ const newIds = [];
286
+ const previousIds = Array.isArray(opts.processedIds) ? opts.processedIds : [];
266
287
  let nextPageToken = null;
267
- do {
268
- const messagesResult = await getMessagesResult(
269
- resolvedUserId,
270
- options.query,
271
- nextPageToken
272
- );
273
- if (!((_a = messagesResult.messages) == null ? void 0 : _a.length)) {
274
- console.log("No messages found.");
275
- break;
276
- }
277
- nextPageToken = messagesResult.nextPageToken;
278
- const currentPageIds = messagesResult.messages.map((message) => message.id);
279
- const unprocessedIds = currentPageIds.filter(
280
- (id) => !previousIds.includes(id)
281
- );
282
- for (const messageId of unprocessedIds) {
283
- const content = {
284
- messageId
285
- };
286
- const messageResult = await getMessageResult(userId, messageId);
287
- for (const desiredContentHint of options.desiredContents) {
288
- const desiredContent = getDesiredContent(desiredContentHint);
289
- const messageContent = await getMessageContent(
290
- messageResult,
291
- desiredContent
292
- );
293
- if (messageContent && content[desiredContent.name]) {
294
- throw new Error(
295
- `Duplicate content name detected: ${desiredContent.name}`
288
+ doNextPageToken:
289
+ do {
290
+ const messagesResult = await getMessagesResult(
291
+ opts.userId,
292
+ opts.query,
293
+ nextPageToken
294
+ );
295
+ if (!((_a = messagesResult.messages) == null ? void 0 : _a.length)) {
296
+ console.log("No messages found.");
297
+ break;
298
+ }
299
+ nextPageToken = messagesResult.nextPageToken;
300
+ for (const message of messagesResult.messages) {
301
+ newIds.push(message.id);
302
+ if (previousIds.includes(message.id)) {
303
+ continue;
304
+ }
305
+ const content = {
306
+ messageId: message.id
307
+ };
308
+ const messageResult = await getMessageResult(opts.userId, message.id);
309
+ for (const contentIndicator of contentIndicators) {
310
+ const messageContent = await getMessageContent(
311
+ messageResult,
312
+ contentIndicator
296
313
  );
314
+ if (messageContent && content[contentIndicator.name]) {
315
+ throw new Error(
316
+ `Duplicate content name detected: ${contentIndicator.name}`
317
+ );
318
+ }
319
+ content[_b = contentIndicator.name] ?? (content[_b] = messageContent);
320
+ }
321
+ contents.push(content);
322
+ if (contents.length >= opts.maxResults) {
323
+ break doNextPageToken;
297
324
  }
298
- content[_b = desiredContent.name] ?? (content[_b] = messageContent);
299
325
  }
300
- contents.push(content);
301
- }
302
- currentIds.push(...currentPageIds);
303
- } while (nextPageToken);
326
+ } while (nextPageToken);
304
327
  const nextState = {
305
328
  ...composeNextState(state, contents),
306
- processedIds: currentIds
329
+ processedIds: newIds
307
330
  };
308
331
  return nextState;
309
332
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-gmail",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "OpenFn gmail adaptor",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,42 +1,52 @@
1
1
  /**
2
2
  * Used to isolate the type of content to retrieve from the message.
3
- * @typedef {Object} DesiredContent
3
+ * @typedef {Object} MessageContent
4
4
  * @public
5
- * @property {string} type - Message content type. Valid types: from, date, subject, body, archive, file.
6
- * @property {string?} [name=null] - A custom description for the content type. Optional.
5
+ * @property {string} [type] - Message content type. Valid types: from, date, subject, body, archive, file.
6
+ * @property {string} [name] - A custom description for the content type.
7
7
  * @property {RegExp|string} [archive] - Identifier to isolate the desired attachment when type is 'archive'.
8
8
  * Use a regular expression for pattern matching or a string for a literal match. Required if type is 'archive'.
9
9
  * @property {RegExp|string} [file] - Identifier to isolate the desired attachment when type is 'file' or 'archive'.
10
10
  * Use a regular expression for pattern matching or a string for a literal match. Required if type is 'file' or 'archive'.
11
- * @property {number?} [maxLength=null] - Maximum number of characters to retrieve from the content. Optional.
11
+ * @property {number?} [maxLength] - Maximum number of characters to retrieve from the content.
12
12
  */
13
13
  /**
14
14
  * Configurable options provided to the Gmail adaptor.
15
15
  * @typedef {Object} Options
16
16
  * @public
17
- * @property {string} userId - The email address of the Gmail account.
18
- * @property {string?} [query=null] - Custom query to limit the messages result. Adheres to the Gmail search syntax. Optional.
19
- * @property {Array<string|DesiredContent>?} [desiredContents=['from', 'date', 'subject', 'body']]
20
- * An array of strings or DesiredContent objects used to specify which parts of the message to retrieve. Optional, default is `['from', 'date', 'subject', 'body']`.
21
- * @property {Array<string>?} [processedIds=null] - Ignore message ids which have already been processed. Optional.
17
+ * @property {string?} [query] - Gmail search query string.
18
+ * @property {Array<string|MessageContent>} [contents=['from', 'date', 'subject', 'body']]
19
+ * An array of strings or MessageContent objects used to specify which parts of the message to retrieve.
20
+ * @property {Array<string>} [processedIds] - Ignore message ids which have already been processed.
21
+ * @property {string?} [email] - The user account to retrieve messages from. Defaults to the authenticated user.
22
+ * @property {int?} [maxResults] - Maximum number of messages to process per request. Default is 1000.
22
23
  */
23
24
  /**
24
- * Requests contents from messages of a Gmail account.
25
+ * Downloads contents from messages of a Gmail account.
25
26
  * @public
26
27
  * @function
27
- * @param {string} userId - The email address of the account to retrieve messages from.
28
- * @param {Options} userOptions - Customized options including desired contents and query.
29
- * @returns {Function} A function that processes the state.
30
- * @example
28
+ * @param {Options} options - Customized options including desired contents and query.
29
+ * @state {Array} data - The returned message objects, of the form `{ messageId, contents } `
30
+ * @state {Array<string>} processedIds - An array of string ids processed by this request
31
+ * @returns {Operation}
32
+ * @example <caption>Get a message with a specific subject</caption>
33
+ * getContentsFromMessages(
34
+ * {
35
+ * query: 'subject:my+test+message'
36
+ * }
37
+ * )
38
+ * @example <caption>Get messages after a specific date, with subject and report.txt attachment</caption>
31
39
  * getContentsFromMessages(
32
- * 'test@tester.com',
33
40
  * {
34
- * query: 'in:inbox subject:my+test+message',
35
- * desiredContents: ['date', 'from', 'subject', { type: 'body', maxLength: 50 }]
41
+ * query: 'after:15/01/2025',
42
+ * contents: [
43
+ * 'subject',
44
+ * { type: 'file', name: 'metadata', file: 'report.txt'}
45
+ * ]
36
46
  * }
37
47
  * )
38
48
  */
39
- export function getContentsFromMessages(userId: string, userOptions: Options): Function;
49
+ export function getContentsFromMessages(options: Options): Operation;
40
50
  /**
41
51
  * Execute a sequence of operations.
42
52
  * Wraps `language-common/execute`, and prepends initial state for http.
@@ -48,7 +58,7 @@ export function execute(...operations: Operations): Operation;
48
58
  /**
49
59
  * Used to isolate the type of content to retrieve from the message.
50
60
  */
51
- export type DesiredContent = any;
61
+ export type MessageContent = any;
52
62
  /**
53
63
  * Configurable options provided to the Gmail adaptor.
54
64
  */
package/types/Utils.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export function getMessagesResult(userId: any, query: any, lastPageToken: any): Promise<{
1
+ export function getMessagesResult(userId: any, query: any, pageToken: any): Promise<{
2
2
  messages: any;
3
3
  nextPageToken: any;
4
4
  }>;
@@ -8,7 +8,7 @@ export function getMessageResult(userId: any, messageId: any): Promise<{
8
8
  parts: any;
9
9
  headers: any;
10
10
  }>;
11
- export function getDesiredContent(hint: any): any;
11
+ export function getContentIndicators(defaultContentRequests: any, contentRequests: any): any[];
12
12
  export function getMessageContent(message: any, desiredContent: any): Promise<any>;
13
13
  export function createConnection(state: any): any;
14
14
  export function removeConnection(state: any): any;