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