transferir transferencia tiempo quien pueden propietario personas pasar otra nuevo mismo google editar documento cuántas cuenta copiar como archivos google-apps-script

google-apps-script - transferencia - transferir google drive a otra cuenta



Transferir la propiedad de un archivo a otro usuario en Google Apps Script (4)

He creado una pequeña interfaz de usuario de subida que incluyo en una página de Google Sites. Permite que un usuario cargue un documento. Dado que el script se publica, se ejecuta en mi cuenta y el archivo subido se carga en mi unidad de Google. Puedo desde el script de aplicaciones agregar la persona que cargó el archivo como editor, pero lo que me gustaría hacer es convertirlo en el propietario de un archivo. (desde el script de aplicaciones puede hacer un .getOwner () en un archivo ... pero no un .setOwner () ..... ¿Alguien sabe una solución alternativa?

Gracias,

Daniel


¡Probar esto! (al menos funcionó para mí)

var newFolder = DriveApp.createFolder(folderName).addEditor(ownerEmail).setOwner(ownerEmail).addEditor(group.getEmail()).removeEditor(Session.getActiveUser().getEmail());

Lo anterior crea una carpeta y agrega un nuevo editor, establece que el nuevo editor sea el propietario, agrega otro grupo a los editores y finalmente elimina al usuario que acaba de crear la carpeta de los editores.


Me di cuenta de una solución alternativa: no estoy seguro de si es exactamente lo que están buscando. Simplemente dé acceso a la cuenta a la que le gustaría cambiar la propiedad. Acceda al documento / formulario / etc. de esa cuenta y luego haga una copia de dicho documento. Ahora eres el propietario. Tendrás que volver a invitar a otros.


Actualizado 12 de septiembre de 2016:

Este código usa una cuenta de servicio a la que se le ha otorgado la Delegación de autoridad de dominio de Google Apps . Esto le permite cambiar el propietario de cualquier archivo propiedad de cualquier usuario en el dominio. Este código usa la biblioteca Google apps-script-oauth2 de Eric Koleda.

var PRIVATE_KEY = PropertiesService.getScriptProperties().getProperty(''PRIVATE_KEY''); var CLIENT_EMAIL = PropertiesService.getScriptProperties().getProperty(''CLIENT_EMAIL''); /** * Transfers ownership of a file or folder to another account on the domain. * * @param {String} fileId The id of the file or folder * @param {String} ownerEmail The email address of the new owner. */ function transferOwnership(fileId, ownerEmail) { var file = DriveApp.getFileById(fileId); var currentOwnerEmail = file.getOwner().getEmail(); //the user that we need to impersonate var service = getService(currentOwnerEmail); if (service.hasAccess()) { var url = ''https://www.googleapis.com/drive/v2/files/'' + fileId + ''/permissions''; var payload = {value: ownerEmail, type: ''user'', role: ''owner''}; var options = {method: "post", contentType: "application/json", headers : { Authorization: ''Bearer '' + service.getAccessToken() }, payload: JSON.stringify(payload)//, ,muteHttpExceptions: true }; //debugger; //throw ''test my errors''; var response = UrlFetchApp.fetch(url, options); if (response.getResponseCode() === 200 || (response.getResponseCode() === 400 && response.getContentText().indexOf(''were successfully shared'')) ) { return response.getContentText(); } if (response.getResponseCode() === 401 && response.getContentText().indexOf(''Invalid Credentials'')) { throw ''Unable to transfer ownership from owner '' + currentOwnerEmail + '' ... '' + ''Please make sure the file/'s owner has a Google Apps license (and not a Google Apps Vault - Former Employee license) and try again.''; } throw response.getContentText(); } else { throw service.getLastError(); } } /** * Reset the authorization state, so that it can be re-tested. */ function reset() { var service = getService(); service.reset(); } /** * Configures the service. */ function getService(userEmail) { return OAuth2.createService(''GoogleDrive:'' + userEmail) // Set the endpoint URL. .setTokenUrl(''https://accounts.google.com/o/oauth2/token'') // Set the private key and issuer. .setPrivateKey(PRIVATE_KEY) .setIssuer(CLIENT_EMAIL) // Set the name of the user to impersonate. This will only work for // Google Apps for Work/EDU accounts whose admin has setup domain-wide // delegation: // https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority .setSubject(userEmail) // Set the property store where authorized tokens should be persisted. .setPropertyStore(PropertiesService.getScriptProperties()) // Set the scope. This must match one of the scopes configured during the // setup of domain-wide delegation. .setScope(''https://www.googleapis.com/auth/drive''); }

Respuesta anterior (obsoleta ahora ya que la API de la lista de documentos está en desuso):

Puede lograr esto en Google Apps Script accediendo a la API de la Lista de documentos utilizando el protocolo raw atom xml. Debes ser un súper administrador del dominio. Aquí hay un ejemplo que funciona para mí:

/** * Change Owner of a file or folder * Run this as admin and authorise first in the script editor. */ function changeOwner(newOwnerEmail, fileOrFolderId){ var file = DocsList.getFileById(fileOrFolderId); var oldOwnerEmail = file.getOwner().getEmail(); if (oldOwnerEmail === newOwnerEmail) { return; } file.removeEditor(newOwnerEmail); var base = ''https://docs.google.com/feeds/''; var fetchArgs = googleOAuth_(''docs'', base); 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=''owner''/>" +"<gAcl:scope type=''user'' value=''"+newOwnerEmail+"''/>" +"</entry>"; fetchArgs.payload = rawXml; fetchArgs.contentType = ''application/atom+xml''; var url = base + encodeURIComponent(oldOwnerEmail) + ''/private/full/''+fileOrFolderId+''/acl?v=3&alt=json''; var content = UrlFetchApp.fetch(url, fetchArgs).getContentText(); } //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("anonymous"); oAuthConfig.setConsumerSecret("anonymous"); return {oAuthServiceName:name, oAuthUseToken:"always"}; }


Desafortunadamente, el script de Apps no admite el cambio de propietario de un archivo. El Issue 74 es una solicitud de función para agregar esta capacidad, y si eres el protagonista del problema, mostrarás tu apoyo a la función y recibirás notificaciones de las actualizaciones.

------ EDITADO ------

Ahora hay un método práctico llamado setOwner, que se puede encontrar aquí: https://developers.google.com/apps-script/reference/drive/file#setOwner(User)

También existe la posibilidad de pasar la dirección de correo electrónico del nuevo propietario en lugar del objeto Usuario, lo que es aún más útil en algunos casos: https://developers.google.com/apps-script/reference/drive/file#setOwner(String)