bgneal@285: """
bgneal@285: This module contains core functionality for the oembed application.
bgneal@679: 
bgneal@285: """
bgneal@908: from contextlib import closing
bgneal@679: import json
bgneal@285: import urllib
bgneal@285: import urllib2
bgneal@285: import gzip
bgneal@285: try:
bgneal@285:     from cStringIO import StringIO
bgneal@285: except ImportError:
bgneal@285:     from StringIO import StringIO
bgneal@285: 
bgneal@285: 
bgneal@285: 
bgneal@285: USER_AGENT = 'gremmies python oembed'
bgneal@285: 
bgneal@285: 
bgneal@908: def get_oembed(api_endpoint, url, fmt='json', **opts):
bgneal@285:     """
bgneal@285:     Perform the GET request to retrieve the embedded media data from the given
bgneal@285:     API endpoint for the given URL. Return the result as a Python dictionary.
bgneal@285: 
bgneal@908:     fmt specifies the response format, and should be 'json' or 'xml'.
bgneal@285:     opts are any additional GET options that should be present in the GET
bgneal@285:     request.
bgneal@285: 
bgneal@285:     """
bgneal@285:     opts['url'] = url
bgneal@908:     opts['format'] = fmt
bgneal@285:     api_url = "%s?%s" % (api_endpoint, urllib.urlencode(opts))
bgneal@285: 
bgneal@285:     headers = {
bgneal@361:         'User-Agent': USER_AGENT,
bgneal@285:         'Accept-Encoding': 'gzip',
bgneal@285:     }
bgneal@285:     request = urllib2.Request(api_url, headers=headers)
bgneal@908:     with closing(urllib2.urlopen(request)) as response:
bgneal@908:         headers = response.info()
bgneal@908:         result = response.read()
bgneal@285: 
bgneal@285:     if headers.get('content-encoding') == 'gzip':
bgneal@908:         with closing(gzip.GzipFile(fileobj=StringIO(result))) as f:
bgneal@908:             result = f.read()
bgneal@285: 
bgneal@285:     return json.loads(result)
bgneal@285: 
bgneal@285: if __name__ == "__main__":
bgneal@285:     try:
bgneal@285:         print get_oembed("http://www.youtube.com/oembed",
bgneal@907:                          "http://www.youtube.com/watch?v=7_IMzJldOf4",
bgneal@907:                          scheme='https')
bgneal@285:     except urllib2.HTTPError, e:
bgneal@285:         print e