Drive API - file or folder access timeout - google-apps-script

I have a simple script to get files from Drive and print. When I run this it runs for about 400-500 seconds and I am getting timeout error.
I have two google accounts. Same script works in account-1(testing account) but not in account-2(main account).
Any help in isolating this issue would be more helpful.
Tried stepping through debugger the control comes back again and again to line-4 (file.hasNext()). How do I debug and make this script work?
My goal: to open specific file in the drive given a file name.
function myHelloWorld() {
Logger.log("Hello world\n");
var files = DriveApp.getFiles();
if (files.hasNext()) {
Logger.log("There are files\n");
}
}
Note:
1) Permission to run this script in both accounts were allowed (as part of first run).
2) No log messages were generated (View->Logs)
3) Timeout error was found in (View->Execution transcript)

Code works fine
#KarthikMS - there's nothing wrong with the code. It works perfectly fine from my app: it's debugging nicely - see here:
It's logging as expected
And you can also see the logs: it's running nicely too:
The code: do you want it to iterate?
I suspect that you want it to iterate through all the files? If so you need to use a while() statement and not an if statement. Then it will iterate through all the files. Something like this
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}
Have you given this script permission to access your google drive?
You will need to authenticate the script to access your google drive. See here:
https://developers.google.com/apps-script/guides/services/authorization
I hope this helps?

It works okay:
Try it this way:
function myFiles()
{
var files = DriveApp.getFiles();
while(files.hasNext())
{
var fi=files.next();
Logger.log('FileName: %s',fi.getName());
}
}

Related

How to open an url and save a file sent as response (excel) directly to google drive with google script

Hello and thanks for your time.
Below you will find a link (request) for the data/excel file that I would like to save directly to my google drive and in the future import to google sheets:
https://digital.feprecisionplus.com/corppen/en-GB/cp-am/DownloadTool/GetPriceHistoryFile?modelString={%22GrsProjectId%22:%2236800083%22,%22ProjectName%22:%22corppen%22,%22ToolId%22:16,%22LanguageId%22:%221%22,%22LanguageCode%22:%22en-GB%22,%22OverrideDocumentCountryCode%22:null,%22forSaleIn%22:%22%22,%22FSIexclCT%22:%22%22}&filtersString={%22TypeCode%22:%22FA:N6SQ%22,%22FundName%22:%22JLR%20Bond%22,%22BaseCurrency%22:%22GBX%22,%22PriceType%22:1,%22TimePeriod%22:%22%22,%22StartDate%22:%22Mon%20Mar%2001%202021%22,%22EndDate%22:%22Thu%20Mar%2004%202021%22}
I tried google script below ( "my_URL" to be replaced with the link above)
function uploadFile() {
var blob = UrlFetchApp.fetch("my_URL").getBlob()
file = DriveApp.getFolderById("my_FolderID").createFile(blob);
}
but I am getting "Exception: Invalid argument: "my_URL"" response.
Would anyone be able to help me with getting that file saved to drive?
Cheers
Modification points:
When I tested your script using your URL, no error occurs. The XLSX file could be created. But from but I am getting "Exception: Invalid argument: "my_URL"" response., I thought that you might have used https://digital.feprecisionplus.com/corppen/en-GB/cp-am/DownloadTool/GetPriceHistoryFile?modelString={%22GrsProjectId%22:%2236800083%22,%22ProjectName%22:%22corppen%22,%22ToolId%22:16,%22LanguageId%22:%221%22,%22LanguageCode%22:%22en-GB%22,%22OverrideDocumentCountryCode%22:null,%22forSaleIn%22:%22%22,%22FSIexclCT%22:%22%22}&filtersString={%22TypeCode%22:%22FA:N6SQ%22,%22FundName%22:%22JLR%20Bond%22,%22BaseCurrency%22:%22GBX%22,%22PriceType%22:1,%22TimePeriod%22:%22%22,%22StartDate%22:%22Mon%20Mar%2001%202021%22,%22EndDate%22:%22Thu%20Mar%2004%202021%22} as the URL. If it's so, such error occurs.
In this case, please test the URL of https://digital.feprecisionplus.com/corppen/en-GB/cp-am/DownloadTool/GetPriceHistoryFile?modelString=%7B%22GrsProjectId%22:%2236800083%22,%22ProjectName%22:%22corppen%22,%22ToolId%22:16,%22LanguageId%22:%221%22,%22LanguageCode%22:%22en-GB%22,%22OverrideDocumentCountryCode%22:null,%22forSaleIn%22:%22%22,%22FSIexclCT%22:%22%22%7D&filtersString=%7B%22TypeCode%22:%22FA:N6SQ%22,%22FundName%22:%22JLR%20Bond%22,%22BaseCurrency%22:%22GBX%22,%22PriceType%22:1,%22TimePeriod%22:%22%22,%22StartDate%22:%22Mon%20Mar%2001%202021%22,%22EndDate%22:%22Thu%20Mar%2004%202021%22%7D.
{ and } are encoded to %7B and %7D, respectively. (I thought that this might be the reason of your issue.)
When above points are reflected to your script, it becomes as follows.
Modified script:
function uploadFile() {
var url = "https://digital.feprecisionplus.com/corppen/en-GB/cp-am/DownloadTool/GetPriceHistoryFile?modelString=%7B%22GrsProjectId%22:%2236800083%22,%22ProjectName%22:%22corppen%22,%22ToolId%22:16,%22LanguageId%22:%221%22,%22LanguageCode%22:%22en-GB%22,%22OverrideDocumentCountryCode%22:null,%22forSaleIn%22:%22%22,%22FSIexclCT%22:%22%22%7D&filtersString=%7B%22TypeCode%22:%22FA:N6SQ%22,%22FundName%22:%22JLR%20Bond%22,%22BaseCurrency%22:%22GBX%22,%22PriceType%22:1,%22TimePeriod%22:%22%22,%22StartDate%22:%22Mon%20Mar%2001%202021%22,%22EndDate%22:%22Thu%20Mar%2004%202021%22%7D";
var blob = UrlFetchApp.fetch(url).getBlob();
file = DriveApp.getFolderById("my_FolderID").createFile(blob);
}
Before you use this script, please replace my_FolderID with your folder ID.

Issues reading shared folder using DriveApp when other users run the Apps Script

I've got a Google Sheet that uses App Script to read data from an external spreadsheet saved in a shared folder. There are multiple files in that folder (all named the same thing). I have one particular function that reads all files in a given folder and returns the id of the most recent one (which I then use to load the data from that file else where in the script).
The script was created using my corporate account and works perfectly when I execute it myself. However when other users try to run the same script they receive the follow error message:
TypeError: Cannot read property '1' of undefined
at get_latest_file_id(Code:380:21)
at get_timesheet_data(Code:19:12)
at unitTest(Code:78:3)
The error is obviously related to the fact that result[0][1] is undefined, however I'm not sure why. I suspect it has to do with permissions and my use of DriveApp. I've tested the following things:
I have tried using my personal Gmail account to run the script and read the file stored shared in a folder stored on my corporate account, this works fine.
I've tried moving the shared file to my personal account and run the script from my corporate account, this too works fine.
However if I use one of my colleagues accounts it doesn't work regardless if the file is stored on my corporate account (which is part of the same org) or on my personal account. When users run the script I get the usual "this developer isn't verified" and you have to choose to give access the first time the script is being run, but other than that I don't get any error messages that seems to point to permission so I'm not sure how to debug/proceed.
I'd appreciate any direction you could give me and suggestions for possible work arounds.
//RETREIVES THE FILE ID OF THE MOST RECENTLY CREATED FILE WITH A SPECIFIC NAME FROM A SPECIFIC FOLDER.
function get_latest_file_id(foldername,filename) {
var folder = DriveApp.getFolderById('XXXXXXXXXXXXXXXX');
var files = DriveApp.getFilesByName(filename);
var result = [];
while (files.hasNext()) {
var file = files.next();
result.push([file.getDateCreated(),file.getId()]);
}
result.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
var id = result[0][1];
// Logger.log('Most recent ID:', id);
return id;// return most recent file IDs
}//ENDS
Try This
function get_latest_file_id(foldername,filename) {
var folder = DriveApp.getFolderById('XXXXXXXXXXXXXXXX');
var files = DriveApp.getFilesByName(filename);
var result = [];
while (files.hasNext()) {
var file = files.next();
result.push([file.getDateCreated(),file.getId()]);
}
result.sort(function(x,y){
var xp = x[0];
var yp = y[0];
return xp == yp ? 0 : xp > yp ? 1 : -1;
var id = result[0][1];
});
}
Adding this answer for better visibility, specially for people that in the future may find this question.
The error TypeError: Cannot read property '1' of undefined means that result[0] is undefined. Because we are only populating the result using push, this means that the array is empty.
The reason for that is that the user doesn't see any files in the folder. Making sure that the users can access the folder and files will fix the issue. In this case, OP invited the users to the folder, which fixed the issue.

Inserting Image into Google Sheets from Google Drive using Apps Script

I have been trying for 9 days to add an image that is uploaded to my drive (via the use of a google form) into my Google sheet using Apps Script, but it isn't working and I have no idea why, this is my code below:
function getImage(){
var folderImage = DriveApp.getFolderById("0B7gxdApLS0TYfm1pRHpHSG4yTm96bm1PbTZQc1VmdGpxajY4N1J4M1gtR1BiZ0lOSl9NMjQ");
Logger.log(folderImage.getFiles().next().setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW));
Logger.log(folderImage.getFiles().next().getSharingAccess());
Logger.log(folderImage.getFiles().next().getSharingPermission());
var imageFile = folderImage.getFiles().next().getBlob();
detailSheet.insertImage(imageFile, 1, 13);
}
I have even tried making the sharing and access permissions of the to be as open as possible but I keep getting this error message:
"We're sorry, a server error occurred. Please wait a bit and try again"
I find the error message ambiguous which leads me at a dead end. Usually the message gives me a good idea of where I have gone wrong.
I believe my code is correct, and during my research I have found no definitive reason this shouldn't work. Does anybody know where I am going wrong?
A solution would be great but preferably a critique on my code so I can learn :)
Couple of issues with your script:
You never bind to a specific file, so to work with the same file you have to reinitialize the iterator each time.
You don't verify its mimetype prior to using it as an image
An example that resolves those issues:
function addFolderPNGs_(sheet, folderId) {
const folder = folderId ? DriveApp.getFolderById(folderId) : DriveApp.getRootFolder(); // scope only to the root or given folder.
const imgs = folder.getFilesByType(MimeType.PNG);
var targetRow = sheet.getLastRow();
while (imgs.hasNext()) {
var img = imgs.next();
Logger.log(img.getName())
sheet.insertImage(img.getBlob(), 1, ++targetRow);
}
}
References
getFilesByType is either folder-specific (above) or operates on all of Google Drive
DriveApp
Folder
MimeTypes
Sheet#insertImage

Why Google Apps Script hangs on calling next() function

Today I can't run scripts connected to a specific Google Spreadsheet which contains .next() function calls, which I use to access other Spreadsheets by name. It shows Running script Cancel Dismiss message at the top of spreadsheet until exceeding maximum execution time. The strange thing is that I have similar files for every day with exactly same scripts, and the one for yesterday works fine. I created MWE below. So, when I run it I can get the alerts for the first 2 messages, but not the 3rd one.
function test_script_hanging() {
var ui = SpreadsheetApp.getUi();
ui.alert("before getting files by name");
var getFilefile = DriveApp.getFilesByName("file");
ui.alert("after getting files by name");
var getID = getFilefile.next().getId();
ui.alert("after getting Id");
}
In some situations I notice an error message saying something like "Authorization is needed to perform this action" on the line where the .next() function is being called. I tried to revoke authorization of the file and give authorization again, but that didn't help. I tried to give full access to a given script, but couldn't google the way to do it.
Maybe I can add some more functions in my script to require full access during authorization, and maybe that will help to run my main function.
My questions are:
Why the script hangs?
How to fix this?
Can such kind of things (randomly and without any notice) happen in a free version of Google account?
This works for me:
var fldr = DriveApp.getFolderById(folderID)
var file = fldr.getFilesByName(filename);
while(file.hasNext())
{
var fi = file.next();
if(fi.getName() == filename)
{
var id=fi.getId();
}
}

When i open a generated PDF it results in a error using the new spreadsheets

I brought the code down in the function below to the bare minimum and the file creation of the PDF is ok.
But if I use a file id created with the “new spreadsheet” setting on. The PDF opens with a error. If I switch back to the old version of the spreadsheets the file is actually ok.
Must be something wrong with the blob creation? Is this a know issue?
Thanks,
function alone() {
try {
var spreadSheetFile = DriveApp.getFileById("1lljK6wItraoMhI4NM3kueN69LZ3MSs-2mCWiM-W7tEU");
var pdf = spreadSheetFile.getAs('application/pdf');
} catch (e) {
Logger.log ("Catched something: "+e+"\n"+e.stack);
}
DriveApp.createFile(pdf);
}
While there are multiple issues in the tracker regarding getAs(), none seem specific to the new Sheets. I suggest that you enter a new issue.
There are also many known problems with Apps Script support for the new Sheets offering. Again, no mention of File.getAs() there.