nfl.py 15 KB

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