]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/ustream.py
New upstream version 2016.12.01
[youtubedl] / youtube_dl / extractor / ustream.py
1 from __future__ import unicode_literals
2
3 import random
4 import re
5
6 from .common import InfoExtractor
7 from ..compat import (
8 compat_str,
9 compat_urlparse,
10 )
11 from ..utils import (
12 encode_data_uri,
13 ExtractorError,
14 int_or_none,
15 float_or_none,
16 mimetype2ext,
17 str_or_none,
18 )
19
20
21 class UstreamIE(InfoExtractor):
22 _VALID_URL = r'https?://(?:www\.)?ustream\.tv/(?P<type>recorded|embed|embed/recorded)/(?P<id>\d+)'
23 IE_NAME = 'ustream'
24 _TESTS = [{
25 'url': 'http://www.ustream.tv/recorded/20274954',
26 'md5': '088f151799e8f572f84eb62f17d73e5c',
27 'info_dict': {
28 'id': '20274954',
29 'ext': 'flv',
30 'title': 'Young Americans for Liberty February 7, 2012 2:28 AM',
31 'description': 'Young Americans for Liberty February 7, 2012 2:28 AM',
32 'timestamp': 1328577035,
33 'upload_date': '20120207',
34 'uploader': 'yaliberty',
35 'uploader_id': '6780869',
36 },
37 }, {
38 # From http://sportscanada.tv/canadagames/index.php/week2/figure-skating/444
39 # Title and uploader available only from params JSON
40 'url': 'http://www.ustream.tv/embed/recorded/59307601?ub=ff0000&lc=ff0000&oc=ffffff&uc=ffffff&v=3&wmode=direct',
41 'md5': '5a2abf40babeac9812ed20ae12d34e10',
42 'info_dict': {
43 'id': '59307601',
44 'ext': 'flv',
45 'title': '-CG11- Canada Games Figure Skating',
46 'uploader': 'sportscanadatv',
47 },
48 'skip': 'This Pro Broadcaster has chosen to remove this video from the ustream.tv site.',
49 }, {
50 'url': 'http://www.ustream.tv/embed/10299409',
51 'info_dict': {
52 'id': '10299409',
53 },
54 'playlist_count': 3,
55 }, {
56 'url': 'http://www.ustream.tv/recorded/91343263',
57 'info_dict': {
58 'id': '91343263',
59 'ext': 'mp4',
60 'title': 'GitHub Universe - General Session - Day 1',
61 'upload_date': '20160914',
62 'description': 'GitHub Universe - General Session - Day 1',
63 'timestamp': 1473872730,
64 'uploader': 'wa0dnskeqkr',
65 'uploader_id': '38977840',
66 },
67 'params': {
68 'skip_download': True, # m3u8 download
69 },
70 }]
71
72 def _get_stream_info(self, url, video_id, app_id_ver, extra_note=None):
73 def num_to_hex(n):
74 return hex(n)[2:]
75
76 rnd = random.randrange
77
78 if not extra_note:
79 extra_note = ''
80
81 conn_info = self._download_json(
82 'http://r%d-1-%s-recorded-lp-live.ums.ustream.tv/1/ustream' % (rnd(1e8), video_id),
83 video_id, note='Downloading connection info' + extra_note,
84 query={
85 'type': 'viewer',
86 'appId': app_id_ver[0],
87 'appVersion': app_id_ver[1],
88 'rsid': '%s:%s' % (num_to_hex(rnd(1e8)), num_to_hex(rnd(1e8))),
89 'rpin': '_rpin.%d' % rnd(1e15),
90 'referrer': url,
91 'media': video_id,
92 'application': 'recorded',
93 })
94 host = conn_info[0]['args'][0]['host']
95 connection_id = conn_info[0]['args'][0]['connectionId']
96
97 return self._download_json(
98 'http://%s/1/ustream?connectionId=%s' % (host, connection_id),
99 video_id, note='Downloading stream info' + extra_note)
100
101 def _get_streams(self, url, video_id, app_id_ver):
102 # Sometimes the return dict does not have 'stream'
103 for trial_count in range(3):
104 stream_info = self._get_stream_info(
105 url, video_id, app_id_ver,
106 extra_note=' (try %d)' % (trial_count + 1) if trial_count > 0 else '')
107 if 'stream' in stream_info[0]['args'][0]:
108 return stream_info[0]['args'][0]['stream']
109 return []
110
111 def _parse_segmented_mp4(self, dash_stream_info):
112 def resolve_dash_template(template, idx, chunk_hash):
113 return template.replace('%', compat_str(idx), 1).replace('%', chunk_hash)
114
115 formats = []
116 for stream in dash_stream_info['streams']:
117 # Use only one provider to avoid too many formats
118 provider = dash_stream_info['providers'][0]
119 fragments = [{
120 'url': resolve_dash_template(
121 provider['url'] + stream['initUrl'], 0, dash_stream_info['hashes']['0'])
122 }]
123 for idx in range(dash_stream_info['videoLength'] // dash_stream_info['chunkTime']):
124 fragments.append({
125 'url': resolve_dash_template(
126 provider['url'] + stream['segmentUrl'], idx,
127 dash_stream_info['hashes'][compat_str(idx // 10 * 10)])
128 })
129 content_type = stream['contentType']
130 kind = content_type.split('/')[0]
131 f = {
132 'format_id': '-'.join(filter(None, [
133 'dash', kind, str_or_none(stream.get('bitrate'))])),
134 'protocol': 'http_dash_segments',
135 # TODO: generate a MPD doc for external players?
136 'url': encode_data_uri(b'<MPD/>', 'text/xml'),
137 'ext': mimetype2ext(content_type),
138 'height': stream.get('height'),
139 'width': stream.get('width'),
140 'fragments': fragments,
141 }
142 if kind == 'video':
143 f.update({
144 'vcodec': stream.get('codec'),
145 'acodec': 'none',
146 'vbr': stream.get('bitrate'),
147 })
148 else:
149 f.update({
150 'vcodec': 'none',
151 'acodec': stream.get('codec'),
152 'abr': stream.get('bitrate'),
153 })
154 formats.append(f)
155 return formats
156
157 def _real_extract(self, url):
158 m = re.match(self._VALID_URL, url)
159 video_id = m.group('id')
160
161 # some sites use this embed format (see: https://github.com/rg3/youtube-dl/issues/2990)
162 if m.group('type') == 'embed/recorded':
163 video_id = m.group('id')
164 desktop_url = 'http://www.ustream.tv/recorded/' + video_id
165 return self.url_result(desktop_url, 'Ustream')
166 if m.group('type') == 'embed':
167 video_id = m.group('id')
168 webpage = self._download_webpage(url, video_id)
169 content_video_ids = self._parse_json(self._search_regex(
170 r'ustream\.vars\.offAirContentVideoIds=([^;]+);', webpage,
171 'content video IDs'), video_id)
172 return self.playlist_result(
173 map(lambda u: self.url_result('http://www.ustream.tv/recorded/' + u, 'Ustream'), content_video_ids),
174 video_id)
175
176 params = self._download_json(
177 'https://api.ustream.tv/videos/%s.json' % video_id, video_id)
178
179 error = params.get('error')
180 if error:
181 raise ExtractorError(
182 '%s returned error: %s' % (self.IE_NAME, error), expected=True)
183
184 video = params['video']
185
186 title = video['title']
187 filesize = float_or_none(video.get('file_size'))
188
189 formats = [{
190 'id': video_id,
191 'url': video_url,
192 'ext': format_id,
193 'filesize': filesize,
194 } for format_id, video_url in video['media_urls'].items() if video_url]
195
196 if not formats:
197 hls_streams = self._get_streams(url, video_id, app_id_ver=(11, 2))
198 if hls_streams:
199 # m3u8_native leads to intermittent ContentTooShortError
200 formats.extend(self._extract_m3u8_formats(
201 hls_streams[0]['url'], video_id, ext='mp4', m3u8_id='hls'))
202
203 '''
204 # DASH streams handling is incomplete as 'url' is missing
205 dash_streams = self._get_streams(url, video_id, app_id_ver=(3, 1))
206 if dash_streams:
207 formats.extend(self._parse_segmented_mp4(dash_streams))
208 '''
209
210 self._sort_formats(formats)
211
212 description = video.get('description')
213 timestamp = int_or_none(video.get('created_at'))
214 duration = float_or_none(video.get('length'))
215 view_count = int_or_none(video.get('views'))
216
217 uploader = video.get('owner', {}).get('username')
218 uploader_id = video.get('owner', {}).get('id')
219
220 thumbnails = [{
221 'id': thumbnail_id,
222 'url': thumbnail_url,
223 } for thumbnail_id, thumbnail_url in video.get('thumbnail', {}).items()]
224
225 return {
226 'id': video_id,
227 'title': title,
228 'description': description,
229 'thumbnails': thumbnails,
230 'timestamp': timestamp,
231 'duration': duration,
232 'view_count': view_count,
233 'uploader': uploader,
234 'uploader_id': uploader_id,
235 'formats': formats,
236 }
237
238
239 class UstreamChannelIE(InfoExtractor):
240 _VALID_URL = r'https?://(?:www\.)?ustream\.tv/channel/(?P<slug>.+)'
241 IE_NAME = 'ustream:channel'
242 _TEST = {
243 'url': 'http://www.ustream.tv/channel/channeljapan',
244 'info_dict': {
245 'id': '10874166',
246 },
247 'playlist_mincount': 17,
248 }
249
250 def _real_extract(self, url):
251 m = re.match(self._VALID_URL, url)
252 display_id = m.group('slug')
253 webpage = self._download_webpage(url, display_id)
254 channel_id = self._html_search_meta('ustream:channel_id', webpage)
255
256 BASE = 'http://www.ustream.tv'
257 next_url = '/ajax/socialstream/videos/%s/1.json' % channel_id
258 video_ids = []
259 while next_url:
260 reply = self._download_json(
261 compat_urlparse.urljoin(BASE, next_url), display_id,
262 note='Downloading video information (next: %d)' % (len(video_ids) + 1))
263 video_ids.extend(re.findall(r'data-content-id="(\d.*)"', reply['data']))
264 next_url = reply['nextUrl']
265
266 entries = [
267 self.url_result('http://www.ustream.tv/recorded/' + vid, 'Ustream')
268 for vid in video_ids]
269 return {
270 '_type': 'playlist',
271 'id': channel_id,
272 'display_id': display_id,
273 'entries': entries,
274 }