Skip to content

Instantly share code, notes, and snippets.

@ryanotella
Last active August 29, 2015 14:19
Show Gist options
  • Save ryanotella/d1e22981275c9971c81f to your computer and use it in GitHub Desktop.
Save ryanotella/d1e22981275c9971c81f to your computer and use it in GitHub Desktop.
Using Google Drive API to restore files removed from shared folders
<?php
/**
* Requires "google/apiclient"
*/
class GoogleDriveRestore
{
/** @var Google_Client */
private $client;
/**
* It needs a list of the files to be restored.
*
* @see https://developers.google.com/admin-sdk/reports/v1/reference/activities
* @param $files
*/
public function restore($files)
{
foreach ($files as $file) {
$this->restoreDocument($file['owner'], $file['fileId'], $file['parentId']);
}
}
/**
* @param string $actor
* @return \Google_Auth_AssertionCredentials
*/
private function buildCredentials($actor)
{
$privateKeyPath = '../GoogleServiceAccount-59cce8265c72.p12';
if (!is_readable($privateKeyPath)) {
throw new \RuntimeException("Server must be fully configured to remove this item");
}
return new \Google_Auth_AssertionCredentials(
'[email protected]',
array('https://www.googleapis.com/auth/drive'),
file_get_contents($privateKeyPath),
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
$actor
);
}
/**
* @param $ownerEmailAddress
* @param $fileId
* @param $parentId
* @return Google_Service_Drive_DriveFile
*/
protected function restoreDocument($ownerEmailAddress, $fileId, $parentId)
{
$this->client = new \Google_Client();
$this->client->setAssertionCredentials($this->buildCredentials($ownerEmailAddress));
/** @var \Google_Auth_OAuth2 $auth */
$auth = $this->client->getAuth();
if ($auth->isAccessTokenExpired()) {
$auth->refreshTokenWithAssertion();
}
$drive = new \Google_Service_Drive($this->client);
$file = $drive->files->get($fileId);
if ($file->id !== $fileId) {
print "\n\033[1;31mFile ID didn't match\033[0m";
}
if ($this->hasParent($file, $parentId)) {
print "\n\033[1;33mAlready done\033[0m";
return $file;
}
$file = new Google_Service_Drive_DriveFile();
$file = $drive->files->patch($fileId, $file, array('addParents' => "$parentId"));
if ($this->hasParent($file, $parentId)) {
print "\n\033[1;32mSuccess\033[0m";
} else {
print "\n\033[1;31mFailed\033[0m";
}
return $file;
}
/**
* @param Google_Service_Drive_DriveFile $file
* @param $parentId
* @return bool
*/
private function hasParent(\Google_Service_Drive_DriveFile $file, $parentId)
{
$parents = $file->getParents();
return isset($parents[0]) && $parents[0]['id'] === $parentId;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment