-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgmail_sandbox.js
333 lines (285 loc) · 10.4 KB
/
gmail_sandbox.js
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
/**
* ===============[ TABLE OF CONTENTS ]=================
* 0. Initialize
* 0.1 Libraries
* 0.2 Globals
*
* 1. Helper Functions
* 1.1 keepTokenAlive
* 1.1 checkAccess
* 1.3 someCallback
*
* 2. Main Tests Functions
* 2.1 TESTS
* 2.2 main
* 2.3 RUN TESTS
*
******************************************************
/* ===============[ 0. Initialize ]===================*/
// 0.1 Libraries
process.env.DOTENV_LOADED || require("dotenv").config();
require("colors");
const debug = require("debug")("gmail_sandbox");
const fs = require('fs');
const path = require("path");
const Utils = require("./utils");
const GmailSandbox = require('./lib/GmailSandbox');
// 0.2 Globals
// GMAIL Token Credentials
const PATH_TO_GMAIL_CREDENTIALS = path.join(__dirname, 'config/gmail-credentials.json');
const creds_token_user = fs.existsSync(PATH_TO_GMAIL_CREDENTIALS) ? JSON.parse(fs.readFileSync(PATH_TO_GMAIL_CREDENTIALS, 'utf8')) : {};
const PATH_TO_GOOGLE_DRIVE_CREDENTIALS = path.join(__dirname, 'config/google-drive-creds.json');
const creds_service_user = fs.existsSync(PATH_TO_GOOGLE_DRIVE_CREDENTIALS) ? JSON.parse(fs.readFileSync(PATH_TO_GOOGLE_DRIVE_CREDENTIALS, 'utf8')) : {};
// Gmail Token
const TOKEN_DIR = path.join(__dirname, '.keys/');
const PATH_TO_GMAIL_TOKEN = TOKEN_DIR + 'gmail-token.json';
const creds_gmail_token = fs.existsSync(PATH_TO_GMAIL_TOKEN) ? JSON.parse(fs.readFileSync(PATH_TO_GMAIL_TOKEN, 'utf8')) : {};
// File
const fileName = "a\\testFile.txt";
const rootPath = `C:\\Users\\ccollins\\Downloads`;
const localPath = path.join(rootPath, fileName);
// Source and Destination Paths
const gDrivePath = localPath.split(/[\\\/]/).slice(-1).join('/');
// Source and Destination Prefixes
const gDrivePrefix = fileName.split(/[\\\/]/).slice(0, -1).join('/');
// GmailSandbox options
const ROOT_FOLDER = process.env.GDRIVE_ROOT_FOLDER;
const GOOGLE_AUTH_SCOPE = [process.env.GOOGLE_GMAIL_SCOPE || 'https://www.googleapis.com/auth/gmail.readonly', process.env.GOOGLE_DRIVE_SCOPE || 'https://www.googleapis.com/auth/drive'];
const gmailInstance = new GmailSandbox({ ROOT_FOLDER, PATH_TO_GMAIL_TOKEN, GOOGLE_AUTH_SCOPE });
/* ===============[ 1. Helper Functions ]=============*/
/** 1.1
* Refreshes our gmail token.
*
* @param {function} callback - if provided than will run the callback after refreshing the token
* @return {*} gmail_service - gmail api service. If callback was provided than returns results of the callback.
*/
const keepTokenAlive = async (callback) => {
let gmail_service;
try {
// Check if we have access
if (Date.now() > (creds_gmail_token.expiry_date || Date.now() - 1000)) {
debug(`Expired ${((Date.now() - (creds_gmail_token.expiry_date || Date.now() - 1000)) / 60000).toFixed(2)} minutes ago`.magenta);
} else {
debug(`Token should be valid until ${Utils.formatDate(creds_gmail_token.expiry_date || Date.now())}`.yellow);
}
gmail_service = await gmailInstance.useTokenAccountAuth(creds_token_user, PATH_TO_GMAIL_TOKEN, creds_gmail_token, callback);
debug("Token is valid!".green);
} catch (ex) {
debug(ex.stack);
debug("Access denied. Trying to request Auth Token".magenta);
gmail_service = await gmailInstance.requestAuthToken(creds_token_user, PATH_TO_GMAIL_TOKEN, callback);
if (gmailInstance.isAuthActive(gmail_service)) {
debug("Our auth token is valid!".green);
} else {
debug("===============[ Error ]=================".red);
debug("Our auth token is not valid!".red);
debug("=========================================".red);
return
}
}
if (!callback) {
debug("returning gmail_service".yellow);
} else {
debug("returning callback results".yellow);
}
return gmail_service;
}
// 1.2 Check Access
const checkAccess = async (callback) => {
let gdrive;
try {
// Check if we have access
gdrive = await gmailInstance.useServiceAccountAuth(creds_service_user, callback);
} catch (ex) {
debug("===============[ Error ]=================".red);
debug(ex.stack);
debug("=========================================".red);
}
if (!callback) {
debug("returning gdrive service".yellow);
} else {
debug("returning callback results".yellow);
}
return gdrive;
}
/** 1.3
* A test callback function to show example usage of a callback in keepTokenAlive()
*
* @return {object} this - object of whatever was bind to the callback.
* For example, someCallback.(args.inputParams)
*/
const someCallback = function () {
debug("Running someCallback function".yellow);
return this;
}
/* =========[ 2. Main Tests Functions ]==============*/
// 2.1 TESTS
const TESTS = [
{
"name": "Read Gmail",
"enabled": true,
"function": "readGmail",
"args": { 'q': 'label:inbox' },
},
{
"name": `List Files in ${gDrivePrefix}`,
"enabled": true,
"function": "listFiles",
"args": { 'pageToken': null, 'recursive': true, gDrivePrefix },
},
{
"name": `List Folders in ${gDrivePrefix}`,
"enabled": false,
"function": "listFiles",
"args": { 'pageToken': null, 'recursive': true, gDrivePrefix, 'listFolders': true },
}
];
const EXAMPLES = [
{
"id": 1,
"name": "With Callback",
"enabled": false,
"description": "Refreshes token and then runs a callback"
},
{
"id": 2,
"name": "With gmail or gdrive service",
"enabled": false,
"description": "Gives you direct access to googlesapi where you can invoke the api functions directly"
},
{
"id": 3,
"name": "With gmailInstance",
"enabled": true,
"description": "This is the most ideal way because you can have access to all of gmailInstance functions with valid google_auth"
},
];
const EXAMPLE = EXAMPLES.find(({ enabled }) => enabled === true);
/** 2.2
* Example Usage:
* node --trace-warnings gmail_sandbox.js
* node gmail_sandbox.js --inputFunction="readGmail" --q="label:inbox"
* node gmail_sandbox.js --inputFunction="listFiles" --gDrivePrefix="a"
*
* @param {*} inputFunction - function ran by TESTS or invoked directly through yargs
* @param {*} inputParams - parameters for inputFunction
*
* @return {number} exit_code
*/
const main = async (inputFunction, inputParams) => {
// Initiate Arguments
let args;
if (process.argv.length > 2) {
args = require('yargs').argv;
args.inputParams = {};
let { inputFunction, ...remainingArgs } = require('yargs').argv || {};
if (inputFunction) args = { inputFunction };
if (remainingArgs) {
if (typeof remainingArgs === 'string') {
args.inputParams = require(remainingArgs);
} else if (typeof remainingArgs === 'object') {
args.inputParams = remainingArgs;
}
}
} else if (inputParams) {
args = { inputFunction, inputParams };
} else {
debug("===================================".yellow);
debug("Invalid arguments passed.".yellow);
debug({ ...inputParams, ...{ invalid_args: process.argv.slice(2) } });
debug("\nExample Usage,");
debug('node gmail_sandbox.js --inputFunction="readGmail" --q="label:inbox"'.cyan);
debug('node gmail_sandbox.js --inputFunction="listFiles" --gDrivePrefix="a"'.cyan);
debug("\nList of functions include: ");
debug(TESTS.reduce((acc, t, i) => {
if (t.function && !acc.includes(t.function)) {
acc.push({
'inputFunction': t.function,
'inputParams': Object.keys(t.args)
});
}
return acc;
}, []));
debug("===================================".yellow);
return 1;
}
debug("*-*-*-*-*-*-*-[ args ]*-*-*-*-*-*-*-*-*-*".yellow);
debug(args);
debug("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*".yellow);
// Generate results;
let results;
try {
if (gmailInstance[args.inputFunction]) {
switch (EXAMPLE.id) {
case 1:
// With Callback
debug(`===================[ Ex${EXAMPLE.id}. ${EXAMPLE.name} ]==============================`.bgWhite.blue);
debug(`${EXAMPLE.description}`.bold.brightYellow);
if (['readGmail'].includes(args.inputFunction)) {
results = await keepTokenAlive(someCallback.bind(args.inputParams));
}
if (['listFiles'].includes(args.inputFunction)) {
results = await checkAccess(someCallback.bind(args.inputParams));
}
break;
case 2:
// With gmail or gdrive service
debug(`===================[ Ex${EXAMPLE.id}. ${EXAMPLE.name} ]==============================`.bgWhite.blue);
debug(`${EXAMPLE.description}`.bold.brightYellow);
if (['readGmail'].includes(args.inputFunction)) {
let gmail = await keepTokenAlive();
results = await gmail.users.messages.list(args.inputParams);
results = (results && results.data) ? results.data : undefined;
}
if (['listFiles'].includes(args.inputFunction)) {
let gdrive = await checkAccess();
results = await gdrive.files.listAsync(args.inputParams);
results = (results && results.data) ? results.data : undefined;
}
break;
case 3:
// With gmailInstance
debug(`===================[ Ex${EXAMPLE.id}. ${EXAMPLE.name} ]==============================`.bgWhite.blue);
debug(`${EXAMPLE.description}`.bold.brightYellow);
if (['readGmail'].includes(args.inputFunction)) {
await keepTokenAlive();
}
if (['listFiles'].includes(args.inputFunction)) {
await checkAccess();
}
results = await gmailInstance[args.inputFunction](args.inputParams);
break;
default:
debug("No Examples are enabled".yellow);
break;
}
} else {
throw Error(`Invalid function: ${args.inputFunction}`.brightRed);
}
} catch (error) {
debug("=========================================".red);
debug(error);
debug("=========================================".red);
return 1;
}
debug("_____________[ RESULTS ]___________________".rainbow);
debug(results)
debug("___________________________________________".rainbow);
return 0;
}
// 2.3 RUN TESTS
(async () => {
let exit_code = 1;
let counter = 0;
await Utils.asyncForEach(TESTS, async (test) => {
if (test.enabled) {
debug(test.name.toString().brightYellow);
exit_code = await main(test.function, test.args);
counter++;
}
});
if (counter === 0) {
exit_code = await main();
}
process.exit(exit_code);
})();