Search code examples
phpgoogle-drive-api

How to Temporarily Make a Google Drive File Public Using Google Drive API?


I'm working on a project where I need to make a Google Drive file temporarily public for download and then make it private again. I'm using the Google Drive API in PHP.

Here's the code I'm currently using to get the download link of the file:

/**
 * Gets the download link from Drive (without going through our server).
 * @param string $fileId id of the file to be searched.
 * @return string Direct download link of the file.
 */
public function getWebContentLink(string $fileId): string {
    self::setPermissionPublic($fileId);

    $file = $this->service->files->get(
        $fileId, [
            'fields' => 'webContentLink'
        ]
    );

    return $file->getWebContentLink();
}

/**
 * Sets a file's permissions to public.
 * @param string $fileId id of the file to be made public.
 * @return void
 */
private function setPermissionPublic(string $fileId): void {
    $permission = new \Google\Service\Drive\Permission([
        'role' => 'reader',
        'type' => 'anyone'
    ]);
    $permission = $this->service->permissions->create($fileId, $permission);
}

However, this makes the file permanently public. I would like to make it public only for a short period of time (e.g., 1 minute) and then make it private again.

I've looked into the Google Drive API documentation and I'm aware that there isn't a built-in method for temporary links. I've also tried using the expireDate field in the permissions resource, but it didn't work as expected.

Moreover, I'm expecting a high volume of requests (over 1000), so I need a solution that won't overload the server. I also know that Google Drive isn't the best choice for that, but can I get anything that helps my needs?

Any help would be greatly appreciated. Thank you!


Solution

  • private function setPermissionPublic(string $fileId): void {
        $permission = new \Google\Service\Drive\Permission([
            'role' => 'reader',
            'type' => 'anyone'
        ]);
        $permission = $this->service->permissions->create($fileId, $permission);
    }
    

    The code above sets a file to public there is no way to limit how long it is public. If you want to make the code private again after a minute. I suggest that you simply run a permissins.delete after a minute to have the file reverted to private.