[bliptv] Add test with missing duration
[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             # missing duration
107             'url': 'http://blip.tv/rss/flash/6700880',
108             'info_dict': {
109                 'id': '6684191',
110                 'ext': 'm4v',
111                 'title': 'Cowboy Bebop: Gateway Shuffle Review',
112                 'description': 'md5:3acc480c0f9ae157f5fe88547ecaf3f8',
113                 'timestamp': 1386639757,
114                 'upload_date': '20131210',
115                 'uploader': 'sfdebris',
116                 'uploader_id': '706520',
117             }
118         }
119     ]
120
121     @staticmethod
122     def _extract_url(webpage):
123         mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
124         if mobj:
125             return 'http://blip.tv/a/a-' + mobj.group(1)
126         mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9_]+)', webpage)
127         if mobj:
128             return mobj.group(1)
129
130     def _real_extract(self, url):
131         mobj = re.match(self._VALID_URL, url)
132         lookup_id = mobj.group('lookup_id')
133
134         # See https://github.com/rg3/youtube-dl/issues/857 and
135         # https://github.com/rg3/youtube-dl/issues/4197
136         if lookup_id:
137             urlh = self._request_webpage(
138                 'http://blip.tv/play/%s' % lookup_id, lookup_id, 'Resolving lookup id')
139             url = compat_urlparse.urlparse(urlh.geturl())
140             qs = compat_urlparse.parse_qs(url.query)
141             mobj = re.match(self._VALID_URL, qs['file'][0])
142
143         video_id = mobj.group('id')
144
145         rss = self._download_xml('http://blip.tv/rss/flash/%s' % video_id, video_id, 'Downloading video RSS')
146
147         def _x(p):
148             return xpath_with_ns(p, {
149                 'blip': 'http://blip.tv/dtd/blip/1.0',
150                 'media': 'http://search.yahoo.com/mrss/',
151                 'itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd',
152             })
153
154         item = rss.find('channel/item')
155
156         video_id = xpath_text(item, _x('blip:item_id'), 'video id') or lookup_id
157         title = xpath_text(item, 'title', 'title', fatal=True)
158         description = clean_html(xpath_text(item, _x('blip:puredescription'), 'description'))
159         timestamp = parse_iso8601(xpath_text(item, _x('blip:datestamp'), 'timestamp'))
160         uploader = xpath_text(item, _x('blip:user'), 'uploader')
161         uploader_id = xpath_text(item, _x('blip:userid'), 'uploader id')
162         duration = int_or_none(xpath_text(item, _x('blip:runtime'), 'duration'))
163         media_thumbnail = item.find(_x('media:thumbnail'))
164         thumbnail = (media_thumbnail.get('url') if media_thumbnail is not None
165                      else xpath_text(item, 'image', 'thumbnail'))
166         categories = [category.text for category in item.findall('category') if category is not None]
167
168         formats = []
169         subtitles_urls = {}
170
171         media_group = item.find(_x('media:group'))
172         for media_content in media_group.findall(_x('media:content')):
173             url = media_content.get('url')
174             role = media_content.get(_x('blip:role'))
175             msg = self._download_webpage(
176                 url + '?showplayer=20140425131715&referrer=http://blip.tv&mask=7&skin=flashvars&view=url',
177                 video_id, 'Resolving URL for %s' % role)
178             real_url = compat_urlparse.parse_qs(msg.strip())['message'][0]
179
180             media_type = media_content.get('type')
181             if media_type == 'text/srt' or url.endswith('.srt'):
182                 LANGS = {
183                     'english': 'en',
184                 }
185                 lang = role.rpartition('-')[-1].strip().lower()
186                 langcode = LANGS.get(lang, lang)
187                 subtitles_urls[langcode] = url
188             elif media_type.startswith('video/'):
189                 formats.append({
190                     'url': real_url,
191                     'format_id': role,
192                     'format_note': media_type,
193                     'vcodec': media_content.get(_x('blip:vcodec')) or 'none',
194                     'acodec': media_content.get(_x('blip:acodec')),
195                     'filesize': media_content.get('filesize'),
196                     'width': int_or_none(media_content.get('width')),
197                     'height': int_or_none(media_content.get('height')),
198                 })
199         self._check_formats(formats, video_id)
200         self._sort_formats(formats)
201
202         subtitles = self.extract_subtitles(video_id, subtitles_urls)
203
204         return {
205             'id': video_id,
206             'title': title,
207             'description': description,
208             'timestamp': timestamp,
209             'uploader': uploader,
210             'uploader_id': uploader_id,
211             'duration': duration,
212             'thumbnail': thumbnail,
213             'categories': categories,
214             'formats': formats,
215             'subtitles': subtitles,
216         }
217
218     def _get_subtitles(self, video_id, subtitles_urls):
219         subtitles = {}
220         for lang, url in subtitles_urls.items():
221             # For some weird reason, blip.tv serves a video instead of subtitles
222             # when we request with a common UA
223             req = compat_urllib_request.Request(url)
224             req.add_header('User-Agent', 'youtube-dl')
225             subtitles[lang] = [{
226                 # The extension is 'srt' but it's actually an 'ass' file
227                 'ext': 'ass',
228                 'data': self._download_webpage(req, None, note=False),
229             }]
230         return subtitles
231
232
233 class BlipTVUserIE(InfoExtractor):
234     _VALID_URL = r'(?:(?:https?://(?:\w+\.)?blip\.tv/)|bliptvuser:)(?!api\.swf)([^/]+)/*$'
235     _PAGE_SIZE = 12
236     IE_NAME = 'blip.tv:user'
237     _TEST = {
238         'url': 'http://blip.tv/actone',
239         'info_dict': {
240             'id': 'actone',
241             'title': 'Act One: The Series',
242         },
243         'playlist_count': 5,
244     }
245
246     def _real_extract(self, url):
247         mobj = re.match(self._VALID_URL, url)
248         username = mobj.group(1)
249
250         page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
251
252         page = self._download_webpage(url, username, 'Downloading user page')
253         mobj = re.search(r'data-users-id="([^"]+)"', page)
254         page_base = page_base % mobj.group(1)
255         title = self._og_search_title(page)
256
257         # Download video ids using BlipTV Ajax calls. Result size per
258         # query is limited (currently to 12 videos) so we need to query
259         # page by page until there are no video ids - it means we got
260         # all of them.
261
262         video_ids = []
263         pagenum = 1
264
265         while True:
266             url = page_base + "&page=" + str(pagenum)
267             page = self._download_webpage(
268                 url, username, 'Downloading video ids from page %d' % pagenum)
269
270             # Extract video identifiers
271             ids_in_page = []
272
273             for mobj in re.finditer(r'href="/([^"]+)"', page):
274                 if mobj.group(1) not in ids_in_page:
275                     ids_in_page.append(unescapeHTML(mobj.group(1)))
276
277             video_ids.extend(ids_in_page)
278
279             # A little optimization - if current page is not
280             # "full", ie. does not contain PAGE_SIZE video ids then
281             # we can assume that this page is the last one - there
282             # are no more ids on further pages - no need to query
283             # again.
284
285             if len(ids_in_page) < self._PAGE_SIZE:
286                 break
287
288             pagenum += 1
289
290         urls = ['http://blip.tv/%s' % video_id for video_id in video_ids]
291         url_entries = [self.url_result(vurl, 'BlipTV') for vurl in urls]
292         return self.playlist_result(
293             url_entries, playlist_title=title, playlist_id=username)