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