Save Gmail attachment to SHARED Google Drive - javascript

Goal:
Update code below to save attachments to a "Test" folder within "Shared drive"
So far I've been successful in saving attachments to "My Drive" using the gmail2gdrive script found on https://github.com/ahochsteger/gmail2gdrive
This script uses DriveApp.getRootFolder() to find the root folder, but does not look at shared drives.
I have the "Drive" Advanced Service set up and am able to at least view up to 10 folders in the Shared Drive using getSharedDrives(), but have been unsuccessful updating the code to transfer files to a shared drives.

Move a file from MyDrive to Shared Drive
function movefileToSharedDrive() {
const file = DriveApp.getFileById('');//fileid
const fldr = DriveApp.getFolderById('');//shared drive id
Drive.Files.update({"parents": [{"id": fldr.getId()}]}, file.getId(), null, {"supportsAllDrives":true});
}
Drive API Version 2 needs to be enabled

The Folder Drive ID can be found in the URL extension:
Folder Drive ID
Use the folders' Drive IDs (from above) to fill in the appropriate section of the code below (Copies files from desired folder into the shared folder):
function movefileToSharedDrive() {
makeCopy("", ""); //("From My Drive ID", "To Shared Drive ID")
}
function makeCopy(srcFolderId, dstFolderId) {
var srcFolder = DriveApp.getFolderById(srcFolderId);
var dstFolder = DriveApp.getFolderById(dstFolderId);
var files = srcFolder.getFiles();
while (files.hasNext()) {
var file = files.next();
var f = file.makeCopy(dstFolder);
if (file.getMimeType() == MimeType.GOOGLE_APPS_SCRIPT) {
Drive.Files.update({"parents": [{"id": dstFolderId}]}, f.getId());
}
}
}

Related

How to log Google Drive File Names to Google Sheets using Google Apps Script

So I am trying to log files (and their Id) from my Drive to a spreadsheet using Google Apps Script. The problem is that I don't know how to add content to rows of a Google Sheets document.
I know how to log my files and their Id:
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
Logger.log(file.getId());
}
Now I would like to log the Name and Id of my files from one folder to a Google sheet. Does anybody know how to achieve this?
You'll need to get the spreadsheet, and add the file names to a 2D array. The following code requires you to enter the spreadsheet file ID and the sheet tab name.
function logFilesToSheet() {
var arrayForOneRow,file,id,name,outerArray,sh,ss;
id = "";//Enter your spreadsheet file id here
name = "";//Enter the sheet tab name here
ss = SpreadsheetApp.openById(id);
sh = ss.getSheetByName(name);
outerArray = [];
var files = DriveApp.getFiles();
while (files.hasNext()) {
file = files.next();
//Logger.log(file.getName());
//Logger.log(file.getId());
arrayForOneRow = [];//Reset on each loop - Each row needs a new array
arrayForOneRow.push(file.getName());
arrayForOneRow.push(file.getId());
outerArray.push(arrayForOneRow);
}
sh.getRange(sh.getLastRow() + 1,1,outerArray.length,2).setValues(outerArray);
}

How to get producer of a PDF in google app script

I am trying to write a gmail add-on where I iterate over all emails and create a report based on their producers. Iterating over emails is the easiest part and I have done that, however I can't find any way to get producer line of each PDFs.
So far I tried
analyzing the blob, however this is something like writing a PDF library to parse all syntax. producer tag is not clearly present
adding pdf.js, which is a third party open source tool to extract such information. However, I couldn't add it due to ES3 - ES6 support issue.
What's the best way to get the producer line of a PDF in google app script?
Thank you
You want to retrieve the value of Producer from PDF file.
I could understand like above. If my understanding is correct, how about this sample script? In this sample script, from your shared PDF files, the value of Producer is retrieved by 2 regular expressions from the file content. Please think of this as one of several answers.
Sample script:
When you use this script, please set the folder ID of folder that PDF files are put. This script retrieves the value from all PDF files in a folder.
var folderId = "### folderId ###";
var files = DriveApp.getFolderById(folderId).getFilesByType(MimeType.PDF);
var regex = [/Producer\((\w.+)\)/i, /<pdf:Producer>(\w.+)<\/pdf:Producer>/i];
var result = [];
while (files.hasNext()) {
var file = files.next();
var content = file.getBlob().getDataAsString();
var r = regex.reduce(function(s, e) {
var m = content.match(e);
if (Array.isArray(m)) s = m[1];
return s;
}, "");
result.push({
fileName: file.getName(),
fileId: file.getId(),
vaueOfProducer: r,
});
}
Logger.log(result); // Result
Result:
This sample result was retrieved from a folder (my Google Drive) that the shared 3 PDF files were put.
[
{
"fileName": "2348706469653861032.pdf",
"fileId": "###",
"vaueOfProducer": "iText� 7.1.5 �2000-2019 iText Group NV \(iText; licensed version\)"
},
{
"fileName": "Getting started with OneDrive.pdf",
"fileId": "###",
"vaueOfProducer": "Adobe PDF library 15.00"
},
{
"fileName": "DITO-Salesflow-040419-1359-46.pdf",
"fileId": "###",
"vaueOfProducer": "iText 2.1.7 by 1T3XT"
}
]
Note:
About the file of 2348706469653861032.pdf, the characters which cannot be displayed are included in the value of Producer.
This is a sample script. So please modify this for your situation.

How to move PDF files from a parent folder to a subfolder which has the same name as the file

I am working on a project which sends PDFs from a Wordpress website to a Google Drive. The files are PDFs of people who registered for certain events, which are held in certain cities. These PDFs are all sent to a parent folder "registrations". What I need to achieve is to automatically send these PDFs to subfolders like Amsterdam, Rotterdam, Woerden, Westland etc.
The PDFs are all sent to a parent folder "registrations". What I need to achieve is to automatically send these PDFs to subfolders like Amsterdam, Rotterdam. The names of the PDFs are the city names (e.g. Amsterdam).
In conclusion, the question basically is: how could I achieve to send a file with the name Amsterdam to a subfolder with the name Amsterdam, and a file with the name Rotterdam to a folder with the name Rotterdam?
EDIT: I am working on the script, but it is not complete yet. The script below searches for files in a parent folder that contains "woerden" in its name. Next, it moves these files to a folder called "woerden". This works, but the problem is that I will have to create about 300 different scripts to be able to automate the entire process. I am therefore wondering if it is possible to make this script more dynamic. For example, if a file with a name that contains -woerden- it is sent to a folder with the name woerden, and if a file with a name that contains -westland- it will be sent to a folder with the name westland.
function SearchFiles() {
// Parent folder
var parentFolder = DriveApp.getFolderById('15azR1-Fic_F_wPZHzXWKblIyxBB_GVsW'); //parent folder which will be scanned for duplicates
// Log the name of every file in the user's Drive whose name contains "westland".
var files = DriveApp.searchFiles(
'title contains "westland"');
while (files.hasNext()) {
var file = files.next();
// Remove the file from all parent folders
var parents = file.getParents();
while (parents.hasNext()) {
var parent = parents.next();
parent.removeFile(file);
}
DriveApp.getFolderById('1mSW3-uqv_F1m-TfLa_JyGRVK9-sGJYTj').addFile(file);
}
}
I hope that I asked my question clearly. Please let me know if you need some more information.
Cheers,

Automatically create new Google Drive folder from new files

I currently have a Zapier process running that automatically creates 3 new files uploaded from a form into a folder in my Google Drive called "New Users". Each file is formatted as firstname_lastname-filename.ext but this is not good in terms of organization.
Instead, I would like to dynamically create a new folder labeled as firstname_lastname containing the 3 new files every time they come in with the same firstname_lastname, rather than having a generic "New Users" folder filled with hundreds or thousands of files.
Unfortunately I'm a pretty novice programmer, so I'm not quite sure how to go about this using Apps Script.
Any advice?
I've thought about something like:
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
if file.getName().includes("firstname_lastname") { // Check if a file name contains the string firstname_lastname
var folders = DriveApp.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
Logger.log(folder.getName());
if folder.getName().includes("firstname_lastname") { // Check if a folder exists with a name that contains the string firstname_lastname
makeCopy(file.getName(), folder.getName()) // if said folder exists, make a copy of the the file and move it to that folder
} else { // if said folder does not exist...
var newFolderName = file.getName() // let the newFolderName be the same name as the file (I know this isn't right if I want the folder name to be firstname_lastname without the actual uploaded file name plus extension)
createFolder(newFolderName); // then create a folder that has the name newFolderName
makeCopy(file.getName(), folder.getName(newFolderName)) // then make a copy of the file and put it into the folder
}
}
}
}
You may want to first establish your root folder, "New Users". I've created a snippet for the flow:
//New Users Folder
var rootFolder = DriveApp.getFolderById("FOLDER_ID");
function myFunction() {
var files = rootFolder.getFolders();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
if(file.getName() == fileuploadName){
//copy file if folder is existing
file.addFile(child)
}
else{
//create folder
var newFolder = rootFolder.addFolder(child);
newFolder.addFile(child)
}
}
Logger.log("Done")
}
This flow should be ok when you want to implement a dynamic creation of folder then migrate the files to a specific folder name.
Hope this helps.

Creating zip file only contains pdf

In my script I am trying to create a folder, create a date-stamped-document in said folder, create a sub folder, and copy some documents into that sub folder.
All of this works great. When I try to zip the parent folder via either of the methods found here: Creating a zip file inside google drive with apps script - it creates a zip file with a sole PDF file that has the same name as the date-stamped-document. The zipped PDF is blank, and the subfolder isn't there.
Any insight about why this is happening would be great.
var folder = DocsList.createFolder(folderTitle);
var subFolder = folder.createFolder('Attachments');
subfolder.createFile(attachments[]); //In a loop that creates a file from every
//attachment from messages in thread
var doc = DocumentApp.create(docTitle); //Google Doc
var docLocation = DocsList.getFileById(doc.getId());
docLocation.addToFolder(folder);
docLocation.removeFromFolder(DocsList.getRootFolder());
//Everything works fine, I can view file and subfolder, and subfolder's documents
//This is where the problem is:
var zippedFolder = DocsList.getFolder(folder.getName());
zippedFolder.createFile(Utilities.zip(zippedFolder.getFiles(), 'newFiles.zip'));
//this results in a zipped folder containing one blank pdf that has the same title as doc
The DocsList service has been deprecated so Phil Bozak's previous solution no longer works. However, refer to another SO question for solution that works with DriveApp class.
This is a great question. It does not seem that the zip function has the ability to zip sub folders. The reason that your script doesn't work is because you only select the files from the folder.
A solution would be to zip each of the subfolders and store that in the one zipped file. You can use the function that I wrote for this.
function zipFolder(folder) {
var zipped_folders = [];
var folders = folder.getFolders();
for(var i in folders)
zipped_folders.push(zipFolder(folders[i]));
return Utilities.zip(folder.getFiles().concat(zipped_folders),folder.getName()+".zip");
}
This recursively zips all subfolders. Then you need to create the file with something like
DocsList.getFolder("path/to/folder/to/store/zip/file").createFile(zipFolder(folderToZip));
I will put in a feature request to allow subfolders to be zipped.

Categories

Resources