Google Apps Script: Documents and Files Sharing Between the Google Apps Domain


The Google Documents List API allows client applications to view and manipulate files in a user’s Documents List.

In this blog we would learn how to share documents and files between the Google Apps Domain.

When our application requests non-public user data, it must include an authorization token. The token also identifies your application to Google. Requests to the Google Documents List Data API for non-public user data must be authorized by an authenticated user. Here, OAuth authorization is used to authorize Documents List Data API as following:

name='docs';
scope='https://docs.google.com/feeds/';
function googleOAuth_(name,scope) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name);
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey(consumerKey);
  oAuthConfig.setConsumerSecret(consumerSecret);
  return {oAuthServiceName:name, oAuthUseToken:"always"};
}

Document and collection sharing is controlled via the access control list feed. Access control lists are just basic lists that show who has access to a given resource. In the ACL feed, different type of roles scopes are available for a given document or folder.

Document’s resource_id is required to share any document with other. Resource_id is the alphanumeric key, which shows in the url as ‘/d/<…resource_id…>/’. Authenticated user’s documents and files’s resource_id can be accessed by sending an authorized GET request as following:

var url = 'https://docs.google.com/feeds/<user_email_id>/private/full?v=3&alt=json';
var urlFetchResult = UrlFetchApp.fetch(url, fetchArgs);

The result is a feed that lists the user’s documents and files, each entry in the feed represents a resource associated with the user.
We can get particular docs’s resource_id by parse the json result. Then use split() to get document’s resource_id in each entry as follow:

var json = Utilities.jsonParse(urlFetchResult.getContentText());
var entry = json.feed.entry;
for(var i in entry){
  var docId = {};
  for(var j in entry[i]){
    tempDoc.id = entry[i].id.$t.split('%3A')[1];
  }

Post the following request to share document with user:


POST https://docs.google.com/feeds/<user_email_id>/private/full/resource_id/acl
Authorization: <your authorization header here>

<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gAcl='http://schemas.google.com/acl/2007'>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/acl/2007#accessRule'/>
<gAcl:role value='<role_type>'/>
<gAcl:scope type='<scope>' value='<user2_email_id>'/>
</entry>

Here is the complete code:


var consumerKey='<domain_name>'
var consumerSecret='<domain_consumerSecret_key>'
var user1='<email_id>'  //Email_Id of the person, whose docs would be shared
var user2='<email_id>' //Email_Id of the person,to whom docs would be share

function DocumentSharing(){

  var base = 'https://docs.google.com/feeds/';
//oAuth
  var fetchArgs = googleOAuth_('docs', base);
  var url = base + user1+'/private/full?v=3&alt=json';
  var urlFetchResult = UrlFetchApp.fetch(url, fetchArgs);
  var json = Utilities.jsonParse(urlFetchResult.getContentText());
  var entry = json.feed.entry;
  var docs = [];

  fetchArgs.method = 'POST';
  var rawXml = "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gAcl='http://schemas.google.com/acl/2007'>"
  +"<category scheme='http://schemas.google.com/g/2005#kind' "
  +"term='http://schemas.google.com/acl/2007#accessRule'/>"
  +"<gAcl:role value='writer'/>"
  +"<gAcl:scope type='user' value='"+user2+"'/>"
  +"</entry>";
  fetchArgs.payload = rawXml;
  fetchArgs.contentType = 'application/atom+xml';

  for(var i in entry){
    var tempDoc = {};
    for(var j in entry[i]){
      tempDoc.id = entry[i].id.$t.split('%3A')[1];
      tempDoc.title = entry[i].title.$t;
    }
    docs.push(tempDoc);
    var url = base + user1+'/private/full/'+docs[i].id+'/acl?v=3&alt=json';
    try{
      var urlFetch = UrlFetchApp.fetch(url, fetchArgs);
    }
    catch(err){
      MailApp.sendEmail(user2,docs[i].title+"("+user2+")","",
      {htmlBody:"This user already has access to document   <b>"+docs[i].title+"</b>"})
    }
  }
}

//Google oAuth
function googleOAuth_(name,scope) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name);
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey(consumerKey);
  oAuthConfig.setConsumerSecret(consumerSecret);
  return {oAuthServiceName:name, oAuthUseToken:"always"};
}

This script would share your all documents and files with another user. It also sends a notification mail to user (to whom docs is shared). If that user already accessed that document , a 409 server error would occurred. Here, try-catch is used to resolve this problem.

To know more about it Click Here

About Ruchi Agarwal

Software Consultant at Knoldus Software LLP having around 2 year experience working in Scala and java. She has good understanding of various technologies like LiftWeb, Akka, Amazon EC2, jQuery, javascript, CSS etc. She is RAD (Rational Application Developer) for WebSphere Software and RFT (Rational Funtional Tester) for Java certified. She is a skilled professional focused on the basic business functions and creation of software. She has a firm understanding of design methodology. She likes to work with responsibility, dedication and perseverance, she has a facility to establish good interpersonal relationships and foremost she is loyal to her principles, ethics and always giving to the best of her caliber.
This entry was posted in Web and tagged . Bookmark the permalink.

One Response to Google Apps Script: Documents and Files Sharing Between the Google Apps Domain

  1. grant says:

    I want to to thank you for this wonderful read!! I absolutely enjoyed every
    little bit of it. I’ve got you book-marked to look at new stuff you post…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s