-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpWrapper.php
461 lines (388 loc) · 13.4 KB
/
HttpWrapper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
<?php
/*
* (c) 2018 Dennis Birkholz <[email protected]>
*
* $Id$
* Author: $Format:%an <%ae>, %ai$
* Committer: $Format:%cn <%ce>, %ci$
*/
namespace Iqb\Cabinet\GDrive;
use GuzzleHttp\Psr7\Request;
use Psr\Log\LoggerInterface;
/**
* This class wraps the actual GDrive http client.
* It catches authentication errors and automatically retries after refreshing the authentication token.
* It can be replaced by a mock for testing.
*
* @author Dennis Birkholz <[email protected]>
*/
class HttpWrapper
{
const FILE_MIME_TYPE = 'application/octet-stream';
const FOLDER_MIME_TYPE = 'application/vnd.google-apps.folder';
/**
* File containing the client secret data.
* File can be obtained from Google Developer Console for this application.
* @var string
*/
private $clientSecretFile;
/**
* The array structure containing the client secret.
* File can be obtained from Google Developer Console for this application.
* @var array
*/
private $clientSecret;
/**
* The path to a JSON encoded file containing the access and refresh token.
* If set, the file is refreshed whenever updated tokens are received.
*
* @var string
*/
private $accessTokenFile;
/**
* The access token (incl. refresh token).
* @var array
*/
private $accessToken;
/**
* Optional application name to submit when accessing Google API
* @var string
*/
private $applicationName;
/**
* @var \Google_Client
*/
private $client;
/**
* @var \Google_Service_Drive
*/
private $service;
/**
* @var LoggerInterface
*/
private $logger;
public $tries = 10;
public function __construct($clientSecret, $accessToken = null)
{
if (\is_string($clientSecret)) {
$this->clientSecretFile = $clientSecret;
} else {
$this->clientSecret = $clientSecret;
}
if (\is_string($accessToken)) {
$this->accessTokenFile = $accessToken;
} elseif (\is_array($accessToken)) {
$this->accessToken = $accessToken;
}
}
/**
* Set the logger used for debug output
*
* @param LoggerInterface|null $logger
*/
public function setLogger(LoggerInterface $logger = null)
{
$this->logger = $logger;
}
/**
* Prepare a new Google HTTP API client or return a previously assembled instance if available
*
* @return \Google_Client
*/
private function getClient() : \Google_Client
{
if (!$this->client) {
$this->client = new \Google_Client();
if ($this->applicationName) {
$this->client->setApplicationName($this->applicationName);
}
$this->client->setScopes([\Google_Service_Drive::DRIVE]);
$this->client->setAuthConfig($this->clientSecretFile ? $this->clientSecretFile : $this->clientSecret);
$this->client->setAccessType('offline');
$this->refreshAccessToken();
}
return $this->client;
}
private function refreshAccessToken($forceRefresh = false)
{
if (!$this->client) {
return;
}
$changed = false;
if (!$this->accessToken) {
if ($this->accessTokenFile && \file_exists($this->accessTokenFile)) {
$this->accessToken = \json_decode(\file_get_contents($this->accessTokenFile), true);
}
else {
$this->accessToken = $this->getAccessTokenFromAuthCode();
$changed = true;
}
}
$this->client->setAccessToken($this->accessToken);
if ($forceRefresh || $this->client->isAccessTokenExpired()) {
$this->logger && $this->logger->debug(__FUNCTION__ . ': new access token acquired');
$this->accessToken = $this->client->fetchAccessTokenWithRefreshToken();
$changed = true;
}
if ($changed && $this->accessTokenFile) {
$this->logger && $this->logger->debug(__FUNCTION__ . ': access token persisted');
\file_put_contents($this->accessTokenFile, \json_encode($this->accessToken));
}
}
private function getAccessTokenFromAuthCode()
{
// Request authorization from the user.
$authUrl = $this->client->createAuthUrl();
\printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = \trim(\fgets(STDIN));
// Exchange authorization code for an access token.
return $this->client->fetchAccessTokenWithAuthCode($authCode);
}
/**
* Get the Google Drive API client
* @return \Google_Service_Drive
*/
private function getService() : \Google_Service_Drive
{
if (!$this->service) {
$this->service = new \Google_Service_Drive($this->getClient());
}
return $this->service;
}
/**
* @param callable $call
* @param array $params
* @return mixed
*/
private function retryApiCall(callable $call, ...$params)
{
$timeout = 100000;
for ($try = 1; $try <= $this->tries; $try++) {
try {
$this->refreshAccessToken($try > 1);
$result = $call(...$params);
if ($result !== null) {
return $result;
} elseif ($try === $this->tries) {
throw new \RuntimeException("Api call retry failed.");
} else {
$this->logger && $this->logger->debug(__FUNCTION__ . ': call returned null, retrying. (try ' . $try . ' of ' . $this->tries . ')');
}
} catch (\Google_Service_Exception $e) {
// The requested file or directory was not found
if ($e->getCode() === 404) {
return null;
}
// Authorization error, retry
elseif ($e->getCode() === 401) {
$this->logger && $this->logger->debug(__FUNCTION__ . ': API token expired unexpectedly, refreshing token and retrying. (try ' . $try . ' of ' . $this->tries . ')');
}
else {
throw $e;
}
}
\usleep($timeout);
$timeout <<= 1;
}
}
/**
* Fetch the startPageToken that identified the current state of the drive.
* Used to page through unseen updates.
*
* @return string
*/
public function getChangesStartPageToken() : string
{
return $this->retryApiCall(function() {
return $this->getService()->changes->getStartPageToken()->getStartPageToken();
});
}
/**
* Get the root file node of the current Google Drive
*
* @param array $optionalParams
* @return \Google_Service_Drive_DriveFile
*/
final public function getRootFile(array $optionalParams = []) : \Google_Service_Drive_DriveFile
{
return $this->getFile('root', $optionalParams);
}
/**
* Get a file identified by the unique ID from the current Google Drive
*
* @param string $fileId
* @param array $optionalParams
* @return \Google_Service_Drive_DriveFile|null
*/
final public function getFile(string $fileId, array $optionalParams = []) : ?\Google_Service_Drive_DriveFile
{
return $this->retryApiCall(function() use ($fileId, $optionalParams) {
$this->getClient()->setDefer(false);
return $this->getService()->files->get($fileId, $optionalParams);
});
}
/**
* Fetch a list of files
*
* @param array $optionalParams
* @return \Google_Service_Drive_FileList
*/
final public function listFiles(array $optionalParams = []) : \Google_Service_Drive_FileList
{
return $this->retryApiCall(function() use ($optionalParams) {
$this->getClient()->setDefer(false);
return $this->getService()->files->listFiles($optionalParams);
});
}
/**
* Fetch a list of changes that happens since the drive status identified by $nextPageToken
*
* @param string $nextPageToken
* @param array $optionalParams
* @return \Google_Service_Drive_ChangeList
*/
final public function listChanges(string $nextPageToken, array $optionalParams = []) : \Google_Service_Drive_ChangeList
{
return $this->retryApiCall(function() use ($nextPageToken, $optionalParams) {
$this->getClient()->setDefer(false);
return $this->getService()->changes->listChanges($nextPageToken, $optionalParams);
});
}
/**
* Prepare for uploading a new file
*
* @param string $name
* @param string $parent
* @param string $mimeType
* @param int $fileSize
* @param int $chunkSize
* @param array $optionalParams
* @return \Google_Http_MediaFileUpload
*/
final public function fileUploadStart(string $name, string $parent, string $mimeType, int $fileSize, int $chunkSize, array $optionalParams = []) : \Google_Http_MediaFileUpload
{
$file = new \Google_Service_Drive_DriveFile([
'name' => $name,
'parents' => [ $parent ],
]);
$this->getClient()->setDefer(true);
// Create a media file upload to represent our upload process.
$media = new \Google_Http_MediaFileUpload(
$this->getClient(),
$this->getService()->files->create($file, $optionalParams),
$mimeType,
null,
true,
$chunkSize
);
$media->setFileSize($fileSize);
return $media;
}
/**
* Upload the next chunk
*
* @param \Google_Http_MediaFileUpload $fileUpload
* @param string $chunk
* @return \Google_Service_Drive_DriveFile
*/
final public function fileUploadNextChunk(\Google_Http_MediaFileUpload $fileUpload, string $chunk) : ?\Google_Service_Drive_DriveFile
{
$reply = $this->retryApiCall(function() use ($fileUpload, $chunk) {
return $fileUpload->nextChunk($chunk);
});
if ($reply instanceof \Google_Service_Drive_DriveFile) {
return $reply;
} else {
return null;
}
}
/**
* Get a download stream to a file
*
* @param string $fileId
* @param int|null $offset
* @param int|null $bytes
* @return resource
*/
final public function fileDownload(string $fileId, int $offset = null, int $bytes = null)
{
return $this->retryApiCall(function() use ($fileId, $offset, $bytes) {
$httpClient = $this->getClient()->authorize();
$this->getClient()->setDefer(true);
/* @var $fileRequest Request */
$fileRequest = $this->getService()->files->get($fileId, ['alt' => 'media']);
if ($offset !== null) {
$fileRequest = $fileRequest->withAddedHeader('Range', 'bytes=' . $offset . '-' . ($bytes !== null ? $offset+$bytes-1 : ''));
}
$response = $httpClient->send($fileRequest, ['stream' => true]);
return $response->getBody()->detach();
});
}
/**
* Create a new folder
*
* @param string $parentId
* @param string $name
* @param array $optionalParams
* @return \Google_Service_Drive_DriveFile|null
*/
final public function createFolder(string $parentId, string $name, array $optionalParams = []) : ?\Google_Service_Drive_DriveFile
{
return $this->retryApiCall(function() use ($parentId, $name, $optionalParams) {
$file = new \Google_Service_Drive_DriveFile([
'name' => $name,
'mimeType' => self::FOLDER_MIME_TYPE,
'parents' => [ $parentId ],
]);
$this->getClient()->setDefer(false);
$result = $this->getService()->files->create($file, $optionalParams);
if ($result instanceof \Google_Service_Drive_DriveFile) {
return $result;
}
});
}
/**
* Delete a file or folder.
* This operation is not recursive.
*
* @param string $fileId
* @return mixed
*/
final public function deleteFile(string $fileId)
{
return $this->retryApiCall(function() use ($fileId) {
$this->getClient()->setDefer(false);
return $this->getService()->files->delete($fileId);
});
}
/**
* Modify a files meta data.
*
* @param string $fileId
* @param \Google_Service_Drive_DriveFile $file
* @param array $optionalParameters
* @return \Google_Service_Drive_DriveFile|null
*/
final public function updateFileMetadata(string $fileId, \Google_Service_Drive_DriveFile $file, array $optionalParameters = []) : ?\Google_Service_Drive_DriveFile
{
return $this->retryApiCall(function() use ($fileId, $file, $optionalParameters) {
return ($this->getService()->files->update($fileId, $file, $optionalParameters) ?: null);
});
}
/**
* Prevent instances of Google clients to be serialized
* @return array
*/
public function __sleep()
{
return [
'clientSecret',
'clientSecretFile',
'accessToken',
'accessTokenFile',
'applicationName',
'tries',
];
}
}