|
2 | 2 |
|
3 | 3 | namespace App\Helpers; |
4 | 4 |
|
5 | | -use Google\Client; |
6 | | -use Google\Service\Drive; |
| 5 | +use Illuminate\Support\Facades\Http; |
7 | 6 |
|
8 | 7 | class GoogleDriveQuota |
9 | 8 | { |
10 | 9 | public static function getQuota(): array |
11 | 10 | { |
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'); |
20 | 13 | $refreshToken = config('app.google.refresh_token'); |
21 | | - $accessToken = $client->fetchAccessTokenWithRefreshToken($refreshToken); |
22 | | - $client->setAccessToken($accessToken); |
23 | 14 |
|
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 | + ]); |
27 | 22 |
|
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; |
30 | 44 |
|
31 | 45 | return [ |
32 | | - 'used' => self::toGB($usage), |
33 | | - 'total' => self::toGB($limit), |
| 46 | + 'used' => $usageGb, |
| 47 | + 'total' => $limitGb, |
34 | 48 | ]; |
35 | 49 | } |
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 | | - } |
42 | 50 | } |
| 51 | + |
| 52 | + |
0 commit comments