#GPT-4 Conversation #1101064874332782612
1 messages · Page 1 of 1 (latest)
Hi, I need help with google drive app-script. I need you to write a code that:
- Makes a new folder in my drive called “copies”
- Makes a copy of every file that has ever been shared with me on that google drive account, regardless of filetype, and puts the copy of the file into the newly created folder
- Ensures that the files retain their original folder structure, meaning that for example, if somebody shared a folder with me containing images, The copied images will be inside a folder of the same name as the one shared with me, inside the copies folder. There might be multiple layers of folders.
- Be aware of the possibility of google drive app script limitations, there are many, many files to be copied, and the 6 minute limitation will not be enough to copy all the files in one go. Use time based trigger to account for this
- Implement the trigger system so that all I need to do is to copy and paste the script into the editor, review the permissions, and leave it to complete the task. Make sure that the script resumes copying from where it left off, instead of starting over, when it restarts.
I understand your requirements, and here's a solution for your Google Drive App Script. Since you want a solution that covers all aspects and manages triggers, the following code is split into three sections:
- Main function – Sets up the trigger and folder, initializes some quick settings.
- Recursive copy function – Recursively copies folders and files, keeping the original structure.
- Time-limited execution - Manages triggers and the execution window.
Please copy and paste each section of the script into the Google Apps Script editor:
Section 1:
function initializeScript() {
createTriggerIfNeeded();
createCopiesFolderIfNeeded();
}
function createTriggerIfNeeded() {
const triggers = ScriptApp.getProjectTriggers();
let triggerExists = false;
for (const trigger of triggers) {
if (trigger.getHandlerFunction() === 'runCopyFiles') {
triggerExists = true;
break;
}
}
if (!triggerExists) {
ScriptApp.newTrigger('runCopyFiles')
.timeBased()
.everyMinutes(6)
.create();
}
}
function createCopiesFolderIfNeeded() {
const folders = DriveApp.getFoldersByName('copies');
if (!folders.hasNext()) {
DriveApp.createFolder('copies');
}
}
Section 2:
function runCopyFiles() {
const sourceFolder = DriveApp.getFolderById('SHARED_FILES_FOLDER_ID');
const targetFolder = DriveApp.getFolderById('copies');
checkLimitAndCopyFolders(sourceFolder, targetFolder);
}
function checkLimitAndCopyFolders(source, target) {
const startTime = new Date().getTime();
const timeLimit = 340000; // (roughly) 5 minutes and 40 seconds
(function copyFolders(source, target) {
const foldersIterator = source.getFolders();
const filesIterator = source.getFiles();
while (foldersIterator.hasNext()) {
var folder = foldersIterator.next();
var folderCopy = target.createFolder(folder.getName());
copyFolders(folder, folderCopy);
const