Google Drive List All Folders and Files [duplicate] - api

This question already has answers here:
List all files and folder in google drive
(2 answers)
Closed 2 years ago.
Hi I'm looking for a way to get a list for all my folders, sub folders and files from my google drive. I would like it to create a spreadsheet in my drive that outputs:
-All folders names, all sub folder names, all files names and there id (if not the id the url or both). Optional if it is possible output the description
Ive tried the code display on this post that works but it only gives me the file name and link in the parent folder only but I would like all mention information.
if someone knows the correct full code?
// replace your-folder below with the folder for which you want a listing
function listFolderContents() {
var foldername = 'your-folder';
var folderlisting = 'listing of folder ' + foldername;
var folders = DriveApp.getFoldersByName(foldername)
var folder = folders.next();
var contents = folder.getFiles();
var ss = SpreadsheetApp.create(folderlisting);
var sheet = ss.getActiveSheet();
sheet.appendRow( ['name', 'link'] );
var file;
var name;
var link;
var row;
while(contents.hasNext()) {
file = contents.next();
name = file.getName();
link = file.getUrl();
sheet.appendRow( [name, link] );
}
};

Execute this URI request which I generated from the Drive API explorer:
https://www.googleapis.com/drive/v3/files?fields=files%2CincompleteSearch%2Ckind%2CnextPageToken
It will return all your files and the its metada - complete info, which is found in File Resource properties.

Related

Automating Photoshop to edit en rename +600 files with the name of the folder

I have +600 product images on my mac already cut out and catalogued in their own folder. They are all PSD's and I need a script that will do the following.
Grab the name of the folder
Grab all the PSD's in said folder
Combine them in one big PSD in the right order (the filenames are saved sequentially as 1843, 1845, 1846 so they need to open in that order)
save that PSD
save the separate layers as PNG with the name from the folder + _1, _2, _3
I have previous experience in Bash (former Linux user) and tried for hours in Automator but to no success.
Welcome to Stack Overflow. The quick answer is yes this is possible to do via scripting. I might even suggest breaking down into two scripts, one to grab and save the PSDs and the second to save out the layers.
It's not very clear about "combining" the PSDs or about "separate layers, only I don't know if they are different canvas sizes, where you want each PSD to be positioned (x, y offsets & layering) Remember none of use have your files infront of us to refer from.
In short, if you write out pseudo code of what is it you expect your code to do it makes it easier to answer your question.
Here's a few code snippets to get you started:
This will open a folder and retrieve alls the PSDs as an array:
// get all the files to process
var folderIn = Folder.selectDialog("Please select folder to process");
if (folderIn != null)
{
var tempFileList = folderIn.getFiles();
}
var fileList = new Array(); // real list to hold images, not folders
for (var i = 0; i < tempFileList.length; i++)
{
// get the psd extension
var ext = tempFileList[i].toString();
ext = ext.substring(ext.lastIndexOf("."), ext.length);
if (tempFileList[i] instanceof File)
{
if (ext == ".psd") fileList.push (tempFileList[i]);
// else (alert("Ignoring " + tempFileList[i]))
}
}
alert("Files:\n" + fileList.length);
You can save a png with this
function save_png(afilePath)
{
// Save as a png
var pngFile = new File(afilePath);
pngSaveOptions = new PNGSaveOptions();
pngSaveOptions.embedColorProfile = true;
pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
pngSaveOptions.matte = MatteType.NONE; pngSaveOptions.quality = 1;
activeDocument.saveAs(pngFile, pngSaveOptions, false, Extension.LOWERCASE);
}
To open a psd just use
app.open(fileRef);
To save it
function savePSD(afilePath)
{
// save out psd
var psdFile = new File(afilePath);
psdSaveOptions = new PhotoshopSaveOptions();
psdSaveOptions.embedColorProfile = true;
psdSaveOptions.alphaChannels = true;
activeDocument.saveAs(psdFile, psdSaveOptions, false, Extension.LOWERCASE);
}

Where and how do I make another folder to put text files so they work when I export?

I have a folder with my text files that can read and write and work in eclipse. But, when I export to jar, it fails because the files are not found, meaning they are not exported and I don't know how to make eclipse do that. I'm sure the solution is out there, but I don't know exactly what I'm searching for. Do I make a relative directory and how? Or another source folder? What exactly do I need to do?
This shows I have a folder called conf where my files are stored but it is not there on export.
Scanner in = new Scanner(new FileReader("conf/Admins.txt"));
FileWriter out = new FileWriter("conf/CurrentUser.txt");
int id = 0;
String name = "";
String pass = "";
boolean found = false;
while(in.hasNext()) {
id = in.nextInt();
name = in.next();
pass = in.next();
if(id == userID) {
out.write(id + " " + name + " " + pass + "\n");
found = true;
break;
}
}
All I had to do was once exported, put my conf file in the same place as the exported jar file. I don't know if, theres a better way but this is a win for me.

PhantomJS wildcard file deletion

I've searched the net all over for this but unfortunately I could not find the answer I am looking for. Do phantomjs support wildcard deletion? This is the example I found in their site.
var fs = require('fs');
var toDelete = 'someFile.txt';
fs.remove(toDelete);
phantom.exit();
But this is not what I want. I want to delete multiple files of the same type. Say for example I want to delete all the (*.png)png of this directory. Please help.
I think there is no glob-like method in PhantomJS File System module, but you can simply read contents of a directory and delete matching files.
var fs = require('fs');
var path = "/path/to/folder/to/clean/"; // needs trailing slash
var list = fs.list(path);
for(var x = 0; x < list.length; x++){
var file = path + list[x];
if(fs.isFile(file) && file.match(".png$")){
fs.remove(file);
console.log("Deleted " + file);
}
}

Using Google Apps Script to save a single sheet from a spreadsheet as pdf in a specific folder

I am using a Google spreadsheet to prepare invoices and was looking for a simple script that saves a sheet, where the invoice is in, in a "invoices" folder to build an archive.
I "borrowed" code from numerous contributors on Stackoverflow and youtube and came up with a code that works. I had to copy the invoice to a newly created spreadsheet, because it seems to be impossible to create a pdf from one single sheet in type spreadsheet. I also had to use a piece of code to move the pdf from the root to an "invoices" folder
The only thing I am not able to solve is that the spreadsheet created in line 6 consistes of 2 sheets. An empty one and a correctly copied one. The created pdf thus alsa has 2 sheets, one empty and one correct sheet.
Anyone got a clue how to solve this ?
By the way sometimes it takes some minutes before the pdf shows in the folders.
Below is the code
function generatePdf(){
//Create a temporary spreadsheet, to store the desired sheet from the spreadsheet in.
var originalSpreadsheet = SpreadsheetApp.getActive();
originalSpreadsheet.setActiveSheet(originalSpreadsheet.getSheets()[4]);
var name = "Testname"
var newSpreadsheet = SpreadsheetApp.create(name);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet = originalSpreadsheet.getActiveSheet();
sheet.copyTo(newSpreadsheet);
//Save the desired sheet as pdf
var pdf = DriveApp.getFileById(newSpreadsheet.getId()).getAs('application/pdf');
var saveCopy = DriveApp.createFile(pdf);
//Delete temporary spreadsheet
DriveApp.getFilesByName(name).next().setTrashed(true);
//Move the pdf file from the rootfolder to the folder where invoices are to be stored.
var files = DriveApp.getRootFolder().getFiles();
while (files.hasNext()) {
var file = files.next();
var destination = DriveApp.getFolderById("0B3ok04PZOVbgLXA2dy14MVlLRXM");
destination.addFile(file);
var pull = DriveApp.getRootFolder();
pull.removeFile(file);
}
}
I'm not sure if you have encountered this code but you can try this:
function checkSheet() {
var sheetName = "Sheet1";
var folderID = "FOLDER_ID"; // Folder id to save in a folder.
var pdfName = "Invoice "+Date();
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
//repace cell values with text (to avoid broken references)
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
//save to pdf
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = folder.createFile(theBlob);
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
Note:
While testing this code, it creates the pdf in an instant, but it may depend on the invoice template.
References:
Simple Google Apps Script to export a single sheet to PDF and email it to a contact list
Sample Template - Professional Invoice Template (for Testing Purpose)
Hope this helps!
UPDATE

How to move generated PDF to a specific folder in Google Drive

Here is the jist of what I want this script to do.
User submits a form using Google Forms
Form Records to Google Sheet
Sheet replaces text and generate Google Document from Template
Template is copied
PDF is created from this template
PDF is emailed
PDF is moved to a specific folder in Google Drive.
I have all of those things to work except the last step. Can someone help us out here? We are using this for a school, and nobody in our (IT) department knows anything about scripts. Through Googling and searching I have come this far. The last step is to get the PDF to move to a specific folder.
Here is the current code:
// MacArthur High School
// Generic PLC Agenda Script
// Created 18 Jul 2014
// Author: Josh Patrick
// Decatur Public Schools #61
// Document Creation - replace docTemplate links with each template link on the PLC Drive.
var docTemplate = "1DSFCE6mFZib0ZTVOgVqPbLYaRwjS-XNsnsZn5RZewsE";
var docName = "PLC Agenda";
// Form Functions (labeled identifiers for Form)
function onFormSubmit(e) {
var TimeStamp = e.values [0]
var MeetingDate = e.values [1];
var MeetingTime = e.values [2];
var MeetingLocation = e.values [3];
var PLCFocus = e.values [4];
var PlannedActions = e.values [5];
var ResourcesNeeded = e.values [6];
var AssignedEmail = "jwpatrick#dps61.org";
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+ MeetingDate)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replacing Text with Form Information
copyBody.replaceText('keyMeetingDate', MeetingDate);
copyBody.replaceText('keyMeetingTime', MeetingTime);
copyBody.replaceText('keyMeetingLocation', MeetingLocation);
copyBody.replaceText('keyPLCFocus' , PLCFocus);
copyBody.replaceText('keyPlannedActions' , PlannedActions);
copyBody.replaceText('keyResourcesNeeded' ResourcesNeeded);
// Copy Document and Save
copyDoc.saveAndClose();
// Generate PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
// Email
var subject = "ELA PLC Agenda for " + MeetingDate ;
var body = "Attached is the PDF copy of the ELA PLC Agenda for " + MeetingDate;
MailApp.sendEmail(AssignedEmail, subject, body, {htmlBody: body, attachments: pdf});
// Delete Temporary Document
DocsList.getFileById(copyId).setTrashed(true);
}
**** Instead of deleting the temporary document, I want to move it to a specific file in Google Drive. I have looked up the scripts help, but I don't think I have done it correctly. I can get it to copydoc but I cannot get it to move to the right folder.
Any assistance is much appreciated.
addToFolder may fit your need.
developers.google.com/apps-script/reference/docs-list/file#addToFolder(Folder)