-
Notifications
You must be signed in to change notification settings - Fork 0
/
oembed.py
619 lines (445 loc) · 18.2 KB
/
oembed.py
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
'''A Python library that implements an OEmbed consumer to use with OEmbed providers.
Based on reference from http://oembed.com/
oEmbed is a format for allowing an embedded representation of a URL on
third party sites. The simple API allows a website to display embedded content
(such as photos or videos) when a user posts a link to that resource, without
having to parse the resource directly.
OEmbed format authors:
* Cal Henderson (cal [at] iamcal.com)
* Mike Malone (mike [at] pownce.com)
* Leah Culver (leah [at] pownce.com)
* Richard Crowley (r [at] rcrowley.org)
Simple usage:
import oembed
consumer = oembed.OEmbedConsumer()
endpoint = oembed.OEmbedEndpoint('http://www.flickr.com/services/oembed',
['http://*.flickr.com/*'])
consumer.addEndpoint(endpoint)
response = consumer.embed('http://www.flickr.com/photos/wizardbt/2584979382/')
print response['url']
import pprint
pprint.pprint(response.getData())
Copyright (c) 2008 Ariel Barmat, abarmat@gmail.com
Copyright (c) 2010 Mathijs de Bruin, drbob@dokterbob.net
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
'''
import urllib
import urllib2
import logging
import re
import simplejson
try:
from xml.etree import cElementTree as etree
except ImportError:
# Running Python < 2.4 so we need a different import
import cElementTree as etree
__author__ = 'drbob@dokterbob.net'
__version__ = '0.2'
class OEmbedError(Exception):
'''Base class for OEmbed errors'''
class OEmbedInvalidRequest(OEmbedError):
'''Raised when an invalid parameter is used in a request'''
class OEmbedNoEndpoint(OEmbedError):
'''Raised when no endpoint is available for a particular URL'''
class OEmbedResponse(object):
'''
Base class for all OEmbed responses.
This class provides a factory of OEmbed responses according to the format
detected in the type field. It also validates that mandatory fields are
present.
'''
def _validateData(self, data):
pass
def __getitem__(self, name):
return self._data.get(name)
def __iter__(self):
return self.iterkeys()
def iterkeys(self):
return self._data.iterkeys()
def getData(self):
return self._data
def loadData(self, data):
self._validateData(data)
self._data = data
@classmethod
def createLoad(cls, data):
if not data.has_key('type') or \
not data.has_key('version'):
raise OEmbedError('Missing required fields on OEmbed response.')
response = cls.create(data['type'])
response.loadData(data)
return response
@classmethod
def create(cls, responseType):
return resourceTypes.get(responseType, OEmbedResponse)()
@classmethod
def newFromJSON(cls, raw):
data = simplejson.loads(raw)
return cls.createLoad(data)
@classmethod
def newFromXML(cls, raw):
elem = etree.XML(raw)
data = dict([(e.tag, e.text) for e in elem.getiterator() \
if e.tag not in ['oembed']])
return cls.createLoad(data)
class OEmbedPhotoResponse(OEmbedResponse):
'''
This type is used for representing static photos.
'''
def _validateData(self, data):
OEmbedResponse._validateData(self, data)
if not data.has_key('url') or \
not data.has_key('width') or \
not data.has_key('height'):
raise OEmbedError('Missing required fields on OEmbed photo response.')
class OEmbedVideoResponse(OEmbedResponse):
'''
This type is used for representing playable videos.
'''
def _validateData(self, data):
OEmbedResponse._validateData(self, data)
if not data.has_key('html') or \
not data.has_key('width') or \
not data.has_key('height'):
raise OEmbedError('Missing required fields on OEmbed video response.')
class OEmbedLinkResponse(OEmbedResponse):
'''
Responses of this type allow a provider to return any generic embed data
(such as title and author_name), without providing either the url or html
parameters. The consumer may then link to the resource, using the URL
specified in the original request.
'''
class OEmbedRichResponse(OEmbedResponse):
'''
This type is used for rich HTML content that does not fall under
one of the other categories.
'''
def _validateData(self, data):
OEmbedResponse._validateData(self, data)
if not data.has_key('html') or \
not data.has_key('width') or \
not data.has_key('height'):
raise OEmbedError('Missing required fields on OEmbed rich response.')
resourceTypes = {
'photo': OEmbedPhotoResponse,
'video': OEmbedVideoResponse,
'link': OEmbedLinkResponse,
'rich': OEmbedRichResponse
}
class OEmbedEndpoint(object):
'''
A class representing an OEmbed Endpoint exposed by a provider.
This class handles a number of URL schemes and manage resource retrieval.
'''
def __init__(self, url, urlSchemes=None):
'''
Create a new OEmbedEndpoint object.
Args:
url: The url of a provider API (API endpoint).
urlSchemes: A list of URL schemes for this endpoint.
'''
self._urlApi = url
self._urlSchemes = {}
self._initRequestHeaders()
self._urllib = urllib2
if urlSchemes is not None:
map(self.addUrlScheme, urlSchemes)
self._implicitFormat = self._urlApi.find('{format}') != -1
def _initRequestHeaders(self):
self._requestHeaders = {}
self.setUserAgent('python-oembed/' + __version__)
def addUrlScheme(self, url):
'''
Add a url scheme to this endpoint. It takes a url string and create
the OEmbedUrlScheme object internally.
Args:
url: The url string that represents a url scheme to add.
'''
#@todo: validate invalid url format according to http://oembed.com/
if not isinstance(url, str):
raise TypeError('url must be a string value')
if not self._urlSchemes.has_key(url):
self._urlSchemes[url] = OEmbedUrlScheme(url)
def delUrlScheme(self, url):
'''
Remove an OEmbedUrlScheme from the list of schemes.
Args:
url: The url used as key for the urlSchems dict.
'''
if self._urlSchemes.has_key(url):
del self._urlSchemes[url]
def clearUrlSchemes(self):
'''Clear the schemes in this endpoint.'''
self._urlSchemes.clear()
def getUrlSchemes(self):
'''
Get the url schemes in this endpoint.
Returns:
A dict of OEmbedUrlScheme objects. k => url, v => OEmbedUrlScheme
'''
return self._urlSchemes
def match(self, url):
'''
Try to find if url matches against any of the schemes within this
endpoint.
Args:
url: The url to match against each scheme
Returns:
True if a matching scheme was found for the url, False otherwise
'''
for urlScheme in self._urlSchemes.itervalues():
if urlScheme.match(url):
return True
return False
def request(self, url, **opt):
'''
Format the input url and optional parameters, and provides the final url
where to get the given resource.
Args:
url: The url of an OEmbed resource.
**opt: Parameters passed to the url.
Returns:
The complete url of the endpoint and resource.
'''
params = opt
params['url'] = url
urlApi = self._urlApi
if params.has_key('format') and self._implicitFormat:
urlApi = self._urlApi.replace('{format}', params['format'])
del params['format']
return "%s?%s" % (urlApi, urllib.urlencode(params))
def get(self, url, **opt):
'''
Convert the resource url to a complete url and then fetch the
data from it.
Args:
url: The url of an OEmbed resource.
**opt: Parameters passed to the url.
Returns:
OEmbedResponse object according to data fetched
'''
return self.fetch(self.request(url, **opt))
def fetch(self, url):
'''
Fetch url and create a response object according to the mime-type.
Args:
url: The url to fetch data from
Returns:
OEmbedResponse object according to data fetched
'''
opener = self._urllib.build_opener()
opener.addheaders = self._requestHeaders.items()
response = opener.open(url)
headers = response.info()
raw = response.read()
if not headers.has_key('Content-Type'):
raise OEmbedError('Missing mime-type in response')
if headers['Content-Type'].find('application/xml') != -1 or \
headers['Content-Type'].find('text/xml') != -1:
response = OEmbedResponse.newFromXML(raw)
elif headers['Content-Type'].find('application/json') != -1 or \
headers['Content-Type'].find('text/json') != -1 or \
headers['Content-Type'].find('application/x-json') != -1:
response = OEmbedResponse.newFromJSON(raw)
else:
raise OEmbedError('Invalid mime-type in response - %s' % \
headers['Content-Type'])
return response
def setUrllib(self, urllib):
'''
Override the default urllib implementation.
Args:
urllib: an instance that supports the same API as the urllib2 module
'''
self._urllib = urllib
def setUserAgent(self, user_agent):
'''
Override the default user agent
Args:
user_agent: a string that should be send to the server as the User-agent
'''
self._requestHeaders['User-Agent'] = user_agent
class OEmbedAutoDiscovery(OEmbedEndpoint):
def __init__(self):
self._urllib = urllib2
self._initRequestHeaders()
def request(self, url, **opt):
'''
Format the input url and optional parameters, and provides the final url
where to get the given resource.
Args:
url: The url of an OEmbed resource.
**opt: Parameters passed to the url.
Returns:
The complete url of the endpoint and resource.
'''
params = opt
urlApi = self.discover(url)
if not urlApi:
raise OEmbedError('No OEmbed URL could be discovered for %s' % url)
if params.has_key('format') and self._implicitFormat:
urlApi = self._urlApi.replace('{format}', params['format'])
del params['format']
return "%s&%s" % (urlApi, urllib.urlencode(params))
def discover(self, url, format=None):
from scrape import Session
s = Session(agent='Banana King')
r = s.go(url)
head = r.first('head', enders='/head')
if not format or (format == 'json'):
try:
tag = head.firsttag('link', type='application/json+oembed')
return tag['href']
except Exception:
pass
if not format or (format == 'xml'):
try:
head.firsttag('link', type='application/xml+oembed')
return tag['href']
except Exception:
pass
return None
class OEmbedUrlScheme(object):
'''
A class representing an OEmbed URL schema.
'''
def __init__(self, url):
'''
Create a new OEmbedUrlScheme instanace.
Args;
url: The url scheme. It also takes the wildcard character (*).
'''
self._url = url
self._regex = re.compile(url.replace('.', '\.')\
.replace('*', '.*'))
def getUrl(self):
'''
Get the url scheme.
Returns:
The url scheme.
'''
return self._url
def match(self, url):
'''
Match the url against this scheme.
Args:
url: The url to match against this scheme.
Returns:
True if a match was found for the url, False otherwise
'''
return self._regex.match(url) is not None
def __repr__(self):
return "%s - %s" % (object.__repr__(self), self._url)
class OEmbedConsumer(object):
'''
A class representing an OEmbed consumer.
This class manages a number of endpoints, selects the corresponding one
according to the resource url passed to the embed function and fetches
the data.
'''
def __init__(self):
self._endpoints = []
def addEndpoint(self, endpoint):
'''
Add a new OEmbedEndpoint to be manage by the consumer.
Args:
endpoint: An instance of an OEmbedEndpoint class.
'''
self._endpoints.append(endpoint)
def delEndpoint(self, endpoint):
'''
Remove an OEmbedEnpoint from this consumer.
Args:
endpoint: An instance of an OEmbedEndpoint class.
'''
self._endpoints.remove(endpoint)
def clearEndpoints(self):
'''Clear all the endpoints managed by this consumer.'''
del self._endpoints[:]
def getEndpoints(self):
'''
Get the list of endpoints.
Returns:
The list of endpoints in this consumer.
'''
return self._endpoints
def _endpointFor(self, url):
for endpoint in self._endpoints:
if endpoint.match(url):
return endpoint
return None
def _request(self, url, **opt):
endpoint = self._endpointFor(url)
if endpoint is None:
logging.debug('No endpoint found for %s, attempting auto-discovery.' % url)
return OEmbedAutoDiscovery().get(url, **opt)
raise OEmbedNoEndpoint('There are no endpoints available for \'%s\' and autodiscovery failed.'\
% url)
return endpoint.get(url, **opt)
def embed(self, url, format='json', **opt):
'''
Get an OEmbedResponse from one of the providers configured in this
consumer according to the resource url.
Args:
url: The url of the resource to get.
format: Desired response format.
**opt: Optional parameters to pass in the url to the provider.
Returns:
OEmbedResponse object.
'''
if format not in ['json', 'xml']:
raise OEmbedInvalidRequest('Format must be json or xml')
opt['format'] = format
return self._request(url, **opt)
"""
>>> r = DefaultOEmbedConsumer.embed('http://www.flickr.com/photos/14950906@N07/3501945280/')
>>> r['author_name']
'gicol'
>>> r['url']
'http://farm4.static.flickr.com/3582/3501945280_fa47a316b1.jpg'
"""
DefaultOEmbedConsumer = OEmbedConsumer()
DefaultOEmbedConsumer.addEndpoint(
OEmbedEndpoint('http://www.youtube.com/oembed',
['http://www.youtube.com/watch*']))
DefaultOEmbedConsumer.addEndpoint(
OEmbedEndpoint('http://www.flickr.com/services/oembed',
['http://*.flickr.com/*']))
DefaultOEmbedConsumer.addEndpoint(
OEmbedEndpoint('http://revision3.com/api/oembed/',
['http://*.revision3.com/*']))
DefaultOEmbedConsumer.addEndpoint(
OEmbedEndpoint('http://www.hulu.com/api/oembed.{format}',
['http://www.hulu.com/watch/*']))
DefaultOEmbedConsumer.addEndpoint(
OEmbedEndpoint('http://www.vimeo.com/api/oembed.{format}',
['http://www.vimeo.com/*',
'http://vimeo.com/*',
'http://www.vimeo.com/groups/*/*']))
DefaultOEmbedConsumer.addEndpoint(
OEmbedEndpoint('http://lab.viddler.com/services/oembed/',
['http://*.viddler.com/*']))
DefaultOEmbedConsumer.addEndpoint(
OEmbedEndpoint('http://www.scribd.com/services/oembed',
['http://*.scribd.com/*']))
DefaultOEmbedConsumer.addEndpoint(
OEmbedEndpoint('http://qik.com/api/oembed.{format}',
['http://qik.com/*']))
DefaultOEmbedConsumer.addEndpoint(
OEmbedEndpoint('http://www.dailymotion.com/api/oembed',
['http://www.dailymotion.com/*']))