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