]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/nbc.py
[ie/Canal1,CaracolTvPlay] Add extractors (#7151)
[yt-dlp.git] / yt_dlp / extractor / nbc.py
CommitLineData
58284890 1import base64
1139935d
RA
2import json
3import re
0bc56fa6
JMF
4
5from .common import InfoExtractor
176a068c 6from .theplatform import ThePlatformIE, default_ns
fdf9b959 7from .adobepass import AdobePassIE
d0c5fabc 8from ..compat import compat_urllib_parse_unquote
3d2623a8 9from ..networking import HEADRequest
1cc79574 10from ..utils import (
11398b92 11 ExtractorError,
cb73b846 12 RegexNotFoundError,
13 UserNotLive,
14 clean_html,
9be0fe1f 15 determine_ext,
16 float_or_none,
895e5c03 17 int_or_none,
9be0fe1f 18 mimetype2ext,
9160a0c6 19 parse_age_limit,
895e5c03 20 parse_duration,
9be0fe1f 21 remove_end,
b46b65ed 22 smuggle_url,
11398b92 23 traverse_obj,
895e5c03 24 try_get,
cb73b846 25 unescapeHTML,
895e5c03 26 unified_timestamp,
6e416b21 27 update_url_query,
11398b92 28 url_basename,
37e64add 29)
0bc56fa6
JMF
30
31
6368e2e6 32class NBCIE(ThePlatformIE): # XXX: Do not subclass from concrete IE
cb73b846 33 _VALID_URL = r'https?(?P<permalink>://(?:www\.)?nbc\.com/(?:classic-tv/)?[^/]+/video/[^/]+/(?P<id>(?:NBCE|n)?\d+))'
58c1f6f0
S
34
35 _TESTS = [
36 {
fdf9b959 37 'url': 'http://www.nbc.com/the-tonight-show/video/jimmy-fallon-surprises-fans-at-ben-jerrys/2848237',
58c1f6f0 38 'info_dict': {
fdf9b959 39 'id': '2848237',
e881c4bc 40 'ext': 'mp4',
5c8a3f86
JMF
41 'title': 'Jimmy Fallon Surprises Fans at Ben & Jerry\'s',
42 'description': 'Jimmy gives out free scoops of his new "Tonight Dough" ice cream flavor by surprising customers at the Ben & Jerry\'s scoop shop.',
79ba9140 43 'timestamp': 1424246400,
44 'upload_date': '20150218',
45 'uploader': 'NBCU-COM',
cb73b846 46 'episode': 'Jimmy Fallon Surprises Fans at Ben & Jerry\'s',
47 'episode_number': 86,
48 'season': 'Season 2',
49 'season_number': 2,
50 'series': 'Tonight Show: Jimmy Fallon',
51 'duration': 237.0,
52 'chapters': 'count:1',
53 'tags': 'count:4',
54 'thumbnail': r're:https?://.+\.jpg',
58c1f6f0 55 },
e881c4bc 56 'params': {
cb73b846 57 'skip_download': 'm3u8',
e881c4bc 58 },
020cf5eb 59 },
b9b3ab45
YCH
60 {
61 'url': 'http://www.nbc.com/saturday-night-live/video/star-wars-teaser/2832821',
62 'info_dict': {
e881c4bc
YCH
63 'id': '2832821',
64 'ext': 'mp4',
b9b3ab45
YCH
65 'title': 'Star Wars Teaser',
66 'description': 'md5:0b40f9cbde5b671a7ff62fceccc4f442',
79ba9140 67 'timestamp': 1417852800,
68 'upload_date': '20141206',
69 'uploader': 'NBCU-COM',
b9b3ab45 70 },
cb73b846 71 'skip': 'page not found',
0fe2ff78 72 },
e6e90515
YCH
73 {
74 # HLS streams requires the 'hdnea3' cookie
75 'url': 'http://www.nbc.com/Kings/video/goliath/n1806',
76 'info_dict': {
fdf9b959 77 'id': '101528f5a9e8127b107e98c5e6ce4638',
e6e90515
YCH
78 'ext': 'mp4',
79 'title': 'Goliath',
80 'description': 'When an unknown soldier saves the life of the King\'s son in battle, he\'s thrust into the limelight and politics of the kingdom.',
81 'timestamp': 1237100400,
82 'upload_date': '20090315',
83 'uploader': 'NBCU-COM',
84 },
cb73b846 85 'skip': 'page not found',
86 },
87 {
88 # manifest url does not have extension
89 'url': 'https://www.nbc.com/the-golden-globe-awards/video/oprah-winfrey-receives-cecil-b-de-mille-award-at-the-2018-golden-globes/3646439',
90 'info_dict': {
91 'id': '3646439',
92 'ext': 'mp4',
93 'title': 'Oprah Winfrey Receives Cecil B. de Mille Award at the 2018 Golden Globes',
94 'episode': 'Oprah Winfrey Receives Cecil B. de Mille Award at the 2018 Golden Globes',
95 'episode_number': 1,
96 'season': 'Season 75',
97 'season_number': 75,
98 'series': 'The Golden Globe Awards',
99 'description': 'Oprah Winfrey receives the Cecil B. de Mille Award at the 75th Annual Golden Globe Awards.',
100 'uploader': 'NBCU-COM',
101 'upload_date': '20180107',
102 'timestamp': 1515312000,
103 'duration': 570.0,
104 'tags': 'count:8',
105 'thumbnail': r're:https?://.+\.jpg',
106 'chapters': 'count:1',
107 },
108 'params': {
109 'skip_download': 'm3u8',
110 },
111 },
112 {
113 # new video_id format
114 'url': 'https://www.nbc.com/quantum-leap/video/bens-first-leap-nbcs-quantum-leap/NBCE125189978',
115 'info_dict': {
116 'id': 'NBCE125189978',
117 'ext': 'mp4',
118 'title': 'Ben\'s First Leap | NBC\'s Quantum Leap',
119 'description': 'md5:a82762449b7ec4bb83291a7b355ebf8e',
120 'uploader': 'NBCU-COM',
121 'series': 'Quantum Leap',
122 'season': 'Season 1',
123 'season_number': 1,
124 'episode': 'Ben\'s First Leap | NBC\'s Quantum Leap',
125 'episode_number': 1,
126 'duration': 170.171,
127 'chapters': [],
128 'timestamp': 1663956155,
129 'upload_date': '20220923',
130 'tags': 'count:10',
131 'age_limit': 0,
132 'thumbnail': r're:https?://.+\.jpg',
133 },
e6e90515 134 'params': {
cb73b846 135 'skip_download': 'm3u8',
e6e90515 136 },
d673ab65
L
137 },
138 {
139 'url': 'https://www.nbc.com/classic-tv/charles-in-charge/video/charles-in-charge-pilot/n3310',
140 'only_matching': True,
141 },
d0c5fabc
T
142 {
143 # Percent escaped url
144 'url': 'https://www.nbc.com/up-all-night/video/day-after-valentine%27s-day/n2189',
145 'only_matching': True,
146 }
58c1f6f0 147 ]
020cf5eb
JMF
148
149 def _real_extract(self, url):
5ad28e7f 150 permalink, video_id = self._match_valid_url(url).groups()
d0c5fabc 151 permalink = 'http' + compat_urllib_parse_unquote(permalink)
48ff5590 152 video_data = self._download_json(
311ee457 153 'https://friendship.nbc.co/v2/graphql', video_id, query={
48ff5590
RA
154 'query': '''query bonanzaPage(
155 $app: NBCUBrands! = nbc
156 $name: String!
157 $oneApp: Boolean
158 $platform: SupportedPlatforms! = web
159 $type: EntityPageType! = VIDEO
160 $userId: String!
161) {
162 bonanzaPage(
163 app: $app
164 name: $name
165 oneApp: $oneApp
166 platform: $platform
167 type: $type
168 userId: $userId
169 ) {
170 metadata {
311ee457
RA
171 ... on VideoPageData {
172 description
173 episodeNumber
174 keywords
175 locked
176 mpxAccountId
177 mpxGuid
178 rating
48ff5590 179 resourceId
311ee457
RA
180 seasonNumber
181 secondaryTitle
182 seriesShortTitle
183 }
184 }
185 }
48ff5590
RA
186}''',
187 'variables': json.dumps({
188 'name': permalink,
189 'oneApp': True,
190 'userId': '0',
191 }),
192 })['data']['bonanzaPage']['metadata']
2eeb588e
RA
193 query = {
194 'mbr': 'true',
195 'manifest': 'm3u',
c3366fdf 196 'switch': 'HLSServiceSecure',
2eeb588e 197 }
311ee457 198 video_id = video_data['mpxGuid']
9160a0c6
TSJ
199 tp_path = 'NnzsPC/media/guid/%s/%s' % (video_data.get('mpxAccountId') or '2410887629', video_id)
200 tpm = self._download_theplatform_metadata(tp_path, video_id)
201 title = tpm.get('title') or video_data.get('secondaryTitle')
311ee457 202 if video_data.get('locked'):
2eeb588e 203 resource = self._get_mvpd_resource(
48ff5590
RA
204 video_data.get('resourceId') or 'nbcentertainment',
205 title, video_id, video_data.get('rating'))
2eeb588e
RA
206 query['auth'] = self._extract_mvpd_auth(
207 url, video_id, 'nbcentertainment', resource)
208 theplatform_url = smuggle_url(update_url_query(
311ee457 209 'http://link.theplatform.com/s/NnzsPC/media/guid/%s/%s' % (video_data.get('mpxAccountId') or '2410887629', video_id),
2eeb588e 210 query), {'force_smil_url': True})
9160a0c6
TSJ
211
212 # Empty string or 0 can be valid values for these. So the check must be `is None`
213 description = video_data.get('description')
214 if description is None:
215 description = tpm.get('description')
216 episode_number = int_or_none(video_data.get('episodeNumber'))
217 if episode_number is None:
218 episode_number = int_or_none(tpm.get('nbcu$airOrder'))
219 rating = video_data.get('rating')
220 if rating is None:
221 try_get(tpm, lambda x: x['ratings'][0]['rating'])
222 season_number = int_or_none(video_data.get('seasonNumber'))
223 if season_number is None:
224 season_number = int_or_none(tpm.get('nbcu$seasonNumber'))
225 series = video_data.get('seriesShortTitle')
226 if series is None:
227 series = tpm.get('nbcu$seriesShortTitle')
228 tags = video_data.get('keywords')
229 if tags is None or len(tags) == 0:
230 tags = tpm.get('keywords')
231
2eeb588e 232 return {
e881c4bc 233 '_type': 'url_transparent',
9160a0c6
TSJ
234 'age_limit': parse_age_limit(rating),
235 'description': description,
236 'episode': title,
237 'episode_number': episode_number,
e881c4bc 238 'id': video_id,
9160a0c6
TSJ
239 'ie_key': 'ThePlatform',
240 'season_number': season_number,
241 'series': series,
242 'tags': tags,
2eeb588e
RA
243 'title': title,
244 'url': theplatform_url,
e881c4bc 245 }
020cf5eb
JMF
246
247
a2a4d5fa 248class NBCSportsVPlayerIE(InfoExtractor):
29f7c58a 249 _VALID_URL_BASE = r'https?://(?:vplayer\.nbcsports\.com|(?:www\.)?nbcsports\.com/vplayer)/'
250 _VALID_URL = _VALID_URL_BASE + r'(?:[^/]+/)+(?P<id>[0-9a-zA-Z_]+)'
bfd973ec 251 _EMBED_REGEX = [r'(?:iframe[^>]+|var video|div[^>]+data-(?:mpx-)?)[sS]rc\s?=\s?"(?P<url>%s[^\"]+)' % _VALID_URL_BASE]
a28ccbab 252
5cbb2699 253 _TESTS = [{
12ea5c79 254 'url': 'https://vplayer.nbcsports.com/p/BxmELC/nbcsports_embed/select/9CsDKds0kvHI',
a28ccbab
YCH
255 'info_dict': {
256 'id': '9CsDKds0kvHI',
12ea5c79 257 'ext': 'mp4',
a28ccbab
YCH
258 'description': 'md5:df390f70a9ba7c95ff1daace988f0d8d',
259 'title': 'Tyler Kalinoski hits buzzer-beater to lift Davidson',
79ba9140 260 'timestamp': 1426270238,
261 'upload_date': '20150313',
262 'uploader': 'NBCU-SPORTS',
bfa0e270 263 'duration': 72.818,
264 'chapters': [],
265 'thumbnail': r're:^https?://.*\.jpg$'
a28ccbab 266 }
5cbb2699 267 }, {
bfa0e270 268 'url': 'https://vplayer.nbcsports.com/p/BxmELC/nbcsports_embed/select/media/PEgOtlNcC_y2',
5cbb2699 269 'only_matching': True,
29f7c58a 270 }, {
271 'url': 'https://www.nbcsports.com/vplayer/p/BxmELC/nbcsports/select/PHJSaFWbrTY9?form=html&autoPlay=true',
272 'only_matching': True,
5cbb2699 273 }]
a28ccbab
YCH
274
275 def _real_extract(self, url):
276 video_id = self._match_id(url)
277 webpage = self._download_webpage(url, video_id)
bfa0e270 278 theplatform_url = self._html_search_regex(r'tp:releaseUrl="(.+?)"', webpage, 'url')
a28ccbab
YCH
279 return self.url_result(theplatform_url, 'ThePlatform')
280
281
a2a4d5fa 282class NBCSportsIE(InfoExtractor):
29f7c58a 283 _VALID_URL = r'https?://(?:www\.)?nbcsports\.com//?(?!vplayer/)(?:[^/]+/)+(?P<id>[0-9a-z-]+)'
a2a4d5fa 284
29f7c58a 285 _TESTS = [{
286 # iframe src
a2a4d5fa 287 'url': 'http://www.nbcsports.com//college-basketball/ncaab/tom-izzo-michigan-st-has-so-much-respect-duke',
a2a4d5fa
YCH
288 'info_dict': {
289 'id': 'PHJSaFWbrTY9',
29f7c58a 290 'ext': 'mp4',
a2a4d5fa
YCH
291 'title': 'Tom Izzo, Michigan St. has \'so much respect\' for Duke',
292 'description': 'md5:ecb459c9d59e0766ac9c7d5d0eda8113',
0738187f
YCH
293 'uploader': 'NBCU-SPORTS',
294 'upload_date': '20150330',
295 'timestamp': 1427726529,
bfa0e270 296 'chapters': [],
297 'thumbnail': 'https://hdliveextra-a.akamaihd.net/HD/image_sports/NBCU_Sports_Group_-_nbcsports/253/303/izzodps.jpg',
298 'duration': 528.395,
a2a4d5fa 299 }
29f7c58a 300 }, {
301 # data-mpx-src
302 'url': 'https://www.nbcsports.com/philadelphia/philadelphia-phillies/bruce-bochy-hector-neris-hes-idiot',
303 'only_matching': True,
304 }, {
305 # data-src
306 'url': 'https://www.nbcsports.com/boston/video/report-card-pats-secondary-no-match-josh-allen',
307 'only_matching': True,
308 }]
a2a4d5fa
YCH
309
310 def _real_extract(self, url):
311 video_id = self._match_id(url)
312 webpage = self._download_webpage(url, video_id)
313 return self.url_result(
314 NBCSportsVPlayerIE._extract_url(webpage), 'NBCSportsVPlayer')
315
316
1139935d
RA
317class NBCSportsStreamIE(AdobePassIE):
318 _VALID_URL = r'https?://stream\.nbcsports\.com/.+?\bpid=(?P<id>\d+)'
319 _TEST = {
320 'url': 'http://stream.nbcsports.com/nbcsn/generic?pid=206559',
321 'info_dict': {
322 'id': '206559',
323 'ext': 'mp4',
324 'title': 'Amgen Tour of California Women\'s Recap',
325 'description': 'md5:66520066b3b5281ada7698d0ea2aa894',
326 },
327 'params': {
328 # m3u8 download
329 'skip_download': True,
330 },
331 'skip': 'Requires Adobe Pass Authentication',
332 }
333
334 def _real_extract(self, url):
335 video_id = self._match_id(url)
336 live_source = self._download_json(
337 'http://stream.nbcsports.com/data/live_sources_%s.json' % video_id,
338 video_id)
339 video_source = live_source['videoSources'][0]
340 title = video_source['title']
341 source_url = None
342 for k in ('source', 'msl4source', 'iossource', 'hlsv4'):
343 sk = k + 'Url'
344 source_url = video_source.get(sk) or video_source.get(sk + 'Alt')
345 if source_url:
346 break
347 else:
348 source_url = video_source['ottStreamUrl']
349 is_live = video_source.get('type') == 'live' or video_source.get('status') == 'Live'
350 resource = self._get_mvpd_resource('nbcsports', title, video_id, '')
351 token = self._extract_mvpd_auth(url, video_id, 'nbcsports', resource)
352 tokenized_url = self._download_json(
353 'https://token.playmakerservices.com/cdn',
354 video_id, data=json.dumps({
355 'requestorId': 'nbcsports',
356 'pid': video_id,
357 'application': 'NBCSports',
358 'version': 'v1',
359 'platform': 'desktop',
360 'cdn': 'akamai',
361 'url': video_source['sourceUrl'],
362 'token': base64.b64encode(token.encode()).decode(),
363 'resourceId': base64.b64encode(resource.encode()).decode(),
364 }).encode())['tokenizedUrl']
365 formats = self._extract_m3u8_formats(tokenized_url, video_id, 'mp4')
1139935d
RA
366 return {
367 'id': video_id,
39ca3b5c 368 'title': title,
1139935d
RA
369 'description': live_source.get('description'),
370 'formats': formats,
371 'is_live': is_live,
372 }
373
374
6368e2e6 375class NBCNewsIE(ThePlatformIE): # XXX: Do not subclass from concrete IE
a843464a 376 _VALID_URL = r'(?x)https?://(?:www\.)?(?:nbcnews|today|msnbc)\.com/([^/]+/)*(?:.*-)?(?P<id>[^/?]+)'
bfd973ec 377 _EMBED_REGEX = [r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//www\.nbcnews\.com/widget/video-embed/[^"\']+)\1']
0bc56fa6 378
87fe568c 379 _TESTS = [
87fe568c 380 {
574b2a73 381 'url': 'http://www.nbcnews.com/watch/nbcnews-com/how-twitter-reacted-to-the-snowden-interview-269389891880',
895e5c03 382 'md5': 'cf4bc9e6ce0130f00f545d80ecedd4bf',
87fe568c 383 'info_dict': {
a843464a 384 'id': '269389891880',
10e3d734 385 'ext': 'mp4',
87fe568c
JMF
386 'title': 'How Twitter Reacted To The Snowden Interview',
387 'description': 'md5:65a0bd5d76fe114f3c2727aa3a81fe64',
0437307a
RA
388 'timestamp': 1401363060,
389 'upload_date': '20140529',
87fe568c 390 },
87fe568c 391 },
2df54b4b
S
392 {
393 'url': 'http://www.nbcnews.com/feature/dateline-full-episodes/full-episode-family-business-n285156',
394 'md5': 'fdbf39ab73a72df5896b6234ff98518a',
395 'info_dict': {
0437307a 396 'id': '529953347624',
2df54b4b
S
397 'ext': 'mp4',
398 'title': 'FULL EPISODE: Family Business',
399 'description': 'md5:757988edbaae9d7be1d585eb5d55cc04',
400 },
574b2a73 401 'skip': 'This page is unavailable.',
2df54b4b 402 },
d9aa2b78
RS
403 {
404 'url': 'http://www.nbcnews.com/nightly-news/video/nightly-news-with-brian-williams-full-broadcast-february-4-394064451844',
895e5c03 405 'md5': '8eb831eca25bfa7d25ddd83e85946548',
d9aa2b78 406 'info_dict': {
a843464a 407 'id': '394064451844',
d9aa2b78
RS
408 'ext': 'mp4',
409 'title': 'Nightly News with Brian Williams Full Broadcast (February 4)',
410 'description': 'md5:1c10c1eccbe84a26e5debb4381e2d3c5',
0437307a 411 'timestamp': 1423104900,
0437307a 412 'upload_date': '20150205',
d9aa2b78
RS
413 },
414 },
574b2a73 415 {
416 'url': 'http://www.nbcnews.com/business/autos/volkswagen-11-million-vehicles-could-have-suspect-software-emissions-scandal-n431456',
895e5c03 417 'md5': '4a8c4cec9e1ded51060bdda36ff0a5c0',
574b2a73 418 'info_dict': {
895e5c03 419 'id': 'n431456',
574b2a73 420 'ext': 'mp4',
895e5c03
RA
421 'title': "Volkswagen U.S. Chief: We 'Totally Screwed Up'",
422 'description': 'md5:d22d1281a24f22ea0880741bb4dd6301',
0437307a
RA
423 'upload_date': '20150922',
424 'timestamp': 1442917800,
574b2a73 425 },
574b2a73 426 },
cb7d4d0e 427 {
428 'url': 'http://www.today.com/video/see-the-aurora-borealis-from-space-in-stunning-new-nasa-video-669831235788',
429 'md5': '118d7ca3f0bea6534f119c68ef539f71',
430 'info_dict': {
a843464a 431 'id': '669831235788',
cb7d4d0e 432 'ext': 'mp4',
433 'title': 'See the aurora borealis from space in stunning new NASA video',
434 'description': 'md5:74752b7358afb99939c5f8bb2d1d04b1',
435 'upload_date': '20160420',
436 'timestamp': 1461152093,
0437307a
RA
437 },
438 },
439 {
440 'url': 'http://www.msnbc.com/all-in-with-chris-hayes/watch/the-chaotic-gop-immigration-vote-314487875924',
441 'md5': '6d236bf4f3dddc226633ce6e2c3f814d',
442 'info_dict': {
a843464a 443 'id': '314487875924',
0437307a
RA
444 'ext': 'mp4',
445 'title': 'The chaotic GOP immigration vote',
446 'description': 'The Republican House votes on a border bill that has no chance of getting through the Senate or signed by the President and is drawing criticism from all sides.',
ec85ded8 447 'thumbnail': r're:^https?://.*\.jpg$',
0437307a
RA
448 'timestamp': 1406937606,
449 'upload_date': '20140802',
cb7d4d0e 450 },
451 },
3f125c8c
S
452 {
453 'url': 'http://www.nbcnews.com/watch/dateline/full-episode--deadly-betrayal-386250819952',
454 'only_matching': True,
455 },
5de008e8
YCH
456 {
457 # From http://www.vulture.com/2016/06/letterman-couldnt-care-less-about-late-night.html
458 'url': 'http://www.nbcnews.com/widget/video-embed/701714499682',
459 'only_matching': True,
460 },
87fe568c 461 ]
0bc56fa6
JMF
462
463 def _real_extract(self, url):
a843464a 464 video_id = self._match_id(url)
895e5c03
RA
465 webpage = self._download_webpage(url, video_id)
466
135dfa2c 467 data = self._search_nextjs_data(webpage, video_id)['props']['initialState']
895e5c03
RA
468 video_data = try_get(data, lambda x: x['video']['current'], dict)
469 if not video_data:
470 video_data = data['article']['content'][0]['primaryMedia']['video']
471 title = video_data['headline']['primary']
472
473 formats = []
474 for va in video_data.get('videoAssets', []):
475 public_url = va.get('publicUrl')
476 if not public_url:
477 continue
478 if '://link.theplatform.com/' in public_url:
479 public_url = update_url_query(public_url, {'format': 'redirect'})
480 format_id = va.get('format')
481 if format_id == 'M3U':
482 formats.extend(self._extract_m3u8_formats(
483 public_url, video_id, 'mp4', 'm3u8_native',
484 m3u8_id=format_id, fatal=False))
485 continue
486 tbr = int_or_none(va.get('bitrate'), 1000)
487 if tbr:
488 format_id += '-%d' % tbr
489 formats.append({
490 'format_id': format_id,
491 'url': public_url,
492 'width': int_or_none(va.get('width')),
493 'height': int_or_none(va.get('height')),
494 'tbr': tbr,
495 'ext': 'mp4',
496 })
6e416b21 497
895e5c03
RA
498 subtitles = {}
499 closed_captioning = video_data.get('closedCaptioning')
500 if closed_captioning:
501 for cc_url in closed_captioning.values():
502 if not cc_url:
503 continue
504 subtitles.setdefault('en', []).append({
505 'url': cc_url,
506 })
6e416b21 507
a843464a 508 return {
a843464a 509 'id': video_id,
895e5c03
RA
510 'title': title,
511 'description': try_get(video_data, lambda x: x['description']['primary']),
512 'thumbnail': try_get(video_data, lambda x: x['primaryImage']['url']['primary']),
513 'duration': parse_duration(video_data.get('duration')),
514 'timestamp': unified_timestamp(video_data.get('datePublished')),
515 'formats': formats,
516 'subtitles': subtitles,
a843464a 517 }
be457302
YCH
518
519
520class NBCOlympicsIE(InfoExtractor):
58284890 521 IE_NAME = 'nbcolympics'
3e376d18 522 _VALID_URL = r'https?://www\.nbcolympics\.com/videos?/(?P<id>[0-9a-z-]+)'
be457302
YCH
523
524 _TEST = {
525 # Geo-restricted to US
526 'url': 'http://www.nbcolympics.com/video/justin-roses-son-leo-was-tears-after-his-dad-won-gold',
527 'md5': '54fecf846d05429fbaa18af557ee523a',
528 'info_dict': {
529 'id': 'WjTBzDXx5AUq',
530 'display_id': 'justin-roses-son-leo-was-tears-after-his-dad-won-gold',
531 'ext': 'mp4',
532 'title': 'Rose\'s son Leo was in tears after his dad won gold',
533 'description': 'Olympic gold medalist Justin Rose gets emotional talking to the impact his win in men\'s golf has already had on his children.',
534 'timestamp': 1471274964,
535 'upload_date': '20160815',
536 'uploader': 'NBCU-SPORTS',
537 },
538 }
539
540 def _real_extract(self, url):
541 display_id = self._match_id(url)
542
543 webpage = self._download_webpage(url, display_id)
544
3e376d18
W
545 try:
546 drupal_settings = self._parse_json(self._search_regex(
547 r'jQuery\.extend\(Drupal\.settings\s*,\s*({.+?})\);',
548 webpage, 'drupal settings'), display_id)
549
550 iframe_url = drupal_settings['vod']['iframe_url']
551 theplatform_url = iframe_url.replace(
552 'vplayer.nbcolympics.com', 'player.theplatform.com')
553 except RegexNotFoundError:
554 theplatform_url = self._search_regex(
555 r"([\"'])embedUrl\1: *([\"'])(?P<embedUrl>.+)\2",
556 webpage, 'embedding URL', group="embedUrl")
be457302
YCH
557
558 return {
559 '_type': 'url_transparent',
560 'url': theplatform_url,
561 'ie_key': ThePlatformIE.ie_key(),
562 'display_id': display_id,
563 }
58284890
RA
564
565
566class NBCOlympicsStreamIE(AdobePassIE):
567 IE_NAME = 'nbcolympics:stream'
568 _VALID_URL = r'https?://stream\.nbcolympics\.com/(?P<id>[0-9a-z-]+)'
bb36a55c 569 _TESTS = [
570 {
571 'note': 'Tokenized m3u8 source URL',
572 'url': 'https://stream.nbcolympics.com/womens-soccer-group-round-11',
573 'info_dict': {
574 'id': '2019740',
575 'ext': 'mp4',
576 'title': r"re:Women's Group Stage - Netherlands vs\. Brazil [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$",
577 },
578 'params': {
579 'skip_download': 'm3u8',
580 },
581 }, {
582 'note': 'Plain m3u8 source URL',
583 'url': 'https://stream.nbcolympics.com/gymnastics-event-finals-mens-floor-pommel-horse-womens-vault-bars',
584 'info_dict': {
585 'id': '2021729',
586 'ext': 'mp4',
587 'title': r're:Event Finals: M Floor, W Vault, M Pommel, W Uneven Bars [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$',
588 },
589 'params': {
590 'skip_download': 'm3u8',
591 },
58284890 592 },
bb36a55c 593 ]
58284890
RA
594
595 def _real_extract(self, url):
596 display_id = self._match_id(url)
597 webpage = self._download_webpage(url, display_id)
598 pid = self._search_regex(r'pid\s*=\s*(\d+);', webpage, 'pid')
bb36a55c 599
58284890 600 event_config = self._download_json(
bb36a55c 601 f'http://stream.nbcolympics.com/data/event_config_{pid}.json',
602 pid, 'Downloading event config')['eventConfig']
603
604 title = event_config['eventTitle']
605 is_live = {'live': True, 'replay': False}.get(event_config.get('eventStatus'))
bb36a55c 606
58284890 607 source_url = self._download_json(
bb36a55c 608 f'https://api-leap.nbcsports.com/feeds/assets/{pid}?application=NBCOlympics&platform=desktop&format=nbc-player&env=staging',
609 pid, 'Downloading leap config'
610 )['videoSources'][0]['cdnSources']['primary'][0]['sourceUrl']
611
612 if event_config.get('cdnToken'):
613 ap_resource = self._get_mvpd_resource(
614 event_config.get('resourceId', 'NBCOlympics'),
615 re.sub(r'[^\w\d ]+', '', event_config['eventTitle']), pid,
616 event_config.get('ratingId', 'NO VALUE'))
617 media_token = self._extract_mvpd_auth(url, pid, event_config.get('requestorId', 'NBCOlympics'), ap_resource)
618
619 source_url = self._download_json(
620 'https://tokens.playmakerservices.com/', pid, 'Retrieving tokenized URL',
621 data=json.dumps({
622 'application': 'NBCSports',
623 'authentication-type': 'adobe-pass',
624 'cdn': 'akamai',
625 'pid': pid,
626 'platform': 'desktop',
627 'requestorId': 'NBCOlympics',
628 'resourceId': base64.b64encode(ap_resource.encode()).decode(),
629 'token': base64.b64encode(media_token.encode()).decode(),
630 'url': source_url,
631 'version': 'v1',
632 }).encode(),
633 )['akamai'][0]['tokenizedUrl']
634
635 formats = self._extract_m3u8_formats(source_url, pid, 'mp4', live=is_live)
636 for f in formats:
637 # -http_seekable requires ffmpeg 4.3+ but it doesnt seem possible to
638 # download with ffmpeg without this option
0a5a191a 639 f['downloader_options'] = {'ffmpeg_args': ['-seekable', '0', '-http_seekable', '0', '-icy', '0']}
58284890
RA
640
641 return {
642 'id': pid,
643 'display_id': display_id,
644 'title': title,
645 'formats': formats,
bb36a55c 646 'is_live': is_live,
58284890 647 }
11398b92 648
649
650class NBCStationsIE(InfoExtractor):
651 _DOMAIN_RE = '|'.join(map(re.escape, (
652 'nbcbayarea', 'nbcboston', 'nbcchicago', 'nbcconnecticut', 'nbcdfw', 'nbclosangeles',
653 'nbcmiami', 'nbcnewyork', 'nbcphiladelphia', 'nbcsandiego', 'nbcwashington',
654 'necn', 'telemundo52', 'telemundoarizona', 'telemundochicago', 'telemundonuevainglaterra',
655 )))
656 _VALID_URL = rf'https?://(?:www\.)?(?P<site>{_DOMAIN_RE})\.com/(?:[^/?#]+/)*(?P<id>[^/?#]+)/?(?:$|[#?])'
657
658 _TESTS = [{
659 'url': 'https://www.nbclosangeles.com/news/local/large-structure-fire-in-downtown-la-prompts-smoke-odor-advisory/2968618/',
11398b92 660 'info_dict': {
661 'id': '2968618',
662 'ext': 'mp4',
663 'title': 'Large Structure Fire in Downtown LA Prompts Smoke Odor Advisory',
cb73b846 664 'description': 'md5:417ed3c2d91fe9d301e6db7b0942f182',
9be0fe1f 665 'duration': 112.513,
11398b92 666 'timestamp': 1661135892,
cb73b846 667 'upload_date': '20220822',
11398b92 668 'uploader': 'NBC 4',
cb73b846 669 'channel_id': 'KNBC',
11398b92 670 'channel': 'nbclosangeles',
671 },
cb73b846 672 'params': {
673 'skip_download': 'm3u8',
674 },
11398b92 675 }, {
676 'url': 'https://www.telemundoarizona.com/responde/huracan-complica-reembolso-para-televidente-de-tucson/2247002/',
11398b92 677 'info_dict': {
678 'id': '2247002',
679 'ext': 'mp4',
cb73b846 680 'title': 'Huracán complica que televidente de Tucson reciba reembolso',
11398b92 681 'description': 'md5:af298dc73aab74d4fca6abfb12acb6cf',
9be0fe1f 682 'duration': 172.406,
11398b92 683 'timestamp': 1660886507,
684 'upload_date': '20220819',
685 'uploader': 'Telemundo Arizona',
cb73b846 686 'channel_id': 'KTAZ',
11398b92 687 'channel': 'telemundoarizona',
688 },
cb73b846 689 'params': {
690 'skip_download': 'm3u8',
691 },
9be0fe1f 692 }, {
693 # direct mp4 link
694 'url': 'https://www.nbcboston.com/weather/video-weather/highs-near-freezing-in-boston-on-wednesday/2961135/',
695 'md5': '9bf8c41dc7abbb75b1a44f1491a4cc85',
696 'info_dict': {
697 'id': '2961135',
698 'ext': 'mp4',
699 'title': 'Highs Near Freezing in Boston on Wednesday',
700 'description': 'md5:3ec486609a926c99f00a3512e6c0e85b',
701 'duration': 235.669,
702 'timestamp': 1675268656,
703 'upload_date': '20230201',
704 'uploader': '',
705 'channel_id': 'WBTS',
706 'channel': 'nbcboston',
707 },
11398b92 708 }]
709
710 _RESOLUTIONS = {
711 '1080': '1920',
712 '720': '1280',
713 '540': '960',
714 '360': '640',
715 '234': '416',
716 }
717
718 def _real_extract(self, url):
719 channel, video_id = self._match_valid_url(url).group('site', 'id')
720 webpage = self._download_webpage(url, video_id)
721
722 nbc_data = self._search_json(
176a068c 723 r'<script>\s*var\s+nbc\s*=', webpage, 'NBC JSON data', video_id)
11398b92 724 pdk_acct = nbc_data.get('pdkAcct') or 'Yh1nAC'
725 fw_ssid = traverse_obj(nbc_data, ('video', 'fwSSID'))
11398b92 726
cb73b846 727 video_data = self._search_json(
728 r'data-videos="\[', webpage, 'video data', video_id, default={}, transform_source=unescapeHTML)
729 video_data.update(self._search_json(
730 r'data-meta="', webpage, 'metadata', video_id, default={}, transform_source=unescapeHTML))
731 if not video_data:
732 raise ExtractorError('No video metadata found in webpage', expected=True)
11398b92 733
9be0fe1f 734 info, formats = {}, []
cb73b846 735 is_live = int_or_none(video_data.get('mpx_is_livestream')) == 1
736 query = {
737 'formats': 'MPEG-DASH none,M3U none,MPEG-DASH none,MPEG4,MP3',
738 'format': 'SMIL',
739 'fwsitesection': fw_ssid,
740 'fwNetworkID': traverse_obj(nbc_data, ('video', 'fwNetworkID'), default='382114'),
741 'pprofile': 'ots_desktop_html',
742 'sensitive': 'false',
743 'w': '1920',
744 'h': '1080',
745 'mode': 'LIVE' if is_live else 'on-demand',
746 'vpaid': 'script',
747 'schema': '2.0',
748 'sdk': 'PDK 6.1.3',
749 }
11398b92 750
cb73b846 751 if is_live:
752 player_id = traverse_obj(video_data, ((None, ('video', 'meta')), (
753 'mpx_m3upid', 'mpx_pid', 'pid_streaming_web_medium')), get_all=False)
754 info['title'] = f'{channel} livestream'
11398b92 755
756 else:
cb73b846 757 player_id = traverse_obj(video_data, (
758 (None, ('video', 'meta')), ('pid_streaming_web_high', 'mpx_pid')), get_all=False)
11398b92 759
760 date_string = traverse_obj(video_data, 'date_string', 'date_gmt')
761 if date_string:
762 date_string = self._search_regex(
763 r'datetime="([^"]+)"', date_string, 'date string', fatal=False)
764 else:
765 date_string = traverse_obj(
cb73b846 766 nbc_data, ('dataLayer', 'adobe', ('prop70', 'eVar70', 'eVar59')), get_all=False)
11398b92 767
cb73b846 768 video_url = traverse_obj(video_data, ((None, ('video', 'meta')), 'mp4_url'), get_all=False)
11398b92 769 if video_url:
9be0fe1f 770 ext = determine_ext(video_url)
cb73b846 771 height = self._search_regex(r'\d+-(\d+)p', url_basename(video_url), 'height', default=None)
11398b92 772 formats.append({
773 'url': video_url,
9be0fe1f 774 'ext': ext,
11398b92 775 'width': int_or_none(self._RESOLUTIONS.get(height)),
776 'height': int_or_none(height),
9be0fe1f 777 'format_id': f'http-{ext}',
11398b92 778 })
779
cb73b846 780 info.update({
781 'title': video_data.get('title') or traverse_obj(nbc_data, (
782 'dataLayer', (None, 'adobe'), ('contenttitle', 'title', 'prop22')), get_all=False),
783 'description':
784 traverse_obj(video_data, 'summary', 'excerpt', 'video_hero_text')
785 or clean_html(traverse_obj(nbc_data, ('dataLayer', 'summary'))),
786 'timestamp': unified_timestamp(date_string),
787 })
11398b92 788
cb73b846 789 smil = None
790 if player_id and fw_ssid:
791 smil = self._download_xml(
792 f'https://link.theplatform.com/s/{pdk_acct}/{player_id}', video_id,
793 note='Downloading SMIL data', query=query, fatal=is_live)
9be0fe1f 794 subtitles = self._parse_smil_subtitles(smil, default_ns) if smil else {}
795 for video in smil.findall(self._xpath_ns('.//video', default_ns)) if smil else []:
796 info['duration'] = float_or_none(remove_end(video.get('dur'), 'ms'), 1000)
797 video_src_url = video.get('src')
798 ext = mimetype2ext(video.get('type'), default=determine_ext(video_src_url))
799 if ext == 'm3u8':
800 fmts, subs = self._extract_m3u8_formats_and_subtitles(
801 video_src_url, video_id, 'mp4', m3u8_id='hls', fatal=is_live,
802 live=is_live, errnote='No HLS formats found')
803 formats.extend(fmts)
804 self._merge_subtitles(subs, target=subtitles)
805 elif video_src_url:
806 formats.append({
807 'url': video_src_url,
808 'format_id': f'https-{ext}',
809 'ext': ext,
810 'width': int_or_none(video.get('width')),
811 'height': int_or_none(video.get('height')),
812 })
cb73b846 813
814 if not formats:
815 self.raise_no_formats('No video content found in webpage', expected=True)
816 elif is_live:
817 try:
818 self._request_webpage(
819 HEADRequest(formats[0]['url']), video_id, note='Checking live status')
820 except ExtractorError:
821 raise UserNotLive(video_id=channel)
11398b92 822
823 return {
cb73b846 824 'id': video_id,
11398b92 825 'channel': channel,
cb73b846 826 'channel_id': nbc_data.get('callLetters'),
827 'uploader': nbc_data.get('on_air_name'),
11398b92 828 'formats': formats,
cb73b846 829 'subtitles': subtitles,
830 'is_live': is_live,
11398b92 831 **info,
832 }