-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle.js
More file actions
489 lines (398 loc) · 14.3 KB
/
Copy pathgoogle.js
File metadata and controls
489 lines (398 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");
const keyFile = require("./google-credentials-heroku.json");
const { JWT } = require("google-auth-library");
const path = require("path");
async function main(
// Full path to the sevice account credential
keyFile = process.env.GOOGLE_APPLICATION_CREDENTIALS
) {
const SCOPES = [
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive.appdata",
"https://www.googleapis.com/auth/cloud-platform"
];
const keys = require(keyFile);
const client = new JWT({
email: keys.client_email,
key: keys.private_key,
scopes: SCOPES,
});
const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
const res = await client.request({url});
console.log('DNS Info:');
console.log(res.data);
// After acquiring an access_token, you may want to check on the audience, expiration,
// or original scopes requested. You can do that with the `getTokenInfo` method.
const tokenInfo = await client.getTokenInfo(client.credentials.access_token);
console.log(tokenInfo);
const drive = google.drive({
version: 'v3',
auth: client,
});
drive.files.create({
name: 'dejavu-isolated-test',
mimeType: `application/vnd.google-apps.document`,
auth: client
}, (err, res) => {
if (err) return console.log('#add failed to create file ', err);
console.log(res)
})
}
main().catch(console.error);
// temp. this should come from Slack App.
// let topic = "Amex";
function createDocNameForTopic(_topic) {
return `Dejavu Insights - ${_topic}`;
}
// If modifying these scopes, delete token.json.
const SCOPES = [
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive.appdata",
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/cloud-platform"
];
// configure a JWT auth client
// const jwtClient = new google.auth.JWT(
// privatekey.client_email,
// null,
// privatekey.private_key,
// SCOPES);
//authenticate request
// jwtClient.authorize(function (err, tokens) {
// if (err) {
// console.log('* ____ authorize ERROR _____ *', err);
// return;
// } else {
// console.log('* ____ authorize SUCCESS _____ *');
// }
// });
async function search(topic) {
// Create a new JWT client using the key file downloaded from the Google Developer Console
const auth = new google.auth.GoogleAuth({
keyFile: path.join(__dirname, './google-credentials-heroku.json'),
scopes: SCOPES,
});
const client = await auth.getClient();
// Obtain a new drive client, making sure you pass along the auth client
const drive = google.drive({
version: 'v3',
auth: client,
});
const docs = google.docs({
version: "v1",
auth
});
const query = `mimeType = 'application/vnd.google-apps.document'`;
// Make an authorized request to list Drive files.
const res = await drive.files.list({
q: query,
pageSize: 10,
fields:
"nextPageToken, files(id, name, lastModifyingUser, webViewLink, modifiedTime)"
});
return new Promise((resolveTop, rejectTop) => {
let textContents = [];
// if we found qualifying files
if (res.data.files && res.data.files.length) {
const files = res.data.files;
const filesPromises = files.map(async (file) => {
const doc = await docs.documents.get({ documentId: file.id });
// console.log('____________________________ doc ____________________________');
// console.log(doc);
const thisFileResults = [];
doc.data.body.content.forEach(block => {
if (block.paragraph && block.paragraph.elements) {
// console.log('_________ block.paragraph.elements');
block.paragraph.elements.forEach(element => {
if (!!element.textRun && !!element.textRun.content && !!element.textRun.content.includes(topic)) {
thisFileResults.push(element.textRun.content);
//console.log(textContents.length);
}
});
}
});
return new Promise((resolve, reject) => {
resolve(thisFileResults);
});
});
Promise.all(filesPromises).then((filesPromisesArr) => {
textContents = [...filesPromisesArr[0]];
console.log('__________ the length of the response is: ', textContents.length);
resolveTop(textContents);
}).catch(e => console.log('promise all failed ', e));
}
});
}
/**
* add an insight related to a topic in IDEO G-Drive
* @param {string} topic The topic to add content for.
* @param {string} content The research insight itself.
*/
async function add(topic) {
console.log('##### add is called');
console.log('======= key file is: ', keyFile);
const clientEmail = keyFile['client_email']
console.log('clientEmail: ', clientEmail)
const privateKey = keyFile['private_key']
console.log('privateKey: ', privateKey)
const auth = new JWT(clientEmail, null, privateKey, SCOPES)
const url = `https://dns.googleapis.com/dns/v1/projects/${keyFile.project_id}`;
const res = await auth.request({url});
console.log('======================================================================================== ', res.data);
// Create a new JWT client using the key file downloaded from the Google Developer Console
// const auth = new google.auth.GoogleAuth({
// keyFile: path.join(__dirname, './google-credentials-heroku.json'),
// scopes: SCOPES,
// });
const tokens = await auth.authorize()
// const client = await auth.getClient();
// Obtain a new drive client, making sure you pass along the auth client
const drive = google.drive({
version: 'v3',
auth: auth,
});
const docs = google.docs({
version: "v1",
auth: auth
});
// Folder ID for Dejavu. This folder contains all research insights in IDEO Google Drive.
let folderId = null;
// 1. does the insight folder exist?
drive.files.list(
{
q: `mimeType = 'application/vnd.google-apps.folder' and name = 'dejavu'`,
fields: "files(id, name)",
auth
},
(err, res) => {
if (err) {
// error handling
return console.log(
"#add: while looking for `dejavu` folder, the API returned an error: ",
err
);
}
if (res.data.files.length) {
console.log('--------- ', JSON.stringify(res))
console.log("#add: dejavu folder exists: ", res.data.files[0].id);
// folder exists. let's make a doc
// keep the reference to the folder
folderId = res.data.files[0].id;
// check to see if we have a file with today's date
const date = new Date();
const fileName = `dejavu-${(date.getUTCMonth()+1)}-${date.getUTCDate()}-${date.getUTCFullYear()}`
drive.files.list({
q: `mimeType = 'application/vnd.google-apps.document' and name = '${fileName}'`,
fields: "files(id, name)",
auth
}, (err, res) => {
if (err) return console.log('#add: failed to locate file ', fileName);
if (res.data.files.length) {
const fileId = res.data.files[0].id;
const parentId = folderId;
console.log('#add: found the file with name ', fileName, ' ', JSON.stringify(res.data.files), ' file id: ', fileId);
// a dejavu file with today's date already exists!
// let's get its current content from it
drive.files.get({
fileId,
fields: '*',
auth
}, (err, res) => {
if (err) return console.log('#add: failed to get the contents of the file ', fileId);
console.log('#add: success in getting contents of the file ', JSON.stringify(res.data));
})
} else {
// file does not exist
drive.files.create({
name: fileName,
mimeType: `application/vnd.google-apps.document`,
parents: [folderId],
auth
}, (err, res) => {
if (err) return console.log('#add failed to create file ', fileName);
console.log('#add successfully created the file', fileName, JSON.stringify(res));
})
}
})
} else {
// folder does not exist. let's make it
const fileMetadata = {
name: "dejavu",
mimeType: "application/vnd.google-apps.folder"
};
drive.files.create(
{
resource: fileMetadata,
fields: "id",
auth
},
(err, file) => {
if (err) {
// Handle error
console.error(
"#add: error while trying to create `dejavu` folder: ",
err
);
} else {
console.log("#add: made `dejavu` Folder: ", file.data.id);
// keep the reference to the folder
folderId = file.data.id;
}
}
);
}
return Promise.resolve(true);
}
);
}
/**
* HOF that returns a function which will authorize
* and perform the provided callback once authorized.
* @param {function} APICall The callback to call with the authorized client.
*/
function authorizeAndMakeAPICall(APICall) {
return function makeApiCall(argsArray) {
// Load client secrets from a local file.
fs.readFile("credentials.json", (err, content) => {
if (err) return console.log("Error loading credentials.json:", err);
// Authorize a client with credentials, then call the Google Drive API.
authorize(JSON.parse(content), APICall, argsArray);
});
};
}
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback, callbackArgsArray) {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client, ...callbackArgsArray);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: SCOPES
});
console.log("Authorize this app by visiting this url:", authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Enter the code from that page here: ", code => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error("Error retrieving access token", err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), err => {
if (err) return console.error(err);
console.log("Token stored to", TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
module.exports = {
add, search
}
/**
* Search in IDEO G-Drive for a given topic
* @param {string} topic The topic to search for.
*/
async function __search(topic) {
const drive = google.drive({ version: "v3", jwtClient });
const query = `mimeType = 'application/vnd.google-apps.document' and name contains '${topic}'`;
const results = await drive.files.list({
q: query,
pageSize: 10,
fields: "nextPageToken, files(id, name, lastModifyingUser, webViewLink, modifiedTime)"
})
return results;
}
async function _search(auth = jwtClient, topic) {
const drive = google.drive({ version: "v3", auth });
const docs = google.docs({ version: "v1", auth });
const query = `mimeType = 'application/vnd.google-apps.document' and name contains '${topic}'`;
const results = await drive.files.list(
{
q: query,
pageSize: 10,
fields:
"nextPageToken, files(id, name, lastModifyingUser, webViewLink, modifiedTime)"
},
(err, res) => {
// Error Handling
if (err) {
return console.log(
"#search: Searching for topic failed. The API returned an error: " +
err
);
}
// Matching files
const files = res.data.files;
if (files.length) {
return files.map(file => {
console.log(`#search: Found a match: ${file.name} (${file.id})`);
return docs.documents.get(
{
documentId: file.id
},
(err, res) => {
if (err) {
return console.log(
"#search: Error while digging into a matchinc file: " + err
);
}
let output = "";
res.data.body.content.forEach(block => {
if (block.paragraph && block.paragraph.elements) {
block.paragraph.elements.forEach(element => {
if (
element.textRun &&
element.textRun.content &&
typeof element.textRun.content === "string" &&
element.textRun.content.includes(topic)
) {
output = output.concat("\n");
output = output.concat(element.textRun.content);
}
});
}
});
// console.log(
// "#search found the following relevant paragraphs in relevant docs:\n"
// );
// console.log(output);
// console.log("\n");
return output;
}
);
});
}
}
);
console.log('Results is: -------', results);
return results;
}