]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/ustream.py
[ie/matchtv] Fix extractor (#10190)
[yt-dlp.git] / yt_dlp / extractor / ustream.py
CommitLineData
e3d6bdc8 1import random
78af8eb1 2import re
add96eb9 3import urllib.parse
78af8eb1
PH
4
5from .common import InfoExtractor
5820c4a2
S
6from ..utils import (
7 ExtractorError,
e897bd82 8 encode_data_uri,
5820c4a2 9 float_or_none,
e897bd82 10 int_or_none,
34921b43 11 join_nonempty,
e3d6bdc8
YCH
12 mimetype2ext,
13 str_or_none,
5820c4a2 14)
78af8eb1
PH
15
16
17class UstreamIE(InfoExtractor):
8bdd16b4 18 _VALID_URL = r'https?://(?:www\.)?(?:ustream\.tv|video\.ibm\.com)/(?P<type>recorded|embed|embed/recorded)/(?P<id>\d+)'
0eb799ba 19 IE_NAME = 'ustream'
bfd973ec 20 _EMBED_REGEX = [r'<iframe[^>]+?src=(["\'])(?P<url>https?://(?:www\.)?(?:ustream\.tv|video\.ibm\.com)/embed/.+?)\1']
cd9fdccd 21 _TESTS = [{
0eb799ba 22 'url': 'http://www.ustream.tv/recorded/20274954',
0eb799ba
JMF
23 'md5': '088f151799e8f572f84eb62f17d73e5c',
24 'info_dict': {
9e875391
S
25 'id': '20274954',
26 'ext': 'flv',
9e875391 27 'title': 'Young Americans for Liberty February 7, 2012 2:28 AM',
40fbb05e
S
28 'description': 'Young Americans for Liberty February 7, 2012 2:28 AM',
29 'timestamp': 1328577035,
30 'upload_date': '20120207',
31 'uploader': 'yaliberty',
32 'uploader_id': '6780869',
0eb799ba 33 },
cd9fdccd
YCH
34 }, {
35 # From http://sportscanada.tv/canadagames/index.php/week2/figure-skating/444
36 # Title and uploader available only from params JSON
37 'url': 'http://www.ustream.tv/embed/recorded/59307601?ub=ff0000&lc=ff0000&oc=ffffff&uc=ffffff&v=3&wmode=direct',
38 'md5': '5a2abf40babeac9812ed20ae12d34e10',
39 'info_dict': {
40 'id': '59307601',
41 'ext': 'flv',
42 'title': '-CG11- Canada Games Figure Skating',
43 'uploader': 'sportscanadatv',
40fbb05e
S
44 },
45 'skip': 'This Pro Broadcaster has chosen to remove this video from the ustream.tv site.',
67d46a3f
YCH
46 }, {
47 'url': 'http://www.ustream.tv/embed/10299409',
48 'info_dict': {
49 'id': '10299409',
50 },
51 'playlist_count': 3,
e3d6bdc8
YCH
52 }, {
53 'url': 'http://www.ustream.tv/recorded/91343263',
54 'info_dict': {
55 'id': '91343263',
56 'ext': 'mp4',
57 'title': 'GitHub Universe - General Session - Day 1',
58 'upload_date': '20160914',
59 'description': 'GitHub Universe - General Session - Day 1',
60 'timestamp': 1473872730,
61 'uploader': 'wa0dnskeqkr',
62 'uploader_id': '38977840',
63 },
64 'params': {
65 'skip_download': True, # m3u8 download
66 },
8bdd16b4 67 }, {
68 'url': 'https://video.ibm.com/embed/recorded/128240221?&autoplay=true&controls=true&volume=100',
69 'only_matching': True,
cd9fdccd 70 }]
78af8eb1 71
e3d6bdc8
YCH
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(
add96eb9 82 f'http://r{rnd(1e8)}-1-{video_id}-recorded-lp-live.ums.ustream.tv/1/ustream',
e3d6bdc8
YCH
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],
add96eb9 88 'rsid': f'{num_to_hex(rnd(1e8))}:{num_to_hex(rnd(1e8))}',
89 'rpin': f'_rpin.{rnd(1e15)}',
e3d6bdc8
YCH
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(
add96eb9 98 f'http://{host}/1/ustream?connectionId={connection_id}',
e3d6bdc8
YCH
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,
add96eb9 106 extra_note=f' (try {trial_count + 1})' if trial_count > 0 else '')
e3d6bdc8
YCH
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):
add96eb9 113 return template.replace('%', str(idx), 1).replace('%', chunk_hash)
e3d6bdc8
YCH
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(
add96eb9 121 provider['url'] + stream['initUrl'], 0, dash_stream_info['hashes']['0']),
e3d6bdc8
YCH
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,
add96eb9 127 dash_stream_info['hashes'][str(idx // 10 * 10)]),
e3d6bdc8
YCH
128 })
129 content_type = stream['contentType']
130 kind = content_type.split('/')[0]
131 f = {
34921b43 132 'format_id': join_nonempty(
133 'dash', kind, str_or_none(stream.get('bitrate'))),
e3d6bdc8
YCH
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
78af8eb1 157 def _real_extract(self, url):
5ad28e7f 158 m = self._match_valid_url(url)
4853eb63 159 video_id = m.group('id')
b702eceb 160
067aa17e 161 # some sites use this embed format (see: https://github.com/ytdl-org/youtube-dl/issues/2990)
9e875391 162 if m.group('type') == 'embed/recorded':
4853eb63 163 video_id = m.group('id')
b702eceb 164 desktop_url = 'http://www.ustream.tv/recorded/' + video_id
165 return self.url_result(desktop_url, 'Ustream')
5c386252 166 if m.group('type') == 'embed':
4853eb63 167 video_id = m.group('id')
5c386252 168 webpage = self._download_webpage(url, video_id)
67d46a3f
YCH
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(
add96eb9 173 (self.url_result('http://www.ustream.tv/recorded/' + u, 'Ustream') for u in content_video_ids),
67d46a3f 174 video_id)
5c386252 175
4853eb63 176 params = self._download_json(
add96eb9 177 f'https://api.ustream.tv/videos/{video_id}.json', video_id)
f8610ba1 178
5820c4a2
S
179 error = params.get('error')
180 if error:
181 raise ExtractorError(
add96eb9 182 f'{self.IE_NAME} returned error: {error}', expected=True)
78af8eb1 183
5820c4a2 184 video = params['video']
2a813727 185
41db7333
S
186 title = video['title']
187 filesize = float_or_none(video.get('file_size'))
188
5820c4a2 189 formats = [{
dc5756fd 190 'id': video_id,
5820c4a2
S
191 'url': video_url,
192 'ext': format_id,
41db7333 193 'filesize': filesize,
e3d6bdc8
YCH
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
5820c4a2
S
210 description = video.get('description')
211 timestamp = int_or_none(video.get('created_at'))
212 duration = float_or_none(video.get('length'))
5820c4a2 213 view_count = int_or_none(video.get('views'))
cd9fdccd 214
5820c4a2
S
215 uploader = video.get('owner', {}).get('username')
216 uploader_id = video.get('owner', {}).get('id')
78af8eb1 217
5820c4a2
S
218 thumbnails = [{
219 'id': thumbnail_id,
220 'url': thumbnail_url,
221 } for thumbnail_id, thumbnail_url in video.get('thumbnail', {}).items()]
0eb799ba
JMF
222
223 return {
224 'id': video_id,
5820c4a2
S
225 'title': title,
226 'description': description,
227 'thumbnails': thumbnails,
228 'timestamp': timestamp,
229 'duration': duration,
5820c4a2 230 'view_count': view_count,
0eb799ba 231 'uploader': uploader,
5820c4a2
S
232 'uploader_id': uploader_id,
233 'formats': formats,
0eb799ba
JMF
234 }
235
bfd5c93a 236
bfd5c93a 237class UstreamChannelIE(InfoExtractor):
92519402 238 _VALID_URL = r'https?://(?:www\.)?ustream\.tv/channel/(?P<slug>.+)'
0eb799ba 239 IE_NAME = 'ustream:channel'
22a6f150
PH
240 _TEST = {
241 'url': 'http://www.ustream.tv/channel/channeljapan',
242 'info_dict': {
243 'id': '10874166',
244 },
446a03bd 245 'playlist_mincount': 17,
22a6f150 246 }
bfd5c93a 247
248 def _real_extract(self, url):
5ad28e7f 249 m = self._match_valid_url(url)
22a6f150
PH
250 display_id = m.group('slug')
251 webpage = self._download_webpage(url, display_id)
44789f24 252 channel_id = self._html_search_meta('ustream:channel_id', webpage)
bfd5c93a 253
bfd5c93a 254 BASE = 'http://www.ustream.tv'
add96eb9 255 next_url = f'/ajax/socialstream/videos/{channel_id}/1.json'
a921f407 256 video_ids = []
bfd5c93a 257 while next_url:
22a6f150 258 reply = self._download_json(
add96eb9 259 urllib.parse.urljoin(BASE, next_url), display_id,
260 note=f'Downloading video information (next: {len(video_ids) + 1})')
a921f407 261 video_ids.extend(re.findall(r'data-content-id="(\d.*)"', reply['data']))
bfd5c93a 262 next_url = reply['nextUrl']
bfd5c93a 263
22a6f150
PH
264 entries = [
265 self.url_result('http://www.ustream.tv/recorded/' + vid, 'Ustream')
266 for vid in video_ids]
267 return {
268 '_type': 'playlist',
269 'id': channel_id,
270 'display_id': display_id,
271 'entries': entries,
272 }