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