AlexB
AlexB

Reputation: 2184

No item with the given ID could be found on makeCopy() in Google Apps Script

I have an add-on that lets the user download my templates from my drive to theirs provided the add-on is installed in their sheet or doc.

The function that should make a copy is as follows

function createFileCopy(id){
  var file = id.split('.');
  var docName = DriveApp.getFilesByName(file[0]);
  while (docName.hasNext()) {
    var file = docName.next();
    var fileId = file.getId();
    var fileName = file.getName();
  }

  Logger.log(fileId);
  var sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName(TEMPLATES_DATA);
  var data = sheet.getRange(1, 9, sheet.getLastRow()-1, 1).getValues();
  var pos = data.map(function (obj) { return obj[0]; }).indexOf(id);
  if(pos > -1){
//    var val = sheet.getRange("J" + (pos + 1)).getValue() + 1;
    var title = sheet.getRange("A" + (pos + 1)).getValue();
//    sheet.getRange("J" + (pos + 1)).setValue(val);
  }
  var newFile = DriveApp.getFileById(fileId).makeCopy('Copy of '+ title);
  return {
    title: newFile.getName(),
    url: newFile.getUrl()
  }

The problem is that when a user tries to make a copy he/she is getting an error `No item with the given ID could be found, or you do not have permission to access it.'

I have commented 2 lines, I thought that the issue was due to posting back the download increment to the original spreadsheet, but as it turns out this was not the only issue there.

It works fine inside the origin account BTW.

I have asked Add-on Advisor for help but was readdressed here instead.

Please help

Upvotes: 0

Views: 324

Answers (1)

TheAddonDepot
TheAddonDepot

Reputation: 8964

When a user installs an add-on it executes under that user's account. As such they cannot access your template spreadsheets unless they are granted permission to do so.

If you are comfortable sharing files with your end-users, you can programmatically grant/revoke permission to your templates by using an Advanced Service. These advanced services are merely wrappers for their corresponding APIs so in this case you need to leverage the Drive API V2 documentation to figure out how to add/remove permissions. The following guides and reference should help:

If sharing files is undesirable, you can opt to use a Service Account. Service Accounts are a special kind of account that you can create from the GCP API console. You can grant the service account access to your templates and then use the service account to retrieve the spreadsheet template as a Spreadsheet resource object in JSON format using the spreadsheet API. You can then use this resource object to create a user-owned copy of the spreadsheet without explicitly sharing your template. You can find more info on service accounts by checking other threads here on stackoverflow.

Upvotes: 1

Related Questions