-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathCode.gs
393 lines (290 loc) · 12.2 KB
/
Code.gs
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
/**
*
* Author: Nick Young - @techupover | techupover.com
*
*
* CREDITS
* Kudos to https://www.pbainbridge.co.uk/2020/06/bulk-create-google-drive-folders-20.html
* and various stackoverflow threads for filling in some gaps about how things work
*/
/**
*
* CHANGE THESE VARIABLES PER YOUR PREFERENCES
*
*/
const CUSTOM_MENU_NAME = 'Neat Features'; // the name of the new menu in your google sheet
const CUSTOM_MENU_ITEM = 'Generate Folders Now'; // the menu item you'll click to run the script
const DATA_TAB_NAME = 'folder_data'; // name for the sheet tab that contains the folder info that will be created/processed
const LOG_TAB_NAME = 'log'; // name of the sheet tab that will store the log messages from this script
const DATE_FORMAT = 'yyyy-MM-dd HH:mm:ss'; // date format to use for the log entries. Probably dont change this unless you really really want to.
/**
*
* DO NOT CHANGE ANYTHING UNDER THIS LINE
*
* ONLY CHANGE THINGS IN THE CONFIG.GS FILE
*
*/
/**
* When the spreadsheet is open, add a custom menu
*/
function onOpen() {
var spreadsheet = SpreadsheetApp.getActive();
var customMenuItems = [
{name: CUSTOM_MENU_ITEM, functionName: 'processGoogleSheetData_'}
];
spreadsheet.addMenu(CUSTOM_MENU_NAME, customMenuItems);
}
/**
* Bulk create Google Folders from data within a Google Sheet.
* This is the function to call from the custom menu item.
* Others are referenced by this one.
*/
function processGoogleSheetData_() {
// get current spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Log starting of the script
logEventToGoogleSheet('Script has started');
// display Toast notification
ss.toast('Starting!!!', 'Yep, we are starting...now.');
// get TimeZone
var timeZone = ss.getSpreadsheetTimeZone();
// get Data sheet
var dataSheet = ss.getSheetByName(DATA_TAB_NAME);
// get all data as a 2-D array
var data = dataSheet.getDataRange().getValues();
// create a name:value pair array to send the data to the next Function
var spreadsheetData = {ss:ss, timeZone:timeZone, dataSheet:dataSheet, data:data};
// run Function to create Google Folders
var doCreateFolders = createFolders(spreadsheetData);
// check success status
if (doCreateFolders) {
// display Toast notification
ss.toast('Script complete', 'Finished');
}
else {
// script completed with error
// display Toast notification
ss.toast('Got some errors. Check the logs', 'Finished');
}
// Log starting of the script
logEventToGoogleSheet('Script finished');
}
/**
* Loop through each row and create folders, set permissions
*/
function createFolders(spreadsheetData) {
// extract data from name:value pair array
var ss = spreadsheetData['ss'];
var timeZone = spreadsheetData['timeZone'];
var dataSheet = spreadsheetData['dataSheet'];
var data = spreadsheetData['data'];
// get last row number so we know when to end the loop
var lastRow = dataSheet.getLastRow();
var folderIdMap = new Object();
// start of loop to go through each row iteratively
for (var i=1; i<lastRow; i++) {
// extract values from row of data for easier reference below
var rootFolderId = data[i][0];
var templateDocId = data[i][1]
var newFolderName = data[i][2];
var parentFolderName = data[i][3];
var folderId = data[i][4];
var permissionEmailViewer = data[i][5];
var permissionEmailEditor = data[i][6];
// only perform this row if the folder ID is blank
if(folderId == '') {
// if the sheet doesn't have a specified parent folder name, then it goes in the root.
// if the parent folder name is supplied then it had to have been created by this script,
// so get it from script properties (where the ID is saved during an earlier loop)
if(parentFolderName == '') {
destinationFolderId = rootFolderId;
} else {
var thisMapKey = createMapString(rootFolderId + '___' + parentFolderName);
var destinationFolderId = folderIdMap[thisMapKey];
}
// display Toast notification
ss.toast(newFolderName, 'Creating New Folder');
// run Function to create Google Folder and return its URL/ID
var folderDetails = createFolder(newFolderName, destinationFolderId);
// check new Folder created successfully
if (folderDetails) {
// extract Url/Id for easier reference later
var newFolderUrl = folderDetails['newFolderUrl'];
var newFolderId = folderDetails['newFolderId'];
//push the key/folder id to the array map so we can use it later in the loop
var thisMapKey = createMapString(destinationFolderId + '___' + newFolderName);
folderIdMap[thisMapKey] = newFolderId;
// copy the template doc into the new directory (if specified)
if(templateDocId != '') {
makeCopy(templateDocId, newFolderId, newFolderName + ' Template Document');
}
// set the Folder ID value in the google sheet, inserting it as a link
var newFolderLink = '=HYPERLINK("' + newFolderUrl + '","' + newFolderName + '")';
dataSheet.getRange(i+1, 5).setFormula(newFolderLink);
// check if Viewer Permissions need adding - if there are emails in the column for this row
if (permissionEmailViewer != '') {
// run Function to add Folder permissions
var currentRow = i+1;
var addPermissionsFlag = addPermissions('VIEWER', timeZone, dataSheet, permissionEmailViewer,
newFolderId, currentRow, 8);
// if problem adding Permissions return for status message
if (addPermissionsFlag == false) {
// display Toast notification and return false flag
ss.toast('Error when adding Viewer Permissions to: ' + newFolderName, 'Error');
return false;
}
}
// check if Editor Permissions need adding - if there are emails in the column for this row
if (permissionEmailEditor != '') {
// run Function to add Folder permissions
var currentRow = i+1;
var addPermissionsFlag = addPermissions('EDITOR', timeZone, dataSheet, permissionEmailEditor,
newFolderId, currentRow, 9);
// if problem adding Permissions return for status message
if (addPermissionsFlag == false) {
// display Toast notification and return false flag
ss.toast('Error when adding EDITOR Permissions to: ' + newFolderName, 'Error');
return false;
}
}
// write all pending updates to the google sheet using flush() method
SpreadsheetApp.flush();
} else {
// write error into 'Permission Added?' cell and return false value
dataSheet.getRange(i+1, 4).setValue('Error creating folder. Please see Logs');
// new Folder not created successfully
return false;
}
} else {
ss.toast('Skipping Row - Folder ID already set', 'Moving onto the next row to process');
}
} // end of loop to go through each row in turn **********************************
// completed successfully
return true;
}
function makeCopy(sourceDocumentId, destinationFolderId, destinationFileName) {
var destinationFolder = DriveApp.getFolderById(destinationFolderId);
return DriveApp.getFileById(sourceDocumentId).makeCopy(destinationFileName,destinationFolder);
}
/**
* Function to create new Google Drive Folder and return details (url, id)
*/
function createFolder(folderName, destinationFolderId) {
try {
// get destination Folder
var destinationFolder = DriveApp.getFolderById(destinationFolderId);
}
catch(e) {
logEventToGoogleSheet('Error getting destination folder: ' + e + e.stack);
var destinationFolder = false;
}
// proceed if successfully got destination folder
if (destinationFolder) {
var documentProperties = PropertiesService.getDocumentProperties();
try {
// create new Folder in destination
var newFolder = destinationFolder.createFolder(folderName);
// get new Drive Folder Url/Id and return to Parent Function
var newFolderUrl = newFolder.getUrl();
var newFolderId = newFolder.getId();
var folderDetails = {newFolderUrl:newFolderUrl, newFolderId:newFolderId};
return folderDetails;
}
catch(e) {
logEventToGoogleSheet('Error creating new Folder: ' + e + e.stack);
return false;
}
}
else {
// return false as unable to get destination folder
return false;
}
}
/**
* Function to add permissions to each Folder using the provided email address(es).
*
* role var can be either VIEWER or EDITOR
*/
function addPermissions(role, timeZone, dataSheet, permissionEmail, newFolderId, currentRow, permAddedCol) {
// split up email address array to be able to loop through them separately
var emailAddresses = permissionEmail.split(',');
logEventToGoogleSheet(role + ' emailAddress array is: ' + emailAddresses);
// get length of array for loop
var emailAddressesLength = emailAddresses.length;
try {
// get Google Drive Folder
var newFolder = DriveApp.getFolderById(newFolderId);
}
catch(e) {
logEventToGoogleSheet('Error getting destination folder: ' + e + e.stack);
var newFolder = false;
}
// proceed if successfully got destination folder
if (newFolder) {
// loop through each email address and add as 'Editor' *******************
for (var i=0; i<emailAddressesLength; i++) {
var emailAddress = emailAddresses[i].trim();
logEventToGoogleSheet(role + ' emailAddress for adding permission is: ' + emailAddress);
try {
if(role == 'VIEWER') {
logEventToGoogleSheet('Adding ' + emailAddress + ' as ' + role);
newFolder.addViewer(emailAddress);
var success = true;
}
if(role == 'EDITOR') {
logEventToGoogleSheet('Adding ' + emailAddress + ' as ' + role);
newFolder.addEditor(emailAddress);
var success = true;
}
// add 'Edit' permission using email address
if (success) {
// write timestamp into 'Permission Added?' cell
var date = new Date;
var timeStamp = Utilities.formatDate(date, timeZone, DATE_FORMAT);
dataSheet.getRange(currentRow, permAddedCol).setValue(timeStamp);
}
else {
// write error into 'Permission Added?' cell and return false value
dataSheet.getRange(currentRow, permAddedCol).setValue('Error adding ' + role + ' permission. Please see Logs');
return false;
}
}
catch(e) {
logEventToGoogleSheet('Error adding ' + role + ' permission: ' + e + e.stack);
}
}
}
else {
// write error into cell and return false value
dataSheet.getRange(currentRow, permAddedCol).setValue('Error getting folder. Please see Logs');
// return false as unable to get Google Drive Folder
return false;
}
// return true as all permissions added successfully
return true;
}
/**
* Write log message to Google Sheet
*/
function logEventToGoogleSheet(text_to_log) {
// get the user running the script
var activeUserEmail = Session.getActiveUser().getEmail();
// get the relevant spreadsheet to output log details
var ss = SpreadsheetApp.getActiveSpreadsheet();
var googleSheet = ss.getSheetByName(LOG_TAB_NAME);
// create and format a timestamp
var now = new Date();
var timeZone = ss.getSpreadsheetTimeZone();
var niceDateTime = Utilities.formatDate(now, timeZone, DATE_FORMAT);
// create array of data for pasting into log sheet
var logData = [niceDateTime, activeUserEmail, text_to_log];
// append details into next row of log sheet
googleSheet.appendRow(logData);
}
/**
* Create a string that can easily be used as an object/array key for reference
* during the create folder loop. (Helps with identifying the parent folder dynamically)
*/
function createMapString(input_string) {
return input_string.replace(/\W/g, '');
}