Mike79
Mike79

Reputation: 89

Check if google document is neither edited nor viewed

Does google app script offers a class with a method allowing to check if a document with a given id is edited or viewed.

I'm build an application that allows user to delete google document from the google disk but before moving file to trash I would like to check if the file is neither edited nor viewed.

The similiar question has been posted here, but no solution provided. Getting a list of active file viewers with apps script

Please note the the lock service is not a solution to this problem.

Upvotes: 1

Views: 63

Answers (1)

Alan Wells
Alan Wells

Reputation: 31300

The Google Drive API must be used to get revisions to a file. The built-in DriveApp service, which is different than the Advanced Drive service, has no capability to get file revisions information, except for getLastUpdated() method, which gets the date when the file was last updated. The Drive API can be used within Apps Script by using the Advanced Drive service.

Advanced Services within Apps Script must be enabled. Click the "Resources" menu, and then choose the Advanced Google services menu item.

After you have enabled the Advanced Drive Service, the "Drive" class will show up in the context menu. Use Ctrl + Space Bar to have a list of available classes displayed in the code editor.

To get revisions to a specific file, use the Revisions class of the Advanced Drive service.

Drive.Revisions.list(fileId)

Check for no revisions:

function trash_If_No_Changes_(fileID) {
  var revs;

  revs = Drive.Revisions.list(fileID);

  if (revs.items && revs.items.length === 0) {
    trashFile_(fileID);
  }

}

The Advanced Drive Service can also delete a file without sending it to the trash first.

function trashFile_(fileID) {
  var i;
  /*
    This deletes a file without sending it to the trash
  */

  for (i=1;i<4;i++) {
  try{
    Drive.Files.remove(fileID);//deletes a file without sending it to the trash
    return;//return here instead of break because if this is successful the task is completed
  } catch(e) {
    if (i!==3) {Utilities.sleep(i*1500);}
    if (i>=3) {
      errHndl_(e,'trashFile','Can not delete the file by ID');
      return false;
    }
  };
  }
}

If you want to avoid the need to ask the user for broad access to their Drive, then you may want to try setting the scope:

https://www.googleapis.com/auth/drive.file

In the appsscript.json manifest file.

Upvotes: 3

Related Questions