Script to change owner of a document in Google Docs

心已入冬 提交于 2019-12-01 01:41:37

Resolved this issue.

I removed the encodeURIComponent() methods, which is apparently not necessary for the URL. I also used the OAuthApp library (found here) to begin to construct the fetch options for the URLFetchApp.fetch() method. I'm not sure if only one or both of these fixes resolved the issue, but the script consistently works now so I'm a happy person.

Complete updated code below:

function changeOwner(newOwnerEmail, file)
{
  var fileId = file.getId();
  var oldOwnerEmail = file.getOwner().getEmail();

  if (oldOwnerEmail == newOwnerEmail) { return; }

  file.removeEditor(newOwnerEmail);  //should this be oldOwnerEmail?
  var base = 'https://docs.google.com/feeds/';

  var options = OAuthApp.getAuth('docs');

  options.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='owner'/>"
      +"<gAcl:scope type='user' value='"+newOwnerEmail+"'/>"
      +"</entry>";
  options.payload = rawXml;
  options.contentType = 'application/atom+xml';

  var API_KEY = getAPIKey();  
  var url = base + oldOwnerEmail+'/private/full/'+fileId+'/acl?v=3&alt=json&key='+API_KEY

  try 
  { 
    var result = UrlFetchApp.fetch(url, options);
    docsObject  = Utilities.jsonParse(result.getContentText());
  }
  catch (err) { Logger.log(err.message) }

}//end changeOwner()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!