is there a reason my getOAuthToken() was working and now isnt? - google-apps-script

var sourceFolderId = "15Kux2yyL_OWoZBwnYPbJtyrlp1zQjY3T";
var folder = DriveApp.getFolderById(sourceFolderId);
var token = ScriptApp.getOAuthToken()
var imageUrl = folder.getFilesByName(uid).next().getDownloadUrl() + "&access_token=" +
ScriptApp.getOAuthToken();
var slide = Slides.Presentations.get(newTargetDocId).slides[0]
Logger.log(token)
Logger.log(imageUrl)
I have been using the above code to get an image from google drive and using batchupdate put it into google slides, however the auth token no longer allows a download, do i need to refresh it somehow?
The url goes to the correct image and the image is the correct file format but the code returns
API call to slides.presentations.batchUpdate failed with error: Invalid requests[1].createImage: The provided image is in an unsupported format. (line 243, file "Code").
I know the image is ok as i have already used it. I know the url is correct as it takes me to the image if i cut the authtoken off. The authtoken on the end no longer allows me to download the file on another browser.
New code based on comment about Drive changes
var sourceFolderId = "15Ku...............zQjY3T";
var folder = DriveApp.getFolderById(sourceFolderId);
var file = folder.getFilesByName(uid).next()
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
var imageUrl = "https://drive.google.com/uc?export=download&id=" + file.getId();
But now i get an invalid argument error on file.setSharing line

var sourceFolderId = "15Ku...............zQjY3T";
var folder = DriveApp.getFolderById(sourceFolderId);
var file = folder.getFilesByName(uid).next()
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
var imageUrl = "https://drive.google.com/uc?export=download&id=" + file.getId();
General file permissions will need to be altered to allow this to run with Gsuite admin pages

Related

Get external URL and save to Drive

I want to take a PDF URL and save it to Drive. The folder ID and URL are correct.
function uploadDoc(){
var folder = DriveApp.getFolderById('my_folder_id');
var url = 'my_url';
var blob = UrlFetchApp.fetch(url);
var blob2 = blob.getAs('appl‌​ication/pdf');
var newFile = folder.createFile('filename.pdf',blob2);
}
When I run this, I get:
Exception: Converting from binary/octet-stream to appl‌​ication/pdf is not supported.
You'll need to fix two things:
After UrlFetchApp.fetch(url) you need to use the getBlob() method. The getAs('appl‌​ication/pdf') method is not strictly required.
If you are using a blob, then you need to use the createFile(blob) method.
You are using the createFile(name, content) method and in this method, content is string not blob.
Then to name of the new file, you'll need the setName(name) method.
function uploadDoc() {
var url = 'https://www.gstatic.com/covid19/mobility/2021-02-21_AF_Mobility_Report_en.pdf';
var foID = 'my_folder_id';
var folder = DriveApp.getFolderById(foID);
var blob = UrlFetchApp.fetch(url).getBlob();
var newFile = folder.createFile(blob).setName('filename.pdf');
}

Fetch file from external URL and upload to Google Drive using Apps Script

I'm not sure if this is even possible. I'm trying to fetch file that being uploaded to formfacade server via the add-on in google form. I'm using it to allow other non-gmail users to upload file without having to sign-in.
I referred to answer from Mogsdad and dheeraj raj in
Can I download file from URL link generated by google apps script to use UrlFetchApp to meet this objective. Below are my codes:
Method 1 :
function UrlFile2gdrive() {
var sheet=SpreadsheetApp.getActiveSheet();
var lrow=sheet.getLastRow();
//var fileURL=sheet.getRange(lrow,2).getValue();
var fileURL='https://formfacade.com/uploaded/1FAIpQLSfscYq_sbYcT2P3Sj3AvSD2zYKalIM0SKdPTESf1wE9Rq8qew/'
+'97dc1ee0-f212-11ea-95c3-bdb6c5ab13b3/2124651919/A%20Sample%20PDF.pdf'
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response=UrlFetchApp.fetch(fileURL,params);
Logger.log(response.getContentText());
var fileBlob=response.getBlob();
var folder='0B2b-M7h6xF-Mflk3dGswano2TnJ3dGlmZG8wOUREMFg4blM5SHBuM3lqYmdPOThZSTBTSWs'
var filename=fileURL.split("/").pop();
//var filename=fileURL.split("%2F").pop();
var file=decodeURIComponent(filename);
Logger.log("filename : "+file);
var newfile=DriveApp.getFolderById(folder).createFile(fileBlob.setName(file));
//var newfile=DriveApp.getFolderById(folder).createFile(response.setName(filename));
}
Method 2
//api-key : AIzaSyCcbdBCI-Kgcz3tE1N4paeF9a-vdi3Uzz8
//Declare function
function URL2gdriveWithPswd() {
//Getting url,existing name and new name for image from the sheet in
//variable url, name and new_name respectively
var sh = SpreadsheetApp.getActiveSheet();
var row = sh.getLastRow();
Logger.log(row);
//for (var i = 2; i <= row; i++) {
/*var url = sh.getRange(i, 2).getValue();
Logger.log(url);
var name = sh.getRange(i, 3).getValue();
var new_name = sh.getRange(i, 4).getValue();*/
var url = sh.getRange(row, 2).getValue();
Logger.log(url);
var filenm=url.split("/").pop();
var new_name=decodeURIComponent(filenm);
var name = sh.getRange(row, 3).getValue();
//var new_name = sh.getRange(row, 4).getValue();
//Creating authentication token for downloading image, it may not be //required if image can be downloaded without login into
var user = "dtestsys#gmail.com";
var password = "1851235656";
var headers = {
"Accept": "application/xml",
"Content-Type": "application/xml",
"Authorization": "Basic " + Utilities.base64Encode(user + ":" + password)
};
//defining method to download file
var options = {
"method": "get",
"headers": headers
};
//Getting folder name where to store downloaded image
var folders = DriveApp.getFoldersByName('File Uploader (File responses)');
while (folders.hasNext()) {
var folder = folders.next();
Logger.log(folder.getName());
}
//Getting response on hit of url using downloading method defined //earlier storing in Blob
var response = UrlFetchApp.fetch(url, options).getBlob();
//Creating image in folder defined with response in blob and logging same file //in log to check, if required
var file = folder.createFile(response);
Logger.log(file);
//renaming image
var images = folder.getFiles();
while (images.hasNext()) {
var image = images.next();
file.setName(new_name);
Logger.log("imagename : "+image.getName());
}
//}
}
However, both methods managed to get a file into my gdrive but the content consists of the html codes only (https://drive.google.com/file/d/1NYQoMmCQEoP3z6L8niq1mpvIx7xl83zu/view?usp=sharing), which I think the URL passed in google response sheet is just a "mask". I noticed that inside the file has some lines that mentioned api-key and code (next to user email address). Is it possible to achieve my objective? Are those api-key and code would be useful to get authorized to access the file and download it in gdrive?
I rechecked.The link produced and passed into my google sheet response is only the login page that redirects to another XML file. When I copied back the final URL after the original file content is displayed, the URL is as below:
https://storage.googleapis.com/formfacade-public/1FAIpQLSfscYq_sbYcT2P3Sj3AvSD2zYKalIM0SKdPTESf1wE9Rq8qew%2F97dc1ee0-f212-11ea-95c3-bdb6c5ab13b3%2F2124651919%2FA%20Sample%20PDF.pdf?GoogleAccessId=firebase-adminsdk-pve0p%40formfacade.iam.gserviceaccount.com&Expires=1599671507&Signature=fBzWej0fEgF6Aw7oCHX%2FTTUfHbcep%2Bj%2B%2FhB3fYFUDeq0SFTuyJ6jTnLWQJmldD6XkVug0%2BNki7ZPNo2ESufvIfQjhVLKXgvp7UiQheJ4GYL%2BtXgFLaUyglgemmfp7KSvIvPxpMcpC2lR8em3E5YIvMRr9tcfzagvusQYHEb9mlD7k833bVoqFUVWuP%2FkP8tl%2BHYVL15kSXAjtFif4QZpu%2FFHwSik89Keo78LKTm0U8hZiAMeYDQZWF6w1pcKpy04md3xKtDPwZYCoUWOOtKkCI6JLskE5HweDvMCGnDbxW8o6SWD%2BIC%2FlaNC6%2BJ81OB10cuRqwQPEc9LnfgCZK7b1A%3D%3D
When I pasted the above link, I got to see as per screenshot below:-
. So, I'm guessing they don't share direct access link to the uploaded file so that we are left with the option to buy/subscribe the paid version.
Would anyone knows if there's any better altrnative(s) I could use to achieve this objective? Like maybe a link with API-key just like what I learnt from #Tanaike in his previous answer on Convert-API to convert pdf file to PNG? Of course it has some limits for the free version but it still is a very helpful solution.
You are not assigning content-type of the blob anywhere. But if you do the naming right it would not matter. In method 1 you are trying to set a name on the blob when you should be setting it on the file created from the Blob.
Try setting the name on the file after creating it.
Example:
function myFunction() {
var url ="http://www.africau.edu/images/default/sample.pdf";
var response = UrlFetchApp.fetch(url);
console.log(response.getResponseCode());
var blob=response.getAs('application/pdf');
var folder = "<SOME-FOLDER-ID>";
var fileName=decodeURIComponent(url.split("/").pop());
console.log("File named : "+fileName);
var file=DriveApp.getFolderById(folder).createFile(blob);
// Set the name to the created file after creating it!
file.setName(fileName);
}
For reference see class File.

Downloading a Google Slides presentation as PowerPoint doc using Google Apps Script?

The GUI of Google Slides offers to download a GSlides presentation as a Powerpoint (myFile.pptx). I could not find the equivalent in the Google Apps Script documentation - any pointer?
EDIT
Thanks to comments and answers, I tried this snippet:
function testFileOps() {
// Converts the file named 'Synthese' (which happens to be a Google Slide doc) into a pptx
var files = DriveApp.getFilesByName('Synthese');
var rootFolder = DriveApp.getRootFolder();
while (files.hasNext()) {
var file = files.next();
var blobPptx = file.getBlob().getAs('application/vnd.openxmlformats-officedocument.presentationml.presentation');
var result = rootFolder.createFile(blobPptx);
}
}
It returns an error:
Converting from application/vnd.google-apps.presentation to
application/vnd.openxmlformats-officedocument.presentationml.presentation
is not supported. (line 7, file "Code")
SECOND EDIT
As per another suggestion in comments, I tried to make an http call from Google App Script, that would directly convert the gslides into pptx, without size limit. It produces a file on G Drive, but this file is corrupted / unreadable. The GAS script:
function convertFileToPptx() {
// Converts a public Google Slide file into a pptx
var rootFolder = DriveApp.getRootFolder();
var response = UrlFetchApp.fetch('https://docs.google.com/presentation/d/1Zc4-yFoUYONXSLleV_IaFRlNk6flRKUuAw8M36VZe-4/export/pptx');
var blobPptx = response.getContent();
var result = rootFolder.createFile('test2.pptx',blobPptx,MimeType.MICROSOFT_POWERPOINT);
}
Notes:
I got the mime type for pptx here
using the mime type 'pptx' returns the same error message
How about this modification?
Modification point:
response.getContent() returns byte array. So please use response.getBlob().
Modified script:
function convertFileToPptx() {
var fileId = "1Zc4-yFoUYONXSLleV_IaFRlNk6flRKUuAw8M36VZe-4";
var outputFileName = "test2.pptx";
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
var rootFolder = DriveApp.getRootFolder();
var response = UrlFetchApp.fetch(url);
var blobPptx = response.getBlob();
var result = rootFolder.createFile(blobPptx.setName(outputFileName));
}
Note:
If you want to convert Google Slides, which are not published, in your Google Drive, please use access token. At that time please modify url as follows.
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx?access_token=' + ScriptApp.getOAuthToken();
DriveApp.createFile() creates a file on root folder as the default.
References:
Class HTTPResponse
getOAuthToken()
As mentioned by tehhowch, you could get the Google Slide file from your Drive and get it as a .pptx. (Not sure of mime type.)
File#getAs:
I add all modifications with token part and specific folder
function convertFileToPptx() {
var fileId = "Your File ID";
var outputFileName = "name.pptx";
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
//var rootFolder = DriveApp.getRootFolder();
var rootFolder = DriveApp.getFolderById("Your Folder ID")
var params = {method:"GET", headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url,params);
var blobPptx = response.getBlob();
var result = rootFolder.createFile(blobPptx.setName(outputFileName));
}
To get the byte[] do:
function downloadAsPPTX(){
var presentation = SlidesApp.getActivePresentation();
var fileId = presentation.getId();
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
var response = UrlFetchApp.fetch(url);
var blobPptx = response.getBlob();
Logger.log("size: "+blobPptx.getBytes().length);
}

Google Script - How to use unzip

I am downloading a .zip from a website. It contains one .txt file. I would like to access the data in the txt and write it to a spreadsheet. I'm open to either accessing it directly and not extracting the zip OR extracting the zip, saving the txt to a Google Drive Folder, and accessing it once it is saved.
When I use Utilities.unzip(), I can never get it to unzip the file and usually end up with an "Invalid argument" error. In the code below, the last section before else contains the unzip command. It successfully saves the file to the correct Google Folder but then I can't extract it.
function myFunction() {
// define where to gather data from
var url = '<insert url here>';
var filename = "ReportUploadTesting05.zip";
var response = UrlFetchApp.fetch(url, {
// muteHttpExceptions: true,
// validateHttpsCertificates: false,
followRedirects: true // Default is true anyway.
});
// get spreadsheet for follow up info
var Sp = SpreadsheetApp.getActiveSpreadsheet();
if (response.getResponseCode() === 200) {
// get folder details of spreadsheet for saving future files
var folderURL = getParentFolder(Sp);
var folderID = getIdFromUrl(folderURL);
var folder = DriveApp.getFolderById(folderID);
// save zip file
var blob = response.getBlob();
var file = folder.createFile(blob);
file.setName(filename);
file.setDescription("Downloaded from " + url);
var fileID = file.getId();
Logger.log(fileID);
Logger.log(blob)
// extract zip (not working)
file.setContent('application/zip')
var fileUnzippedBlob = Utilities.unzip(file); // invalid argument error occurs here
var filename = 'unzipped file'
var fileUnzipped = folder.createFile(fileUnzippedBlob)
fileUnzipped.setName(filename)
}
else {
Logger.log(response.getResponseCode());
}
}
I've followed the instructions on the Utilities page. I can get their exact example to work. I've tried creating a .zip on my computer, uploading it to Google Drive and attempted to open it unsuccessfully. Obviously there are some subtleties of using the unzip that I'm missing.
Could you help me understand this?
I was running into the same "Invalid arguments" error in my testing, so instead of using:
file.setContent('application/zip')
I used:
file.setContentTypeFromExtension();
And, that solved the problem for me. Also, as #tukusejssirs mentioned, a zip file can contain multiple files, so unzip() returns an array of blobs (as documented here). That means you either need to loop through the files, or if you know you only have one, explicitly reference it's position in the array, like this:
var fileUnzipped = folder.createFile(fileUnzippedBlob[0])
Here's my entire script, which covers both of these issues:
/**
* Fetches a zip file from a URL, unzips it, then uploads a new file to the user's Drive.
*/
function uploadFile() {
var url = '<url goes here>';
var zip = UrlFetchApp.fetch('url').getBlob();
zip.setContentTypeFromExtension();
var unzippedFile = Utilities.unzip(zip);
var filename = unzippedFile[0].getName();
var contentType = unzippedFile[0].getContentType();
var csv = unzippedFile[0];
var file = {
title: filename,
mimeType: contentType
};
file = Drive.Files.insert(file, csv);
Logger.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);
var fileId = file.id;
// Move the file to a specific folder within Drive (Link: https://drive.google.com/drive/folders/<folderId>)
var folderId = '<folderId>';
var folder = DriveApp.getFolderById(folderId);
var driveFile = DriveApp.getFileById(fileId);
folder.addFile(driveFile);
}
I think the answer to your question may be found here. Is there a size limit to a blob for Utilities.unzip(blob) in Google Apps Script?
If the download is over 100 mb the full file cannot be downloaded. Due to that it will not be in the proper zip format. Throwing the cannot unzip file error.
I believe that the creation of the blob from a file (in this case the .zip file) requires the .next(); otherwise it did not work for me.
Also note that the .zip file might contain more than one file, therefore I included a for cycle.
Anyway, my working/tested solution/script is the following:
function unzip(folderName, fileZipName){
// Variables
// var folderName = "folder_name";
// var fileZipName = "file_name.zip";
var folderId = getFolderId(folderName);
var folder = DriveApp.getFolderById(folderId);
var fileZip = folder.getFilesByName(fileZipName);
var fileExtractedBlob, fileZipBlob, i;
// Decompression
fileZipBlob = fileZip.next().getBlob();
fileZipBlob.setContentType("application/zip");
fileExtractedBlob = Utilities.unzip(fileZipBlob);
for (i=0; i < fileExtractedBlob.length; i++){
folder.createFile(fileExtractedBlob[i]);
}
}

Fail to read information from a web site using Google Apps Script

I have tried to use "UrlFetchApp.Fetch" in google apps script to retrieve data from https://metoc.ndbc.noaa.gov/web/guest/jtwc".
However, the information highlighted in red as shown here "web capture" cannot be captured in the file I downloaded. Please help, thanks.
var FILE_NAME = 'data.txt'
var Google_DRive_ID = 'your google drive folder id'
var RESOURCE_URL = 'https://metoc.ndbc.noaa.gov/web/guest/jtwc'
var folder = DriveApp.getFolderById(Google_DRive_ID);
var exportUrl = RESOURCE_URL
var data = UrlFetchApp.fetch(exportUrl)
folder.createFile(FILE_NAME, data)
When I saw the source of https://metoc.ndbc.noaa.gov/web/guest/jtwc, it was found that the source you want is included in iframe with the id="_48_INSTANCE_0SiamlX2KcM6_iframe". The source URL is src="/ProductFeeds-portlet/img/jtwc/html/coop.jsp?". When your script is modified using the URL, it is as follows.
Modified script :
var root = "https://metoc.ndbc.noaa.gov";
var src = "/ProductFeeds-portlet/img/jtwc/html/coop.jsp?"; // You can also use "/ProductFeeds-portlet/img/jtwc/html/coop.jsp"
var FILE_NAME = 'data.txt'
var Google_DRive_ID = 'your google drive folder id'
var RESOURCE_URL = root + src;
var folder = DriveApp.getFolderById(Google_DRive_ID);
var exportUrl = RESOURCE_URL
var data = UrlFetchApp.fetch(exportUrl)
folder.createFile(FILE_NAME, data)
If I misunderstand your question, I'm sorry.