[tvp] Modernize
[youtube-dl] / youtube_dl / extractor / bliptv.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from .subtitles import SubtitlesInfoExtractor
7 from ..utils import (
8     compat_urllib_request,
9     unescapeHTML,
10     parse_iso8601,
11     compat_urlparse,
12     clean_html,
13     compat_str,
14 )
15
16
17 class BlipTVIE(SubtitlesInfoExtractor):
18     _VALID_URL = r'https?://(?:\w+\.)?blip\.tv/(?:(?:.+-|rss/flash/)(?P<id>\d+)|((?:play/|api\.swf#)(?P<lookup_id>[\da-zA-Z+_]+)))'
19
20     _TESTS = [
21         {
22             'url': 'http://blip.tv/cbr/cbr-exclusive-gotham-city-imposters-bats-vs-jokerz-short-3-5796352',
23             'md5': 'c6934ad0b6acf2bd920720ec888eb812',
24             'info_dict': {
25                 'id': '5779306',
26                 'ext': 'mov',
27                 'title': 'CBR EXCLUSIVE: "Gotham City Imposters" Bats VS Jokerz Short 3',
28                 'description': 'md5:9bc31f227219cde65e47eeec8d2dc596',
29                 'timestamp': 1323138843,
30                 'upload_date': '20111206',
31                 'uploader': 'cbr',
32                 'uploader_id': '679425',
33                 'duration': 81,
34             }
35         },
36         {
37             # https://github.com/rg3/youtube-dl/pull/2274
38             'note': 'Video with subtitles',
39             'url': 'http://blip.tv/play/h6Uag5OEVgI.html',
40             'md5': '309f9d25b820b086ca163ffac8031806',
41             'info_dict': {
42                 'id': '6586561',
43                 'ext': 'mp4',
44                 'title': 'Red vs. Blue Season 11 Episode 1',
45                 'description': 'One-Zero-One',
46                 'timestamp': 1371261608,
47                 'upload_date': '20130615',
48                 'uploader': 'redvsblue',
49                 'uploader_id': '792887',
50                 'duration': 279,
51             }
52         },
53         {
54             # https://bugzilla.redhat.com/show_bug.cgi?id=967465
55             'url': 'http://a.blip.tv/api.swf#h6Uag5KbVwI',
56             'md5': '314e87b1ebe7a48fcbfdd51b791ce5a6',
57             'info_dict': {
58                 'id': '6573122',
59                 'ext': 'mov',
60                 'upload_date': '20130520',
61                 'description': 'Two hapless space marines argue over what to do when they realize they have an astronomically huge problem on their hands.',
62                 'title': 'Red vs. Blue Season 11 Trailer',
63                 'timestamp': 1369029609,
64                 'uploader': 'redvsblue',
65                 'uploader_id': '792887',
66             }
67         },
68         {
69             'url': 'http://blip.tv/play/gbk766dkj4Yn',
70             'md5': 'fe0a33f022d49399a241e84a8ea8b8e3',
71             'info_dict': {
72                 'id': '1749452',
73                 'ext': 'mp4',
74                 'upload_date': '20090208',
75                 'description': 'Witness the first appearance of the Nostalgia Critic character, as Doug reviews the movie Transformers.',
76                 'title': 'Nostalgia Critic: Transformers',
77                 'timestamp': 1234068723,
78                 'uploader': 'NostalgiaCritic',
79                 'uploader_id': '246467',
80             }
81         }
82     ]
83
84     def _real_extract(self, url):
85         mobj = re.match(self._VALID_URL, url)
86         lookup_id = mobj.group('lookup_id')
87
88         # See https://github.com/rg3/youtube-dl/issues/857 and
89         # https://github.com/rg3/youtube-dl/issues/4197
90         if lookup_id:
91             urlh = self._request_webpage(
92                 'http://blip.tv/play/%s' % lookup_id, lookup_id, 'Resolving lookup id')
93             url = compat_urlparse.urlparse(urlh.geturl())
94             qs = compat_urlparse.parse_qs(url.query)
95             mobj = re.match(self._VALID_URL, qs['file'][0])
96
97         video_id = mobj.group('id')
98
99         rss = self._download_xml('http://blip.tv/rss/flash/%s' % video_id, video_id, 'Downloading video RSS')
100
101         def blip(s):
102             return '{http://blip.tv/dtd/blip/1.0}%s' % s
103
104         def media(s):
105             return '{http://search.yahoo.com/mrss/}%s' % s
106
107         def itunes(s):
108             return '{http://www.itunes.com/dtds/podcast-1.0.dtd}%s' % s
109
110         item = rss.find('channel/item')
111
112         video_id = item.find(blip('item_id')).text
113         title = item.find('./title').text
114         description = clean_html(compat_str(item.find(blip('puredescription')).text))
115         timestamp = parse_iso8601(item.find(blip('datestamp')).text)
116         uploader = item.find(blip('user')).text
117         uploader_id = item.find(blip('userid')).text
118         duration = int(item.find(blip('runtime')).text)
119         media_thumbnail = item.find(media('thumbnail'))
120         thumbnail = media_thumbnail.get('url') if media_thumbnail is not None else item.find(itunes('image')).text
121         categories = [category.text for category in item.findall('category')]
122
123         formats = []
124         subtitles = {}
125
126         media_group = item.find(media('group'))
127         for media_content in media_group.findall(media('content')):
128             url = media_content.get('url')
129             role = media_content.get(blip('role'))
130             msg = self._download_webpage(
131                 url + '?showplayer=20140425131715&referrer=http://blip.tv&mask=7&skin=flashvars&view=url',
132                 video_id, 'Resolving URL for %s' % role)
133             real_url = compat_urlparse.parse_qs(msg.strip())['message'][0]
134
135             media_type = media_content.get('type')
136             if media_type == 'text/srt' or url.endswith('.srt'):
137                 LANGS = {
138                     'english': 'en',
139                 }
140                 lang = role.rpartition('-')[-1].strip().lower()
141                 langcode = LANGS.get(lang, lang)
142                 subtitles[langcode] = url
143             elif media_type.startswith('video/'):
144                 formats.append({
145                     'url': real_url,
146                     'format_id': role,
147                     'format_note': media_type,
148                     'vcodec': media_content.get(blip('vcodec')),
149                     'acodec': media_content.get(blip('acodec')),
150                     'filesize': media_content.get('filesize'),
151                     'width': int(media_content.get('width')),
152                     'height': int(media_content.get('height')),
153                 })
154         self._sort_formats(formats)
155
156         # subtitles
157         video_subtitles = self.extract_subtitles(video_id, subtitles)
158         if self._downloader.params.get('listsubtitles', False):
159             self._list_available_subtitles(video_id, subtitles)
160             return
161
162         return {
163             'id': video_id,
164             'title': title,
165             'description': description,
166             'timestamp': timestamp,
167             'uploader': uploader,
168             'uploader_id': uploader_id,
169             'duration': duration,
170             'thumbnail': thumbnail,
171             'categories': categories,
172             'formats': formats,
173             'subtitles': video_subtitles,
174         }
175
176     def _download_subtitle_url(self, sub_lang, url):
177         # For some weird reason, blip.tv serves a video instead of subtitles
178         # when we request with a common UA
179         req = compat_urllib_request.Request(url)
180         req.add_header('Youtubedl-user-agent', 'youtube-dl')
181         return self._download_webpage(req, None, note=False)
182
183
184 class BlipTVUserIE(InfoExtractor):
185     _VALID_URL = r'(?:(?:https?://(?:\w+\.)?blip\.tv/)|bliptvuser:)(?!api\.swf)([^/]+)/*$'
186     _PAGE_SIZE = 12
187     IE_NAME = 'blip.tv:user'
188     _TEST = {
189         'url': 'http://blip.tv/actone',
190         'info_dict': {
191             'id': 'actone',
192             'title': 'Act One: The Series',
193         },
194         'playlist_count': 5,
195     }
196
197     def _real_extract(self, url):
198         mobj = re.match(self._VALID_URL, url)
199         username = mobj.group(1)
200
201         page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
202
203         page = self._download_webpage(url, username, 'Downloading user page')
204         mobj = re.search(r'data-users-id="([^"]+)"', page)
205         page_base = page_base % mobj.group(1)
206         title = self._og_search_title(page)
207
208         # Download video ids using BlipTV Ajax calls. Result size per
209         # query is limited (currently to 12 videos) so we need to query
210         # page by page until there are no video ids - it means we got
211         # all of them.
212
213         video_ids = []
214         pagenum = 1
215
216         while True:
217             url = page_base + "&page=" + str(pagenum)
218             page = self._download_webpage(
219                 url, username, 'Downloading video ids from page %d' % pagenum)
220
221             # Extract video identifiers
222             ids_in_page = []
223
224             for mobj in re.finditer(r'href="/([^"]+)"', page):
225                 if mobj.group(1) not in ids_in_page:
226                     ids_in_page.append(unescapeHTML(mobj.group(1)))
227
228             video_ids.extend(ids_in_page)
229
230             # A little optimization - if current page is not
231             # "full", ie. does not contain PAGE_SIZE video ids then
232             # we can assume that this page is the last one - there
233             # are no more ids on further pages - no need to query
234             # again.
235
236             if len(ids_in_page) < self._PAGE_SIZE:
237                 break
238
239             pagenum += 1
240
241         urls = ['http://blip.tv/%s' % video_id for video_id in video_ids]
242         url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
243         return self.playlist_result(
244             url_entries, playlist_title=title, playlist_id=username)