6 from .common
import InfoExtractor
7 from ..networking
.exceptions
import HTTPError
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
)
32 for playback
in (feed
.get('playbacks') or []):
33 playback_url
= playback
.get('url')
36 name
= playback
.get('name')
37 ext
= determine_ext(playback_url
)
39 formats
.extend(self
._extract
_m
3u8_formats
(
40 playback_url
, video_id
, 'mp4',
41 'm3u8_native', m3u8_id
=name
, fatal
=False))
47 mobj
= re
.search(r
'_(\d+)K_(\d+)X(\d+)', name
)
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
)
57 'fps': int(mobj
.group(3)),
58 'height': int(mobj
.group(2)),
59 'tbr': int(mobj
.group(4)),
60 'width': int(mobj
.group(1)),
65 for cut
in (try_get(feed
, lambda x
: x
['image']['cuts'], list) or []):
70 'height': int_or_none(cut
.get('height')),
72 'width': int_or_none(cut
.get('width')),
75 language
= (video
.get('language') or 'EN').lower()
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
):
92 (?:[\da-z_-]+\.)*mlb\.com/
95 (?:[^/]+/)*video/[^/]+/c-|
97 shared/video/embed/(?:embed|m-internal-embed)\.html|
98 (?:[^/]+/)+(?:play|index)\.jsp|
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/[^"\']+)',
110 'url
': 'https
://www
.mlb
.com
/mariners
/video
/ackleys
-spectacular
-catch
/c
-34698933',
111 'md5
': '632358dacfceec06bad823b83d21df2d
',
115 'title
': "Ackley's spectacular catch
",
116 'description': 'md5:7f5a981eb4f3cbc8daf2aeffa2215bf0',
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',
129 'title': 'Stanton prepares for Derby',
130 'description': 'md5:d00ce1e5fd9c9069e9c13ab4faedfa57',
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',
143 'title': 'Cespedes repeats as Derby champ',
144 'description': 'md5:08df253ce265d4cf6fb09f581fafad07',
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',
157 'title': 'Bautista on Home Run Derby',
158 'description': 'md5:b80b34031143d0986dddc64a8839f0fb',
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'
194 def _get_feed(video):
198 def _extract_mlb_subtitles(feed, language):
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')
205 subtitles.setdefault(language, []).append({
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',
216 class MLBVideoIE(MLBBaseIE):
217 _VALID_URL = r'https?://(?:www\.)?mlb\.com/(?:[^/]+/)*video/(?P<id>[^/?&#]+)'
219 'url': 'https://www.mlb.com/mariners/video/ackley-s-spectacular-catch-c34698933',
220 'md5': '632358dacfceec06bad823b83d21df2d',
222 'id': 'c04a8863-f569-42e6-9f87-992393657614',
224 'title': "Ackley
's spectacular catch",
225 'description
': 'md5
:7f5a981eb4f3cbc8daf2aeffa2215bf0
',
227 'timestamp
': 1405995000,
228 'upload_date
': '20140722',
229 'thumbnail
': r're
:^https?
://.+',
232 _TIMESTAMP_KEY = 'timestamp
'
235 def suitable(cls, url):
236 return False if MLBIE.suitable(url) else super().suitable(url)
239 def _get_feed(video):
240 return video['feeds
'][0]
243 def _extract_mlb_subtitles(feed, language):
245 for cc_location in (feed.get('closedCaptions
') or []):
246 subtitles.setdefault(language, []).append({
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
',
256 mediaPlayback(ids: "%s") {
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
'
285 'url
': 'https
://www
.mlb
.com
/tv
/g661581
/vee2eff5f
-a7df
-4c20
-bdb4
-7b926fa12638
',
289 'title
': '2022-07-02 - St
. Louis Cardinals
@ Philadelphia Phillies
',
290 'release_date
': '20220702',
291 'release_timestamp
': 1656792300,
293 'params
': {'skip_download
': 'm3u8
'},
295 # makeup game: has multiple dates, need to avoid games with 'rescheduleDate
'
296 'url
': 'https
://www
.mlb
.com
/tv
/g747039
/vd22541c4
-5a29
-45f7
-822b
-635ec041cf5e
',
300 'title
': '2024-07-29 - Toronto Blue Jays
@ Baltimore Orioles
',
301 'release_date
': '20240729',
302 'release_timestamp
': 1722280200,
304 'params
': {'skip_download
': 'm3u8
'},
306 _GRAPHQL_INIT_QUERY = '''\
307 mutation initSession($device: InitSessionInput!, $clientType: ClientType!, $experience: ExperienceTypeInput) {
308 initSession(device: $device, clientType: $clientType, experience: $experience) {
325 _GRAPHQL_PLAYBACK_QUERY = '''\
326 mutation initPlaybackSession(
327 $adCapabilities: [AdExperienceType]
331 $quality: PlaybackQuality
334 adCapabilities: $adCapabilities
337 sessionId: $sessionId
349 _APP_VERSION = '7.8.2'
356 def _api_headers(self):
357 if (self._token_expiry - 120) <= time.time():
358 self.write_debug('Access token has expired
; re
-logging
in')
359 self._perform_login(*self._get_login_info())
360 return {'Authorization
': f'Bearer
{self
._access
_token
}'}
362 def _real_initialize(self):
363 if not self._access_token:
364 self.raise_login_required(
365 'All videos are only available to registered users
', method='password
')
367 def _set_device_id(self, username):
368 if not self._device_id:
369 self._device_id = self.cache.load(
370 self._NETRC_MACHINE, 'device_ids
', default={}).get(username)
373 self._device_id = str(uuid.uuid4())
374 self.cache.store(self._NETRC_MACHINE, 'device_ids
', {username: self._device_id})
376 def _perform_login(self, username, password):
378 self._access_token = self._download_json(
379 'https
://ids
.mlb
.com
/oauth2
/aus1m088yK07noBfh356
/v1
/token
', None,
380 'Logging
in', 'Unable to log
in', headers={
381 'User
-Agent
': 'okhttp
/3.12.1',
382 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
383 }, data=urlencode_postdata({
384 'grant_type
': 'password
',
385 'username
': username,
386 'password
': password,
387 'scope
': 'openid offline_access
',
388 'client_id
': '0oa3e1nutA
1HLzAKG
356',
390 except ExtractorError as error:
391 if isinstance(error.cause, HTTPError) and error.cause.status == 400:
392 raise ExtractorError('Invalid username
or password
', expected=True)
395 self._token_expiry = traverse_obj(self._access_token, ({jwt_decode_hs256}, 'exp
', {int})) or 0
396 self._set_device_id(username)
398 self._session_id = self._call_api({
399 'operationName
': 'initSession
',
400 'query
': self._GRAPHQL_INIT_QUERY,
403 'appVersion
': self._APP_VERSION,
404 'deviceFamily
': 'desktop
',
405 'knownDeviceId
': self._device_id,
406 'languagePreference
': 'ENGLISH
',
414 }, None, 'session ID
')['data
']['initSession
']['sessionId
']
416 def _call_api(self, data, video_id, description='GraphQL JSON
', fatal=True):
417 return self._download_json(
418 'https
://media
-gateway
.mlb
.com
/graphql
', video_id,
419 f'Downloading {description}
', f'Unable to download {description}
', fatal=fatal,
422 'Accept
': 'application
/json
',
423 'Content
-Type
': 'application
/json
',
424 'x
-client
-name
': 'WEB
',
425 'x
-client
-version
': self._APP_VERSION,
426 }, data=json.dumps(data, separators=(',', ':')).encode())
428 def _extract_formats_and_subtitles(self, broadcast, video_id):
429 feed = traverse_obj(broadcast, ('homeAway
', {str.title}))
430 medium = traverse_obj(broadcast, ('type', {str}))
431 language = traverse_obj(broadcast, ('language
', {str.lower}))
432 format_id = join_nonempty(feed, medium, language)
434 response = self._call_api({
435 'operationName
': 'initPlaybackSession
',
436 'query
': self._GRAPHQL_PLAYBACK_QUERY,
438 'adCapabilities
': ['GOOGLE_STANDALONE_AD_PODS
'],
439 'deviceId
': self._device_id,
440 'mediaId
': broadcast['mediaId
'],
441 'quality
': 'PLACEHOLDER
',
442 'sessionId
': self._session_id,
444 }, video_id, f'{format_id} broadcast JSON
', fatal=False)
446 playback = traverse_obj(response, ('data
', 'initPlaybackSession
', 'playback
', {dict}))
447 m3u8_url = traverse_obj(playback, ('url
', {url_or_none}))
448 token = traverse_obj(playback, ('token
', {str}))
450 if not (m3u8_url and token):
451 errors = '; '.join(traverse_obj(response, ('errors
', ..., 'message
', {str})))
452 if 'not entitled
' in errors:
453 raise ExtractorError(errors, expected=True)
454 elif errors: # Only warn when 'blacked out
' since radio formats are available
455 self.report_warning(f'API returned errors
for {format_id}
: {errors}
')
457 self.report_warning(f'No formats available
for {format_id} broadcast
; skipping
')
460 cdn_headers = {'x
-cdn
-token
': token}
461 fmts, subs = self._extract_m3u8_formats_and_subtitles(
462 m3u8_url.replace(f'/{token}
/', '/'), video_id, 'mp4
',
463 m3u8_id=format_id, fatal=False, headers=cdn_headers)
465 fmt['http_headers
'] = cdn_headers
466 fmt.setdefault('format_note
', join_nonempty(feed, medium, delim=' '))
467 fmt.setdefault('language
', language)
468 if fmt.get('vcodec
') == 'none
' and fmt['language
'] == 'en
':
469 fmt['source_preference
'] = 10
473 def _real_extract(self, url):
474 video_id = self._match_id(url)
475 data = self._download_json(
476 'https
://statsapi
.mlb
.com
/api
/v1
/schedule
', video_id, query={
478 'hydrate
': 'broadcasts(all
),statusFlags
',
480 metadata = traverse_obj(data, (
481 'dates
', ..., 'games
',
482 lambda _, v: str(v['gamePk
']) == video_id and not v.get('rescheduleDate
'), any))
484 broadcasts = traverse_obj(metadata, (
485 'broadcasts
', lambda _, v: v['mediaId
'] and v['mediaState
']['mediaStateCode
'] != 'MEDIA_OFF
'))
487 formats, subtitles = [], {}
488 for broadcast in broadcasts:
489 fmts, subs = self._extract_formats_and_subtitles(broadcast, video_id)
491 self._merge_subtitles(subs, target=subtitles)
495 'title
': join_nonempty(
496 traverse_obj(metadata, ('officialDate
', {str})),
497 traverse_obj(metadata, ('teams
', ('away
', 'home
'), 'team
', 'name
', {str}, all, {' @ '.join})),
499 'is_live
': traverse_obj(broadcasts, (..., 'mediaState
', 'mediaStateCode
', {str}, any)) == 'MEDIA_ON
',
500 'release_timestamp
': traverse_obj(metadata, ('gameDate
', {parse_iso8601})),
502 'subtitles
': subtitles,
506 class MLBArticleIE(InfoExtractor):
507 _VALID_URL = r'https?
://www\
.mlb\
.com
/news
/(?P
<id>[\w
-]+)'
509 'url
': 'https
://www
.mlb
.com
/news
/manny
-machado
-robs
-guillermo
-heredia
-reacts
',
511 'id': '36db7394
-343c
-4ea3
-b8ca
-ead2e61bca9a
',
512 'title
': 'Machado
\'s grab draws hilarious irate reaction
',
513 'modified_timestamp
': 1675888370,
514 'description
': 'md5
:a19d4eb0487b2cb304e9a176f6b67676
',
515 'modified_date
': '20230208',
517 'playlist_mincount
': 2,
520 def _real_extract(self, url):
521 display_id = self._match_id(url)
522 webpage = self._download_webpage(url, display_id)
523 apollo_cache_json = self._search_json(r'window\
.initState\s
*=', webpage, 'window
.initState
', display_id)['apolloCache
']
525 content_real_info = traverse_obj(
526 apollo_cache_json, ('ROOT_QUERY
', lambda k, _: k.startswith('getArticle
')), get_all=False)
528 return self.playlist_from_matches(
529 traverse_obj(content_real_info, ('parts
', lambda _, v: v['__typename
'] == 'Video
' or v['type'] == 'video
')),
530 getter=lambda x: f'https
://www
.mlb
.com
/video
/{x
["slug"]}',
531 ie=MLBVideoIE, playlist_id=content_real_info.get('translationId
'),
532 title=self._html_search_meta('og
:title
', webpage),
533 description=content_real_info.get('summary
'),
534 modified_timestamp=parse_iso8601(content_real_info.get('lastUpdatedDate
')))