7 from .common 
import InfoExtractor
 
  13     compat_urllib_parse_urlparse
, 
  14     compat_urllib_request
, 
  21 class BlipTVIE(InfoExtractor
): 
  22     """Information extractor for blip.tv""" 
  24     _VALID_URL 
= r
'^(?:https?://)?(?:\w+\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$' 
  25     _URL_EXT 
= r
'^.*\.([a-z0-9]+)$' 
  28         u
'url': u
'http://blip.tv/cbr/cbr-exclusive-gotham-city-imposters-bats-vs-jokerz-short-3-5796352', 
  29         u
'file': u
'5779306.m4v', 
  30         u
'md5': u
'80baf1ec5c3d2019037c1c707d676b9f', 
  32             u
"upload_date": u
"20111205",  
  33             u
"description": u
"md5:9bc31f227219cde65e47eeec8d2dc596",  
  34             u
"uploader": u
"Comic Book Resources - CBR TV",  
  35             u
"title": u
"CBR EXCLUSIVE: \"Gotham City Imposters\" Bats VS Jokerz Short 3" 
  39     def report_direct_download(self
, title
): 
  40         """Report information extraction.""" 
  41         self
.to_screen(u
'%s: Direct download detected' % title
) 
  43     def _real_extract(self
, url
): 
  44         mobj 
= re
.match(self
._VALID
_URL
, url
) 
  46             raise ExtractorError(u
'Invalid URL: %s' % url
) 
  48         # See https://github.com/rg3/youtube-dl/issues/857 
  49         api_mobj 
= re
.match(r
'http://a\.blip\.tv/api\.swf#(?P<video_id>[\d\w]+)', url
) 
  50         if api_mobj 
is not None: 
  51             url 
= 'http://blip.tv/play/g_%s' % api_mobj
.group('video_id') 
  52         urlp 
= compat_urllib_parse_urlparse(url
) 
  53         if urlp
.path
.startswith('/play/'): 
  54             response 
= self
._request
_webpage
(url
, None, False) 
  55             redirecturl 
= response
.geturl() 
  56             rurlp 
= compat_urllib_parse_urlparse(redirecturl
) 
  57             file_id 
= compat_parse_qs(rurlp
.fragment
)['file'][0].rpartition('/')[2] 
  58             url 
= 'http://blip.tv/a/a-' + file_id
 
  59             return self
._real
_extract
(url
) 
  66         json_url 
= url 
+ cchar 
+ 'skin=json&version=2&no_wrap=1' 
  67         request 
= compat_urllib_request
.Request(json_url
) 
  68         request
.add_header('User-Agent', 'iTunes/10.6.1') 
  69         self
.report_extraction(mobj
.group(1)) 
  71         urlh 
= self
._request
_webpage
(request
, None, False, 
  72             u
'unable to download video info webpage') 
  73         if urlh
.headers
.get('Content-Type', '').startswith('video/'): # Direct download 
  74             basename 
= url
.split('/')[-1] 
  75             title
,ext 
= os
.path
.splitext(basename
) 
  76             title 
= title
.decode('UTF-8') 
  77             ext 
= ext
.replace('.', '') 
  78             self
.report_direct_download(title
) 
  88         if info 
is None: # Regular URL 
  90                 json_code_bytes 
= urlh
.read() 
  91                 json_code 
= json_code_bytes
.decode('utf-8') 
  92             except (compat_urllib_error
.URLError
, compat_http_client
.HTTPException
, socket
.error
) as err
: 
  93                 raise ExtractorError(u
'Unable to read video info webpage: %s' % compat_str(err
)) 
  96                 json_data 
= json
.loads(json_code
) 
  97                 if 'Post' in json_data
: 
  98                     data 
= json_data
['Post'] 
 102                 upload_date 
= datetime
.datetime
.strptime(data
['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d') 
 103                 if 'additionalMedia' in data
: 
 104                     formats 
= sorted(data
['additionalMedia'], key
=lambda f
: int(f
['media_height'])) 
 105                     best_format 
= formats
[-1] 
 106                     video_url 
= best_format
['url'] 
 108                     video_url 
= data
['media']['url'] 
 109                 umobj 
= re
.match(self
._URL
_EXT
, video_url
) 
 111                     raise ValueError('Can not determine filename extension') 
 115                     'id': compat_str(data
['item_id']), 
 117                     'uploader': data
['display_name'], 
 118                     'upload_date': upload_date
, 
 119                     'title': data
['title'], 
 121                     'format': data
['media']['mimeType'], 
 122                     'thumbnail': data
['thumbnailUrl'], 
 123                     'description': data
['description'], 
 124                     'player_url': data
['embedUrl'], 
 125                     'user_agent': 'iTunes/10.6.1', 
 127             except (ValueError,KeyError) as err
: 
 128                 raise ExtractorError(u
'Unable to parse video information: %s' % repr(err
)) 
 133 class BlipTVUserIE(InfoExtractor
): 
 134     """Information Extractor for blip.tv users.""" 
 136     _VALID_URL 
= r
'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$' 
 138     IE_NAME 
= u
'blip.tv:user' 
 140     def _real_extract(self
, url
): 
 142         mobj 
= re
.match(self
._VALID
_URL
, url
) 
 144             raise ExtractorError(u
'Invalid URL: %s' % url
) 
 146         username 
= mobj
.group(1) 
 148         page_base 
= 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1' 
 150         page 
= self
._download
_webpage
(url
, username
, u
'Downloading user page') 
 151         mobj 
= re
.search(r
'data-users-id="([^"]+)"', page
) 
 152         page_base 
= page_base 
% mobj
.group(1) 
 155         # Download video ids using BlipTV Ajax calls. Result size per 
 156         # query is limited (currently to 12 videos) so we need to query 
 157         # page by page until there are no video ids - it means we got 
 164             url 
= page_base 
+ "&page=" + str(pagenum
) 
 165             page 
= self
._download
_webpage
(url
, username
, 
 166                                           u
'Downloading video ids from page %d' % pagenum
) 
 168             # Extract video identifiers 
 171             for mobj 
in re
.finditer(r
'href="/([^"]+)"', page
): 
 172                 if mobj
.group(1) not in ids_in_page
: 
 173                     ids_in_page
.append(unescapeHTML(mobj
.group(1))) 
 175             video_ids
.extend(ids_in_page
) 
 177             # A little optimization - if current page is not 
 178             # "full", ie. does not contain PAGE_SIZE video ids then 
 179             # we can assume that this page is the last one - there 
 180             # are no more ids on further pages - no need to query 
 183             if len(ids_in_page
) < self
._PAGE
_SIZE
: 
 188         urls 
= [u
'http://blip.tv/%s' % video_id 
for video_id 
in video_ids
] 
 189         url_entries 
= [self
.url_result(vurl
, 'BlipTV') for vurl 
in urls
] 
 190         return [self
.playlist_result(url_entries
, playlist_title 
= username
)]