[BlipTVIE] Extract all formats
[youtube-dl] / youtube_dl / extractor / bliptv.py
1 import datetime
2 import json
3 import re
4 import socket
5
6 from .common import InfoExtractor
7 from ..utils import (
8     compat_http_client,
9     compat_parse_qs,
10     compat_str,
11     compat_urllib_error,
12     compat_urllib_parse_urlparse,
13     compat_urllib_request,
14
15     ExtractorError,
16     unescapeHTML,
17     determine_ext,
18 )
19
20
21 class BlipTVIE(InfoExtractor):
22     """Information extractor for blip.tv"""
23
24     _VALID_URL = r'^(?:https?://)?(?:www\.)?blip\.tv/((.+/)|(play/)|(api\.swf#))(.+)$'
25     IE_NAME = u'blip.tv'
26     _TEST = {
27         u'url': u'http://blip.tv/cbr/cbr-exclusive-gotham-city-imposters-bats-vs-jokerz-short-3-5796352',
28         u'file': u'5779306.m4v',
29         u'md5': u'80baf1ec5c3d2019037c1c707d676b9f',
30         u'info_dict': {
31             u"upload_date": u"20111205", 
32             u"description": u"md5:9bc31f227219cde65e47eeec8d2dc596", 
33             u"uploader": u"Comic Book Resources - CBR TV", 
34             u"title": u"CBR EXCLUSIVE: \"Gotham City Imposters\" Bats VS Jokerz Short 3"
35         }
36     }
37
38     def report_direct_download(self, title):
39         """Report information extraction."""
40         self.to_screen(u'%s: Direct download detected' % title)
41
42     def _real_extract(self, url):
43         mobj = re.match(self._VALID_URL, url)
44         if mobj is None:
45             raise ExtractorError(u'Invalid URL: %s' % url)
46
47         # See https://github.com/rg3/youtube-dl/issues/857
48         api_mobj = re.match(r'http://a\.blip\.tv/api\.swf#(?P<video_id>[\d\w]+)', url)
49         if api_mobj is not None:
50             url = 'http://blip.tv/play/g_%s' % api_mobj.group('video_id')
51         urlp = compat_urllib_parse_urlparse(url)
52         if urlp.path.startswith('/play/'):
53             response = self._request_webpage(url, None, False)
54             redirecturl = response.geturl()
55             rurlp = compat_urllib_parse_urlparse(redirecturl)
56             file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
57             url = 'http://blip.tv/a/a-' + file_id
58             return self._real_extract(url)
59
60         if '?' in url:
61             cchar = '&'
62         else:
63             cchar = '?'
64         json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
65         request = compat_urllib_request.Request(json_url)
66         request.add_header('User-Agent', 'iTunes/10.6.1')
67         self.report_extraction(mobj.group(1))
68         urlh = self._request_webpage(request, None, False,
69             u'unable to download video info webpage')
70
71         try:
72             json_code_bytes = urlh.read()
73             json_code = json_code_bytes.decode('utf-8')
74         except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
75             raise ExtractorError(u'Unable to read video info webpage: %s' % compat_str(err))
76
77         try:
78             json_data = json.loads(json_code)
79             if 'Post' in json_data:
80                 data = json_data['Post']
81             else:
82                 data = json_data
83
84             upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
85             formats = []
86             if 'additionalMedia' in data:
87                 for f in sorted(data['additionalMedia'], key=lambda f: int(f['media_height'])):
88                     if not int(f['media_width']): # filter m3u8
89                         continue
90                     formats.append({
91                         'url': f['url'],
92                         'ext': determine_ext(f['url']),
93                         'format_id': f['role'],
94                         'width': int(f['media_width']),
95                         'height': int(f['media_height']),
96                     })
97             else:
98                 formats.append({
99                     'url': data['media']['url'],
100                     'ext': determine_ext(data['media']['url']),
101                     'width': int(data['media']['width']),
102                     'height': int(data['media']['height']),
103                 })
104
105             return {
106                 'id': compat_str(data['item_id']),
107                 'uploader': data['display_name'],
108                 'upload_date': upload_date,
109                 'title': data['title'],
110                 'thumbnail': data['thumbnailUrl'],
111                 'description': data['description'],
112                 'user_agent': 'iTunes/10.6.1',
113                 'formats': formats,
114             }
115         except (ValueError, KeyError) as err:
116             raise ExtractorError(u'Unable to parse video information: %s' % repr(err))
117
118
119 class BlipTVUserIE(InfoExtractor):
120     """Information Extractor for blip.tv users."""
121
122     _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
123     _PAGE_SIZE = 12
124     IE_NAME = u'blip.tv:user'
125
126     def _real_extract(self, url):
127         # Extract username
128         mobj = re.match(self._VALID_URL, url)
129         if mobj is None:
130             raise ExtractorError(u'Invalid URL: %s' % url)
131
132         username = mobj.group(1)
133
134         page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
135
136         page = self._download_webpage(url, username, u'Downloading user page')
137         mobj = re.search(r'data-users-id="([^"]+)"', page)
138         page_base = page_base % mobj.group(1)
139
140
141         # Download video ids using BlipTV Ajax calls. Result size per
142         # query is limited (currently to 12 videos) so we need to query
143         # page by page until there are no video ids - it means we got
144         # all of them.
145
146         video_ids = []
147         pagenum = 1
148
149         while True:
150             url = page_base + "&page=" + str(pagenum)
151             page = self._download_webpage(url, username,
152                                           u'Downloading video ids from page %d' % pagenum)
153
154             # Extract video identifiers
155             ids_in_page = []
156
157             for mobj in re.finditer(r'href="/([^"]+)"', page):
158                 if mobj.group(1) not in ids_in_page:
159                     ids_in_page.append(unescapeHTML(mobj.group(1)))
160
161             video_ids.extend(ids_in_page)
162
163             # A little optimization - if current page is not
164             # "full", ie. does not contain PAGE_SIZE video ids then
165             # we can assume that this page is the last one - there
166             # are no more ids on further pages - no need to query
167             # again.
168
169             if len(ids_in_page) < self._PAGE_SIZE:
170                 break
171
172             pagenum += 1
173
174         urls = [u'http://blip.tv/%s' % video_id for video_id in video_ids]
175         url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
176         return [self.playlist_result(url_entries, playlist_title = username)]