-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVidlyAPI.inc
425 lines (379 loc) · 12.6 KB
/
VidlyAPI.inc
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
<?php
/**
* Vid.ly API
*/
class VidlyAPI {
public $api_user = '';
public $api_key = '';
public $notify_url = '';
// When set to a non-empty value (1, TRUE, 'Hi') this variable will be filled
// with debug information from the request. Example usage:
//
// $api->debug = TRUE;
// $api->addMedia($sources);
// echo $api->debug; // Will now contain the debug log
// $api->debug = FALSE; // Discard the debug log and turn debugging off
public $debug = FALSE;
// Either NULL or an array of errors generated by the last request.
// @see _parseResponse()
public $errors = NULL;
// Either NULL or an array of successes from the last request.
// @see _parseResponse()
public $successes = NULL;
// Either NULL or an array of result objects.
public $result = NULL;
// The Message and MessageCode of the last request
public $message = NULL;
public $message_code = NULL;
// Either NULL or the BatchID this response is associated with.
public $batch_id = NULL;
// URL for the vid.ly API. Watch out, the trailing slash IS necessary.
public $vidly_api_url = 'http://m.vid.ly/api/';
/**
* VidlyAPI constructor.
*
* @param (string) $api_user
* @param (string) $api_key
* @param (string) $notify_url
* The default URL where vid.ly will post notifications for completed jobs.
*
* NOTE: Setting this to FALSE will disable all vid.ly notifications.
* This is not recommended.
*/
function __construct($api_user, $api_key, $notify_url) {
$this->api_user = $api_user;
$this->api_key = $api_key;
$this->notify_url = $notify_url;
}
/**
* Verifies that the currently set User and Key are valid.
*
* @return (boolean)
*/
function userAndKeyAreValid() {
// Send a safe request using bad data. The ErrorCode will indicate whether
// the request failed because of invalid credentials or otherwise.
// Yes, this is hackish :-(.
$this->getStatus(array('TEST'));
return $this->errors->ErrorCode != '1.3';
}
/**
* Add a new media to user's queue. Creates new short URL and generates 24
* various output formats. Also allows to specify user defined custom
* formats.
*
* NOTE: Currently custom formats are not supported by this class.
*
* @param (array) $sources
* A list of source objects. For example:
*
* $sources = array(
* // Most basic example, just a URL to a video
* stdClass::__set_state(array(
* 'SourceFile' => 'http://example.com/cats.mov',
* )),
* // More complex example, a video hosted on S3
* stdClass::__set_state(array(
* 'SourceFile' => 'http://[AWS_KEY:AWS_SECRET@][bucket].s3.amazonaws.com/cats.mov',
* 'CDN' => 'AWS',
* )),
* )
*
* @param (string) $notify_url
* Override the default notify_url specified in the constructor.
*/
function addMedia($sources, $notify_url = NULL) {
return $this->_performRequest('AddMedia', $sources, $notify_url);
}
/**
* Add a new media to user's queue. Creates new short URL and generates only
* 5 output formats. This API call is designed for customers who do not want
* to incur the ongoing storage expense of all 24 of our standard web and
* mobile output formats and are less concerned with complete mobile device
* coverage. Also allows to specify user defined custom formats.
*
* NOTE: This API method will only generate video formats for MOBILE devices.
*
* see: http://www.blog.vid.ly/index.php/index/news-entry/mobile_diet_vid.ly_lite_a.k.a_diet_vid.ly_is_here
*
* @param (array) $sources
* Same format as addMedia.
* @param (string) $notify_url
* Override the default notify_url specified in the constructor.
*/
function addMediaLite($sources, $notify_url = NULL) {
return $this->_performRequest('AddMediaLite', $sources, $notify_url);
}
/**
* Allows to update an existing Vid.ly URL with new source content. Very
* simple! Via API you can use the UpdateMedia call along with the shortlink
* and you're ready to roll.
*
* @param (array) $sources
* A list of objects referencing the source of the new media and the
* existing shortLink. The format is essentially the same as that
* described in addMedia. For example:
*
* $sources = array(
* // Most basic example, just a URL to a video
* stdClass::__set_state(array(
* 'MediaShortLink' => 'http://vid.ly/abc123',
* 'SourceFile' => 'http://example.com/more_awesome_cats.mov'
* )),
* )
*
* @param (string) $notify_url
* Override the default notify_url specified in the constructor.
*/
function updateMedia($sources, $notify_url = NULL) {
return $this->_performRequest('UpdateMedia', $sources, $notify_url);
}
/**
* Removes uploaded videos by short URL or by BatchID.
*
* NOTE: Only removal by short URL is supported.
*
* @param (array) $shortLinks
* An array of short URLS. For example: array('http://vid.ly/abc123')
*/
function deleteMedia($shortLinks) {
return $this->_performRequest('DeleteMedia', $shortLinks, FALSE);
}
/**
* Can be used to obtain status information on jobs, by BatchID or
* MediaShortlink.
*
* @param (array) $shortLinks
* Same format as in deleteMedia.
*/
function getStatus($shortLinks) {
return $this->_performRequest('GetStatus', $shortLinks, FALSE);
}
/**
* Get browser and mobile devices visits statistics for specified time
* range and short URL. If short URL is not specified, will return
* cumulative stats for all your videos.
*
* @param (object) $filter
* An object containing properties for any of 'StartDate', 'EndDate' or
* 'MediaShortLink'. For example:
*
* $filter = stdClass::__set_state(array(
* 'StartDate' => '2012-01-01 00:00:00',
* ));
*/
function getStatistics($filter = NULL) {
return $this->_performRequest('GetStatistics', $filter, FALSE);
}
/**
* Sends a request to the vid.ly API server using cURL, parses the result
* and returns it. Optionally, a notify URL can be specified which will
* asynchronously receive a callback with the result of the request.
*
* @param (string) $action
* The API action to perform. The $params must suitably match the action.
* @param (array) $params
* A list of API parameters corresponding to $action.
* @param (mixed) $notify_url
* FALSE The result of the request will be returned directly,
* ie: synchronously.
*
* NULL, '' Use default notify_url, as supplied in the constructor.
*
* '...' Everything else is assumed to be a valid callback URL where
* the response will be POSTED.
*/
function _performRequest($action, $params, $notify_url) {
if (is_string($notify_url) && strlen($notify_url) > 0) {
// Do nothing, this $notify_url will override the default
}
else if ($notify_url === FALSE) {
// Notification callback will be disabled
}
else {
$notify_url = $this->notify_url;
}
$xml = '<?xml version="1.0"?>';
$xml .= '<Query>';
$xml .= '<Action>' . $action . '</Action>';
$xml .= '<UserID>' . $this->api_user . '</UserID>';
$xml .= '<UserKey>' . $this->api_key . '</UserKey>';
if ($notify_url) {
$xml .= '<Notify>' . $notify_url . '</Notify>';
}
if ($params) {
$xml .= $this->_xmlParams($action, $params);
}
$xml .= '</Query>';
if ($this->debug) {
$this->debug .= "QUERY:\n";
$this->debug .= var_export($xml, 1) . "\n";
}
// Buy 30 seconds for the cURL request and 10 seconds to process it
ini_set('max_execution_time', 40);
$ch = curl_init($this->vidly_api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('xml' => $xml));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
if ($this->debug) {
$this->debug .= "RAW RESULT:\n";
$this->debug .= var_export($result, 1) . "\n";
}
return $this->_parseResponse($result);
}
/**
* Turns parameters into corresponding XML for a given $action
*/
function _xmlParams($action, $params) {
switch ($action) {
case 'AddMedia':
case 'AddMediaLite':
case 'UpdateMedia':
$wrapper = 'Source';
break;
case 'DeleteMedia':
case 'GetStatus':
$wrapper = 'MediaShortLink';
break;
case 'GetStatistics':
$wrapper = 'Filter';
default:
return FALSE;
}
$xml = '';
foreach ($params as $data) {
$xml .= $this->_xmlTagify((object) array($wrapper => $data));
}
return $xml;
}
/**
* Recursively flattens an object into XML.
*/
function _xmlTagify($obj, $depth = 0) {
// Safety
if ($depth > 50) return '';
$xml = '';
foreach ($obj as $tag => $data) {
switch (gettype($data)) {
case 'object':
case 'array':
$xml .= "<{$tag}>" . $this->_xmlTagify($data, $depth + 1) . "</{$tag}>";
break;
default:
$xml .= "<{$tag}>" . $this->_xmlEscape($data) . "</{$tag}>";
break;
}
}
return $xml;
}
function _xmlEscape($string) {
return str_replace(
array("<", ">", "\"", "'", "&"),
array("<", ">", """, "'", "&"),
$string
);
}
function _resetResponse() {
$this->message = NULL;
$this->message_code = NULL;
$this->errors = NULL;
$this->batch_id = NULL;
$this->successes = NULL;
$this->result = NULL;
}
/**
* Parses a vid.ly response and returns the response data object, or FALSE
* on error.
*
* The $errors and $successes attributes will be updated accordingly.
*
* @param (string) $xml
*/
function _parseResponse($xml) {
$this->_resetResponse();
try {
$xml = @new SimpleXMLElement($xml);
} catch (Exception $e) {
// Avoid throwing warnings below by having $xml be an empty object
$xml = (object) array();
$this->errors = (object) array(
'ErrorCode' => '-1.0',
'ErrorName' => 'VidlyAPI: Invalid XML response, could not parse.'
);
if ($this->debug) {
$this->debug .= "FAILURE could not parse XML response\n";
}
}
if ($this->debug) {
$this->debug .= "RESPONSE SimpleXMLElement:\n";
$this->debug .= var_export($xml, 1) . "\n";
}
if (isset($xml->Message)) {
$this->message = (string) $xml->Message;
}
if (isset($xml->MessageCode)) {
$this->message_code = (string) $xml->MessageCode;
}
if (isset($xml->Errors)) {
$this->errors = (object) array();
$this->_simpleXMLToObject($xml->Errors->children(), $this->errors);
}
if (isset($xml->BatchID)) {
$this->batch_id = (string) $xml->BatchID;
}
if (isset($xml->Success)) {
$this->successes = (object) array();
$this->_simpleXMLToObject($xml->Success->children(), $this->successes);
}
if (isset($xml->Result)) {
$this->result = (object) array();
$this->_simpleXMLToObject($xml->Result->children(), $this->result);
}
if (empty($this->errors) && empty($this->successes) && empty($this->result)) {
$this->errors = (object) array(
'ErrorCode' => '-1.1',
'ErrorName' => 'VidlyAPI: No errors, successes or results could be parsed from the XML response.'
);
}
// Drupal specific debugging
if (function_exists('variable_get') && variable_get('vidly_api_debug', FALSE)) {
watchdog('VidlyAPI', "Debug: <pre>!debug</pre>", array('!debug' => htmlspecialchars($this->debug)));
}
return TRUE;
}
/**
* Recursively flattens a SimpleXML object into a normal stdClass object.
*
* Note that this is a destructive operation as XML attributes are
* not preserved.
*/
function _simpleXMLToObject($xml, &$obj, $depth = 0) {
if ($depth > 50) return;
foreach ($xml as $node) {
$tag_name = (string) $node->getName();
$children = $node->children();
if (isset($obj->{$tag_name})) {
if (!is_array($obj->{$tag_name})) {
$obj->{$tag_name} = array($obj->{$tag_name});
}
}
if (is_array($obj->{$tag_name})) {
$next_node =& $obj->{$tag_name}[];
}
else {
$next_node =& $obj->{$tag_name};;
}
if (!$children->getName()) {
$next_node = (string) $node;
}
else {
$next_node = (object) array();
$this->_simpleXMLToObject($children, $next_node, $depth + 1);
}
}
}
}