Integrare le Google Drive API con PHP - Step 4

- Pubblicato in coding di - Permalink

enter image description here

Rimuovere la condivisione di un elemento

    public function removeShareFileFolder(array $params = [])
    {
        if (empty($params["fileFolder"]) OR empty($params["mailDest"])) {
            return false;
        }

        $esito = false;

        try {
            $client = $this->manageDriveClient();
            $service = new Google\Service\Drive($client);

            $optParams = array(
                'fields' => 'nextPageToken, permissions(id, emailAddress, role, type)'
            );

            $permissions = $service->permissions->listPermissions($params["fileFolder"], $optParams);

            foreach ($permissions->getPermissions() as $permission) {
                if ($permission->emailAddress === $params["mailDest"]) {
                    try {
                        $rsn = $service->permissions->delete($params["fileFolder"], $permission->getId());
                        $esito = true;
                        break;
                    } catch(Exception $e) {

                    }
                }
            }
        } catch(Exception $e) {

        }

        return false;
    }

Upload di un file su Google Drive

    private function readEntChunk($handle, $chunkSize)
    {
        $byteCount = 0;
        $giantChunk = "";
        while (!feof($handle)) {
            $chunk = fread($handle, 8192);
            $byteCount += strlen($chunk);
            $giantChunk .= $chunk;
            if ($byteCount >= $chunkSize) {
                return $giantChunk;
            }
        }

        return $giantChunk;
    }

    public function checkAndSend2Drive(array $params)
    {
        if (empty($params["uploadName"]) OR empty($params["uploadParn"]) OR empty($params["uploadType"]) OR empty($params["uploadSize"]) OR empty($params["uploadPath"])) {
            return false;
        }

        try {
            $client = $this->manageDriveClient();
            $service = new Google\Service\Drive($client);
            $handle = null;

            $file = new Google\Service\Drive\DriveFile();
            $file->setName($params["uploadName"]);
            $file->setParents([$params["uploadParn"]]);

            $chunkSizeBytes = 1 * 1024 * 1024;
            $client->setDefer(true);

            $request = $service->files->create($file);

            $media = new Google\Http\MediaFileUpload(
                $client, $request, $params["uploadType"], null, true, $chunkSizeBytes
            );

            $media->setFileSize($params["uploadSize"]);

            $status = false;
            $handle = fopen(__DIR__ . "public/" . $params["uploadPath"], "rb");

            while (!$status && !feof($handle)) {
                $chunk = $this->readEntChunk($handle, $chunkSizeBytes);
                $status = $media->nextChunk($chunk);
            }

            if ($status !== false && !empty($status->id)) {
                fclose($handle);
                unlink(__DIR__ . "public/" . $params["uploadPath"]);
                return $status->id;
            }

            return false;
        } catch (Exception $e) {
            if ($handle) fclose($handle);
            throw $e;
        }
    }

Download file da Google Drive

    public function downloadFileFromDrive(array $params = [])
    {
        if (empty($params["code"]) OR empty($params["name"])) {
            return false;
        }

        try {
            $client = $this->manageDriveClient();
            $service = new Google\Service\Drive($client);

            $files = $service->files->get($params["code"],[
                'fields'    =>  'size'
            ]);

            if (intval($files->size) === 0 OR empty($files->size)) {
                return;
            }

            $fileId = $params["code"];
            $fileSize = intval($files->size);

            $http = $client->authorize();

            $tempPath = __DIR__."/public/temp/".time();
            $tempPath .= '-'.$params["name"];

            $fp = fopen($tempPath, 'w');

            $chunkSizeBytes = 1 * 1024 * 1024;
            $chunkStart = 0;

            while ($chunkStart < $fileSize) {
                $chunkEnd = min($chunkStart + $chunkSizeBytes - 1, $fileSize - 1);
                $response = $http->request('GET', sprintf('/drive/v3/files/%s', $fileId), [
                    'query' => ['alt' => 'media'],
                    'headers' => [
                        'Range' => sprintf('bytes=%s-%s', $chunkStart, $chunkEnd)
                    ]
                ]);

                $chunkStart = $chunkEnd + 1;
                fwrite($fp, $response->getBody()->getContents());
            }

            fclose($fp);

            $iron = file_get_contents($tempPath);
            unlink($tempPath);

            return (!empty($iron)) ? $iron : '';
        } catch(Exception $e) {

        }

        return false;
    }

Informazioni su Quota e consumo

    private function convertFileSize($bytes, $decimals = 2)
    {
        $size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
        $factor = floor((strlen($bytes) - 1) / 3);
        $dimf = sprintf("%.{$decimals}f", $bytes / pow(1024, $factor));
        return sprintf("%s %s", $dimf, @$size[$factor]);
    }

    public function aboutSpace()
    {
        try {
            $client = $this->manageDriveClient();
            $service = new Google\Service\Drive($client);

            $optParams = ['fields' => '*'];
            $datax = (array)$service->about->get($optParams);

            $res = [];
            if (array_key_exists("user", $datax) && !empty($datax["user"])) {
                $res["user"] = [
                    "displayName"   =>  $datax["user"]->displayName,
                    "emailAddress"  =>  $datax["user"]->emailAddress,
                    "photoLink"     =>  $datax["user"]->photoLink
                ];
            }

            if (array_key_exists("storageQuota", $datax) && !empty($datax["storageQuota"])) {
                $qlim = intval($datax["storageQuota"]->limit);
                $totu = intval($datax["storageQuota"]->usage);
                $drvu = intval($datax["storageQuota"]->usageInDrive);
                $trsu = intval($datax["storageQuota"]->usageInDriveTrash);

                $realu = (intval($datax["storageQuota"]->usage) - intval($datax["storageQuota"]->usageInDriveTrash));

                $res["quota"] = [
                    "limit"             =>  intval($qlim),
                    "humanLimit"        =>  $this->convertFileSize($qlim),
                    "totalUsage"        =>  intval($totu),
                    "humanTotalUsage"   =>  $this->convertFileSize($totu),
                    "driveUsage"        =>  intval($drvu),
                    "humanDriveUsage"   =>  $this->convertFileSize($drvu),
                    "trashUsage"        =>  $trsu,
                    "humanTrashUsage"   =>  $this->convertFileSize($trsu),
                    "realUsageNoTrash"  =>  $this->convertFileSize($realu),
                    "percent"           =>  intval(((intval($totu) * 100) / intval($qlim)))
                ];
            }

            return json_encode($res);
        } catch(Exception $e) {
            echo $e->getMessage();
        }

        return false;
    }

Elenco contenuto di una cartella

    public function getContentDriveList(array $params = [])
    {
        if (empty($params)) {
            return false;
        }

        $optn = ["fields" => "files(id,name,mimeType,parents,properties,trashed,quotaBytesUsed,kind,size,modifiedTime,createdTime)"];

        if (!empty($params)) {
            $dataQ = "";
            $o = [];
            if (array_key_exists("parent", $params)) {
                $dataQ .= "'%s' in parents";
                $o[] = str_replace("'", "\\'", $params["parent"]);
            }

            if (array_key_exists("isTrashed", $params)) {
                $dataQ .= (empty($o)) ? "trashed=%s" : " and trashed=%s";
                $o[] = $params["isTrashed"] ? 'true' : 'false';
            }

            if (array_key_exists("type", $params)) {
                if ($params["type"] === "file") {
                    $dataQ .= (empty($o)) ? "mimeType != 'application/vnd.google-apps.folder'" : " and mimeType != 'application/vnd.google-apps.folder'";
                }

                if ($params["type"] === "folder") {
                    $dataQ .= (empty($o)) ? "mimeType = 'application/vnd.google-apps.folder'" : " and mimeType = 'application/vnd.google-apps.folder'";
                }
            }

            if (array_key_exists("name", $params)) {
                $dataQ .= (empty($o)) ? "name = '%s'" : " and name = '%s'";
                $o[] = str_replace("'", "\\'", $params["name"]);
            }

            if (isset($dataQ) && !empty($dataQ)) {
                $optn["q"] = vsprintf($dataQ, $o);
            }
        }

        try {
            $client = $this->manageDriveClient();
            $service = new Google\Service\Drive($client);

            $files = $service->files->listFiles($optn)->getFiles();

            $dataDrive = [];
            if (count($files) > 0) {
                foreach ($files as $fx) {
                    $dataDrive[] = [
                        "ident"     =>  $fx->id,
                        "kind"      =>  $fx->kind,
                        "type"      =>  $fx->mimeType,
                        "name"      =>  $fx->name,
                        "parents"   =>  (!empty($fx->parents) && is_array($fx->parents)) ? implode(",", $fx->parents) : "",
                        "quota"     =>  $fx->quotaBytesUsed,
                        "size"      =>  $fx->size,
                        "datemake"  =>  $fx->getCreatedTime(),
                        "lastmod"   =>  $fx->getModifiedTime(),
                        "isTrashed" =>  $fx->trashed ? 'true' : 'false'
                    ];
                }
            }

            return $dataDrive;
        } catch(Exception $e) {
            echo $e->getMessage();
        }

        return false;
    }
→