This repository has been archived by the owner on Nov 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathworker.js
85 lines (63 loc) · 2.05 KB
/
worker.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
const { workerData, parentPort } = require('worker_threads')
const { google } = require('googleapis');
const { options, folder } = workerData;
const fs = require('fs');
const TOKEN_PATH = 'gdrive.token';
const credentials = JSON.parse(fs.readFileSync('credentials.json'));
const token = fs.readFileSync(TOKEN_PATH);
let driveAPI;
if (credentials.type && credentials.type === "service_account") {
const {
client_email,
private_key
} = credentials;
const jwtClient = new google.auth.JWT(
client_email,
null,
private_key,
['https://www.googleapis.com/auth/drive']);
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessTokenJWT(jwtClient, callback);
jwtClient.setCredentials(JSON.parse(token));
driveAPI = google.drive({
version: 'v3',
auth: jwtClient
});
retrieveAllFiles(options).then(data => parentPort.postMessage(data)).catch(console.error);
});
} else {
const {
client_secret,
client_id,
redirect_uris
} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
driveAPI = google.drive({
version: 'v3',
auth: oAuth2Client
});
retrieveAllFiles(options).then(data => parentPort.postMessage(data)).catch(console.error);
});
}
options.q = `\'${folder.id}\' in parents and trashed = false and mimeType != \'application/vnd.google-apps.folder\'`;
delete options.pageToken;
function retrieveAllFiles(options, result = []) {
return new Promise(async (resolve, reject) => {
const resp = await driveAPI.files.list(options).catch(reject);
result = result.concat(resp.data.files);
if (resp.data.nextPageToken) {
options.pageToken = resp.data.nextPageToken;
const res = await retrieveAllFiles(options, result).catch(reject);
await timeout(321);
resolve(res);
} else {
resolve(result);
}
});
}
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}