Skip to content

Commit f83dcd8

Browse files
Refactor GoogleDriveQuota to use HTTP client for token retrieval and storage info
1 parent 2550bc7 commit f83dcd8

File tree

1 file changed

+35
-25
lines changed

1 file changed

+35
-25
lines changed

app/Helpers/GoogleDriveQuota.php

Lines changed: 35 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,41 +2,51 @@
22

33
namespace App\Helpers;
44

5-
use Google\Client;
6-
use Google\Service\Drive;
5+
use Illuminate\Support\Facades\Http;
76

87
class GoogleDriveQuota
98
{
109
public static function getQuota(): array
1110
{
12-
$client = new Client();
13-
$client->setClientId(config('app.google.client_id'));
14-
$client->setClientSecret(config('app.google.client_secret'));
15-
$client->setRedirectUri(env('APP_URL') . '/google/oauth/callback');
16-
$client->setAccessType('offline');
17-
$client->setScopes(['https://www.googleapis.com/auth/drive.metadata.readonly']);
18-
19-
// refresh token -> access token
11+
$clientId = config('app.google.client_id');
12+
$clientSecret = config('app.google.client_secret');
2013
$refreshToken = config('app.google.refresh_token');
21-
$accessToken = $client->fetchAccessTokenWithRefreshToken($refreshToken);
22-
$client->setAccessToken($accessToken);
2314

24-
$service = new Drive($client);
25-
$about = $service->about->get(['fields' => 'storageQuota']);
26-
$q = $about->getStorageQuota();
15+
// Step 1: Refresh token -> Access token
16+
$response = Http::asForm()->post('https://oauth2.googleapis.com/token', [
17+
'client_id' => $clientId,
18+
'client_secret' => $clientSecret,
19+
'refresh_token' => $refreshToken,
20+
'grant_type' => 'refresh_token',
21+
]);
2722

28-
$limit = $q->getLimit(); // total bytes
29-
$usage = $q->getUsage(); // used bytes
23+
if ($response->failed()) {
24+
return [
25+
'used_gb' => null,
26+
'total_gb' => null,
27+
'error' => $response->json(),
28+
];
29+
}
30+
31+
$accessToken = $response->json()['access_token'];
32+
33+
// Step 2: Get storage info
34+
$about = Http::withToken($accessToken)
35+
->get('https://www.googleapis.com/drive/v3/about?fields=storageQuota')
36+
->json();
37+
38+
$limit = $about['storageQuota']['limit'] ?? 0;
39+
$usage = $about['storageQuota']['usage'] ?? 0;
40+
41+
// Convert bytes to GB
42+
$limitGb = $limit ? round($limit / (1024 ** 3), 2) : 0;
43+
$usageGb = $usage ? round($usage / (1024 ** 3), 2) : 0;
3044

3145
return [
32-
'used' => self::toGB($usage),
33-
'total' => self::toGB($limit),
46+
'used' => $usageGb,
47+
'total' => $limitGb,
3448
];
3549
}
36-
37-
private static function toGB($bytes): ?float
38-
{
39-
if ($bytes === null) return null;
40-
return round($bytes / (1024 ** 3), 2); // convert to GB (2 decimal)
41-
}
4250
}
51+
52+

0 commit comments

Comments
 (0)