renakre
renakre

Reputation: 8291

Copying a file and adding a permission in the same batch request in Google Drive Api v3

I have the following code that I want to chance using batch. In this code, first I create a copy of a file, and then using the id of the new file, I am adding a permission.

  File readOnlyFile = new File();
  readOnlyFile.Name = newFileName.Replace(' ', '-') + "_assess";
  readOnlyFile.Parents = new List<string> { targetFolderId };
  FilesResource.CopyRequest fileCreateRequest = _driveService.Files.Copy(readOnlyFile, fileId);
  string readOnlyFileId = fileCreateRequest.Execute().Id;

  if (readOnlyFileId != null)
  {
      newPermission.ExpirationTime = expirationDate;
      newPermission.Type = "anyone";
      newPermission.Role = "reader";
      PermissionsResource.CreateRequest req = _driveService.Permissions.Create(newPermission, readOnlyFileId);
      req.SendNotificationEmail = false;
      req.Execute();
  }

However, I am puzzled when trying to use batch for this task since I will need the id of the newly copied file to add permission. Below is my initial attempt where I do not know how to proceed after batch.Queue(fileCreateRequest, callback). I can add new action to the batch to add permission. But, I do not know how to get the id of the file. Any suggestions? I need to do this for three different files.

 var batch = new BatchRequest(_driveService);
 BatchRequest.OnResponse<Permission> callback = delegate (
     Permission permission,
     RequestError error,
     int index,
     System.Net.Http.HttpResponseMessage message)
 {
     if (error != null)
     {
         // Handle error
         Console.WriteLine(error.Message);
     }
     else
     {
         Console.WriteLine("Permission ID: " + permission.Id);
     }
 };


 Permission newPermission = new Permission();

 File readOnlyFile = new File();
 readOnlyFile.Name = newFileName.Replace(' ', '-') + "_assess";
 readOnlyFile.Parents = new List<string> { targetFolderId };
 FilesResource.CopyRequest fileCreateRequest = _driveService.Files.Copy(readOnlyFile, fileId);
 batch.Queue(fileCreateRequest, callback);

Upvotes: 1

Views: 228

Answers (1)

Jacques-Guzel Heron
Jacques-Guzel Heron

Reputation: 2598

To upload and to configure permissions of a file are two different operations that cannot be batched together. Your approach is correct, you only have to use set up the permissions in a second call.

After uploading the files and retrieving the ids as you do, you have to create a second call to create the permissions.

There is no way to do it in a single request, because for setting up the permissions you need the id of the file; and that is only created after finishing the upload. If you need any more clarification, please ask me without hesitating.

Upvotes: 1

Related Questions