1
votes

I want to share google drive files to other google account user's email id by using google drive PHP api. Sometimes file is sharing with that person and he can view/read that file in his drive, but sometimes I'm unable to share file with him. I'm unabe to find reason of this inconsistency. If file is not sharing then I'm getting following error:

An error occurred: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "internalError",
    "message": "Internal Error. User message: \"An internal error has occurred which prevented the sharing of these item(s): 1544784669.1.junkfile.pdf\""
   }
  ],
  "code": 500,
  "message": "Internal Error. User message: \"An internal error has occurred which prevented the sharing of these item(s): 1544784669.1.junkfile.pdf\""
 }
}
2
Can you provide the detail information about sometimes I'm unable to share file with him.? Although you shared your file to user "A", the file was not shared and user "A" couldn't access to the file. Is my understanding correct? - Tanaike
@Tanaike Yes, I want to share a file with user "A", and it is sharing successfully, and user "A" can access that file also from his drive. But suppose I want to share again one more file with same user, then it is not sharing with that user, means user is getting {"code": 500, "message": "Internal Error. User message: \"An internal error has occurred which prevented the sharing of these item(s)} this error. Why it is not consistent, is there any configuration which I'm missing or what ? - vidya devi
Thank you for replying. I noticed that the answer has already been posted. I think that it will resolve your issue. - Tanaike

2 Answers

1
votes

I've got answer for my own question, after uploading the file into drive we will get $file_google_id and we have to wait for 10 seconds using sleep(10), then only we can share that file with anyone.

 sleep(10);
    $permission=insertPermission($service,$file_google_id,$email_id,'user','reader');
    function insertPermission($service,$fileId,$value,$type,$role) {

        $newPermission = new Google_Service_Drive_Permission();

        $newPermission->setEmailAddress($value); 
        $newPermission->setType($type);
        $newPermission->setRole($role);

        try {
            return $service->permissions->create($fileId, $newPermission);

        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
        return NULL;
    }

Thanks

0
votes

If you are trying to upload a file and share it with another account at the same time, you need to wait a few seconds before performing the permissions request. I could achieve it in my Android app like this (using Kotlin and RxJava):

private fun uploadFile(accessToken: String, fileName: String, fileContent: String) {
  Observable.just(Unit)
    .subscribeOn(Schedulers.io())
    .subscribe({
      val httpTransport = NetHttpTransport()
      val credential = Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
          .build()
      credential.accessToken = accessToken
      val service = Drive.Builder(httpTransport, JacksonFactory.getDefaultInstance(),
          credential)
          .setApplicationName("Your App Name")
          .build()
      val fileMetadata = File()
      fileMetadata.name = fileName
      val localFile = createFile(fileName, fileContent)
      val mediaContent = InputStreamContent("text/plain", localFile);
      val file = service.files().create(fileMetadata, mediaContent)
          .setFields("id")
          .execute()
      Log.d(TAG, "File ID: " + file.id)

      Observable.interval(10, TimeUnit.SECONDS)
          .take(1)
          .subscribe {
            val callback = object : JsonBatchCallback<Permission>() {

              @Throws(IOException::class)
              override fun onFailure(e: GoogleJsonError, responseHeaders: HttpHeaders) {
                Log.d(TAG, "error: ${e.message}")
              }

              @Throws(IOException::class)
              override fun onSuccess(permission: Permission, responseHeaders: HttpHeaders) {
                Log.d(TAG, "Permission ID: ${permission.id}")
              }
            }
            val batch = service.batch()
            val userPermission = Permission()
                .setType("user")
                .setRole("writer")
                .setEmailAddress("[email protected]")
            service.permissions().create(file.id, userPermission)
                .setFields("id")
                .queue(batch, callback)
            batch.execute()
          }
    }) {
      Log.d(TAG, "error: ", it)
    }
  }

private fun createFile(fileName: String, fileContent: String): InputStream? {
  try {
    val outputStreamWriter = OutputStreamWriter(
        application.openFileOutput(fileName, Context.MODE_PRIVATE))
    outputStreamWriter.write(fileContent)
    outputStreamWriter.close()
    return application.openFileInput(fileName)
  } catch (e: IOException) {
    Log.e(TAG, "File write failed: ", e)
  }
  return null
}