Skip to content

Commit 86845a6

Browse files
committed
1st commit
0 parents  commit 86845a6

9 files changed

+1082
-0
lines changed

GetFolderTreeForDriveAPI.js

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
/**
2+
* ### Description
3+
* Get folder tree using Drive API from own drive, shared drive and service account's drive.
4+
* When you want to retrieve the folder tree from the service account, please give the access token from the service account.
5+
*
6+
* ref: https://developers.google.com/drive/api/reference/rest/v3
7+
*
8+
* Required scopes:
9+
* - `https://www.googleapis.com/auth/drive.metadata.readonly`
10+
* - `https://www.googleapis.com/auth/script.external_request`
11+
*/
12+
class GetFolderTreeForDriveAPI {
13+
14+
/**
15+
*
16+
* @param {Object} object Source folder ID.
17+
* @param {String} object.id Source folder ID. Default is root folder.
18+
*/
19+
constructor(object) {
20+
const { id = "root", accessToken = ScriptApp.getOAuthToken() } = object;
21+
22+
/** @private */
23+
this.id = id;
24+
25+
/** @private */
26+
this.headers = { authorization: `Bearer ${accessToken}` };
27+
28+
/** @private */
29+
this.url = "https://www.googleapis.com/drive/v3/files";
30+
31+
if (typeof Drive == "undefined" || Drive.getVersion() != "v3") {
32+
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");
33+
}
34+
}
35+
36+
/**
37+
* ### Description
38+
* Get folder tree.
39+
*
40+
* @param {Object} object Object for retrieving folder tree.
41+
* @returns {Array} Array including folder tree.
42+
*/
43+
getTree(object = {}) {
44+
const loop = object => {
45+
const { id = this.id, parents = { ids: [], names: [] }, folders = [] } = object;
46+
if (parents.ids.length == 0) {
47+
const folder = JSON.parse(UrlFetchApp.fetch(this.addQueryParameters_(`${this.url}/${id}`, { supportsAllDrives: true, fields: "name" }), { headers: this.headers }).getContentText());
48+
parents.ids.push(id);
49+
parents.names.push(folder.name);
50+
}
51+
const pid = [...parents.ids];
52+
const pn = [...parents.names];
53+
const query = {
54+
q: `'${id}' in parents and mimeType='${MimeType.FOLDER}' and trashed=false`,
55+
fields: "files(id,name,parents),nextPageToken",
56+
pageSize: 1000,
57+
supportsAllDrives: true,
58+
includeItemsFromAllDrives: true,
59+
};
60+
const folderList = [];
61+
let pageToken = "";
62+
do {
63+
const res = UrlFetchApp.fetch(this.addQueryParameters_(this.url, query), { headers: this.headers });
64+
const obj = JSON.parse(res.getContentText());
65+
if (obj.files.length > 0) {
66+
folderList.push(...obj.files.map(o => ({ id: o.id, treeIds: [...pid, o.id], treeNames: [...pn, o.name] })));
67+
}
68+
pageToken = obj.nextPageToken;
69+
query.pageToken = pageToken;
70+
} while (pageToken);
71+
if (folderList.length > 0) {
72+
folders.push(...folderList);
73+
folderList.forEach(({ id, treeIds, treeNames }) =>
74+
loop({ id, parents: { ids: treeIds, names: treeNames }, folders })
75+
);
76+
}
77+
return folders.map(({ treeIds, treeNames }) => ({ treeIds, treeNames }));
78+
}
79+
return loop(object);
80+
}
81+
82+
/**
83+
* ### Description
84+
* Get folder tree with files in each folder.
85+
*
86+
* @param {Object} object Object for retrieving folder tree with files.
87+
* @returns {Array} Array including folder tree with files.
88+
*/
89+
getTreeWithFiles(object = {}) {
90+
const loop = object => {
91+
const { id = this.id, parents = { ids: [], names: [] }, folders = [] } = object;
92+
if (parents.ids.length == 0) {
93+
const folder = JSON.parse(UrlFetchApp.fetch(this.addQueryParameters_(`${this.url}/${id}`, { supportsAllDrives: true, fields: "name" }), { headers: this.headers }).getContentText());
94+
parents.ids.push(id);
95+
parents.names.push(folder.name);
96+
folders.push({ id, treeIds: parents.ids, treeNames: parents.names, parent: { folderId: id, folderName: folder.name }, fileList: this.getFiles_({ id }) });
97+
}
98+
const pid = [...parents.ids];
99+
const pn = [...parents.names];
100+
const query = {
101+
q: `'${id}' in parents and mimeType='${MimeType.FOLDER}' and trashed=false`,
102+
fields: "files(id,name,parents),nextPageToken",
103+
pageSize: 1000,
104+
supportsAllDrives: true,
105+
includeItemsFromAllDrives: true,
106+
};
107+
const folderList = [];
108+
let pageToken = "";
109+
do {
110+
const res = UrlFetchApp.fetch(this.addQueryParameters_(this.url, query), { headers: this.headers });
111+
const obj = JSON.parse(res.getContentText());
112+
if (obj.files.length > 0) {
113+
folderList.push(...obj.files.map(o =>
114+
({ id: o.id, treeIds: [...pid, o.id], treeNames: [...pn, o.name], parent: { folderId: o.id, folderName: o.name }, fileList: this.getFiles_(o) })
115+
));
116+
}
117+
pageToken = obj.nextPageToken;
118+
query.pageToken = pageToken;
119+
} while (pageToken);
120+
if (folderList.length > 0) {
121+
folders.push(...folderList);
122+
folderList.forEach(({ id, treeIds, treeNames }) =>
123+
loop({ id, parents: { ids: treeIds, names: treeNames }, folders })
124+
);
125+
}
126+
return folders.map(({ treeIds, treeNames, parent, fileList }) => ({ treeIds, treeNames, parent, fileList }));
127+
}
128+
return loop(object);
129+
}
130+
131+
/**
132+
* ### Description
133+
* Get filename with path.
134+
*
135+
* @param {String} delimiter Delimiter for showing path. Default is "/".
136+
* @returns {Array} Array including filenames including each path.
137+
*/
138+
getFilenameWithPath(delimiter = "/") {
139+
return this.getTreeWithFiles().flatMap(({ treeNames, fileList }) => {
140+
const path = treeNames.join(delimiter);
141+
return fileList.map(({ name }) => `${path}${delimiter}${name}`);
142+
});
143+
}
144+
145+
/**
146+
* ### Description
147+
* Get files under a folder.
148+
*
149+
* @param {Object} object Object including folder ID.
150+
* @returns {Array} Array including files.
151+
* @private
152+
*/
153+
getFiles_(object) {
154+
const { id } = object;
155+
const query = {
156+
q: `'${id}' in parents and mimeType!='${MimeType.FOLDER}' and trashed=false`,
157+
fields: "files(id,name,mimeType),nextPageToken",
158+
pageSize: 1000,
159+
supportsAllDrives: true,
160+
includeItemsFromAllDrives: true,
161+
};
162+
const fileList = [];
163+
let pageToken = "";
164+
do {
165+
const res = UrlFetchApp.fetch(this.addQueryParameters_(this.url, query), { headers: this.headers });
166+
const obj = JSON.parse(res.getContentText());
167+
if (obj.files.length > 0) {
168+
fileList.push(...obj.files.map(o => ({ name: o.name, id: o.id, mimeType: o.mimeType })));
169+
}
170+
pageToken = obj.nextPageToken;
171+
query.pageToken = pageToken;
172+
} while (pageToken);
173+
return fileList;
174+
}
175+
176+
/**
177+
* ### Description
178+
* This method is used for adding the query parameters to the URL.
179+
* Ref: https://github.com/tanaikech/UtlApp?tab=readme-ov-file#addqueryparameters
180+
*
181+
* @param {String} url The base URL for adding the query parameters.
182+
* @param {Object} obj JSON object including query parameters.
183+
* @return {String} URL including the query parameters.
184+
* @private
185+
*/
186+
addQueryParameters_(url, obj) {
187+
if (url === null || obj === null || typeof url != "string") {
188+
throw new Error("Please give URL (String) and query parameter (JSON object).");
189+
}
190+
return (url == "" ? "" : `${url}?`) + Object.entries(obj).flatMap(([k, v]) => Array.isArray(v) ? v.map(e => `${k}=${encodeURIComponent(e)}`) : `${k}=${encodeURIComponent(v)}`).join("&");
191+
}
192+
}

GetFolderTreeForDriveApp.js

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
/**
2+
* ### Description
3+
* Get folder tree using DriveApp (Drive service) from own drive and shared drive.
4+
*
5+
* ref: https://developers.google.com/apps-script/reference/drive
6+
*
7+
* Required scopes:
8+
* - `https://www.googleapis.com/auth/drive.readonly`
9+
*/
10+
class GetFolderTreeForDriveApp {
11+
12+
/**
13+
*
14+
* @param {Object} object Source folder ID.
15+
* @param {String} object.id Source folder ID. Default is root folder.
16+
*/
17+
constructor(object) {
18+
const { id = "root" } = object;
19+
20+
/** @private */
21+
this.id = id;
22+
}
23+
24+
/**
25+
* ### Description
26+
* Get folder tree.
27+
*
28+
* @param {Object} object Object for retrieving folder tree.
29+
* @returns {Array} Array including folder tree.
30+
*/
31+
getTree(object = {}) {
32+
const loop = object => {
33+
const { id = this.id, parents = { ids: [], names: [] }, folders = [] } = object;
34+
const folder = DriveApp.getFolderById(id);
35+
if (parents.ids.length == 0) {
36+
parents.ids.push(id);
37+
parents.names.push(folder.getName());
38+
}
39+
const pid = [...parents.ids];
40+
const pn = [...parents.names];
41+
const fols = folder.getFolders();
42+
const folderList = [];
43+
while (fols.hasNext()) {
44+
const f = fols.next();
45+
folderList.push({ id: f.getId(), treeIds: [...pid, f.getId()], treeNames: [...pn, f.getName()] });
46+
}
47+
if (folderList.length > 0) {
48+
folders.push(...folderList);
49+
folderList.forEach(({ id, treeIds, treeNames }) =>
50+
loop({ id, parents: { ids: treeIds, names: treeNames }, folders })
51+
);
52+
}
53+
return folders.map(({ treeIds, treeNames }) => ({ treeIds, treeNames }));
54+
}
55+
return loop(object);
56+
}
57+
58+
/**
59+
* ### Description
60+
* Get folder tree with files in each folder.
61+
*
62+
* @param {Object} object Object for retrieving folder tree with files.
63+
* @returns {Array} Array including folder tree with files.
64+
*/
65+
getTreeWithFiles(object = {}) {
66+
const loop = object => {
67+
const { id = this.id, parents = { ids: [], names: [] }, folders = [] } = object;
68+
const folder = DriveApp.getFolderById(id);
69+
if (parents.ids.length == 0) {
70+
parents.ids.push(id);
71+
parents.names.push(folder.getName());
72+
folders.push({ id, treeIds: parents.ids, treeNames: parents.names, parent: { folderId: id, folderName: folder.getName() }, fileList: this.getFiles_(folder) });
73+
}
74+
const pid = [...parents.ids];
75+
const pn = [...parents.names];
76+
const fols = folder.getFolders();
77+
const folderList = [];
78+
while (fols.hasNext()) {
79+
const f = fols.next();
80+
const folderId = f.getId();
81+
const folderName = f.getName();
82+
folderList.push({ id: f.getId(), treeIds: [...pid, folderId], treeNames: [...pn, folderName], parent: { folderId, folderName }, fileList: this.getFiles_(f) });
83+
}
84+
if (folderList.length > 0) {
85+
folders.push(...folderList);
86+
folderList.forEach(({ id, treeIds, treeNames }) =>
87+
loop({ id, parents: { ids: treeIds, names: treeNames }, folders })
88+
);
89+
}
90+
return folders.map(({ treeIds, treeNames, parent, fileList }) => ({ treeIds, treeNames, parent, fileList }));
91+
}
92+
return loop(object);
93+
}
94+
95+
/**
96+
* ### Description
97+
* Get filename with path.
98+
*
99+
* @param {String} delimiter Delimiter for showing path. Default is "/".
100+
* @returns {Array} Array including filenames including each path.
101+
*/
102+
getFilenameWithPath(delimiter = "/") {
103+
return this.getTreeWithFiles().flatMap(({ treeNames, fileList }) => {
104+
const path = treeNames.join(delimiter);
105+
return fileList.map(({ name }) => `${path}${delimiter}${name}`);
106+
});
107+
}
108+
109+
/**
110+
* ### Description
111+
* Get files under a folder.
112+
*
113+
* @param {DriveApp.Folder} folder Folder object.
114+
* @returns {Array} Array including files.
115+
* @private
116+
*/
117+
getFiles_(folder) {
118+
const fileList = [];
119+
const files = folder.getFiles();
120+
while (files.hasNext()) {
121+
const file = files.next();
122+
fileList.push({ name: file.getName(), id: file.getId(), mimeType: file.getMimeType() });
123+
}
124+
return fileList;
125+
}
126+
}

LICENCE

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
The MIT License (MIT)
2+
Copyright (c) 2024 Kanshi TANAIKE
3+
4+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5+
6+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7+
8+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

0 commit comments

Comments
 (0)