google-drive-apigoogle-api-php-clientservice-accounts

Unable to transfer ownership of file from service account to google drive user


When attempting to transfer ownership I get the following error:

"domain": "global",
"reason": "invalidSharingRequest",
"message": "Bad Request. User message: \"You can't change the owner of this item.\""

Here is my code:

use Google_Client; 
use Google_Service_Drive;
use Google_Service_Drive_DriveFile;
use Google_Service_Drive_Permission;

public function uploadDocument() {

 $FOLDER_ID = 'my_folder_ID_string';

 $client = new Google_Client();
 $client->setAuthConfig(base_path('service_account_credentials.json'));
 $client->setScopes(array('https://www.googleapis.com/auth/drive'));

 $service = new Google_Service_Drive($client);

 $fileMetadata = new Google_Service_Drive_DriveFile(array(
                                                     'name' => 'Test.pdf',
                                                     'parents' => [$FOLDER_ID]
                                                    ));

 $content = file_get_contents(public_path('tmp/Test.pdf'));

 $file = $service->files->create($fileMetadata, array(
                                                    'data' => $content,
                                                    'mimeType' => 'application/pdf',
                                                    'uploadType' => 'multipart',
                                                    'fields' => 'id'
                                                     ));

  // Transfer Ownership
  $newPermission = new Google_Service_Drive_Permission();
  $newPermission->setRole('owner');
  $newPermission->setType('user');
  $newPermission->setEmailAddress('email@gmail.com');
  $optParams = array('transferOwnership' => 'true');

  $service->permissions->create($file->id, $newPermission, $optParams);

}

The folder is successfully uploaded to Google Drive in the shared folder (owner is 'email@gmail.com', service account is 'editor'), however the owner of the uploaded file is the service account and the editor is 'email@gmail.com'.


Solution

  • You cannot change the owner of a file located on a shared drive

    As per documentation:

    Files within a shared drive are owned by the shared drive, not individual users.

    Consequently, there is no need to "take away" the ownership from the service account.

    You can make give users any other role, e.g. organizer which would allow the user to move the file out of the shared drive and thus become the owner of the file.\

    UPDATE

    If the files are uploaded by the service account to a shared folder on the user's Drive rather than to a shared Drive, the situation is different.

    In specific: