Create a gist now

Instantly share code, notes, and snippets.

This is the full script solution for Stack Overflow Q14518410, "a google apps script to move or restore google drive's files from the trash"http://stackoverflow.com/questions/14518410/a-google-apps-script-to-move-or-restore-google-drives-files-from-the-trash
// See http://stackoverflow.com/questions/14518410/a-google-apps-script-to-move-or-restore-google-drives-files-from-the-trash
var addonName = 'Rescue Files';
var rescueFldrName = 'Rescued Files'; // The name of the folder that rescued files should be placed into
/**
* Adds an addon menu to the active spreadsheet.
*/
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu(addonName)
.addItem('Get trashed file list', 'getTrashedFilesUI')
.addItem('Rescue Listed files', 'rescueListedFilesUI')
.addSeparator()
.addItem('Rescue ALL files', 'rescueAllFilesUI')
.addToUi();
}
/*********************************************************************************************************
* User Interface functions poll user for input and report results.
*/
function getTrashedFilesUI() {
var yesNo = Browser.msgBox(addonName,
"Replace current sheet with list of trashed files?",
Browser.Buttons.YES_NO);
if ("yes" == yesNo) {
getTrashedFiles();
};
}
function rescueListedFilesUI() {
var yesNo = Browser.msgBox(addonName,
"Rescue trashed files listed in this spreadsheet?",
Browser.Buttons.YES_NO);
if ("yes" == yesNo) {
var count = rescueListedFiles();
Browser.msgBox("Rescued " + count + " Files");
};
}
function rescueAllFilesUI() {
var yesNo = Browser.msgBox(addonName,
"Rescue ALL trashed files?",
Browser.Buttons.YES_NO);
if ("yes" == yesNo) {
var count = rescueAllFiles();
Browser.msgBox("Rescued " + count + " Files");
};
}
/*********************************************************************************************************
* Primary operation functions
*/
/**
* Get array of files in user's Google Drive trash.
* From: http://stackoverflow.com/a/14541247/1677912
*
* @returns {Object[]} Array of DriveApp file objects
*/
function getTrashedFiles() {
var trashedSearch = DriveApp.searchFiles('trashed=true');
var files = [];
files.push(["ID","File Name","Type","URL"]);
while (trashedSearch.hasNext()) {
var file = trashedSearch.next();
files.push([file.getId(),file.getName(),docTypeToText_(file.getMimeType()),file.getUrl()]);
}
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.getRange(1, 1, files.length, files[0].length)
.setValues(files);
return files;
}
/**
* Untrash then move files listed in spreadsheet to rescue folder.
* From: http://stackoverflow.com/a/14541247/1677912
*
* @returns {Number} Count of Rescued files.
*/
function rescueListedFiles() {
var fileList = SpreadsheetApp.getActiveSheet()
.getDataRange().getValues()
.splice(1); // Skip header line
// Find or create target folder
var rescueFldrIterator = DriveApp.getFoldersByName(rescueFldrName);
var rescueFldr = rescueFldrIterator.hasNext() ? rescueFldrIterator.next() : DriveApp.createFolder(rescueFldrName);
var count = 0;
for (var i=0; i<fileList.length; i++) {
var fileId = fileList[i][0];
var file = DriveApp.getFileById(fileId);
// Untrash the file
if (rescueFile( file, rescueFldr )) count++;
}
return( count );
};
/**
* Untrash then move all trashed files to rescue folder.
* From: http://stackoverflow.com/a/14541247/1677912
*
* @returns {Number} Count of Rescued files.
*/
function rescueAllFiles() {
// Find or create target folder
var rescueFldrIterator = DriveApp.getFoldersByName(rescueFldrName);
var rescueFldr = rescueFldrIterator.hasNext() ? rescueFldrIterator.next() : DriveApp.createFolder(rescueFldrName);
// Get file iterator with all trashed files
var trashed = DriveApp.searchFiles('trashed=true');
var count = 0;
while (trashed.hasNext()) {
var file = trashed.next();
// Untrash the file
if (rescueFile( file, rescueFldr )) count++;
}
return(count);
};
/*********************************************************************************************************
* Utility functions
*/
/**
* Rescue given file from trash, if there.
*
* @param {File} file DriveApp File object to be rescued
* @param {Folder} rescueFldr DriveApp Folder object to receive rescued file
*
* @returns {Boolean} `true` if file rescued.
*/
function rescueFile( file, rescueFldr ) {
if (file.isTrashed()) {
// Untrash the file
file.setTrashed(false);
// Unlink any & all folders this file used to appear in
var oldFolders = file.getParents();
while (oldFolders.hasNext()) {
oldFolders.next().removeFile(file);
}
// Link the Rescued file to target directory.
rescueFldr.addFile(file);
Logger.log("Rescued: "+ JSON.stringify(getFileInfo(file)));
return( true );
}
else
// Nothing to do
return( false );
}
/**
/**
* Return an object containing relevant information about the given file.
* See https://developers.google.com/apps-script/class_file.
* From: https://gist.github.com/mogsdad/4644369
*
* @param {Object} file File or Folder object to examine.
*
* @return {Object} Interesting file attributes.
* <pre>{
* id: unique id (ID) of the folder or file
* name: the name of the File
* size: the size of the File
* type: The type of the file
* created: date that the File was created
* description: the description of the File
* owner: user id of the owner of the File
* otherViewers: list of user ids of viewers of the File, w/o owner
* otherEditors: list of user ids of editors of the File, w/o owner
* }</pre>
*/
function getFileInfo (file) {
var fileInfo = {
id: file.getId(),
name: file.getName(),
size: file.getSize(),
type: (file.getMimeType) ? docTypeToText_(file.getMimeType()) : "folder", // DriveApp Folders don't have getMimeType() method.
created: file.getDateCreated(),
description: file.getDescription(),
owner: userNames([file.getOwner()],false),
otherViewers: userNames(file.getViewers(),true),
otherEditors: userNames(file.getEditors(),true)
};
return fileInfo;
}
/**
* Return string representation of a Document Type.
*
* @param {FileType} type Enum as defined in https://developers.google.com/apps-script/class_docslist_filetype.
* @return {String} String matching the provided type. "UNKNOWN" if type was not known.
*/
function docTypeToText_(type) {
var typeText = "";
switch (type) {
case MimeType.GOOGLE_DOCS:
typeText = "DOCUMENT";
break;
case MimeType.GOOGLE_DRAWINGS:
typeText = "DRAWING";
break;
case MimeType.GOOGLE_SLIDES:
typeText = "SLIDES";
break;
case MimeType.GOOGLE_SHEETS:
typeText = "SPREADSHEET";
break;
case MimeType.FOLDER:
typeText = "FOLDER";
break;
case MimeType.GOOGLE_APPS_SCRIPT:
typeText = "SCRIPT";
break;
case MimeType.GOOGLE_FORMS:
typeText = "FORM";
break;
default:
typeText = type;
break;
}
return typeText;
}
/**
* Return a comma-separated list of user IDs, from an array of Class User.
*
* @param {array} users Array of Class User.
* @param {boolean} skipOwner If true, do not include file owner in results
*
* @returns {string} Comma-sparated list of user IDs.
*/
function userNames( users, skipOwner ) {
var retval = "";
var startAt = skipOwner ? 1 : 0; // Owner listed first in editors & viewers lists
if (users.length <= startAt) {
retval = "none";
}
else {
for (var i=startAt; i<users.length; i++) {
if (i > startAt) retval += ", "
var userId = "";
try {
userId = users[i].getEmail()//.getUserLoginId()
} catch(e)
{
// Possible permission problem
userId = "unknown";
}
retval += userId;
}
}
return retval
}
/**
* Get array of files on user's Google Drive that have been shared with them.
* From http://stackoverflow.com/a/15947340/1677912
*
* @returns {Array} Array of file resources
* (see https://developers.google.com/drive/v2/reference/files#resource)
*/
function getSharedWithMe() {
var optionalArgs = {q:"sharedWithMe=true"};
var sharedFiles = Drive.Files.list(optionalArgs);
debugger; // pause in debugger
return sharedFiles.items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment