-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGetFolderTreeForDriveAPI.js
192 lines (182 loc) · 7.4 KB
/
GetFolderTreeForDriveAPI.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
/**
* ### Description
* Get folder tree using Drive API from own drive, shared drive and service account's drive.
* When you want to retrieve the folder tree from the service account, please give the access token from the service account.
*
* ref: https://developers.google.com/drive/api/reference/rest/v3
*
* Required scopes:
* - `https://www.googleapis.com/auth/drive.metadata.readonly`
* - `https://www.googleapis.com/auth/script.external_request`
*/
class GetFolderTreeForDriveAPI {
/**
*
* @param {Object} object Source folder ID.
* @param {String} object.id Source folder ID. Default is root folder.
*/
constructor(object) {
const { id = "root", accessToken = ScriptApp.getOAuthToken() } = object;
/** @private */
this.id = id;
/** @private */
this.headers = { authorization: `Bearer ${accessToken}` };
/** @private */
this.url = "https://www.googleapis.com/drive/v3/files";
if (typeof Drive == "undefined" || Drive.getVersion() != "v3") {
throw new Error("Please enable Drive API v3 at Advanced Google services. ref: https://developers.google.com/apps-script/guides/services/advanced#enable_advanced_services");
}
}
/**
* ### Description
* Get folder tree.
*
* @param {Object} object Object for retrieving folder tree.
* @returns {Array} Array including folder tree.
*/
getTree(object = {}) {
const loop = object => {
const { id = this.id, parents = { ids: [], names: [] }, folders = [] } = object;
if (parents.ids.length == 0) {
const folder = JSON.parse(UrlFetchApp.fetch(this.addQueryParameters_(`${this.url}/${id}`, { supportsAllDrives: true, fields: "name" }), { headers: this.headers }).getContentText());
parents.ids.push(id);
parents.names.push(folder.name);
}
const pid = [...parents.ids];
const pn = [...parents.names];
const query = {
q: `'${id}' in parents and mimeType='${MimeType.FOLDER}' and trashed=false`,
fields: "files(id,name,parents),nextPageToken",
pageSize: 1000,
supportsAllDrives: true,
includeItemsFromAllDrives: true,
};
const folderList = [];
let pageToken = "";
do {
const res = UrlFetchApp.fetch(this.addQueryParameters_(this.url, query), { headers: this.headers });
const obj = JSON.parse(res.getContentText());
if (obj.files.length > 0) {
folderList.push(...obj.files.map(o => ({ id: o.id, treeIds: [...pid, o.id], treeNames: [...pn, o.name] })));
}
pageToken = obj.nextPageToken;
query.pageToken = pageToken;
} while (pageToken);
if (folderList.length > 0) {
folders.push(...folderList);
folderList.forEach(({ id, treeIds, treeNames }) =>
loop({ id, parents: { ids: treeIds, names: treeNames }, folders })
);
}
return folders.map(({ treeIds, treeNames }) => ({ treeIds, treeNames }));
}
return loop(object);
}
/**
* ### Description
* Get folder tree with files in each folder.
*
* @param {Object} object Object for retrieving folder tree with files.
* @returns {Array} Array including folder tree with files.
*/
getTreeWithFiles(object = {}) {
const loop = object => {
const { id = this.id, parents = { ids: [], names: [] }, folders = [] } = object;
if (parents.ids.length == 0) {
const folder = JSON.parse(UrlFetchApp.fetch(this.addQueryParameters_(`${this.url}/${id}`, { supportsAllDrives: true, fields: "name" }), { headers: this.headers }).getContentText());
parents.ids.push(id);
parents.names.push(folder.name);
folders.push({ id, treeIds: parents.ids, treeNames: parents.names, parent: { folderId: id, folderName: folder.name }, fileList: this.getFiles_({ id }) });
}
const pid = [...parents.ids];
const pn = [...parents.names];
const query = {
q: `'${id}' in parents and mimeType='${MimeType.FOLDER}' and trashed=false`,
fields: "files(id,name,parents),nextPageToken",
pageSize: 1000,
supportsAllDrives: true,
includeItemsFromAllDrives: true,
};
const folderList = [];
let pageToken = "";
do {
const res = UrlFetchApp.fetch(this.addQueryParameters_(this.url, query), { headers: this.headers });
const obj = JSON.parse(res.getContentText());
if (obj.files.length > 0) {
folderList.push(...obj.files.map(o =>
({ id: o.id, treeIds: [...pid, o.id], treeNames: [...pn, o.name], parent: { folderId: o.id, folderName: o.name }, fileList: this.getFiles_(o) })
));
}
pageToken = obj.nextPageToken;
query.pageToken = pageToken;
} while (pageToken);
if (folderList.length > 0) {
folders.push(...folderList);
folderList.forEach(({ id, treeIds, treeNames }) =>
loop({ id, parents: { ids: treeIds, names: treeNames }, folders })
);
}
return folders.map(({ treeIds, treeNames, parent, fileList }) => ({ treeIds, treeNames, parent, fileList }));
}
return loop(object);
}
/**
* ### Description
* Get filename with path.
*
* @param {String} delimiter Delimiter for showing path. Default is "/".
* @returns {Array} Array including filenames including each path.
*/
getFilenameWithPath(delimiter = "/") {
return this.getTreeWithFiles().flatMap(({ treeNames, fileList }) => {
const path = treeNames.join(delimiter);
return fileList.map(({ name }) => `${path}${delimiter}${name}`);
});
}
/**
* ### Description
* Get files under a folder.
*
* @param {Object} object Object including folder ID.
* @returns {Array} Array including files.
* @private
*/
getFiles_(object) {
const { id } = object;
const query = {
q: `'${id}' in parents and mimeType!='${MimeType.FOLDER}' and trashed=false`,
fields: "files(id,name,mimeType),nextPageToken",
pageSize: 1000,
supportsAllDrives: true,
includeItemsFromAllDrives: true,
};
const fileList = [];
let pageToken = "";
do {
const res = UrlFetchApp.fetch(this.addQueryParameters_(this.url, query), { headers: this.headers });
const obj = JSON.parse(res.getContentText());
if (obj.files.length > 0) {
fileList.push(...obj.files.map(o => ({ name: o.name, id: o.id, mimeType: o.mimeType })));
}
pageToken = obj.nextPageToken;
query.pageToken = pageToken;
} while (pageToken);
return fileList;
}
/**
* ### Description
* This method is used for adding the query parameters to the URL.
* Ref: https://github.com/tanaikech/UtlApp?tab=readme-ov-file#addqueryparameters
*
* @param {String} url The base URL for adding the query parameters.
* @param {Object} obj JSON object including query parameters.
* @return {String} URL including the query parameters.
* @private
*/
addQueryParameters_(url, obj) {
if (url === null || obj === null || typeof url != "string") {
throw new Error("Please give URL (String) and query parameter (JSON object).");
}
return (url == "" ? "" : `${url}?`) + Object.entries(obj).flatMap(([k, v]) => Array.isArray(v) ? v.map(e => `${k}=${encodeURIComponent(e)}`) : `${k}=${encodeURIComponent(v)}`).join("&");
}
}