-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathclass-api-client.php
More file actions
406 lines (356 loc) · 11.9 KB
/
class-api-client.php
File metadata and controls
406 lines (356 loc) · 11.9 KB
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
<?php
/**
* Contains the API_Client class.
*
* @package skaut-google-drive-gallery
*/
namespace Sgdg;
use ArrayAccess;
use Countable;
use Iterator;
use Sgdg\Exceptions\API_Exception;
use Sgdg\Exceptions\API_Rate_Limit_Exception;
use Sgdg\Exceptions\Exception as Sgdg_Exception;
use Sgdg\Exceptions\Internal_Exception;
use Sgdg\Exceptions\Not_Found_Exception;
use Sgdg\Exceptions\Plugin_Not_Authorized_Exception;
use Sgdg\Frontend\Pagination_Helper;
use Sgdg\Options;
use Sgdg\Vendor\Google\Client;
use Sgdg\Vendor\Google\Collection;
use Sgdg\Vendor\Google\Http\Batch;
use Sgdg\Vendor\Google\Model;
use Sgdg\Vendor\Google\Service\Drive;
use Sgdg\Vendor\Google\Service\Drive\FileList;
use Sgdg\Vendor\Google\Service\Exception as Google_Service_Exception;
use Sgdg\Vendor\Google\Task\Runner;
use Sgdg\Vendor\GuzzleHttp\Exception\TransferException;
use Sgdg\Vendor\GuzzleHttp\Promise\Promise;
use Sgdg\Vendor\GuzzleHttp\Promise\PromiseInterface;
use Sgdg\Vendor\GuzzleHttp\Promise\Utils;
use Sgdg\Vendor\GuzzleHttp\Psr7\Request;
use Traversable;
/**
* API client
*
* @SuppressWarnings("PHPMD.CouplingBetweenObjects")
*/
final class API_Client {
/**
* Google API client
*
* @var Client|null $raw_client
*/
private static $raw_client = null;
/**
* Google Drive API client
*
* @var Drive|null $drive_client
*/
private static $drive_client = null;
/**
* The current Google API batch
*
* @var Batch|null $current_batch
*/
private static $current_batch = null;
/**
* The currently pending API requests as a list of callbacks.
*
* @var array<callable> $pending_requests
*/
private static $pending_requests;
/**
* Returns a Google client with set-up app info, but without authorization.
*
* @return Client
*/
public static function get_unauthorized_raw_client() {
$raw_client = self::$raw_client;
if ( null === $raw_client ) {
$raw_client = new Client();
$raw_client->setAuthConfig(
array(
'client_id' => Options::$client_id->get(),
'client_secret' => Options::$client_secret->get(),
'redirect_uris' => array(
esc_url_raw( admin_url( 'admin.php?page=sgdg_basic&action=oauth_redirect' ) ),
),
)
);
$raw_client->setAccessType( 'offline' );
$raw_client->setPrompt( 'consent' );
$raw_client->addScope( Drive::DRIVE_READONLY );
self::$raw_client = $raw_client;
}
return $raw_client;
}
/**
* Returns a fully configured and authorized Google client.
*
* @return Client
*
* @throws Plugin_Not_Authorized_Exception Not authorized.
*/
public static function get_authorized_raw_client() {
$raw_client = self::get_unauthorized_raw_client();
$access_token = get_option( 'sgdg_access_token', false );
if ( false === $access_token ) {
throw new Plugin_Not_Authorized_Exception();
}
$raw_client->setAccessToken( $access_token );
if ( $raw_client->isAccessTokenExpired() ) {
$raw_client->fetchAccessTokenWithRefreshToken( $raw_client->getRefreshToken() );
$new_access_token = $raw_client->getAccessToken();
$merged_access_token = array_merge( $access_token, $new_access_token );
update_option( 'sgdg_access_token', $merged_access_token );
}
return $raw_client;
}
/**
* Returns a fully set-up Google Drive API client.
*
* @return Drive
*
* @throws Plugin_Not_Authorized_Exception Not authorized.
*/
public static function get_drive_client() {
$drive_client = self::$drive_client;
if ( null === $drive_client ) {
$raw_client = self::get_authorized_raw_client();
$drive_client = new Drive( $raw_client );
$drive_client->getClient()->setUseBatch( true );
self::$drive_client = $drive_client;
}
return $drive_client;
}
/**
* Registers a request to be executed later.
*
* @param Request $request The Google API request.
* @param callable $transform A function to be executed when the request completes, in the format `function( $response ): $output` where `$response` is the Google API response. The function should do any transformations on the output data necessary.
* @param callable|null $rejection_handler A function to be executed when the request fails, in the format `function( $exception ): $output` where `$exception` is the exception in question and `$output` should be a RejectedPromise.
*
* @return PromiseInterface A promise that will be resolved in `$callback`.
*
* @throws Internal_Exception The method was called without an initialized batch.
* @throws Plugin_Not_Authorized_Exception Not authorized.
*/
public static function async_request( $request, $transform, $rejection_handler = null ) {
self::initialize_batch();
if ( null === self::$current_batch ) {
throw new Internal_Exception();
}
$key = wp_rand();
// @phan-suppress-next-line PhanPossiblyNonClassMethodCall
self::$current_batch->add( $request, $key );
$promise = new Promise();
self::$pending_requests[ 'response-' . $key ] = static function ( $response ) use ( $transform, $promise ) {
try {
self::check_response( $response );
$promise->resolve( $transform( $response ) );
} catch ( Sgdg_Exception $e ) {
$promise->reject( $e );
}
};
return $promise->then( null, $rejection_handler );
}
/**
* Registers a paginated request to be executed later.
*
* @param callable $request A function which makes the Google API request. In the format `function( $page_token )` where `$page_token` is the pagination token to use.
* @param callable $transform A function to be executed when the request completes, in the format `function( $response ): $output` where `$response` is the Google API response. The function should do any transformations on the output data necessary.
* @param Pagination_Helper $pagination_helper An initialized pagination helper.
* @param callable|null $rejection_handler A function to be executed when the request fails, in the format `function( $exception ): $output` where `$exception` is the exception in question and `$output` should be a RejectedPromise.
*
* @return PromiseInterface A promise that will be resolved in `$callback`.
*
* @throws Internal_Exception The method was called without an initialized batch.
* @throws Plugin_Not_Authorized_Exception Not authorized.
*/
public static function async_paginated_request(
$request,
$transform,
$pagination_helper,
$rejection_handler = null
) {
self::initialize_batch();
/**
* Gets one page.
*
* @throws Internal_Exception The method was called without an initialized batch.
*
* phpcs:disable SlevomatCodingStandard.PHP.DisallowReference.DisallowedInheritingVariableByReference
*/
$page = static function (
$page_token,
$promise,
$previous_output
) use (
$request,
$transform,
$pagination_helper,
&$page
) {
if ( null === self::$current_batch ) {
throw new Internal_Exception();
}
$key = wp_rand();
// @phan-suppress-next-line PhanPossiblyNonClassMethodCall
self::$current_batch->add( $request( $page_token ), $key );
self::$pending_requests[ 'response-' . $key ] = static function (
$response
) use (
$promise,
$previous_output,
$transform,
$pagination_helper,
&$page
) {
try {
self::check_response( $response );
$new_page_token = $response->getNextPageToken();
$output = $transform( $response );
$output = array_merge( $previous_output, $output );
if ( null === $new_page_token || ! $pagination_helper->should_continue() ) {
$promise->resolve( $output );
return;
}
$page( $new_page_token, $promise, $output );
} catch ( Sgdg_Exception $e ) {
$promise->reject( $e );
}
};
};
// phpcs:enable
$promise = new Promise();
$page( null, $promise, array() );
return $promise->then( null, $rejection_handler );
}
/**
* Executes all queued requests and resolves all promises repeatedly until there is nothing to be done.
*
* @param array<int|string, PromiseInterface> $promises The promises to resolve and throw exceptions if they reject.
*
* @return array<int|string, mixed> A list of results from the promises. Is in the same format as the parameter `$promises`, i.e. if an associative array of promises is passed, an associative array of results will be returned.
*
* @throws Sgdg_Exception Any exception thrown in promises or callbacks.
*/
public static function execute( $promises = array() ) {
self::execute_current_batch();
Utils::queue()->run();
if ( count( self::$pending_requests ) > 0 ) {
self::execute();
}
return Utils::all( $promises )->wait();
}
/**
* Sets up request batching.
*
* @return void
*
* @throws Plugin_Not_Authorized_Exception Not authorized.
*/
private static function initialize_batch() {
if ( ! is_null( self::$current_batch ) ) {
if ( count( self::$pending_requests ) < 100 ) {
return;
}
self::execute_current_batch();
}
self::$current_batch = self::get_drive_client()->createBatch();
self::$pending_requests = array();
}
/**
* Executes the current batch request and calls its callbacks
*
* @return void
*
* @throws Sgdg_Exception Any exception thrown in promises or callbacks.
*/
private static function execute_current_batch() {
$batch = self::$current_batch;
if ( is_null( $batch ) ) {
return;
}
self::$current_batch = null;
/**
* The closure executes the batch and throws the exception if it is a rate limit exceeded exception (this is needed by the task runner).
*
* @throws Google_Service_Exception Rate limit excepted.
*/
$task = new Runner(
array(
'retries' => 100,
),
'Batch Drive call',
static function () use ( $batch ) {
try {
$ret = $batch->execute();
} catch ( TransferException $e ) {
// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
throw new Google_Service_Exception( $e->getMessage() );
}
foreach ( $ret as $response ) {
$exception = self::wrap_response_exception( $response );
if (
$response instanceof Google_Service_Exception &&
$exception instanceof API_Rate_Limit_Exception
) {
throw $response;
}
}
return $ret;
}
);
$responses = $task->run();
foreach ( $responses as $key => $response ) {
call_user_func( self::$pending_requests[ $key ], $response );
unset( self::$pending_requests[ $key ] );
}
}
/**
* Checks the API response and throws an exception if there was a problem.
*
* @param ArrayAccess<mixed, mixed>|Countable|Iterator|Collection|Model|FileList|Traversable|iterable<mixed> $response The API response.
*
* @return void
*
* @throws API_Rate_Limit_Exception Rate limit exceeded.
* @throws Not_Found_Exception The requested resource couldn't be found.
* @throws API_Exception A wrapped API exception.
*/
private static function check_response( $response ) {
$exception = self::wrap_response_exception( $response );
if ( null !== $exception ) {
throw $exception;
}
}
/**
* Checks the API response and throws an exception if there was a problem.
*
* @param ArrayAccess<mixed, mixed>|Countable|Iterator|Collection|Model|FileList|Traversable|iterable<mixed> $response The API response.
*
* @return API_Rate_Limit_Exception|Not_Found_Exception|API_Exception|null The wrapped exception or null if the response is not an exception.
*/
private static function wrap_response_exception( $response ) {
if ( ! ( $response instanceof Google_Service_Exception ) ) {
return null;
}
$errors = $response->getErrors();
if ( null === $errors ) {
return new API_Exception( $response );
}
$error_reasons = array_column( $errors, 'reason' );
if (
in_array( 'rateLimitExceeded', $error_reasons, true ) ||
in_array( 'userRateLimitExceeded', $error_reasons, true )
) {
return new API_Rate_Limit_Exception( $response );
}
if ( in_array( 'notFound', $error_reasons, true ) ) {
return new Not_Found_Exception();
}
return new API_Exception( $response );
}
}