]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/nfl.py
[ie/nfl.com:plus:replay] Fix extractor (#7838)
[yt-dlp.git] / yt_dlp / extractor / nfl.py
CommitLineData
8b37c58f 1import base64
2import json
632e5684 3import re
8b37c58f 4import time
5import uuid
632e5684 6
8b37c58f 7from .anvato import AnvatoIE
632e5684
NJ
8from .common import InfoExtractor
9from ..utils import (
8b37c58f 10 ExtractorError,
29f7c58a 11 clean_html,
12 determine_ext,
13 get_element_by_class,
8b37c58f 14 traverse_obj,
15 urlencode_postdata,
632e5684
NJ
16)
17
18
29f7c58a 19class NFLBaseIE(InfoExtractor):
20 _VALID_URL_BASE = r'''(?x)
5b4c5463
S
21 https?://
22 (?P<host>
23 (?:www\.)?
24 (?:
25 (?:
26 nfl|
27 buffalobills|
28 miamidolphins|
29 patriots|
30 newyorkjets|
31 baltimoreravens|
32 bengals|
33 clevelandbrowns|
34 steelers|
35 houstontexans|
36 colts|
37 jaguars|
29f7c58a 38 (?:titansonline|tennesseetitans)|
5b4c5463 39 denverbroncos|
29f7c58a 40 (?:kc)?chiefs|
5b4c5463
S
41 raiders|
42 chargers|
43 dallascowboys|
44 giants|
45 philadelphiaeagles|
29f7c58a 46 (?:redskins|washingtonfootball)|
5b4c5463
S
47 chicagobears|
48 detroitlions|
49 packers|
50 vikings|
51 atlantafalcons|
52 panthers|
53 neworleanssaints|
54 buccaneers|
55 azcardinals|
29f7c58a 56 (?:stlouis|the)rams|
5b4c5463
S
57 49ers|
58 seahawks
59 )\.com|
60 .+?\.clubs\.nfl\.com
61 )
62 )/
5b4c5463 63 '''
dd4411aa 64 _VIDEO_CONFIG_REGEX = r'<script[^>]+id="[^"]*video-config-[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}[^"]*"[^>]*>\s*({.+});?\s*</script>'
8b37c58f 65 _ANVATO_PREFIX = 'anvato:GXvEgwyJeWem8KCYXfeoHWknwP48Mboj:'
29f7c58a 66
1eaca74b 67 _CLIENT_DATA = {
68 'clientKey': '4cFUW6DmwJpzT9L7LrG3qRAcABG5s04g',
69 'clientSecret': 'CZuvCL49d9OwfGsR',
70 'deviceId': str(uuid.uuid4()),
71 'deviceInfo': base64.b64encode(json.dumps({
72 'model': 'desktop',
73 'version': 'Chrome',
74 'osName': 'Windows',
75 'osVersion': '10.0',
76 }, separators=(',', ':')).encode()).decode(),
77 'networkType': 'other',
78 'nflClaimGroupsToAdd': [],
79 'nflClaimGroupsToRemove': [],
80 }
81 _ACCOUNT_INFO = {}
82 _API_KEY = None
83
84 _TOKEN = None
85 _TOKEN_EXPIRY = 0
86
87 def _get_account_info(self, url, slug):
88 if not self._API_KEY:
89 webpage = self._download_webpage(url, slug, fatal=False) or ''
90 self._API_KEY = self._search_regex(
91 r'window\.gigyaApiKey\s*=\s*["\'](\w+)["\'];', webpage, 'API key',
92 fatal=False) or '3_Qa8TkWpIB8ESCBT8tY2TukbVKgO5F6BJVc7N1oComdwFzI7H2L9NOWdm11i_BY9f'
93
94 cookies = self._get_cookies('https://auth-id.nfl.com/')
95 login_token = traverse_obj(cookies, (
96 (f'glt_{self._API_KEY}', lambda k, _: k.startswith('glt_')), {lambda x: x.value}), get_all=False)
97 if not login_token:
98 self.raise_login_required()
99 if 'ucid' not in cookies:
100 raise ExtractorError(
101 'Required cookies for the auth-id.nfl.com domain were not found among passed cookies. '
102 'If using --cookies, these cookies must be exported along with .nfl.com cookies, '
103 'or else try using --cookies-from-browser instead', expected=True)
104
105 account = self._download_json(
106 'https://auth-id.nfl.com/accounts.getAccountInfo', slug,
107 note='Downloading account info', data=urlencode_postdata({
108 'include': 'profile,data',
109 'lang': 'en',
110 'APIKey': self._API_KEY,
111 'sdk': 'js_latest',
112 'login_token': login_token,
113 'authMode': 'cookie',
114 'pageURL': url,
115 'sdkBuild': traverse_obj(cookies, (
116 'gig_canary_ver', {lambda x: x.value.partition('-')[0]}), default='15170'),
117 'format': 'json',
118 }), headers={'Content-Type': 'application/x-www-form-urlencoded'})
119
120 self._ACCOUNT_INFO = traverse_obj(account, {
121 'signatureTimestamp': 'signatureTimestamp',
122 'uid': 'UID',
123 'uidSignature': 'UIDSignature',
124 })
125
126 if len(self._ACCOUNT_INFO) != 3:
127 raise ExtractorError('Failed to retrieve account info with provided cookies', expected=True)
128
129 def _get_auth_token(self, url, slug):
130 if self._TOKEN and self._TOKEN_EXPIRY > int(time.time() + 30):
131 return
132
133 if not self._ACCOUNT_INFO:
134 self._get_account_info(url, slug)
135
136 token = self._download_json(
137 'https://api.nfl.com/identity/v3/token%s' % (
138 '/refresh' if self._ACCOUNT_INFO.get('refreshToken') else ''),
139 slug, headers={'Content-Type': 'application/json'}, note='Downloading access token',
140 data=json.dumps({**self._CLIENT_DATA, **self._ACCOUNT_INFO}, separators=(',', ':')).encode())
141
142 self._TOKEN = token['accessToken']
143 self._TOKEN_EXPIRY = token['expiresIn']
144 self._ACCOUNT_INFO['refreshToken'] = token['refreshToken']
145
29f7c58a 146 def _parse_video_config(self, video_config, display_id):
147 video_config = self._parse_json(video_config, display_id)
148 item = video_config['playlist'][0]
149 mcp_id = item.get('mcpID')
150 if mcp_id:
8b37c58f 151 info = self.url_result(f'{self._ANVATO_PREFIX}{mcp_id}', AnvatoIE, mcp_id)
29f7c58a 152 else:
153 media_id = item.get('id') or item['entityId']
dd4411aa 154 title = item.get('title')
29f7c58a 155 item_url = item['url']
156 info = {'id': media_id}
157 ext = determine_ext(item_url)
158 if ext == 'm3u8':
159 info['formats'] = self._extract_m3u8_formats(item_url, media_id, 'mp4')
29f7c58a 160 else:
161 info['url'] = item_url
162 if item.get('audio') is True:
163 info['vcodec'] = 'none'
164 is_live = video_config.get('live') is True
165 thumbnails = None
166 image_url = item.get(item.get('imageSrc')) or item.get(item.get('posterImage'))
167 if image_url:
168 thumbnails = [{
169 'url': image_url,
170 'ext': determine_ext(image_url, 'jpg'),
171 }]
172 info.update({
39ca3b5c 173 'title': title,
29f7c58a 174 'is_live': is_live,
175 'description': clean_html(item.get('description')),
176 'thumbnails': thumbnails,
177 })
178 return info
179
180
181class NFLIE(NFLBaseIE):
182 IE_NAME = 'nfl.com'
183 _VALID_URL = NFLBaseIE._VALID_URL_BASE + r'(?:videos?|listen|audio)/(?P<id>[^/#?&]+)'
5b4c5463 184 _TESTS = [{
29f7c58a 185 'url': 'https://www.nfl.com/videos/baker-mayfield-s-game-changing-plays-from-3-td-game-week-14',
5b4c5463 186 'info_dict': {
29f7c58a 187 'id': '899441',
5b4c5463 188 'ext': 'mp4',
29f7c58a 189 'title': "Baker Mayfield's game-changing plays from 3-TD game Week 14",
190 'description': 'md5:85e05a3cc163f8c344340f220521136d',
191 'upload_date': '20201215',
192 'timestamp': 1608009755,
ec85ded8 193 'thumbnail': r're:^https?://.*\.jpg$',
29f7c58a 194 'uploader': 'NFL',
dd4411aa 195 'tags': 'count:6',
196 'duration': 157,
197 'categories': 'count:3',
7ebd5376 198 }
5b4c5463 199 }, {
29f7c58a 200 'url': 'https://www.chiefs.com/listen/patrick-mahomes-travis-kelce-react-to-win-over-dolphins-the-breakdown',
201 'md5': '6886b32c24b463038c760ceb55a34566',
5b4c5463 202 'info_dict': {
29f7c58a 203 'id': 'd87e8790-3e14-11eb-8ceb-ff05c2867f99',
204 'ext': 'mp3',
205 'title': 'Patrick Mahomes, Travis Kelce React to Win Over Dolphins | The Breakdown',
206 'description': 'md5:12ada8ee70e6762658c30e223e095075',
dd4411aa 207 },
208 'skip': 'HTTP Error 404: Not Found',
5b4c5463 209 }, {
29f7c58a 210 'url': 'https://www.buffalobills.com/video/buffalo-bills-military-recognition-week-14',
5b4c5463
S
211 'only_matching': True,
212 }, {
29f7c58a 213 'url': 'https://www.raiders.com/audio/instant-reactions-raiders-week-14-loss-to-indianapolis-colts-espn-jason-fitz',
5b4c5463
S
214 'only_matching': True,
215 }]
5f4c3188 216
632e5684 217 def _real_extract(self, url):
29f7c58a 218 display_id = self._match_id(url)
219 webpage = self._download_webpage(url, display_id)
220 return self._parse_video_config(self._search_regex(
221 self._VIDEO_CONFIG_REGEX, webpage, 'video config'), display_id)
5f4c3188 222
632e5684 223
29f7c58a 224class NFLArticleIE(NFLBaseIE):
225 IE_NAME = 'nfl.com:article'
226 _VALID_URL = NFLBaseIE._VALID_URL_BASE + r'news/(?P<id>[^/#?&]+)'
227 _TEST = {
228 'url': 'https://www.buffalobills.com/news/the-only-thing-we-ve-earned-is-the-noise-bills-coaches-discuss-handling-rising-e',
229 'info_dict': {
230 'id': 'the-only-thing-we-ve-earned-is-the-noise-bills-coaches-discuss-handling-rising-e',
231 'title': "'The only thing we've earned is the noise' | Bills coaches discuss handling rising expectations",
232 },
233 'playlist_count': 4,
234 }
632e5684 235
29f7c58a 236 def _real_extract(self, url):
237 display_id = self._match_id(url)
238 webpage = self._download_webpage(url, display_id)
239 entries = []
240 for video_config in re.findall(self._VIDEO_CONFIG_REGEX, webpage):
241 entries.append(self._parse_video_config(video_config, display_id))
242 title = clean_html(get_element_by_class(
243 'nfl-c-article__title', webpage)) or self._html_search_meta(
244 ['og:title', 'twitter:title'], webpage)
245 return self.playlist_result(entries, display_id, title)
8b37c58f 246
247
248class NFLPlusReplayIE(NFLBaseIE):
249 IE_NAME = 'nfl.com:plus:replay'
1eaca74b 250 _VALID_URL = r'https?://(?:www\.)?nfl.com/plus/games/(?P<slug>[\w-]+)(?:/(?P<id>\d+))?'
8b37c58f 251 _TESTS = [{
252 'url': 'https://www.nfl.com/plus/games/giants-at-vikings-2022-post-1/1572108',
253 'info_dict': {
254 'id': '1572108',
255 'ext': 'mp4',
256 'title': 'New York Giants at Minnesota Vikings',
257 'description': 'New York Giants play the Minnesota Vikings at U.S. Bank Stadium on January 15, 2023',
258 'uploader': 'NFL',
259 'upload_date': '20230116',
260 'timestamp': 1673864520,
261 'duration': 7157,
262 'categories': ['Game Highlights'],
263 'tags': ['Minnesota Vikings', 'New York Giants', 'Minnesota Vikings vs. New York Giants'],
264 'thumbnail': r're:^https?://.*\.jpg',
265 },
266 'params': {'skip_download': 'm3u8'},
1eaca74b 267 }, {
268 'note': 'Subscription required',
269 'url': 'https://www.nfl.com/plus/games/giants-at-vikings-2022-post-1',
270 'playlist_count': 4,
271 'info_dict': {
272 'id': 'giants-at-vikings-2022-post-1',
273 },
274 }, {
275 'note': 'Subscription required',
276 'url': 'https://www.nfl.com/plus/games/giants-at-patriots-2011-pre-4',
277 'playlist_count': 2,
278 'info_dict': {
279 'id': 'giants-at-patriots-2011-pre-4',
280 },
281 }, {
282 'note': 'Subscription required',
283 'url': 'https://www.nfl.com/plus/games/giants-at-patriots-2011-pre-4',
284 'info_dict': {
285 'id': '950701',
286 'ext': 'mp4',
287 'title': 'Giants @ Patriots',
288 'description': 'Giants at Patriots on September 01, 2011',
289 'uploader': 'NFL',
290 'upload_date': '20210724',
291 'timestamp': 1627085874,
292 'duration': 1532,
293 'categories': ['Game Highlights'],
294 'tags': ['play-by-play'],
295 'thumbnail': r're:^https?://.*\.jpg',
296 },
297 'params': {
298 'skip_download': 'm3u8',
299 'extractor_args': {'nflplusreplay': {'type': ['condensed_game']}},
300 },
8b37c58f 301 }]
302
1eaca74b 303 _REPLAY_TYPES = {
304 'full_game': 'Full Game',
305 'full_game_spanish': 'Full Game - Spanish',
306 'condensed_game': 'Condensed Game',
307 'all_22': 'All-22',
308 }
309
8b37c58f 310 def _real_extract(self, url):
1eaca74b 311 slug, video_id = self._match_valid_url(url).group('slug', 'id')
312 requested_types = self._configuration_arg('type', ['all'])
313 if 'all' in requested_types:
314 requested_types = list(self._REPLAY_TYPES.keys())
315 requested_types = traverse_obj(self._REPLAY_TYPES, (None, requested_types))
316
317 if not video_id:
318 self._get_auth_token(url, slug)
319 headers = {'Authorization': f'Bearer {self._TOKEN}'}
320 game_id = self._download_json(
321 f'https://api.nfl.com/football/v2/games/externalId/slug/{slug}', slug,
322 'Downloading game ID', query={'withExternalIds': 'true'}, headers=headers)['id']
323 replays = self._download_json(
324 'https://api.nfl.com/content/v1/videos/replays', slug, 'Downloading replays JSON',
325 query={'gameId': game_id}, headers=headers)
326 if len(requested_types) == 1:
327 video_id = traverse_obj(replays, (
328 'items', lambda _, v: v['subType'] == requested_types[0], 'mcpPlaybackId'), get_all=False)
329
330 if video_id:
331 return self.url_result(f'{self._ANVATO_PREFIX}{video_id}', AnvatoIE, video_id)
332
333 def entries():
334 for replay in traverse_obj(
335 replays, ('items', lambda _, v: v['mcpPlaybackId'] and v['subType'] in requested_types)
336 ):
337 video_id = replay['mcpPlaybackId']
338 yield self.url_result(f'{self._ANVATO_PREFIX}{video_id}', AnvatoIE, video_id)
339
340 return self.playlist_result(entries(), slug)
8b37c58f 341
342
343class NFLPlusEpisodeIE(NFLBaseIE):
344 IE_NAME = 'nfl.com:plus:episode'
345 _VALID_URL = r'https?://(?:www\.)?nfl.com/plus/episodes/(?P<id>[\w-]+)'
346 _TESTS = [{
1eaca74b 347 'note': 'Subscription required',
8b37c58f 348 'url': 'https://www.nfl.com/plus/episodes/kurt-s-qb-insider-conference-championships',
349 'info_dict': {
350 'id': '1576832',
351 'ext': 'mp4',
1eaca74b 352 'title': 'Conference Championships',
8b37c58f 353 'description': 'md5:944f7fab56f7a37430bf8473f5473857',
354 'uploader': 'NFL',
355 'upload_date': '20230127',
356 'timestamp': 1674782760,
357 'duration': 730,
358 'categories': ['Analysis'],
359 'tags': ['Cincinnati Bengals at Kansas City Chiefs (2022-POST-3)'],
360 'thumbnail': r're:^https?://.*\.jpg',
361 },
362 'params': {'skip_download': 'm3u8'},
363 }]
364
8b37c58f 365 def _real_extract(self, url):
366 slug = self._match_id(url)
1eaca74b 367 self._get_auth_token(url, slug)
8b37c58f 368 video_id = self._download_json(
369 f'https://api.nfl.com/content/v1/videos/episodes/{slug}', slug, headers={
370 'Authorization': f'Bearer {self._TOKEN}',
371 })['mcpPlaybackId']
372
373 return self.url_result(f'{self._ANVATO_PREFIX}{video_id}', AnvatoIE, video_id)