-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathClient.php
More file actions
365 lines (319 loc) · 9.57 KB
/
Client.php
File metadata and controls
365 lines (319 loc) · 9.57 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
<?php
namespace Brightcove\API;
use Brightcove\API\Exception\AuthenticationException;
use Brightcove\API\Exception\APIException;
use Brightcove\Object\ObjectInterface;
/**
* This Class handles the communication with the Brightcove APIs.
*/
class Client {
/**
* A filename for a verbose request log.
*
* @var string
*/
public static $debugRequests = NULL;
/**
* CURLOPT_HTTPPROXYTUNNEL
*
* @var bool
*/
public static $httpProxyTunnel = NULL;
/**
* CURLOPT_PROXYAUTH
*
* @var int
*/
public static $proxyAuth = NULL;
/**
* CURLOPT_PROXYPORT
*
* @var int
*/
public static $proxyPort = NULL;
/**
* CURLOPT_PROXYTYPE
*
* @var int
*/
public static $proxyType = NULL;
/**
* CURLOPT_PROXY
*
* @var string
*/
public static $proxy = NULL;
/**
* CURLOPT_PROXYUSERPWD
*
* @var string
*/
public static $proxyUserPassword = NULL;
/**
* OAuth2 access token.
*
* @var string
*/
protected $access_token;
/**
* Token expiration
*
* @var int
*/
protected $expires_in;
public function __construct($access_token, $expires_in = 0) {
$this->access_token = $access_token;
$this->expires_in = $expires_in;
}
/**
* Returns the OAuth2 access token.
*
* @return string
*/
public function getAccessToken() {
return $this->access_token;
}
/**
* Returns the access token expiration.
*
* This value might not be correct. The object stores the response
* from Brightcove, but it does not adjust it as the time passes.
*
* @return int
*/
public function getExpiresIn() {
return $this->expires_in;
}
/**
* Checks if this class has an access token.
*
* This usually means that the client is authorized, but not necessarily.
*
* @return bool
*/
public function isAuthorized() {
return (bool) $this->getAccessToken();
}
/**
* Sends an HTTP request.
*
* This method is an abstraction over curl.
*
* @param string $method
* HTTP method.
* @param string $url
* Full URL.
* @param array $headers
* Headers in curl format: an array of lines, not an associative array.
* @param null|string $postdata
* Postdata to send.
* @param null|callable $extraconfig
* A callback to set extra options on curl. This callback takes one argument,
* which is a curl resource and returns nothing.
* @return array
* A two item array. The first item is the status code, the second is the
* response body.
*/
public static function HTTPRequest($method, $url, array $headers = [], $postdata = NULL, callable $extraconfig = NULL) {
$ch = curl_init();
if ($postdata !== NULL) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$headers[] = 'Content-Type: application/json';
}
curl_setopt_array($ch, [
CURLOPT_AUTOREFERER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SAFE_UPLOAD => TRUE,
CURLOPT_MAXREDIRS => 5,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HEADER => TRUE,
]);
self::configureProxy($ch);
if ($extraconfig !== NULL) {
$extraconfig($ch);
}
$rawresult = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$res_headers = substr($rawresult, 0, $header_size);
$result = substr($rawresult, $header_size);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (self::$debugRequests) {
file_put_contents(self::$debugRequests, var_export([
'request' => "{$method} {$url}",
'request_body' => $postdata,
'headers' => $headers,
'response' => [$code, $result],
'response_headers' => $res_headers,
], TRUE) . "\n\n", FILE_APPEND);
}
curl_close($ch);
return [$code, $result];
}
/**
* Configures the proxy settings on a curl resource.
*
* @param resource $ch Curl resource
*/
protected static function configureProxy($ch) {
if (self::$httpProxyTunnel) {
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, self::$httpProxyTunnel);
}
if (self::$proxyAuth) {
curl_setopt($ch, CURLOPT_PROXYAUTH, self::$proxyAuth);
}
if (self::$proxyPort) {
curl_setopt($ch, CURLOPT_PROXYPORT, self::$proxyPort);
}
if (self::$proxyType) {
curl_setopt($ch, CURLOPT_PROXYTYPE, self::$proxyType);
}
if (self::$proxy) {
curl_setopt($ch, CURLOPT_PROXY, self::$proxy);
}
if (self::$proxyUserPassword) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, self::$proxyUserPassword);
}
}
/**
* A factory method to create an authorized Client instance.
*
* @param string $client_id
* OAuth2 client ID.
* @param string $client_secret
* OAuth2 client secret.
* @return Client
* An authorized client.
* @throws AuthenticationException
*/
public static function authorize($client_id, $client_secret) {
list($code, $response) = self::HTTPRequest('POST', 'https://oauth.brightcove.com/v3/access_token',
['Content-Type: application/x-www-form-urlencoded'],
'grant_type=client_credentials',
function ($ch) use ($client_id, $client_secret) {
curl_setopt($ch, CURLOPT_USERPWD, "{$client_id}:{$client_secret}");
});
if ($code !== 200) {
throw new AuthenticationException();
}
$json = json_decode($response, TRUE);
if ($json['token_type'] !== 'Bearer') {
throw new AuthenticationException('Unsupported token type: ' . $json['token_type']);
}
return new Client($json['access_token'], $json['expires_in']);
}
/**
* Sends an authorized request to a Brightcove API endpoint.
*
* @param string $method
* HTTP method.
* @param string $api_type
* API type, e.g. cms, di etc.
* @param string $account
* Brightcove account ID.
* @param string $endpoint
* API endpoint.
* @param string|null $result
* NULL to return the unmarshalled JSON, or a class name to deserialize into.
* This class must implement ObjectInterface.
* @param bool $is_array
* TRUE if the result is an array of objects. Not used when $result is NULL.
* @param ObjectInterface $post
* A ObjectInterface to post.
* @return ObjectInterface|ObjectInterface[]|null
* The endpoint result.
* @throws APIException
*/
public function request($method, $api_type, $account, $endpoint, $result, $is_array = FALSE, ObjectInterface $post = NULL) {
$body = NULL;
if ($post) {
if ($method === 'PATCH') {
$body = $post->patchJSON();
} else {
$body = $post->postJSON();
}
$body = json_encode($body);
}
list($code, $res) = self::HTTPRequest($method, "https://{$api_type}.api.brightcove.com/v1/accounts/{$account}{$endpoint}",
["Authorization: Bearer {$this->access_token}"], $body);
if ($code < 200 || $code >= 300) {
throw new APIException("Invalid status code: expected 200-299, got {$code}.\n\n{$res}", $code, NULL, $res);
}
$json = json_decode($res, TRUE);
if (is_null($result)) {
return $json;
}
if ($is_array) {
$ret = [];
foreach ($json as $item) {
$ret[] = call_user_func([$result, 'fromJSON'], $item);
}
return $ret;
}
return call_user_func([$result, 'fromJSON'], $json);
}
/**
* Sends an authorized request to the Brightcove Analytics API endpoint.
*
* @param string $method
* HTTP method.
* @param string $api_type
* API type, e.g. cms, di etc.
* @param string $account
* Brightcove account ID.
* @param string $dimensions
* Dimensions for API request.
* @param string|null $result
* NULL to return the unmarshalled JSON, or a class name to deserialize into.
* This class must implement ObjectInterface.
* @param date $from
* Start date for API request.
* @param date $to
* End date for API request.
* @param array $fields
* Array of fields to include in request.
* @param int $limit
* Limit for API request.
* @param string $sort
* Sort for API request.
* @param bool $is_array
* TRUE if the result is an array of objects. Not used when $result is NULL.
* @param ObjectInterface $post
* A ObjectInterface to post.
* @return ObjectInterface|ObjectInterface[]|null
* The endpoint result.
* @throws APIException
*/
public function requestAnalytics($method, $api_type, $account, $dimensions, $result, $from, $to, $fields, $limit = 10, $sort = '-video_view', $is_array = FALSE, ObjectInterface $post = NULL) {
$body = NULL;
$fields_str = implode(',', $fields);
if ($post) {
if ($method === 'PATCH') {
$body = $post->patchJSON();
} else {
$body = $post->postJSON();
}
$body = json_encode($body);
}
list($code, $res) = self::HTTPRequest($method,
"https://{$api_type}.api.brightcove.com/v1/data?accounts={$account}&dimensions={$dimensions}&limit={$limit}&sort={$sort}&from={$from}&to={$to}&fields={$fields_str}",
["Authorization: Bearer {$this->access_token}"], $body);
if ($code < 200 || $code >= 300) {
throw new APIException("Invalid status code: expected 200-299, got {$code}.\n\n{$res}", $code, NULL, $res);
}
$json = json_decode($res, TRUE);
if (is_null($result)) {
return $json;
}
if ($is_array) {
$ret = [];
foreach ($json as $item) {
$ret[] = call_user_func([$result, 'fromJSON'], $item);
}
return $ret;
}
return call_user_func([$result, 'fromJSON'], $json);
}
}