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