]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/theplatform.py
[ie/orf:on] Improve extraction (#9677)
[yt-dlp.git] / yt_dlp / extractor / theplatform.py
CommitLineData
e9bf7479 1import re
9fb2f1cd
S
2import time
3import hmac
4import binascii
5import hashlib
6
e9bf7479 7
9f02ff53 8from .once import OnceIE
818ac213 9from .adobepass import AdobePassIE
3d2623a8 10from ..networking import Request
1cc79574 11from ..utils import (
22a0a952 12 determine_ext,
f8b56e95 13 ExtractorError,
18e4088f 14 float_or_none,
402a3efc 15 int_or_none,
4dfbf869 16 parse_qs,
18e4088f 17 unsmuggle_url,
22a0a952 18 update_url_query,
18e4088f 19 xpath_with_ns,
cafcf657 20 mimetype2ext,
4459bef2 21 find_xpath_attr,
339c339f 22 traverse_obj,
23 update_url,
24 urlhandle_detect_ext,
e9bf7479 25)
339c339f 26from ..networking import HEADRequest
e9bf7479 27
f877c6ae
YCH
28default_ns = 'http://www.w3.org/2005/SMIL21/Language'
29_x = lambda p: xpath_with_ns(p, {'smil': default_ns})
e9bf7479
JMF
30
31
9f02ff53 32class ThePlatformBaseIE(OnceIE):
371dcc1d 33 _TP_TLD = 'com'
25586c60 34
c687ac74 35 def _extract_theplatform_smil(self, smil_url, video_id, note='Downloading SMIL data'):
f5a723a7
RA
36 meta = self._download_xml(
37 smil_url, video_id, note=note, query={'format': 'SMIL'},
38 headers=self.geo_verification_headers())
cae21032 39 error_element = find_xpath_attr(meta, _x('.//smil:ref'), 'src')
9aac22c1
S
40 if error_element is not None:
41 exception = find_xpath_attr(
42 error_element, _x('.//smil:param'), 'name', 'exception')
43 if exception is not None:
44 if exception.get('value') == 'GeoLocationBlocked':
45 self.raise_geo_restricted(error_element.attrib['abstract'])
46 elif error_element.attrib['src'].startswith(
47 'http://link.theplatform.%s/s/errorFiles/Unavailable.'
48 % self._TP_TLD):
49 raise ExtractorError(
50 error_element.attrib['abstract'], expected=True)
26e1c351 51
550e6541 52 smil_formats, subtitles = self._parse_smil_formats_and_subtitles(
26e1c351
YCH
53 meta, smil_url, video_id, namespace=default_ns,
54 # the parameters are from syfy.com, other sites may use others,
55 # they also work for nbc.com
56 f4m_params={'g': 'UXWGVKRWHFSP', 'hdcore': '3.0.3'},
57 transform_rtmp_url=lambda streamer, src: (streamer, 'mp4:' + src))
58
9f02ff53 59 formats = []
60 for _format in smil_formats:
61 if OnceIE.suitable(_format['url']):
62 formats.extend(self._extract_once_formats(_format['url']))
63 else:
22a0a952
YCH
64 media_url = _format['url']
65 if determine_ext(media_url) == 'm3u8':
66 hdnea2 = self._get_cookies(media_url).get('hdnea2')
67 if hdnea2:
68 _format['url'] = update_url_query(media_url, {'hdnea3': hdnea2.value})
69
9f02ff53 70 formats.append(_format)
26e1c351 71
c687ac74 72 return formats, subtitles
26e1c351 73
bf830248 74 def _download_theplatform_metadata(self, path, video_id):
371dcc1d 75 info_url = 'http://link.theplatform.%s/s/%s?format=preview' % (self._TP_TLD, path)
bf830248 76 return self._download_json(info_url, video_id)
26e1c351 77
bf830248 78 def _parse_theplatform_metadata(self, info):
26e1c351
YCH
79 subtitles = {}
80 captions = info.get('captions')
81 if isinstance(captions, list):
82 for caption in captions:
83 lang, src, mime = caption.get('lang', 'en'), caption.get('src'), caption.get('type')
11f502fa 84 subtitles.setdefault(lang, []).append({
cafcf657 85 'ext': mimetype2ext(mime),
26e1c351 86 'url': src,
11f502fa 87 })
26e1c351 88
fd178b87
RA
89 duration = info.get('duration')
90 tp_chapters = info.get('chapters', [])
91 chapters = []
92 if tp_chapters:
93 def _add_chapter(start_time, end_time):
94 start_time = float_or_none(start_time, 1000)
95 end_time = float_or_none(end_time, 1000)
96 if start_time is None or end_time is None:
97 return
98 chapters.append({
99 'start_time': start_time,
100 'end_time': end_time,
101 })
102
103 for chapter in tp_chapters[:-1]:
104 _add_chapter(chapter.get('startTime'), chapter.get('endTime'))
105 _add_chapter(tp_chapters[-1].get('startTime'), tp_chapters[-1].get('endTime') or duration)
106
7e09c147 107 def extract_site_specific_field(field):
108 # A number of sites have custom-prefixed keys, e.g. 'cbc$seasonNumber'
109 return traverse_obj(info, lambda k, v: v and k.endswith(f'${field}'), get_all=False)
110
26e1c351
YCH
111 return {
112 'title': info['title'],
113 'subtitles': subtitles,
114 'description': info['description'],
115 'thumbnail': info['defaultThumbnailUrl'],
fd178b87 116 'duration': float_or_none(duration, 1000),
79ba9140 117 'timestamp': int_or_none(info.get('pubDate'), 1000) or None,
118 'uploader': info.get('billingCode'),
fd178b87 119 'chapters': chapters,
7e09c147 120 'creator': traverse_obj(info, ('author', {str})) or None,
121 'categories': traverse_obj(info, (
122 'categories', lambda _, v: v.get('label') in ('category', None), 'name', {str})) or None,
123 'tags': traverse_obj(info, ('keywords', {lambda x: re.split(r'[;,]\s?', x) if x else None})),
124 'location': extract_site_specific_field('region'),
125 'series': extract_site_specific_field('show'),
126 'season_number': int_or_none(extract_site_specific_field('seasonNumber')),
127 'media_type': extract_site_specific_field('programmingType') or extract_site_specific_field('type'),
26e1c351
YCH
128 }
129
bf830248
RA
130 def _extract_theplatform_metadata(self, path, video_id):
131 info = self._download_theplatform_metadata(path, video_id)
132 return self._parse_theplatform_metadata(info)
133
26e1c351 134
818ac213 135class ThePlatformIE(ThePlatformBaseIE, AdobePassIE):
a97bcd80 136 _VALID_URL = r'''(?x)
9fb2f1cd 137 (?:https?://(?:link|player)\.theplatform\.com/[sp]/(?P<provider_id>[^/]+)/
433af6ad 138 (?:(?:(?:[^/]+/)+select/)?(?P<media>media/(?:guid/\d+/)?)?|(?P<config>(?:[^/\?]+/(?:swf|config)|onsite)/select/))?
a97bcd80 139 |theplatform:)(?P<id>[^/\?&]+)'''
bfd973ec 140 _EMBED_REGEX = [
141 r'''(?x)
142 <meta\s+
143 property=(["'])(?:og:video(?::(?:secure_)?url)?|twitter:player)\1\s+
144 content=(["'])(?P<url>https?://player\.theplatform\.com/p/.+?)\2''',
145 r'(?s)<(?:iframe|script)[^>]+src=(["\'])(?P<url>(?:https?:)?//player\.theplatform\.com/p/.+?)\1'
146 ]
e9bf7479 147
bd7a6478 148 _TESTS = [{
e9bf7479 149 # from http://www.metacafe.com/watch/cb-e9I_cZgTgIPd/blackberrys_big_bold_z30/
ed86f38a
JMF
150 'url': 'http://link.theplatform.com/s/dJ5BDC/e9I_cZgTgIPd/meta.smil?format=smil&Tracking=true&mbr=true',
151 'info_dict': {
152 'id': 'e9I_cZgTgIPd',
153 'ext': 'flv',
154 'title': 'Blackberry\'s big, bold Z30',
155 'description': 'The Z30 is Blackberry\'s biggest, baddest mobile messaging device yet.',
156 'duration': 247,
79ba9140 157 'timestamp': 1383239700,
158 'upload_date': '20131031',
159 'uploader': 'CBSI-NEW',
e9bf7479 160 },
ed86f38a 161 'params': {
e9bf7479 162 # rtmp download
ed86f38a 163 'skip_download': True,
e9bf7479 164 },
433af6ad 165 'skip': '404 Not Found',
bd7a6478 166 }, {
372f08c9 167 # from http://www.cnet.com/videos/tesla-model-s-a-second-step-towards-a-cleaner-motoring-future/
bd7a6478
YCH
168 'url': 'http://link.theplatform.com/s/kYEXFC/22d_qsQ6MIRT',
169 'info_dict': {
170 'id': '22d_qsQ6MIRT',
171 'ext': 'flv',
172 'description': 'md5:ac330c9258c04f9d7512cf26b9595409',
173 'title': 'Tesla Model S: A second step towards a cleaner motoring future',
79ba9140 174 'timestamp': 1426176191,
175 'upload_date': '20150312',
176 'uploader': 'CBSI-NEW',
bd7a6478
YCH
177 },
178 'params': {
179 # rtmp download
180 'skip_download': True,
339c339f 181 },
19c90e40 182 'skip': 'CNet no longer uses ThePlatform',
6e054aac
S
183 }, {
184 'url': 'https://player.theplatform.com/p/D6x-PC/pulse_preview/embed/select/media/yMBg9E8KFxZD',
185 'info_dict': {
186 'id': 'yMBg9E8KFxZD',
187 'ext': 'mp4',
188 'description': 'md5:644ad9188d655b742f942bf2e06b002d',
189 'title': 'HIGHLIGHTS: USA bag first ever series Cup win',
79ba9140 190 'uploader': 'EGSM',
339c339f 191 },
19c90e40 192 'skip': 'Dead link',
6e054aac
S
193 }, {
194 'url': 'http://player.theplatform.com/p/NnzsPC/widget/select/media/4Y0TlYUr_ZT7',
195 'only_matching': True,
05fe2594
YCH
196 }, {
197 'url': 'http://player.theplatform.com/p/2E2eJC/nbcNewsOffsite?guid=tdy_or_siri_150701',
9f02ff53 198 'md5': 'fb96bb3d85118930a5b055783a3bd992',
05fe2594
YCH
199 'info_dict': {
200 'id': 'tdy_or_siri_150701',
201 'ext': 'mp4',
202 'title': 'iPhone Siri’s sassy response to a math question has people talking',
203 'description': 'md5:a565d1deadd5086f3331d57298ec6333',
204 'duration': 83.0,
ec85ded8 205 'thumbnail': r're:^https?://.*\.jpg$',
05fe2594
YCH
206 'timestamp': 1435752600,
207 'upload_date': '20150701',
79ba9140 208 'uploader': 'NBCU-NEWS',
05fe2594 209 },
19c90e40 210 'skip': 'Error: Player PID "nbcNewsOffsite" is disabled',
9a4acbfa
S
211 }, {
212 # From http://www.nbc.com/the-blacklist/video/sir-crispin-crandall/2928790?onid=137781#vc137781=1
213 # geo-restricted (US), HLS encrypted with AES-128
214 'url': 'http://player.theplatform.com/p/NnzsPC/onsite_universal/select/media/guid/2410887629/2928790?fwsitesection=nbc_the_blacklist_video_library&autoPlay=true&carouselID=137781',
215 'only_matching': True,
bd7a6478 216 }]
5f6a1245 217
898f4b49 218 @classmethod
bfd973ec 219 def _extract_embed_urls(cls, url, webpage):
a0566bbf 220 # Are whitespaces ignored in URLs?
067aa17e 221 # https://github.com/ytdl-org/youtube-dl/issues/12044
bfd973ec 222 for embed_url in super()._extract_embed_urls(url, webpage):
223 yield re.sub(r'\s', '', embed_url)
898f4b49 224
9fb2f1cd
S
225 @staticmethod
226 def _sign_url(url, sig_key, sig_secret, life=600, include_qs=False):
227 flags = '10' if include_qs else '00'
228 expiration_date = '%x' % (int(time.time()) + life)
229
230 def str_to_hex(str):
231 return binascii.b2a_hex(str.encode('ascii')).decode('ascii')
232
dcf094d6
YCH
233 def hex_to_bytes(hex):
234 return binascii.a2b_hex(hex.encode('ascii'))
9fb2f1cd 235
197224b7 236 relative_path = re.match(r'https?://link\.theplatform\.com/s/([^?]+)', url).group(1)
dcf094d6 237 clear_text = hex_to_bytes(flags + expiration_date + str_to_hex(relative_path))
9fb2f1cd
S
238 checksum = hmac.new(sig_key.encode('ascii'), clear_text, hashlib.sha1).hexdigest()
239 sig = flags + expiration_date + checksum + str_to_hex(sig_secret)
240 return '%s&sig=%s' % (url, sig)
241
10e3d734 242 def _real_extract(self, url):
9fb2f1cd 243 url, smuggled_data = unsmuggle_url(url, {})
29f7c58a 244 self._initialize_geo_bypass({
245 'countries': smuggled_data.get('geo_countries'),
246 })
9fb2f1cd 247
5ad28e7f 248 mobj = self._match_valid_url(url)
9fb2f1cd 249 provider_id = mobj.group('provider_id')
10e3d734 250 video_id = mobj.group('id')
9fb2f1cd
S
251
252 if not provider_id:
253 provider_id = 'dJ5BDC'
254
c02ec7d4 255 path = provider_id + '/'
6e054aac 256 if mobj.group('media'):
c02ec7d4 257 path += mobj.group('media')
258 path += video_id
6e054aac 259
4dfbf869 260 qs_dict = parse_qs(url)
05fe2594
YCH
261 if 'guid' in qs_dict:
262 webpage = self._download_webpage(url, video_id)
263 scripts = re.findall(r'<script[^>]+src="([^"]+)"', webpage)
264 feed_id = None
265 # feed id usually locates in the last script.
266 # Seems there's no pattern for the interested script filename, so
267 # I try one by one
268 for script in reversed(scripts):
ee5cd841 269 feed_script = self._download_webpage(
325bb615
S
270 self._proto_relative_url(script, 'http:'),
271 video_id, 'Downloading feed script')
272 feed_id = self._search_regex(
273 r'defaultFeedId\s*:\s*"([^"]+)"', feed_script,
274 'default feed id', default=None)
05fe2594
YCH
275 if feed_id is not None:
276 break
277 if feed_id is None:
278 raise ExtractorError('Unable to find feed id')
279 return self.url_result('http://feed.theplatform.com/f/%s/%s?byGuid=%s' % (
280 provider_id, feed_id, qs_dict['guid'][0]))
281
6140baf4
JMF
282 if smuggled_data.get('force_smil_url', False):
283 smil_url = url
067aa17e 284 # Explicitly specified SMIL (see https://github.com/ytdl-org/youtube-dl/issues/7385)
ad1f4e79 285 elif '/guid/' in url:
18e4088f
S
286 headers = {}
287 source_url = smuggled_data.get('source_url')
288 if source_url:
289 headers['Referer'] = source_url
3d2623a8 290 request = Request(url, headers=headers)
18e4088f 291 webpage = self._download_webpage(request, video_id)
ad1f4e79
S
292 smil_url = self._search_regex(
293 r'<link[^>]+href=(["\'])(?P<url>.+?)\1[^>]+type=["\']application/smil\+xml',
294 webpage, 'smil url', group='url')
295 path = self._search_regex(
296 r'link\.theplatform\.com/s/((?:[^/?#&]+/)+[^/?#&]+)', smil_url, 'path')
4c92fd2e 297 smil_url += '?' if '?' not in smil_url else '&' + 'formats=m3u,mpeg4'
6140baf4 298 elif mobj.group('config'):
5f6a1245 299 config_url = url + '&form=json'
10e3d734
PH
300 config_url = config_url.replace('swf/', 'config/')
301 config_url = config_url.replace('onsite/', 'onsite/config/')
302 config = self._download_json(config_url, video_id, 'Downloading config')
28479149
YCH
303 if 'releaseUrl' in config:
304 release_url = config['releaseUrl']
305 else:
306 release_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
4c92fd2e 307 smil_url = release_url + '&formats=MPEG4&manifest=f4m'
10e3d734 308 else:
4c92fd2e 309 smil_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
9fb2f1cd
S
310
311 sig = smuggled_data.get('sig')
312 if sig:
313 smil_url = self._sign_url(smil_url, sig['key'], sig['secret'])
e9bf7479 314
c687ac74 315 formats, subtitles = self._extract_theplatform_smil(smil_url, video_id)
f8b56e95 316
339c339f 317 # With some sites, manifest URL must be forced to extract HLS formats
318 if not traverse_obj(formats, lambda _, v: v['format_id'].startswith('hls')):
319 m3u8_url = update_url(url, query='mbr=true&manifest=m3u', fragment=None)
320 urlh = self._request_webpage(
321 HEADRequest(m3u8_url), video_id, 'Checking for HLS formats', 'No HLS formats found', fatal=False)
322 if urlh and urlhandle_detect_ext(urlh) == 'm3u8':
323 m3u8_fmts, m3u8_subs = self._extract_m3u8_formats_and_subtitles(
324 m3u8_url, video_id, m3u8_id='hls', fatal=False)
325 formats.extend(m3u8_fmts)
326 self._merge_subtitles(m3u8_subs, target=subtitles)
327
bf830248 328 ret = self._extract_theplatform_metadata(path, video_id)
c687ac74 329 combined_subtitles = self._merge_subtitles(ret.get('subtitles', {}), subtitles)
26e1c351
YCH
330 ret.update({
331 'id': video_id,
332 'formats': formats,
c687ac74 333 'subtitles': combined_subtitles,
26e1c351 334 })
e9bf7479 335
26e1c351 336 return ret
748ec667 337
f877c6ae 338
26e1c351 339class ThePlatformFeedIE(ThePlatformBaseIE):
5839d556 340 _URL_TEMPLATE = '%s//feed.theplatform.com/f/%s/%s?form=json&%s'
7ff129d3 341 _VALID_URL = r'https?://feed\.theplatform\.com/f/(?P<provider_id>[^/]+)/(?P<feed_id>[^?/]+)\?(?:[^&]+&)*(?P<filter>by(?:Gui|I)d=(?P<id>[^&]+))'
5839d556 342 _TESTS = [{
26e1c351
YCH
343 # From http://player.theplatform.com/p/7wvmTC/MSNBCEmbeddedOffSite?guid=n_hardball_5biden_140207
344 'url': 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207',
9f02ff53 345 'md5': '6e32495b5073ab414471b615c5ded394',
26e1c351
YCH
346 'info_dict': {
347 'id': 'n_hardball_5biden_140207',
348 'ext': 'mp4',
349 'title': 'The Biden factor: will Joe run in 2016?',
350 'description': 'Could Vice President Joe Biden be preparing a 2016 campaign? Mark Halperin and Sam Stein weigh in.',
ec85ded8 351 'thumbnail': r're:^https?://.*\.jpg$',
26e1c351
YCH
352 'upload_date': '20140208',
353 'timestamp': 1391824260,
354 'duration': 467.0,
355 'categories': ['MSNBC/Issues/Democrats', 'MSNBC/Issues/Elections/Election 2016'],
0738187f 356 'uploader': 'NBCU-NEWS',
26e1c351 357 },
7ff129d3
GF
358 }, {
359 'url': 'http://feed.theplatform.com/f/2E2eJC/nnd_NBCNews?byGuid=nn_netcast_180306.Copy.01',
360 'only_matching': True,
5839d556 361 }]
26e1c351 362
c7d6f614 363 def _extract_feed_info(self, provider_id, feed_id, filter_query, video_id, custom_fields=None, asset_types_query={}, account_id=None):
5839d556
RA
364 real_url = self._URL_TEMPLATE % (self.http_scheme(), provider_id, feed_id, filter_query)
365 entry = self._download_json(real_url, video_id)['entries'][0]
35328915 366 main_smil_url = 'http://link.theplatform.com/s/%s/media/guid/%d/%s' % (provider_id, account_id, entry['guid']) if account_id else entry.get('plmedia$publicUrl')
26e1c351
YCH
367
368 formats = []
c687ac74 369 subtitles = {}
26e1c351
YCH
370 first_video_id = None
371 duration = None
5839d556 372 asset_types = []
26e1c351 373 for item in entry['media$content']:
5839d556 374 smil_url = item['plfile$url']
3dc71d82 375 cur_video_id = ThePlatformIE._match_id(smil_url)
26e1c351
YCH
376 if first_video_id is None:
377 first_video_id = cur_video_id
378 duration = float_or_none(item.get('plfile$duration'))
4dfbf869 379 file_asset_types = item.get('plfile$assetTypes') or parse_qs(smil_url)['assetTypes']
35328915 380 for asset_type in file_asset_types:
5839d556
RA
381 if asset_type in asset_types:
382 continue
383 asset_types.append(asset_type)
384 query = {
385 'mbr': 'true',
386 'formats': item['plfile$format'],
387 'assetTypes': asset_type,
388 }
389 if asset_type in asset_types_query:
390 query.update(asset_types_query[asset_type])
391 cur_formats, cur_subtitles = self._extract_theplatform_smil(update_url_query(
c7d6f614 392 main_smil_url or smil_url, query), video_id, 'Downloading SMIL data for %s' % asset_type)
5839d556
RA
393 formats.extend(cur_formats)
394 subtitles = self._merge_subtitles(subtitles, cur_subtitles)
f877c6ae 395
26e1c351
YCH
396 thumbnails = [{
397 'url': thumbnail['plfile$url'],
398 'width': int_or_none(thumbnail.get('plfile$width')),
399 'height': int_or_none(thumbnail.get('plfile$height')),
400 } for thumbnail in entry.get('media$thumbnails', [])]
401
402 timestamp = int_or_none(entry.get('media$availableDate'), scale=1000)
403 categories = [item['media$name'] for item in entry.get('media$categories', [])]
404
bf830248 405 ret = self._extract_theplatform_metadata('%s/%s' % (provider_id, first_video_id), video_id)
c687ac74 406 subtitles = self._merge_subtitles(subtitles, ret['subtitles'])
26e1c351 407 ret.update({
e9bf7479 408 'id': video_id,
e9bf7479 409 'formats': formats,
c687ac74 410 'subtitles': subtitles,
26e1c351
YCH
411 'thumbnails': thumbnails,
412 'duration': duration,
413 'timestamp': timestamp,
414 'categories': categories,
415 })
5839d556
RA
416 if custom_fields:
417 ret.update(custom_fields(entry))
26e1c351
YCH
418
419 return ret
5839d556
RA
420
421 def _real_extract(self, url):
5ad28e7f 422 mobj = self._match_valid_url(url)
5839d556
RA
423
424 video_id = mobj.group('id')
425 provider_id = mobj.group('provider_id')
426 feed_id = mobj.group('feed_id')
427 filter_query = mobj.group('filter')
428
429 return self._extract_feed_info(provider_id, feed_id, filter_query, video_id)