[ie/wistia] Support password-protected videos (#11100)
[yt-dlp3.git] / yt_dlp / extractor / mlb.py
blob935bf85615e97d4f509d3eabcd1dc73c47b9736a
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': {'skip_download': 'm3u8'},
294 }, {
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',
297 'info_dict': {
298 'id': '747039',
299 'ext': 'mp4',
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) {
309 deviceId
310 sessionId
311 entitlements {
312 code
314 location {
315 countryCode
316 regionName
317 zipCode
318 latitude
319 longitude
321 clientExperience
322 features
324 }'''
325 _GRAPHQL_PLAYBACK_QUERY = '''\
326 mutation initPlaybackSession(
327 $adCapabilities: [AdExperienceType]
328 $mediaId: String!
329 $deviceId: String!
330 $sessionId: String!
331 $quality: PlaybackQuality
333 initPlaybackSession(
334 adCapabilities: $adCapabilities
335 mediaId: $mediaId
336 deviceId: $deviceId
337 sessionId: $sessionId
338 quality: $quality
340 playbackSessionId
341 playback {
343 token
344 expiration
348 }'''
349 _APP_VERSION = '7.8.2'
350 _device_id = None
351 _session_id = None
352 _access_token = None
353 _token_expiry = 0
355 @property
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)
371 if self._device_id:
372 return
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):
377 try:
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': '0oa3e1nutA1HLzAKG356',
389 }))['access_token']
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)
393 raise
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,
401 'variables': {
402 'device': {
403 'appVersion': self._APP_VERSION,
404 'deviceFamily': 'desktop',
405 'knownDeviceId': self._device_id,
406 'languagePreference': 'ENGLISH',
407 'manufacturer': '',
408 'model': '',
409 'os': '',
410 'osVersion': '',
412 'clientType': 'WEB',
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,
420 headers={
421 **self._api_headers,
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,
437 'variables': {
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}')
456 else:
457 self.report_warning(f'No formats available for {format_id} broadcast; skipping')
458 return [], {}
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)
464 for fmt in fmts:
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
471 return fmts, subs
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={
477 'gamePk': video_id,
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)
490 formats.extend(fmts)
491 self._merge_subtitles(subs, target=subtitles)
493 return {
494 'id': video_id,
495 'title': join_nonempty(
496 traverse_obj(metadata, ('officialDate', {str})),
497 traverse_obj(metadata, ('teams', ('away', 'home'), 'team', 'name', {str}, all, {' @ '.join})),
498 delim=' - '),
499 'is_live': traverse_obj(broadcasts, (..., 'mediaState', 'mediaStateCode', {str}, any)) == 'MEDIA_ON',
500 'release_timestamp': traverse_obj(metadata, ('gameDate', {parse_iso8601})),
501 'formats': formats,
502 'subtitles': subtitles,
506 class MLBArticleIE(InfoExtractor):
507 _VALID_URL = r'https?://www\.mlb\.com/news/(?P<id>[\w-]+)'
508 _TESTS = [{
509 'url': 'https://www.mlb.com/news/manny-machado-robs-guillermo-heredia-reacts',
510 'info_dict': {
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')))