-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest.traktivity.php
462 lines (415 loc) · 13.6 KB
/
rest.traktivity.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
462
<?php
/**
* REST API endpoints.
*
* @package Traktivity
*/
defined( 'ABSPATH' ) || die( 'No script kiddies please!' );
/**
* Custom REST API endpoints.
* We'll use it to check the status of the plugin, and return aggregated data.
*
* @since 1.1.0
*/
class Traktivity_Api {
/**
* Constructor
*/
function __construct() {
add_action( 'rest_api_init', array( $this, 'register_endpoints' ) );
}
/**
* Register all endpoints.
*
* @since 1.1.0
*/
public function register_endpoints() {
/**
* Get existing credentials.
*
* @since 2.0.0
*/
register_rest_route( 'traktivity/v1', '/settings', array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_settings' ),
'permission_callback' => array( $this, 'permissions_check' ),
) );
/**
* Edit Settings.
*
* @since 2.0.0
*/
register_rest_route( 'traktivity/v1', '/settings/edit', array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'post_settings' ),
'permission_callback' => array( $this, 'permissions_check' ),
) );
/**
* Check the validity of our Trakt.tv credentials.
*
* @since 1.1.0
*/
register_rest_route( 'traktivity/v1', '/connection/(?P<user>[a-z0-9\-\.]+)/(?P<trakt>[a-zA-Z0-9-]+)', array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'test_trakt_api_connection' ),
'permission_callback' => array( $this, 'permissions_check' ),
'args' => array(
'user' => array(
'required' => true,
'validate_callback' => array( $this, 'validate_string' ),
),
'trakt' => array(
'required' => true,
'validate_callback' => array( $this, 'validate_string' ),
),
),
) );
/**
* Check the validity of our TMDb credentials.
*
* @since 2.0.0
*/
register_rest_route( 'traktivity/v1', '/tmdb/(?P<tmdb>[a-zA-Z0-9-]+)', array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'test_tmdb_api_connection' ),
'permission_callback' => array( $this, 'permissions_check' ),
'args' => array(
'tmdb' => array(
'required' => true,
'validate_callback' => array( $this, 'validate_string' ),
),
),
) );
/**
* Check Sync status for Traktivity.
*
* @since 1.1.0
*/
register_rest_route( 'traktivity/v1', '/sync', array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'trigger_sync' ),
'permission_callback' => array( $this, 'permissions_check' ),
) );
/**
* Traktivity Stats Info.
*
* @since 2.2.0
*/
register_rest_route( 'traktivity/v1', '/stats', array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_stats' ),
'permission_callback' => '__return_true',
) );
}
/**
* Check permissions for each one of our requests.
*
* @since 1.1.0
*
* @param WP_REST_Request $request Full details about the request.
*
* @return bool $permission Returns true if user is allowed to call the API.
*/
public function permissions_check( $request ) {
return current_user_can( 'manage_options' );
}
/**
* Validate an API key.
*
* @since 1.1.0
*
* @param string $param Parameter that needs to be validated.
* @param WP_REST_Request $request Full details about the request.
* @param string $key key argument.
*
* @return bool $validated Is the API key in a valid format.
*/
public function validate_string( $param, $request, $key ) {
return is_string( $param );
}
/**
* Check the status of our Trakt.tv connection.
*
* @since 1.0.0
*
* @param WP_REST_Request $request Full details about the request.
*
* @return WP_REST_Response $response Status of our Trakt.tv connection. Response code matches the response from the API.
*/
public function test_trakt_api_connection( $request ) {
// Get parameter from request.
if ( isset( $request['user'], $request['trakt'] ) ) {
$user = $request['user'];
$trakt = $request['trakt'];
} else {
return new WP_Error(
'not_found',
esc_html__( 'You did not specify your username or a Trakt.tv API key.', 'traktivity' ),
array(
'status' => 404,
)
);
}
/**
* Query the API using the API key provided in the API request.
*/
$headers = array(
'Content-Type' => 'application/json',
'trakt-api-version' => TRAKTIVITY__API_VERSION,
'trakt-api-key' => esc_html( $trakt ),
);
$query_url = sprintf(
'%1$s/users/%2$s/history?limit=1',
TRAKTIVITY__API_URL,
esc_html( $user )
);
$data = wp_remote_get(
esc_url_raw( $query_url ),
array(
'headers' => $headers,
)
);
if ( is_wp_error( $data ) ) {
$response = array(
'message' => esc_html__( 'Trakt.tv is unavailable right now. Try again later.', 'traktivity' ),
'code' => (int) 500,
);
return new WP_REST_Response( $response, 500 );
}
$code = $data['response']['code'];
/**
* Tweak our endpoint response message based on the response from Trakt.tv API.
*
* @see http://docs.trakt.apiary.io/#introduction/status-codes
*/
if ( 403 === $code ) {
$message = __( 'Invalid API key or unapproved app.' , 'traktivity' );
} elseif ( 429 === $code ) {
$message = __( 'Rate Limit Exceeded with your Trakt.tv App.', 'traktivity' );
} elseif ( 404 === $code ) {
$message = __( 'This Trakt.tv username does not exist.', 'traktivity' );
} elseif ( '2' === substr( $code, 0, 1 ) ) {
$message = __( 'Your Trakt.tv API key is working.', 'traktivity' );
// Let's overwrite the response code. If it's a success, we don't care what success response code, 200 is good enough.
$code = 200;
} elseif ( '5' === substr( $code, 0, 1 ) ) {
$message = __( 'Trakt.tv is unavailable right now. Try again later.', 'traktivity' );
} else {
$message = __( 'Something is not working as it should. Please double check that both your username and your API keys are correct.
If everything looks good, but you still see this message, please let me know, I\'ll see what I can do to help.
Post in the WordPress.org support forums and give me as many details as possible about your setup.
Thank you!', 'traktivity' );
}
$response = array(
'message' => esc_html( $message ),
'code' => (int) $code,
);
return new WP_REST_Response( $response, 200 );
}
/**
* Check the status of our TMDb connection.
*
* @since 2.0.0
*
* @param WP_REST_Request $request Full details about the request.
*
* @return WP_REST_Response $response Status of our TMDb connection. Response code matches the response from the API.
*/
public function test_tmdb_api_connection( $request ) {
// Get parameter from request.
if ( ! isset( $request['tmdb'] ) ) {
return new WP_Error(
'not_found',
esc_html__( 'You did not specify your TMDb API key.', 'traktivity' ),
array(
'status' => 404,
)
);
}
/**
* Query the API using the API key provided in the API request.
* We'll query a random endpoint, discover/movie.
*
* @see https://developers.themoviedb.org/3/discover
*/
$query_url = sprintf(
'%1$s/%2$s/%3$s?api_key=%4$s',
TRAKTIVITY__TMDB_API_URL,
TRAKTIVITY__TMDB_API_VERSION,
'discover/movie',
esc_attr( $request['tmdb'] )
);
$data = wp_remote_get( esc_url_raw( $query_url ) );
$code = $data['response']['code'];
/**
* Tweak our endpoint response message based on the response from TMDb API.
*
* @see https://www.themoviedb.org/documentation/api/status-codes
*/
if ( 429 === $code ) {
$message = __( 'Rate Limit Exceeded with your TMDb App. Try again later, but give it some time!', 'traktivity' );
} elseif ( '4' === substr( $code, 0, 1 ) ) {
$message = __( 'Your TMDb API key does not exist, or is not valid.', 'traktivity' );
} elseif ( '2' === substr( $code, 0, 1 ) ) {
$message = __( 'Your TMDb API key is working.', 'traktivity' );
// Let's overwrite the response code. If it's a success, we don't care what success response code, 200 is good enough.
$code = 200;
} elseif ( '5' === substr( $code, 0, 1 ) ) {
$message = __( 'TMDb is unavailable right now. Try again later.', 'traktivity' );
} else {
$message = __( 'Something is not working as it should. Please double check that both your username and your API keys are correct.
If everything looks good, but you still see this message, please let me know, I\'ll see what I can do to help.
Post in the WordPress.org support forums and give me as many details as possible about your setup.
Thank you!', 'traktivity' );
}
$response = array(
'message' => esc_html( $message ),
'code' => (int) $code,
);
return new WP_REST_Response( $response, 200 );
}
/**
* Trigger a full synchronization of all past events.
*
* @since 1.1.0
*
* @param WP_REST_Request $request Full details about the request.
*
* @return WP_REST_Response $response Response from the Sync function.
*/
public function trigger_sync( $request ) {
$options = (array) get_option( 'traktivity' );
// Return an error if we have no API Keys to run an import.
if ( ! isset( $options['username'], $options['api_key'] ) ) {
return new WP_REST_Response(
esc_html__( 'You did not specify your username or a Trakt.tv API key.', 'traktivity' ),
200
);
}
// If the 'total_runtime' argument was sent with the request, only recalculate total runtime for each series.
if (
isset( $request['type'] )
&& 'total_runtime' === $request['type']
) {
if ( ! wp_next_scheduled( 'traktivity_total_runtime_sync' ) ) {
wp_schedule_single_event( time(), 'traktivity_total_runtime_sync' );
}
return new WP_REST_Response(
esc_html__( 'We are now recalcutating total runtime for each one of the shows you have watched. Give it a bit of time.', 'traktivity' ),
200
);
}
// Return an error if Synchronization is already complete. No need to run it again.
if (
isset( $options['full_sync'], $options['full_sync']['status'] )
&& 'done' === $options['full_sync']['status']
) {
return new WP_REST_Response(
esc_html__( 'Synchronization is complete.', 'traktivity' ),
200
);
}
// Return an error if Synchronization is currently in progress. Let's let it finish.
if (
isset( $options['full_sync'], $options['full_sync']['status'] )
&& 'in_progress' === $options['full_sync']['status']
) {
// Relaunch full sync if it was running before but was stopped.
if ( ! wp_next_scheduled( 'traktivity_full_sync' ) ) {
wp_schedule_single_event( time(), 'traktivity_full_sync' );
}
// Return a response to let the user know about the sync progress so far.
return new WP_REST_Response(
esc_html__( 'Synchronization is in progress. Give it some time!', 'traktivity' ),
200
);
}
// No errors? Schedule a single event that will start in 2 seconds and trigger the full sync.
if ( ! wp_next_scheduled( 'traktivity_full_sync' ) ) {
wp_schedule_single_event( time(), 'traktivity_full_sync' );
}
return new WP_REST_Response(
esc_html__( 'Synchronization has started. Give it a bit of time now. You can monitor progress in the All Trakt.tv Events menu.', 'traktivity' ),
200
);
}
/**
* Get existing settings in an object.
*
* @since 2.0.0
*
* @param WP_REST_Request $request Full details about the request.
*
* @return WP_REST_Response $response Response from the Sync function.
*/
public function get_settings( $request ) {
$options = (array) get_option( 'traktivity' );
$settings = new stdClass();
if (
isset( $options['username'], $options['api_key'] )
&& ( ! empty( $options['username'] ) && ! empty( $options['api_key'] ) )
) {
$settings->trakt->username = $options['username'];
$settings->trakt->key = $options['api_key'];
}
if ( isset( $options['tmdb_api_key'] ) && ! empty( $options['tmdb_api_key'] ) ) {
$settings->tmdb->key = $options['tmdb_api_key'];
}
if ( isset( $options['step'] ) && ! empty( $options['step'] ) ) {
$settings->tmdb->step = $options['step'];
}
return new WP_REST_Response( $settings, 200 );
}
/**
* Edit settings.
*
* @since 2.0.0
*
* @param WP_REST_Request $request Full details about the request.
*
* @return WP_REST_Response $response Response from the Sync function.
*/
public function post_settings( $request ) {
$options = (array) get_option( 'traktivity' );
if ( isset( $request ) ) {
if ( isset( $request['trakt']['username'] ) && ! empty( $request['trakt']['username'] ) ) {
$options['username'] = esc_attr( $request['trakt']['username'] );
}
if ( isset( $request['trakt']['key'] ) && ! empty( $request['trakt']['key'] ) ) {
$options['api_key'] = esc_attr( $request['trakt']['key'] );
}
if ( isset( $request['tmdb']['key'] ) && ! empty( $request['tmdb']['key'] ) ) {
$options['tmdb_api_key'] = esc_attr( $request['tmdb']['key'] );
}
if ( isset( $request['step'] ) && ! empty( $request['step'] ) ) {
$options['step'] = absint( $request['step'] );
}
update_option( 'traktivity', $options );
return new WP_REST_Response( $request, 200 );
}
return new WP_Error(
'cant-update',
esc_html__( 'Could not update your settings.', 'traktivity' ),
array(
'status' => 500,
)
);
}
/**
* Get stats from the Stats option.
*
* @since 2.2.0
*
* @param WP_REST_Request $request Full details about the request.
*
* @return WP_REST_Response $response Response with all stats.
*/
public function get_stats( $request ) {
$stats = get_option( 'traktivity_stats' );
return new WP_REST_Response(
$stats,
200
);
}
} // End class.
new Traktivity_Api();