]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/nbc.py
[cleanup] Update extractor tests (#7718)
[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
19c90e40 287 'url': 'https://www.nbcsports.com/watch/nfl/profootballtalk/pft-pm/unpacking-addisons-reckless-driving-citation',
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',
19c90e40 382 'md5': 'fb3dcd2d7b1dd9804305fa2fc95ab610', # md5 tends to fluctuate
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',
19c90e40 390 'duration': 46.0,
391 'thumbnail': 'https://media-cldnry.s-nbcnews.com/image/upload/MSNBC/Components/Video/140529/p_tweet_snow_140529.jpg',
87fe568c 392 },
87fe568c 393 },
2df54b4b
S
394 {
395 'url': 'http://www.nbcnews.com/feature/dateline-full-episodes/full-episode-family-business-n285156',
396 'md5': 'fdbf39ab73a72df5896b6234ff98518a',
397 'info_dict': {
0437307a 398 'id': '529953347624',
2df54b4b
S
399 'ext': 'mp4',
400 'title': 'FULL EPISODE: Family Business',
401 'description': 'md5:757988edbaae9d7be1d585eb5d55cc04',
402 },
574b2a73 403 'skip': 'This page is unavailable.',
2df54b4b 404 },
d9aa2b78
RS
405 {
406 'url': 'http://www.nbcnews.com/nightly-news/video/nightly-news-with-brian-williams-full-broadcast-february-4-394064451844',
19c90e40 407 'md5': '40d0e48c68896359c80372306ece0fc3',
d9aa2b78 408 'info_dict': {
a843464a 409 'id': '394064451844',
d9aa2b78
RS
410 'ext': 'mp4',
411 'title': 'Nightly News with Brian Williams Full Broadcast (February 4)',
412 'description': 'md5:1c10c1eccbe84a26e5debb4381e2d3c5',
0437307a 413 'timestamp': 1423104900,
0437307a 414 'upload_date': '20150205',
19c90e40 415 'duration': 1236.0,
416 'thumbnail': 'https://media-cldnry.s-nbcnews.com/image/upload/MSNBC/Components/Video/__NEW/nn_netcast_150204.jpg',
d9aa2b78
RS
417 },
418 },
574b2a73 419 {
420 'url': 'http://www.nbcnews.com/business/autos/volkswagen-11-million-vehicles-could-have-suspect-software-emissions-scandal-n431456',
19c90e40 421 'md5': 'ffb59bcf0733dc3c7f0ace907f5e3939',
574b2a73 422 'info_dict': {
895e5c03 423 'id': 'n431456',
574b2a73 424 'ext': 'mp4',
895e5c03
RA
425 'title': "Volkswagen U.S. Chief: We 'Totally Screwed Up'",
426 'description': 'md5:d22d1281a24f22ea0880741bb4dd6301',
0437307a
RA
427 'upload_date': '20150922',
428 'timestamp': 1442917800,
19c90e40 429 'duration': 37.0,
430 'thumbnail': 'https://media-cldnry.s-nbcnews.com/image/upload/MSNBC/Components/Video/__NEW/x_lon_vwhorn_150922.jpg',
574b2a73 431 },
574b2a73 432 },
cb7d4d0e 433 {
434 'url': 'http://www.today.com/video/see-the-aurora-borealis-from-space-in-stunning-new-nasa-video-669831235788',
19c90e40 435 'md5': '693d1fa21d23afcc9b04c66b227ed9ff',
cb7d4d0e 436 'info_dict': {
a843464a 437 'id': '669831235788',
cb7d4d0e 438 'ext': 'mp4',
439 'title': 'See the aurora borealis from space in stunning new NASA video',
440 'description': 'md5:74752b7358afb99939c5f8bb2d1d04b1',
441 'upload_date': '20160420',
442 'timestamp': 1461152093,
19c90e40 443 'duration': 69.0,
444 'thumbnail': 'https://media-cldnry.s-nbcnews.com/image/upload/MSNBC/Components/Video/201604/2016-04-20T11-35-09-133Z--1280x720.jpg',
0437307a
RA
445 },
446 },
447 {
448 'url': 'http://www.msnbc.com/all-in-with-chris-hayes/watch/the-chaotic-gop-immigration-vote-314487875924',
449 'md5': '6d236bf4f3dddc226633ce6e2c3f814d',
450 'info_dict': {
a843464a 451 'id': '314487875924',
0437307a
RA
452 'ext': 'mp4',
453 'title': 'The chaotic GOP immigration vote',
454 '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 455 'thumbnail': r're:^https?://.*\.jpg$',
0437307a
RA
456 'timestamp': 1406937606,
457 'upload_date': '20140802',
19c90e40 458 'duration': 940.0,
cb7d4d0e 459 },
460 },
3f125c8c
S
461 {
462 'url': 'http://www.nbcnews.com/watch/dateline/full-episode--deadly-betrayal-386250819952',
463 'only_matching': True,
464 },
5de008e8
YCH
465 {
466 # From http://www.vulture.com/2016/06/letterman-couldnt-care-less-about-late-night.html
467 'url': 'http://www.nbcnews.com/widget/video-embed/701714499682',
468 'only_matching': True,
469 },
87fe568c 470 ]
0bc56fa6
JMF
471
472 def _real_extract(self, url):
a843464a 473 video_id = self._match_id(url)
895e5c03
RA
474 webpage = self._download_webpage(url, video_id)
475
135dfa2c 476 data = self._search_nextjs_data(webpage, video_id)['props']['initialState']
895e5c03
RA
477 video_data = try_get(data, lambda x: x['video']['current'], dict)
478 if not video_data:
479 video_data = data['article']['content'][0]['primaryMedia']['video']
480 title = video_data['headline']['primary']
481
482 formats = []
483 for va in video_data.get('videoAssets', []):
484 public_url = va.get('publicUrl')
485 if not public_url:
486 continue
487 if '://link.theplatform.com/' in public_url:
488 public_url = update_url_query(public_url, {'format': 'redirect'})
489 format_id = va.get('format')
490 if format_id == 'M3U':
491 formats.extend(self._extract_m3u8_formats(
492 public_url, video_id, 'mp4', 'm3u8_native',
493 m3u8_id=format_id, fatal=False))
494 continue
495 tbr = int_or_none(va.get('bitrate'), 1000)
496 if tbr:
497 format_id += '-%d' % tbr
498 formats.append({
499 'format_id': format_id,
500 'url': public_url,
501 'width': int_or_none(va.get('width')),
502 'height': int_or_none(va.get('height')),
503 'tbr': tbr,
504 'ext': 'mp4',
505 })
6e416b21 506
895e5c03
RA
507 subtitles = {}
508 closed_captioning = video_data.get('closedCaptioning')
509 if closed_captioning:
510 for cc_url in closed_captioning.values():
511 if not cc_url:
512 continue
513 subtitles.setdefault('en', []).append({
514 'url': cc_url,
515 })
6e416b21 516
a843464a 517 return {
a843464a 518 'id': video_id,
895e5c03
RA
519 'title': title,
520 'description': try_get(video_data, lambda x: x['description']['primary']),
521 'thumbnail': try_get(video_data, lambda x: x['primaryImage']['url']['primary']),
522 'duration': parse_duration(video_data.get('duration')),
523 'timestamp': unified_timestamp(video_data.get('datePublished')),
524 'formats': formats,
525 'subtitles': subtitles,
a843464a 526 }
be457302
YCH
527
528
529class NBCOlympicsIE(InfoExtractor):
58284890 530 IE_NAME = 'nbcolympics'
3e376d18 531 _VALID_URL = r'https?://www\.nbcolympics\.com/videos?/(?P<id>[0-9a-z-]+)'
be457302
YCH
532
533 _TEST = {
534 # Geo-restricted to US
535 'url': 'http://www.nbcolympics.com/video/justin-roses-son-leo-was-tears-after-his-dad-won-gold',
536 'md5': '54fecf846d05429fbaa18af557ee523a',
537 'info_dict': {
538 'id': 'WjTBzDXx5AUq',
539 'display_id': 'justin-roses-son-leo-was-tears-after-his-dad-won-gold',
540 'ext': 'mp4',
541 'title': 'Rose\'s son Leo was in tears after his dad won gold',
542 'description': 'Olympic gold medalist Justin Rose gets emotional talking to the impact his win in men\'s golf has already had on his children.',
543 'timestamp': 1471274964,
544 'upload_date': '20160815',
545 'uploader': 'NBCU-SPORTS',
546 },
19c90e40 547 'skip': '404 Not Found',
be457302
YCH
548 }
549
550 def _real_extract(self, url):
551 display_id = self._match_id(url)
552
553 webpage = self._download_webpage(url, display_id)
554
3e376d18
W
555 try:
556 drupal_settings = self._parse_json(self._search_regex(
557 r'jQuery\.extend\(Drupal\.settings\s*,\s*({.+?})\);',
558 webpage, 'drupal settings'), display_id)
559
560 iframe_url = drupal_settings['vod']['iframe_url']
561 theplatform_url = iframe_url.replace(
562 'vplayer.nbcolympics.com', 'player.theplatform.com')
563 except RegexNotFoundError:
564 theplatform_url = self._search_regex(
565 r"([\"'])embedUrl\1: *([\"'])(?P<embedUrl>.+)\2",
566 webpage, 'embedding URL', group="embedUrl")
be457302
YCH
567
568 return {
569 '_type': 'url_transparent',
570 'url': theplatform_url,
571 'ie_key': ThePlatformIE.ie_key(),
572 'display_id': display_id,
573 }
58284890
RA
574
575
576class NBCOlympicsStreamIE(AdobePassIE):
577 IE_NAME = 'nbcolympics:stream'
578 _VALID_URL = r'https?://stream\.nbcolympics\.com/(?P<id>[0-9a-z-]+)'
bb36a55c 579 _TESTS = [
580 {
581 'note': 'Tokenized m3u8 source URL',
582 'url': 'https://stream.nbcolympics.com/womens-soccer-group-round-11',
583 'info_dict': {
584 'id': '2019740',
585 'ext': 'mp4',
586 '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}$",
587 },
588 'params': {
589 'skip_download': 'm3u8',
590 },
19c90e40 591 'skip': 'Livestream',
bb36a55c 592 }, {
593 'note': 'Plain m3u8 source URL',
594 'url': 'https://stream.nbcolympics.com/gymnastics-event-finals-mens-floor-pommel-horse-womens-vault-bars',
595 'info_dict': {
596 'id': '2021729',
597 'ext': 'mp4',
598 '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}$',
599 },
600 'params': {
601 'skip_download': 'm3u8',
602 },
19c90e40 603 'skip': 'Livestream',
58284890 604 },
bb36a55c 605 ]
58284890
RA
606
607 def _real_extract(self, url):
608 display_id = self._match_id(url)
609 webpage = self._download_webpage(url, display_id)
610 pid = self._search_regex(r'pid\s*=\s*(\d+);', webpage, 'pid')
bb36a55c 611
58284890 612 event_config = self._download_json(
bb36a55c 613 f'http://stream.nbcolympics.com/data/event_config_{pid}.json',
614 pid, 'Downloading event config')['eventConfig']
615
616 title = event_config['eventTitle']
617 is_live = {'live': True, 'replay': False}.get(event_config.get('eventStatus'))
bb36a55c 618
58284890 619 source_url = self._download_json(
bb36a55c 620 f'https://api-leap.nbcsports.com/feeds/assets/{pid}?application=NBCOlympics&platform=desktop&format=nbc-player&env=staging',
621 pid, 'Downloading leap config'
622 )['videoSources'][0]['cdnSources']['primary'][0]['sourceUrl']
623
624 if event_config.get('cdnToken'):
625 ap_resource = self._get_mvpd_resource(
626 event_config.get('resourceId', 'NBCOlympics'),
627 re.sub(r'[^\w\d ]+', '', event_config['eventTitle']), pid,
628 event_config.get('ratingId', 'NO VALUE'))
629 media_token = self._extract_mvpd_auth(url, pid, event_config.get('requestorId', 'NBCOlympics'), ap_resource)
630
631 source_url = self._download_json(
632 'https://tokens.playmakerservices.com/', pid, 'Retrieving tokenized URL',
633 data=json.dumps({
634 'application': 'NBCSports',
635 'authentication-type': 'adobe-pass',
636 'cdn': 'akamai',
637 'pid': pid,
638 'platform': 'desktop',
639 'requestorId': 'NBCOlympics',
640 'resourceId': base64.b64encode(ap_resource.encode()).decode(),
641 'token': base64.b64encode(media_token.encode()).decode(),
642 'url': source_url,
643 'version': 'v1',
644 }).encode(),
645 )['akamai'][0]['tokenizedUrl']
646
647 formats = self._extract_m3u8_formats(source_url, pid, 'mp4', live=is_live)
648 for f in formats:
649 # -http_seekable requires ffmpeg 4.3+ but it doesnt seem possible to
650 # download with ffmpeg without this option
0a5a191a 651 f['downloader_options'] = {'ffmpeg_args': ['-seekable', '0', '-http_seekable', '0', '-icy', '0']}
58284890
RA
652
653 return {
654 'id': pid,
655 'display_id': display_id,
656 'title': title,
657 'formats': formats,
bb36a55c 658 'is_live': is_live,
58284890 659 }
11398b92 660
661
662class NBCStationsIE(InfoExtractor):
663 _DOMAIN_RE = '|'.join(map(re.escape, (
664 'nbcbayarea', 'nbcboston', 'nbcchicago', 'nbcconnecticut', 'nbcdfw', 'nbclosangeles',
665 'nbcmiami', 'nbcnewyork', 'nbcphiladelphia', 'nbcsandiego', 'nbcwashington',
666 'necn', 'telemundo52', 'telemundoarizona', 'telemundochicago', 'telemundonuevainglaterra',
667 )))
668 _VALID_URL = rf'https?://(?:www\.)?(?P<site>{_DOMAIN_RE})\.com/(?:[^/?#]+/)*(?P<id>[^/?#]+)/?(?:$|[#?])'
669
670 _TESTS = [{
671 'url': 'https://www.nbclosangeles.com/news/local/large-structure-fire-in-downtown-la-prompts-smoke-odor-advisory/2968618/',
11398b92 672 'info_dict': {
673 'id': '2968618',
674 'ext': 'mp4',
675 'title': 'Large Structure Fire in Downtown LA Prompts Smoke Odor Advisory',
cb73b846 676 'description': 'md5:417ed3c2d91fe9d301e6db7b0942f182',
9be0fe1f 677 'duration': 112.513,
11398b92 678 'timestamp': 1661135892,
cb73b846 679 'upload_date': '20220822',
11398b92 680 'uploader': 'NBC 4',
cb73b846 681 'channel_id': 'KNBC',
11398b92 682 'channel': 'nbclosangeles',
683 },
cb73b846 684 'params': {
685 'skip_download': 'm3u8',
686 },
11398b92 687 }, {
688 'url': 'https://www.telemundoarizona.com/responde/huracan-complica-reembolso-para-televidente-de-tucson/2247002/',
11398b92 689 'info_dict': {
690 'id': '2247002',
691 'ext': 'mp4',
cb73b846 692 'title': 'Huracán complica que televidente de Tucson reciba reembolso',
11398b92 693 'description': 'md5:af298dc73aab74d4fca6abfb12acb6cf',
9be0fe1f 694 'duration': 172.406,
11398b92 695 'timestamp': 1660886507,
696 'upload_date': '20220819',
697 'uploader': 'Telemundo Arizona',
cb73b846 698 'channel_id': 'KTAZ',
11398b92 699 'channel': 'telemundoarizona',
700 },
cb73b846 701 'params': {
702 'skip_download': 'm3u8',
703 },
9be0fe1f 704 }, {
705 # direct mp4 link
706 'url': 'https://www.nbcboston.com/weather/video-weather/highs-near-freezing-in-boston-on-wednesday/2961135/',
707 'md5': '9bf8c41dc7abbb75b1a44f1491a4cc85',
708 'info_dict': {
709 'id': '2961135',
710 'ext': 'mp4',
711 'title': 'Highs Near Freezing in Boston on Wednesday',
712 'description': 'md5:3ec486609a926c99f00a3512e6c0e85b',
713 'duration': 235.669,
714 'timestamp': 1675268656,
715 'upload_date': '20230201',
716 'uploader': '',
717 'channel_id': 'WBTS',
718 'channel': 'nbcboston',
719 },
11398b92 720 }]
721
722 _RESOLUTIONS = {
723 '1080': '1920',
724 '720': '1280',
725 '540': '960',
726 '360': '640',
727 '234': '416',
728 }
729
730 def _real_extract(self, url):
731 channel, video_id = self._match_valid_url(url).group('site', 'id')
732 webpage = self._download_webpage(url, video_id)
733
734 nbc_data = self._search_json(
176a068c 735 r'<script>\s*var\s+nbc\s*=', webpage, 'NBC JSON data', video_id)
11398b92 736 pdk_acct = nbc_data.get('pdkAcct') or 'Yh1nAC'
737 fw_ssid = traverse_obj(nbc_data, ('video', 'fwSSID'))
11398b92 738
cb73b846 739 video_data = self._search_json(
740 r'data-videos="\[', webpage, 'video data', video_id, default={}, transform_source=unescapeHTML)
741 video_data.update(self._search_json(
742 r'data-meta="', webpage, 'metadata', video_id, default={}, transform_source=unescapeHTML))
743 if not video_data:
744 raise ExtractorError('No video metadata found in webpage', expected=True)
11398b92 745
9be0fe1f 746 info, formats = {}, []
cb73b846 747 is_live = int_or_none(video_data.get('mpx_is_livestream')) == 1
748 query = {
749 'formats': 'MPEG-DASH none,M3U none,MPEG-DASH none,MPEG4,MP3',
750 'format': 'SMIL',
751 'fwsitesection': fw_ssid,
752 'fwNetworkID': traverse_obj(nbc_data, ('video', 'fwNetworkID'), default='382114'),
753 'pprofile': 'ots_desktop_html',
754 'sensitive': 'false',
755 'w': '1920',
756 'h': '1080',
757 'mode': 'LIVE' if is_live else 'on-demand',
758 'vpaid': 'script',
759 'schema': '2.0',
760 'sdk': 'PDK 6.1.3',
761 }
11398b92 762
cb73b846 763 if is_live:
764 player_id = traverse_obj(video_data, ((None, ('video', 'meta')), (
765 'mpx_m3upid', 'mpx_pid', 'pid_streaming_web_medium')), get_all=False)
766 info['title'] = f'{channel} livestream'
11398b92 767
768 else:
cb73b846 769 player_id = traverse_obj(video_data, (
770 (None, ('video', 'meta')), ('pid_streaming_web_high', 'mpx_pid')), get_all=False)
11398b92 771
772 date_string = traverse_obj(video_data, 'date_string', 'date_gmt')
773 if date_string:
774 date_string = self._search_regex(
775 r'datetime="([^"]+)"', date_string, 'date string', fatal=False)
776 else:
777 date_string = traverse_obj(
cb73b846 778 nbc_data, ('dataLayer', 'adobe', ('prop70', 'eVar70', 'eVar59')), get_all=False)
11398b92 779
cb73b846 780 video_url = traverse_obj(video_data, ((None, ('video', 'meta')), 'mp4_url'), get_all=False)
11398b92 781 if video_url:
9be0fe1f 782 ext = determine_ext(video_url)
cb73b846 783 height = self._search_regex(r'\d+-(\d+)p', url_basename(video_url), 'height', default=None)
11398b92 784 formats.append({
785 'url': video_url,
9be0fe1f 786 'ext': ext,
11398b92 787 'width': int_or_none(self._RESOLUTIONS.get(height)),
788 'height': int_or_none(height),
9be0fe1f 789 'format_id': f'http-{ext}',
11398b92 790 })
791
cb73b846 792 info.update({
793 'title': video_data.get('title') or traverse_obj(nbc_data, (
794 'dataLayer', (None, 'adobe'), ('contenttitle', 'title', 'prop22')), get_all=False),
795 'description':
796 traverse_obj(video_data, 'summary', 'excerpt', 'video_hero_text')
797 or clean_html(traverse_obj(nbc_data, ('dataLayer', 'summary'))),
798 'timestamp': unified_timestamp(date_string),
799 })
11398b92 800
cb73b846 801 smil = None
802 if player_id and fw_ssid:
803 smil = self._download_xml(
804 f'https://link.theplatform.com/s/{pdk_acct}/{player_id}', video_id,
805 note='Downloading SMIL data', query=query, fatal=is_live)
9be0fe1f 806 subtitles = self._parse_smil_subtitles(smil, default_ns) if smil else {}
807 for video in smil.findall(self._xpath_ns('.//video', default_ns)) if smil else []:
808 info['duration'] = float_or_none(remove_end(video.get('dur'), 'ms'), 1000)
809 video_src_url = video.get('src')
810 ext = mimetype2ext(video.get('type'), default=determine_ext(video_src_url))
811 if ext == 'm3u8':
812 fmts, subs = self._extract_m3u8_formats_and_subtitles(
813 video_src_url, video_id, 'mp4', m3u8_id='hls', fatal=is_live,
814 live=is_live, errnote='No HLS formats found')
815 formats.extend(fmts)
816 self._merge_subtitles(subs, target=subtitles)
817 elif video_src_url:
818 formats.append({
819 'url': video_src_url,
820 'format_id': f'https-{ext}',
821 'ext': ext,
822 'width': int_or_none(video.get('width')),
823 'height': int_or_none(video.get('height')),
824 })
cb73b846 825
826 if not formats:
827 self.raise_no_formats('No video content found in webpage', expected=True)
828 elif is_live:
829 try:
830 self._request_webpage(
831 HEADRequest(formats[0]['url']), video_id, note='Checking live status')
832 except ExtractorError:
833 raise UserNotLive(video_id=channel)
11398b92 834
835 return {
cb73b846 836 'id': video_id,
11398b92 837 'channel': channel,
cb73b846 838 'channel_id': nbc_data.get('callLetters'),
839 'uploader': nbc_data.get('on_air_name'),
11398b92 840 'formats': formats,
cb73b846 841 'subtitles': subtitles,
842 'is_live': is_live,
11398b92 843 **info,
844 }