Lock files in Google Drive

Stéphane Giron
2 min readOct 9, 2020

--

Google just release a new option to lock file to prevent editing.

Google Drive API details

This new feature is available by API and can be used in V2 and V3.

The settings in json Files object to check are these ones :

"contentRestrictions": [
{
"readOnly": boolean,
"reason": string,
"restrictingUser": {
"kind": "drive#user",
"displayName": string,
"picture": {
"url": string
},
"isAuthenticatedUser": boolean,
"permissionId": string,
"emailAddress": string
},
"restrictionDate": datetime,
"type": string
}
]

By default in Google Drive V2 request the “contentRestrictions” setting is not included you have to request it explictely.

Check if a Google Drivle file is locked

function getFileLock(id) {
var fileId = id || FILE_ID;
var file = Drive.Files.get(fileId,{"fields":"contentRestrictions"});
// Logger.log(file.contentRestrictions)
if(!file.contentRestrictions){
// No restriction set
Logger.log('File is not locked.')
}else{
var locks = file.contentRestrictions;
for( var i = 0 ; i < locks.length ; i++ ){
var lock = locks[i];
if(lock.readOnly){
// File is locked.
Logger.log('File is locked by '+lock.restrictingUser.displayName + ' since ' + lock.restrictionDate)
Logger.log('Reason : ' + lock.reason)
}else{
Logger.log('File is not locked')
}
}
}
}

We have to check if “contentRestrictions” exist because by default if nothing is set the parameter is not set.

Lock a Google Drive File by API

function setFileLock(){
var fileId = FILE_ID;
var reason = 'We lock this file for testing ;-)'

var resource = {
contentRestrictions : [{readOnly:true,reason:reason}]
}

var file = Drive.Files.patch(resource, fileId);
getFileLock(fileId)
}

Unlock a Google Drive file by API

function deleteFileLock(){
var fileId = FILE_ID;

var resource = {
contentRestrictions : [{readOnly:false}]
}
var file = Drive.Files.patch(resource, fileId);
getFileLock(fileId)
}

It is pretty simple to use lock/unlock in Google Drive.

You can find this code in GitHub : link.

--

--