[ie/mlbtv] Fix extractor (#10515)
[yt-dlp.git] / yt_dlp / extractor / mlb.py
blob230c218e7225f7063dc2b2dd741b4e1e5040d572
1 import json
2 import re
3 import time
4 import uuid
6 from .common import InfoExtractor
7 from ..networking.exceptions import HTTPError
8 from ..utils import (
9 ExtractorError,
10 determine_ext,
11 int_or_none,
12 join_nonempty,
13 jwt_decode_hs256,
14 parse_duration,
15 parse_iso8601,
16 try_get,
17 url_or_none,
18 urlencode_postdata,
20 from ..utils.traversal import traverse_obj
23 class MLBBaseIE(InfoExtractor):
24 def _real_extract(self, url):
25 display_id = self._match_id(url)
26 video = self._download_video_data(display_id)
27 video_id = video['id']
28 title = video['title']
29 feed = self._get_feed(video)
31 formats = []
32 for playback in (feed.get('playbacks') or []):
33 playback_url = playback.get('url')
34 if not playback_url:
35 continue
36 name = playback.get('name')
37 ext = determine_ext(playback_url)
38 if ext == 'm3u8':
39 formats.extend(self._extract_m3u8_formats(
40 playback_url, video_id, 'mp4',
41 'm3u8_native', m3u8_id=name, fatal=False))
42 else:
43 f = {
44 'format_id': name,
45 'url': playback_url,
47 mobj = re.search(r'_(\d+)K_(\d+)X(\d+)', name)
48 if mobj:
49 f.update({
50 'height': int(mobj.group(3)),
51 'tbr': int(mobj.group(1)),
52 'width': int(mobj.group(2)),
54 mobj = re.search(r'_(\d+)x(\d+)_(\d+)_(\d+)K\.mp4', playback_url)
55 if mobj:
56 f.update({
57 'fps': int(mobj.group(3)),
58 'height': int(mobj.group(2)),
59 'tbr': int(mobj.group(4)),
60 'width': int(mobj.group(1)),
62 formats.append(f)
64 thumbnails = []
65 for cut in (try_get(feed, lambda x: x['image']['cuts'], list) or []):
66 src = cut.get('src')
67 if not src:
68 continue
69 thumbnails.append({
70 'height': int_or_none(cut.get('height')),
71 'url': src,
72 'width': int_or_none(cut.get('width')),
75 language = (video.get('language') or 'EN').lower()
77 return {
78 'id': video_id,
79 'title': title,
80 'formats': formats,
81 'description': video.get('description'),
82 'duration': parse_duration(feed.get('duration')),
83 'thumbnails': thumbnails,
84 'timestamp': parse_iso8601(video.get(self._TIMESTAMP_KEY)),
85 'subtitles': self._extract_mlb_subtitles(feed, language),
89 class MLBIE(MLBBaseIE):
90 _VALID_URL = r'''(?x)
91 https?://
92 (?:[\da-z_-]+\.)*mlb\.com/
93 (?:
94 (?:
95 (?:[^/]+/)*video/[^/]+/c-|
96 (?:
97 shared/video/embed/(?:embed|m-internal-embed)\.html|
98 (?:[^/]+/)+(?:play|index)\.jsp|
99 )\?.*?\bcontent_id=
101 (?P<id>\d+)
104 _EMBED_REGEX = [
105 r'<iframe[^>]+?src=(["\'])(?P<url>https?://m(?:lb)?\.mlb\.com/shared/video/embed/embed\.html\?.+?)\1',
106 r'data-video-link=["\'](?P<url>http://m\.mlb\.com/video/[^"\']+)',
108 _TESTS = [
110 'url': 'https://www.mlb.com/mariners/video/ackleys-spectacular-catch/c-34698933',
111 'md5': '632358dacfceec06bad823b83d21df2d',
112 'info_dict': {
113 'id': '34698933',
114 'ext': 'mp4',
115 'title': "Ackley's spectacular catch",
116 'description': 'md5:7f5a981eb4f3cbc8daf2aeffa2215bf0',
117 'duration': 66,
118 'timestamp': 1405995000,
119 'upload_date': '20140722',
120 'thumbnail': r're:^https?://.*\.jpg$',
124 'url': 'https://www.mlb.com/video/stanton-prepares-for-derby/c-34496663',
125 'md5': 'bf2619bf9cacc0a564fc35e6aeb9219f',
126 'info_dict': {
127 'id': '34496663',
128 'ext': 'mp4',
129 'title': 'Stanton prepares for Derby',
130 'description': 'md5:d00ce1e5fd9c9069e9c13ab4faedfa57',
131 'duration': 46,
132 'timestamp': 1405120200,
133 'upload_date': '20140711',
134 'thumbnail': r're:^https?://.*\.jpg$',
138 'url': 'https://www.mlb.com/video/cespedes-repeats-as-derby-champ/c-34578115',
139 'md5': '99bb9176531adc600b90880fb8be9328',
140 'info_dict': {
141 'id': '34578115',
142 'ext': 'mp4',
143 'title': 'Cespedes repeats as Derby champ',
144 'description': 'md5:08df253ce265d4cf6fb09f581fafad07',
145 'duration': 488,
146 'timestamp': 1405414336,
147 'upload_date': '20140715',
148 'thumbnail': r're:^https?://.*\.jpg$',
152 'url': 'https://www.mlb.com/video/bautista-on-home-run-derby/c-34577915',
153 'md5': 'da8b57a12b060e7663ee1eebd6f330ec',
154 'info_dict': {
155 'id': '34577915',
156 'ext': 'mp4',
157 'title': 'Bautista on Home Run Derby',
158 'description': 'md5:b80b34031143d0986dddc64a8839f0fb',
159 'duration': 52,
160 'timestamp': 1405405122,
161 'upload_date': '20140715',
162 'thumbnail': r're:^https?://.*\.jpg$',
166 'url': 'https://www.mlb.com/video/hargrove-homers-off-caldwell/c-1352023483?tid=67793694',
167 'only_matching': True,
170 'url': 'http://m.mlb.com/shared/video/embed/embed.html?content_id=35692085&topic_id=6479266&width=400&height=224&property=mlb',
171 'only_matching': True,
174 'url': 'http://mlb.mlb.com/shared/video/embed/embed.html?content_id=36599553',
175 'only_matching': True,
178 'url': 'http://mlb.mlb.com/es/video/play.jsp?content_id=36599553',
179 'only_matching': True,
182 'url': 'https://www.mlb.com/cardinals/video/piscottys-great-sliding-catch/c-51175783',
183 'only_matching': True,
186 # From http://m.mlb.com/news/article/118550098/blue-jays-kevin-pillar-goes-spidey-up-the-wall-to-rob-tim-beckham-of-a-homer
187 'url': 'http://mlb.mlb.com/shared/video/embed/m-internal-embed.html?content_id=75609783&property=mlb&autoplay=true&hashmode=false&siteSection=mlb/multimedia/article_118550098/article_embed&club=mlb',
188 'only_matching': True,
191 _TIMESTAMP_KEY = 'date'
193 @staticmethod
194 def _get_feed(video):
195 return video
197 @staticmethod
198 def _extract_mlb_subtitles(feed, language):
199 subtitles = {}
200 for keyword in (feed.get('keywordsAll') or []):
201 keyword_type = keyword.get('type')
202 if keyword_type and keyword_type.startswith('closed_captions_location_'):
203 cc_location = keyword.get('value')
204 if cc_location:
205 subtitles.setdefault(language, []).append({
206 'url': cc_location,
208 return subtitles
210 def _download_video_data(self, display_id):
211 return self._download_json(
212 f'http://content.mlb.com/mlb/item/id/v1/{display_id}/details/web-v1.json',
213 display_id)
216 class MLBVideoIE(MLBBaseIE):
217 _VALID_URL = r'https?://(?:www\.)?mlb\.com/(?:[^/]+/)*video/(?P<id>[^/?&#]+)'
218 _TEST = {
219 'url': 'https://www.mlb.com/mariners/video/ackley-s-spectacular-catch-c34698933',
220 'md5': '632358dacfceec06bad823b83d21df2d',
221 'info_dict': {
222 'id': 'c04a8863-f569-42e6-9f87-992393657614',
223 'ext': 'mp4',
224 'title': "Ackley's spectacular catch",
225 'description': 'md5:7f5a981eb4f3cbc8daf2aeffa2215bf0',
226 'duration': 66,
227 'timestamp': 1405995000,
228 'upload_date': '20140722',
229 'thumbnail': r're:^https?://.+',
232 _TIMESTAMP_KEY = 'timestamp'
234 @classmethod
235 def suitable(cls, url):
236 return False if MLBIE.suitable(url) else super().suitable(url)
238 @staticmethod
239 def _get_feed(video):
240 return video['feeds'][0]
242 @staticmethod
243 def _extract_mlb_subtitles(feed, language):
244 subtitles = {}
245 for cc_location in (feed.get('closedCaptions') or []):
246 subtitles.setdefault(language, []).append({
247 'url': cc_location,
250 def _download_video_data(self, display_id):
251 # https://www.mlb.com/data-service/en/videos/[SLUG]
252 return self._download_json(
253 'https://fastball-gateway.mlb.com/graphql',
254 display_id, query={
255 'query': '''{
256 mediaPlayback(ids: "%s") {
257 description
258 feeds(types: CMS) {
259 closedCaptions
260 duration
261 image {
262 cuts {
263 width
264 height
268 playbacks {
269 name
274 timestamp
275 title
277 }''' % display_id, # noqa: UP031
278 })['data']['mediaPlayback'][0]
281 class MLBTVIE(InfoExtractor):
282 _VALID_URL = r'https?://(?:www\.)?mlb\.com/tv/g(?P<id>\d{6})'
283 _NETRC_MACHINE = 'mlb'
284 _TESTS = [{
285 'url': 'https://www.mlb.com/tv/g661581/vee2eff5f-a7df-4c20-bdb4-7b926fa12638',
286 'info_dict': {
287 'id': '661581',
288 'ext': 'mp4',
289 'title': '2022-07-02 - St. Louis Cardinals @ Philadelphia Phillies',
290 'release_date': '20220702',
291 'release_timestamp': 1656792300,
293 'params': {
294 'skip_download': True,
297 _GRAPHQL_INIT_QUERY = '''\
298 mutation initSession($device: InitSessionInput!, $clientType: ClientType!, $experience: ExperienceTypeInput) {
299 initSession(device: $device, clientType: $clientType, experience: $experience) {
300 deviceId
301 sessionId
302 entitlements {
303 code
305 location {
306 countryCode
307 regionName
308 zipCode
309 latitude
310 longitude
312 clientExperience
313 features
315 }'''
316 _GRAPHQL_PLAYBACK_QUERY = '''\
317 mutation initPlaybackSession(
318 $adCapabilities: [AdExperienceType]
319 $mediaId: String!
320 $deviceId: String!
321 $sessionId: String!
322 $quality: PlaybackQuality
324 initPlaybackSession(
325 adCapabilities: $adCapabilities
326 mediaId: $mediaId
327 deviceId: $deviceId
328 sessionId: $sessionId
329 quality: $quality
331 playbackSessionId
332 playback {
334 token
335 expiration
339 }'''
340 _APP_VERSION = '7.8.2'
341 _device_id = None
342 _session_id = None
343 _access_token = None
344 _token_expiry = 0
346 @property
347 def _api_headers(self):
348 if (self._token_expiry - 120) <= time.time():
349 self.write_debug('Access token has expired; re-logging in')
350 self._perform_login(*self._get_login_info())
351 return {'Authorization': f'Bearer {self._access_token}'}
353 def _real_initialize(self):
354 if not self._access_token:
355 self.raise_login_required(
356 'All videos are only available to registered users', method='password')
358 def _set_device_id(self, username):
359 if not self._device_id:
360 self._device_id = self.cache.load(
361 self._NETRC_MACHINE, 'device_ids', default={}).get(username)
362 if self._device_id:
363 return
364 self._device_id = str(uuid.uuid4())
365 self.cache.store(self._NETRC_MACHINE, 'device_ids', {username: self._device_id})
367 def _perform_login(self, username, password):
368 try:
369 self._access_token = self._download_json(
370 'https://ids.mlb.com/oauth2/aus1m088yK07noBfh356/v1/token', None,
371 'Logging in', 'Unable to log in', headers={
372 'User-Agent': 'okhttp/3.12.1',
373 'Content-Type': 'application/x-www-form-urlencoded',
374 }, data=urlencode_postdata({
375 'grant_type': 'password',
376 'username': username,
377 'password': password,
378 'scope': 'openid offline_access',
379 'client_id': '0oa3e1nutA1HLzAKG356',
380 }))['access_token']
381 except ExtractorError as error:
382 if isinstance(error.cause, HTTPError) and error.cause.status == 400:
383 raise ExtractorError('Invalid username or password', expected=True)
384 raise
386 self._token_expiry = traverse_obj(self._access_token, ({jwt_decode_hs256}, 'exp', {int})) or 0
387 self._set_device_id(username)
389 self._session_id = self._call_api({
390 'operationName': 'initSession',
391 'query': self._GRAPHQL_INIT_QUERY,
392 'variables': {
393 'device': {
394 'appVersion': self._APP_VERSION,
395 'deviceFamily': 'desktop',
396 'knownDeviceId': self._device_id,
397 'languagePreference': 'ENGLISH',
398 'manufacturer': '',
399 'model': '',
400 'os': '',
401 'osVersion': '',
403 'clientType': 'WEB',
405 }, None, 'session ID')['data']['initSession']['sessionId']
407 def _call_api(self, data, video_id, description='GraphQL JSON', fatal=True):
408 return self._download_json(
409 'https://media-gateway.mlb.com/graphql', video_id,
410 f'Downloading {description}', f'Unable to download {description}', fatal=fatal,
411 headers={
412 **self._api_headers,
413 'Accept': 'application/json',
414 'Content-Type': 'application/json',
415 'x-client-name': 'WEB',
416 'x-client-version': self._APP_VERSION,
417 }, data=json.dumps(data, separators=(',', ':')).encode())
419 def _extract_formats_and_subtitles(self, broadcast, video_id):
420 feed = traverse_obj(broadcast, ('homeAway', {str.title}))
421 medium = traverse_obj(broadcast, ('type', {str}))
422 language = traverse_obj(broadcast, ('language', {str.lower}))
423 format_id = join_nonempty(feed, medium, language)
425 response = self._call_api({
426 'operationName': 'initPlaybackSession',
427 'query': self._GRAPHQL_PLAYBACK_QUERY,
428 'variables': {
429 'adCapabilities': ['GOOGLE_STANDALONE_AD_PODS'],
430 'deviceId': self._device_id,
431 'mediaId': broadcast['mediaId'],
432 'quality': 'PLACEHOLDER',
433 'sessionId': self._session_id,
435 }, video_id, f'{format_id} broadcast JSON', fatal=False)
437 playback = traverse_obj(response, ('data', 'initPlaybackSession', 'playback', {dict}))
438 m3u8_url = traverse_obj(playback, ('url', {url_or_none}))
439 token = traverse_obj(playback, ('token', {str}))
441 if not (m3u8_url and token):
442 errors = '; '.join(traverse_obj(response, ('errors', ..., 'message', {str})))
443 if 'not entitled' in errors:
444 raise ExtractorError(errors, expected=True)
445 elif errors: # Only warn when 'blacked out' since radio formats are available
446 self.report_warning(f'API returned errors for {format_id}: {errors}')
447 else:
448 self.report_warning(f'No formats available for {format_id} broadcast; skipping')
449 return [], {}
451 cdn_headers = {'x-cdn-token': token}
452 fmts, subs = self._extract_m3u8_formats_and_subtitles(
453 m3u8_url.replace(f'/{token}/', '/'), video_id, 'mp4',
454 m3u8_id=format_id, fatal=False, headers=cdn_headers)
455 for fmt in fmts:
456 fmt['http_headers'] = cdn_headers
457 fmt.setdefault('format_note', join_nonempty(feed, medium, delim=' '))
458 fmt.setdefault('language', language)
459 if fmt.get('vcodec') == 'none' and fmt['language'] == 'en':
460 fmt['source_preference'] = 10
462 return fmts, subs
464 def _real_extract(self, url):
465 video_id = self._match_id(url)
466 metadata = traverse_obj(self._download_json(
467 'https://statsapi.mlb.com/api/v1/schedule', video_id, query={
468 'gamePk': video_id,
469 'hydrate': 'broadcasts(all),statusFlags',
470 }), ('dates', ..., 'games', lambda _, v: str(v['gamePk']) == video_id and v['broadcasts'], any))
472 broadcasts = traverse_obj(metadata, (
473 'broadcasts', lambda _, v: v['mediaId'] and v['mediaState']['mediaStateCode'] != 'MEDIA_OFF'))
475 formats, subtitles = [], {}
476 for broadcast in broadcasts:
477 fmts, subs = self._extract_formats_and_subtitles(broadcast, video_id)
478 formats.extend(fmts)
479 self._merge_subtitles(subs, target=subtitles)
481 return {
482 'id': video_id,
483 'title': join_nonempty(
484 traverse_obj(metadata, ('officialDate', {str})),
485 traverse_obj(metadata, ('teams', ('away', 'home'), 'team', 'name', {str}, all, {' @ '.join})),
486 delim=' - '),
487 'is_live': traverse_obj(broadcasts, (..., 'mediaState', 'mediaStateCode', {str}, any)) == 'MEDIA_ON',
488 'release_timestamp': traverse_obj(metadata, ('gameDate', {parse_iso8601})),
489 'formats': formats,
490 'subtitles': subtitles,
494 class MLBArticleIE(InfoExtractor):
495 _VALID_URL = r'https?://www\.mlb\.com/news/(?P<id>[\w-]+)'
496 _TESTS = [{
497 'url': 'https://www.mlb.com/news/manny-machado-robs-guillermo-heredia-reacts',
498 'info_dict': {
499 'id': '36db7394-343c-4ea3-b8ca-ead2e61bca9a',
500 'title': 'Machado\'s grab draws hilarious irate reaction',
501 'modified_timestamp': 1675888370,
502 'description': 'md5:a19d4eb0487b2cb304e9a176f6b67676',
503 'modified_date': '20230208',
505 'playlist_mincount': 2,
508 def _real_extract(self, url):
509 display_id = self._match_id(url)
510 webpage = self._download_webpage(url, display_id)
511 apollo_cache_json = self._search_json(r'window\.initState\s*=', webpage, 'window.initState', display_id)['apolloCache']
513 content_real_info = traverse_obj(
514 apollo_cache_json, ('ROOT_QUERY', lambda k, _: k.startswith('getArticle')), get_all=False)
516 return self.playlist_from_matches(
517 traverse_obj(content_real_info, ('parts', lambda _, v: v['__typename'] == 'Video' or v['type'] == 'video')),
518 getter=lambda x: f'https://www.mlb.com/video/{x["slug"]}',
519 ie=MLBVideoIE, playlist_id=content_real_info.get('translationId'),
520 title=self._html_search_meta('og:title', webpage),
521 description=content_real_info.get('summary'),
522 modified_timestamp=parse_iso8601(content_real_info.get('lastUpdatedDate')))