Search code examples
phpgoogle-cloud-platformgoogle-drive-apigoogle-oauthservice-accounts

Use google drive API to change the owner of a file created with an account service


I used an service account to upload files to a shared folder in google drive.

After some time I discovered that files owned by service account consumed the service's account drive storage (my bad) and now I have run out drive space for the service account .

I already delegated domain-wide authority to the service account so new files will be owned by me and use my personal storage quota.

Did this: Delegating domain-wide authority to the service account

and this How to use the API Key for Google Drive API from PHP via the google/apiclient

To avoid errors and confusion in the future I'd like to change the owner of older files. I keep getting this error:

{ "error": { 
    "code": 400, 
    "message": "Bad Request. User message: \"You can't change the owner of this item.\"", 
    "errors": [ {
       "message": "Bad Request. User message: \"You can't change the owner of this item.\"", 
       "domain": "global", 
       "reason": "invalidSharingRequest" 
    } ] 
  } 
}

Here's my code using PHP Client

$client = new Google_Client();
$client->setApplicationName('My Name');
$client->setScopes(Google_Service_Drive::DRIVE);
$client->setAuthConfig($my_credentials);
$client->setAccessType('offline');
//$client->setSubject('my_personal_account');

$service = new Google_Service_Drive($client);

$newPermission = new Google_Service_Drive_Permission();
$newPermission->setEmailAddress('my_personal_account');
$newPermission->setType('user');
$newPermission->setRole('owner');

$service->permissions->create(
  $fileId, 
  $newPermission, 
  array("fields" => "id", "transferOwnership" => true)
);

I've got the same error with or without setSubject in the client. I've tried using

$newPermission->setRole('writer');
$newPermission->setPendingOwner(true);

but it didn't work.


Solution

  • Transfering the file ownership can only be done between accounts from the same domain. The error occurs because the service account and your account don't belong to the same domain.

    If you have access to a Shared Drive and are able to add users with add files privileges, add the service account and make it move the files to the Shared Drive.

    Related

    Other related