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