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,
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) {
316 _GRAPHQL_PLAYBACK_QUERY = '''\
317 mutation initPlaybackSession(
318 $adCapabilities: [AdExperienceType]
322 $quality: PlaybackQuality
325 adCapabilities: $adCapabilities
328 sessionId: $sessionId
340 _APP_VERSION = '7.8.2'
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)
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):
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
': '0oa3e1nutA
1HLzAKG
356',
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)
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,
394 'appVersion
': self._APP_VERSION,
395 'deviceFamily
': 'desktop
',
396 'knownDeviceId
': self._device_id,
397 'languagePreference
': 'ENGLISH
',
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,
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,
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}
')
448 self.report_warning(f'No formats available
for {format_id} broadcast
; skipping
')
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)
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
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={
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)
479 self._merge_subtitles(subs, target=subtitles)
483 'title
': join_nonempty(
484 traverse_obj(metadata, ('officialDate
', {str})),
485 traverse_obj(metadata, ('teams
', ('away
', 'home
'), 'team
', 'name
', {str}, all, {' @ '.join})),
487 'is_live
': traverse_obj(broadcasts, (..., 'mediaState
', 'mediaStateCode
', {str}, any)) == 'MEDIA_ON
',
488 'release_timestamp
': traverse_obj(metadata, ('gameDate
', {parse_iso8601})),
490 'subtitles
': subtitles,
494 class MLBArticleIE(InfoExtractor):
495 _VALID_URL = r'https?
://www\
.mlb\
.com
/news
/(?P
<id>[\w
-]+)'
497 'url
': 'https
://www
.mlb
.com
/news
/manny
-machado
-robs
-guillermo
-heredia
-reacts
',
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
')))