[ie/dplay] Fix extractors (#10471)
[yt-dlp3.git] / yt_dlp / extractor / mlb.py
blob6f67602a696c3737dcba89ab3241a70959059bcb
1 import re
2 import urllib.parse
3 import uuid
5 from .common import InfoExtractor
6 from ..utils import (
7 determine_ext,
8 int_or_none,
9 join_nonempty,
10 parse_duration,
11 parse_iso8601,
12 try_get,
13 url_or_none,
15 from ..utils.traversal import traverse_obj
18 class MLBBaseIE(InfoExtractor):
19 def _real_extract(self, url):
20 display_id = self._match_id(url)
21 video = self._download_video_data(display_id)
22 video_id = video['id']
23 title = video['title']
24 feed = self._get_feed(video)
26 formats = []
27 for playback in (feed.get('playbacks') or []):
28 playback_url = playback.get('url')
29 if not playback_url:
30 continue
31 name = playback.get('name')
32 ext = determine_ext(playback_url)
33 if ext == 'm3u8':
34 formats.extend(self._extract_m3u8_formats(
35 playback_url, video_id, 'mp4',
36 'm3u8_native', m3u8_id=name, fatal=False))
37 else:
38 f = {
39 'format_id': name,
40 'url': playback_url,
42 mobj = re.search(r'_(\d+)K_(\d+)X(\d+)', name)
43 if mobj:
44 f.update({
45 'height': int(mobj.group(3)),
46 'tbr': int(mobj.group(1)),
47 'width': int(mobj.group(2)),
49 mobj = re.search(r'_(\d+)x(\d+)_(\d+)_(\d+)K\.mp4', playback_url)
50 if mobj:
51 f.update({
52 'fps': int(mobj.group(3)),
53 'height': int(mobj.group(2)),
54 'tbr': int(mobj.group(4)),
55 'width': int(mobj.group(1)),
57 formats.append(f)
59 thumbnails = []
60 for cut in (try_get(feed, lambda x: x['image']['cuts'], list) or []):
61 src = cut.get('src')
62 if not src:
63 continue
64 thumbnails.append({
65 'height': int_or_none(cut.get('height')),
66 'url': src,
67 'width': int_or_none(cut.get('width')),
70 language = (video.get('language') or 'EN').lower()
72 return {
73 'id': video_id,
74 'title': title,
75 'formats': formats,
76 'description': video.get('description'),
77 'duration': parse_duration(feed.get('duration')),
78 'thumbnails': thumbnails,
79 'timestamp': parse_iso8601(video.get(self._TIMESTAMP_KEY)),
80 'subtitles': self._extract_mlb_subtitles(feed, language),
84 class MLBIE(MLBBaseIE):
85 _VALID_URL = r'''(?x)
86 https?://
87 (?:[\da-z_-]+\.)*mlb\.com/
88 (?:
89 (?:
90 (?:[^/]+/)*video/[^/]+/c-|
91 (?:
92 shared/video/embed/(?:embed|m-internal-embed)\.html|
93 (?:[^/]+/)+(?:play|index)\.jsp|
94 )\?.*?\bcontent_id=
96 (?P<id>\d+)
98 '''
99 _EMBED_REGEX = [
100 r'<iframe[^>]+?src=(["\'])(?P<url>https?://m(?:lb)?\.mlb\.com/shared/video/embed/embed\.html\?.+?)\1',
101 r'data-video-link=["\'](?P<url>http://m\.mlb\.com/video/[^"\']+)',
103 _TESTS = [
105 'url': 'https://www.mlb.com/mariners/video/ackleys-spectacular-catch/c-34698933',
106 'md5': '632358dacfceec06bad823b83d21df2d',
107 'info_dict': {
108 'id': '34698933',
109 'ext': 'mp4',
110 'title': "Ackley's spectacular catch",
111 'description': 'md5:7f5a981eb4f3cbc8daf2aeffa2215bf0',
112 'duration': 66,
113 'timestamp': 1405995000,
114 'upload_date': '20140722',
115 'thumbnail': r're:^https?://.*\.jpg$',
119 'url': 'https://www.mlb.com/video/stanton-prepares-for-derby/c-34496663',
120 'md5': 'bf2619bf9cacc0a564fc35e6aeb9219f',
121 'info_dict': {
122 'id': '34496663',
123 'ext': 'mp4',
124 'title': 'Stanton prepares for Derby',
125 'description': 'md5:d00ce1e5fd9c9069e9c13ab4faedfa57',
126 'duration': 46,
127 'timestamp': 1405120200,
128 'upload_date': '20140711',
129 'thumbnail': r're:^https?://.*\.jpg$',
133 'url': 'https://www.mlb.com/video/cespedes-repeats-as-derby-champ/c-34578115',
134 'md5': '99bb9176531adc600b90880fb8be9328',
135 'info_dict': {
136 'id': '34578115',
137 'ext': 'mp4',
138 'title': 'Cespedes repeats as Derby champ',
139 'description': 'md5:08df253ce265d4cf6fb09f581fafad07',
140 'duration': 488,
141 'timestamp': 1405414336,
142 'upload_date': '20140715',
143 'thumbnail': r're:^https?://.*\.jpg$',
147 'url': 'https://www.mlb.com/video/bautista-on-home-run-derby/c-34577915',
148 'md5': 'da8b57a12b060e7663ee1eebd6f330ec',
149 'info_dict': {
150 'id': '34577915',
151 'ext': 'mp4',
152 'title': 'Bautista on Home Run Derby',
153 'description': 'md5:b80b34031143d0986dddc64a8839f0fb',
154 'duration': 52,
155 'timestamp': 1405405122,
156 'upload_date': '20140715',
157 'thumbnail': r're:^https?://.*\.jpg$',
161 'url': 'https://www.mlb.com/video/hargrove-homers-off-caldwell/c-1352023483?tid=67793694',
162 'only_matching': True,
165 'url': 'http://m.mlb.com/shared/video/embed/embed.html?content_id=35692085&topic_id=6479266&width=400&height=224&property=mlb',
166 'only_matching': True,
169 'url': 'http://mlb.mlb.com/shared/video/embed/embed.html?content_id=36599553',
170 'only_matching': True,
173 'url': 'http://mlb.mlb.com/es/video/play.jsp?content_id=36599553',
174 'only_matching': True,
177 'url': 'https://www.mlb.com/cardinals/video/piscottys-great-sliding-catch/c-51175783',
178 'only_matching': True,
181 # From http://m.mlb.com/news/article/118550098/blue-jays-kevin-pillar-goes-spidey-up-the-wall-to-rob-tim-beckham-of-a-homer
182 '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',
183 'only_matching': True,
186 _TIMESTAMP_KEY = 'date'
188 @staticmethod
189 def _get_feed(video):
190 return video
192 @staticmethod
193 def _extract_mlb_subtitles(feed, language):
194 subtitles = {}
195 for keyword in (feed.get('keywordsAll') or []):
196 keyword_type = keyword.get('type')
197 if keyword_type and keyword_type.startswith('closed_captions_location_'):
198 cc_location = keyword.get('value')
199 if cc_location:
200 subtitles.setdefault(language, []).append({
201 'url': cc_location,
203 return subtitles
205 def _download_video_data(self, display_id):
206 return self._download_json(
207 f'http://content.mlb.com/mlb/item/id/v1/{display_id}/details/web-v1.json',
208 display_id)
211 class MLBVideoIE(MLBBaseIE):
212 _VALID_URL = r'https?://(?:www\.)?mlb\.com/(?:[^/]+/)*video/(?P<id>[^/?&#]+)'
213 _TEST = {
214 'url': 'https://www.mlb.com/mariners/video/ackley-s-spectacular-catch-c34698933',
215 'md5': '632358dacfceec06bad823b83d21df2d',
216 'info_dict': {
217 'id': 'c04a8863-f569-42e6-9f87-992393657614',
218 'ext': 'mp4',
219 'title': "Ackley's spectacular catch",
220 'description': 'md5:7f5a981eb4f3cbc8daf2aeffa2215bf0',
221 'duration': 66,
222 'timestamp': 1405995000,
223 'upload_date': '20140722',
224 'thumbnail': r're:^https?://.+',
227 _TIMESTAMP_KEY = 'timestamp'
229 @classmethod
230 def suitable(cls, url):
231 return False if MLBIE.suitable(url) else super().suitable(url)
233 @staticmethod
234 def _get_feed(video):
235 return video['feeds'][0]
237 @staticmethod
238 def _extract_mlb_subtitles(feed, language):
239 subtitles = {}
240 for cc_location in (feed.get('closedCaptions') or []):
241 subtitles.setdefault(language, []).append({
242 'url': cc_location,
245 def _download_video_data(self, display_id):
246 # https://www.mlb.com/data-service/en/videos/[SLUG]
247 return self._download_json(
248 'https://fastball-gateway.mlb.com/graphql',
249 display_id, query={
250 'query': '''{
251 mediaPlayback(ids: "%s") {
252 description
253 feeds(types: CMS) {
254 closedCaptions
255 duration
256 image {
257 cuts {
258 width
259 height
263 playbacks {
264 name
269 timestamp
270 title
272 }''' % display_id, # noqa: UP031
273 })['data']['mediaPlayback'][0]
276 class MLBTVIE(InfoExtractor):
277 _VALID_URL = r'https?://(?:www\.)?mlb\.com/tv/g(?P<id>\d{6})'
278 _NETRC_MACHINE = 'mlb'
280 _TESTS = [{
281 'url': 'https://www.mlb.com/tv/g661581/vee2eff5f-a7df-4c20-bdb4-7b926fa12638',
282 'info_dict': {
283 'id': '661581',
284 'ext': 'mp4',
285 'title': '2022-07-02 - St. Louis Cardinals @ Philadelphia Phillies',
287 'params': {
288 'skip_download': True,
291 _access_token = None
293 def _real_initialize(self):
294 if not self._access_token:
295 self.raise_login_required(
296 'All videos are only available to registered users', method='password')
298 def _perform_login(self, username, password):
299 data = f'grant_type=password&username={urllib.parse.quote(username)}&password={urllib.parse.quote(password)}&scope=openid offline_access&client_id=0oa3e1nutA1HLzAKG356'
300 access_token = self._download_json(
301 'https://ids.mlb.com/oauth2/aus1m088yK07noBfh356/v1/token', None,
302 headers={
303 'User-Agent': 'okhttp/3.12.1',
304 'Content-Type': 'application/x-www-form-urlencoded',
305 }, data=data.encode())['access_token']
307 entitlement = self._download_webpage(
308 f'https://media-entitlement.mlb.com/api/v3/jwt?os=Android&appname=AtBat&did={uuid.uuid4()}', None,
309 headers={
310 'User-Agent': 'okhttp/3.12.1',
311 'Authorization': f'Bearer {access_token}',
314 data = f'grant_type=urn:ietf:params:oauth:grant-type:token-exchange&subject_token={entitlement}&subject_token_type=urn:ietf:params:oauth:token-type:jwt&platform=android-tv'
315 self._access_token = self._download_json(
316 'https://us.edge.bamgrid.com/token', None,
317 headers={
318 'Accept': 'application/json',
319 'Authorization': 'Bearer bWxidHYmYW5kcm9pZCYxLjAuMA.6LZMbH2r--rbXcgEabaDdIslpo4RyZrlVfWZhsAgXIk',
320 'Content-Type': 'application/x-www-form-urlencoded',
321 }, data=data.encode())['access_token']
323 def _real_extract(self, url):
324 video_id = self._match_id(url)
325 airings = self._download_json(
326 f'https://search-api-mlbtv.mlb.com/svc/search/v2/graphql/persisted/query/core/Airings?variables=%7B%22partnerProgramIds%22%3A%5B%22{video_id}%22%5D%2C%22applyEsniMediaRightsLabels%22%3Atrue%7D',
327 video_id)['data']['Airings']
329 formats, subtitles = [], {}
330 for airing in traverse_obj(airings, lambda _, v: v['playbackUrls'][0]['href']):
331 format_id = join_nonempty('feedType', 'feedLanguage', from_dict=airing)
332 m3u8_url = traverse_obj(self._download_json(
333 airing['playbackUrls'][0]['href'].format(scenario='browser~csai'), video_id,
334 note=f'Downloading {format_id} stream info JSON',
335 errnote=f'Failed to download {format_id} stream info, skipping',
336 fatal=False, headers={
337 'Authorization': self._access_token,
338 'Accept': 'application/vnd.media-service+json; version=2',
339 }), ('stream', 'complete', {url_or_none}))
340 if not m3u8_url:
341 continue
342 f, s = self._extract_m3u8_formats_and_subtitles(
343 m3u8_url, video_id, 'mp4', m3u8_id=format_id, fatal=False)
344 formats.extend(f)
345 self._merge_subtitles(s, target=subtitles)
347 return {
348 'id': video_id,
349 'title': traverse_obj(airings, (..., 'titles', 0, 'episodeName'), get_all=False),
350 'is_live': traverse_obj(airings, (..., 'mediaConfig', 'productType'), get_all=False) == 'LIVE',
351 'formats': formats,
352 'subtitles': subtitles,
353 'http_headers': {'Authorization': f'Bearer {self._access_token}'},
357 class MLBArticleIE(InfoExtractor):
358 _VALID_URL = r'https?://www\.mlb\.com/news/(?P<id>[\w-]+)'
359 _TESTS = [{
360 'url': 'https://www.mlb.com/news/manny-machado-robs-guillermo-heredia-reacts',
361 'info_dict': {
362 'id': '36db7394-343c-4ea3-b8ca-ead2e61bca9a',
363 'title': 'Machado\'s grab draws hilarious irate reaction',
364 'modified_timestamp': 1675888370,
365 'description': 'md5:a19d4eb0487b2cb304e9a176f6b67676',
366 'modified_date': '20230208',
368 'playlist_mincount': 2,
371 def _real_extract(self, url):
372 display_id = self._match_id(url)
373 webpage = self._download_webpage(url, display_id)
374 apollo_cache_json = self._search_json(r'window\.initState\s*=', webpage, 'window.initState', display_id)['apolloCache']
376 content_real_info = traverse_obj(
377 apollo_cache_json, ('ROOT_QUERY', lambda k, _: k.startswith('getArticle')), get_all=False)
379 return self.playlist_from_matches(
380 traverse_obj(content_real_info, ('parts', lambda _, v: v['__typename'] == 'Video' or v['type'] == 'video')),
381 getter=lambda x: f'https://www.mlb.com/video/{x["slug"]}',
382 ie=MLBVideoIE, playlist_id=content_real_info.get('translationId'),
383 title=self._html_search_meta('og:title', webpage),
384 description=content_real_info.get('summary'),
385 modified_timestamp=parse_iso8601(content_real_info.get('lastUpdatedDate')))