]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/nba.py
[cleanup] Upgrade syntax
[yt-dlp.git] / yt_dlp / extractor / nba.py
CommitLineData
3cfeb162 1import functools
ecf6de5b 2import re
3
29825140 4from .turner import TurnerBaseIE
3cfeb162 5from ..compat import (
29f7c58a 6 compat_str,
7 compat_urllib_parse_unquote,
3cfeb162 8)
7bbc6428 9from ..utils import (
29f7c58a 10 int_or_none,
11 merge_dicts,
3cfeb162 12 OnDemandPagedList,
29f7c58a 13 parse_duration,
14 parse_iso8601,
4dfbf869 15 parse_qs,
29f7c58a 16 try_get,
17 update_url_query,
18 urljoin,
7bbc6428 19)
5b286728
PH
20
21
29f7c58a 22class NBACVPBaseIE(TurnerBaseIE):
23 def _extract_nba_cvp_info(self, path, video_id, fatal=False):
24 return self._extract_cvp_info(
25 'http://secure.nba.com/%s' % path, video_id, {
26 'default': {
27 'media_src': 'http://nba.cdn.turner.com/nba/big',
28 },
29 'm3u8': {
30 'media_src': 'http://nbavod-f.akamaihd.net',
31 },
32 }, fatal=fatal)
33
34
35class NBAWatchBaseIE(NBACVPBaseIE):
36 _VALID_URL_BASE = r'https?://(?:(?:www\.)?nba\.com(?:/watch)?|watch\.nba\.com)/'
37
38 def _extract_video(self, filter_key, filter_value):
39 video = self._download_json(
40 'https://neulionscnbav2-a.akamaihd.net/solr/nbad_program/usersearch',
41 filter_value, query={
42 'fl': 'description,image,name,pid,releaseDate,runtime,tags,seoName',
43 'q': filter_key + ':' + filter_value,
44 'wt': 'json',
45 })['response']['docs'][0]
46
47 video_id = str(video['pid'])
48 title = video['name']
49
50 formats = []
51 m3u8_url = (self._download_json(
52 'https://watch.nba.com/service/publishpoint', video_id, query={
53 'type': 'video',
54 'format': 'json',
55 'id': video_id,
56 }, headers={
57 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0_1 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A402 Safari/604.1',
58 }, fatal=False) or {}).get('path')
59 if m3u8_url:
60 m3u8_formats = self._extract_m3u8_formats(
61 re.sub(r'_(?:pc|iphone)\.', '.', m3u8_url), video_id, 'mp4',
62 'm3u8_native', m3u8_id='hls', fatal=False)
63 formats.extend(m3u8_formats)
64 for f in m3u8_formats:
65 http_f = f.copy()
66 http_f.update({
67 'format_id': http_f['format_id'].replace('hls-', 'http-'),
68 'protocol': 'http',
69 'url': http_f['url'].replace('.m3u8', ''),
70 })
71 formats.append(http_f)
72
73 info = {
74 'id': video_id,
75 'title': title,
76 'thumbnail': urljoin('https://nbadsdmt.akamaized.net/media/nba/nba/thumbs/', video.get('image')),
77 'description': video.get('description'),
78 'duration': int_or_none(video.get('runtime')),
79 'timestamp': parse_iso8601(video.get('releaseDate')),
80 'tags': video.get('tags'),
81 }
82
83 seo_name = video.get('seoName')
84 if seo_name and re.search(r'\d{4}/\d{2}/\d{2}/', seo_name):
85 base_path = ''
86 if seo_name.startswith('teams/'):
87 base_path += seo_name.split('/')[1] + '/'
88 base_path += 'video/'
89 cvp_info = self._extract_nba_cvp_info(
90 base_path + seo_name + '.xml', video_id, False)
91 if cvp_info:
92 formats.extend(cvp_info['formats'])
93 info = merge_dicts(info, cvp_info)
94
95 self._sort_formats(formats)
96 info['formats'] = formats
97 return info
98
99
100class NBAWatchEmbedIE(NBAWatchBaseIE):
101 IENAME = 'nba:watch:embed'
102 _VALID_URL = NBAWatchBaseIE._VALID_URL_BASE + r'embed\?.*?\bid=(?P<id>\d+)'
103 _TESTS = [{
104 'url': 'http://watch.nba.com/embed?id=659395',
105 'md5': 'b7e3f9946595f4ca0a13903ce5edd120',
106 'info_dict': {
107 'id': '659395',
108 'ext': 'mp4',
109 'title': 'Mix clip: More than 7 points of Joe Ingles, Luc Mbah a Moute, Blake Griffin and 6 more in Utah Jazz vs. the Clippers, 4/15/2017',
110 'description': 'Mix clip: More than 7 points of Joe Ingles, Luc Mbah a Moute, Blake Griffin and 6 more in Utah Jazz vs. the Clippers, 4/15/2017',
111 'timestamp': 1492228800,
112 'upload_date': '20170415',
113 },
114 }]
115
116 def _real_extract(self, url):
117 video_id = self._match_id(url)
118 return self._extract_video('pid', video_id)
119
120
121class NBAWatchIE(NBAWatchBaseIE):
122 IE_NAME = 'nba:watch'
123 _VALID_URL = NBAWatchBaseIE._VALID_URL_BASE + r'(?:nba/)?video/(?P<id>.+?(?=/index\.html)|(?:[^/]+/)*[^/?#&]+)'
6a3e0103 124 _TESTS = [{
26a78d4b 125 'url': 'http://www.nba.com/video/games/nets/2012/12/04/0021200253-okc-bkn-recap.nba/index.html',
29f7c58a 126 'md5': '9d902940d2a127af3f7f9d2f3dc79c96',
26a78d4b 127 'info_dict': {
29f7c58a 128 'id': '70946',
db9b1dbc 129 'ext': 'mp4',
26a78d4b 130 'title': 'Thunder vs. Nets',
7bbc6428
S
131 'description': 'Kevin Durant scores 32 points and dishes out six assists as the Thunder beat the Nets in Brooklyn.',
132 'duration': 181,
29f7c58a 133 'timestamp': 1354597200,
c233e6bc 134 'upload_date': '20121204',
26a78d4b 135 },
6a3e0103
PH
136 }, {
137 'url': 'http://www.nba.com/video/games/hornets/2014/12/05/0021400276-nyk-cha-play5.nba/',
138 'only_matching': True,
46cc1c65 139 }, {
6a11bb77 140 'url': 'http://watch.nba.com/video/channels/playoffs/2015/05/20/0041400301-cle-atl-recap.nba',
8fc226ef 141 'md5': 'b2b39b81cf28615ae0c3360a3f9668c4',
8a278a1d 142 'info_dict': {
29f7c58a 143 'id': '330865',
8a278a1d 144 'ext': 'mp4',
8fc226ef 145 'title': 'Hawks vs. Cavaliers Game 1',
8a278a1d
YCH
146 'description': 'md5:8094c3498d35a9bd6b1a8c396a071b4d',
147 'duration': 228,
29f7c58a 148 'timestamp': 1432094400,
149 'upload_date': '20150521',
3c77a54d 150 },
86a7dbe6 151 }, {
29f7c58a 152 'url': 'http://watch.nba.com/nba/video/channels/nba_tv/2015/06/11/YT_go_big_go_home_Game4_061115',
153 'only_matching': True,
3cfeb162 154 }, {
29f7c58a 155 # only CVP mp4 format available
156 'url': 'https://watch.nba.com/video/teams/cavaliers/2012/10/15/sloan121015mov-2249106',
157 'only_matching': True,
3cfeb162 158 }, {
29f7c58a 159 'url': 'https://watch.nba.com/video/top-100-dunks-from-the-2019-20-season?plsrc=nba&collection=2019-20-season-highlights',
160 'only_matching': True,
161 }]
162
163 def _real_extract(self, url):
164 display_id = self._match_id(url)
4dfbf869 165 collection_id = parse_qs(url).get('collection', [None])[0]
f40ee5e9 166 if self._yes_playlist(collection_id, display_id):
167 return self.url_result(
168 'https://www.nba.com/watch/list/collection/' + collection_id,
169 NBAWatchCollectionIE.ie_key(), collection_id)
29f7c58a 170 return self._extract_video('seoName', display_id)
171
172
173class NBAWatchCollectionIE(NBAWatchBaseIE):
174 IE_NAME = 'nba:watch:collection'
175 _VALID_URL = NBAWatchBaseIE._VALID_URL_BASE + r'list/collection/(?P<id>[^/?#&]+)'
176 _TESTS = [{
177 'url': 'https://watch.nba.com/list/collection/season-preview-2020',
3cfeb162 178 'info_dict': {
29f7c58a 179 'id': 'season-preview-2020',
3cfeb162 180 },
29f7c58a 181 'playlist_mincount': 43,
6a3e0103 182 }]
29f7c58a 183 _PAGE_SIZE = 100
5b286728 184
29f7c58a 185 def _fetch_page(self, collection_id, page):
186 page += 1
187 videos = self._download_json(
188 'https://content-api-prod.nba.com/public/1/endeavor/video-list/collection/' + collection_id,
189 collection_id, 'Downloading page %d JSON metadata' % page, query={
190 'count': self._PAGE_SIZE,
191 'page': page,
192 })['results']['videos']
193 for video in videos:
194 program = video.get('program') or {}
195 seo_name = program.get('seoName') or program.get('slug')
196 if not seo_name:
197 continue
198 yield {
199 '_type': 'url',
200 'id': program.get('id'),
201 'title': program.get('title') or video.get('title'),
202 'url': 'https://www.nba.com/watch/video/' + seo_name,
203 'thumbnail': video.get('image'),
204 'description': program.get('description') or video.get('description'),
205 'duration': parse_duration(program.get('runtimeHours')),
206 'timestamp': parse_iso8601(video.get('releaseDate')),
207 }
3cfeb162 208
29f7c58a 209 def _real_extract(self, url):
210 collection_id = self._match_id(url)
3cfeb162 211 entries = OnDemandPagedList(
29f7c58a 212 functools.partial(self._fetch_page, collection_id),
6be08ce6 213 self._PAGE_SIZE)
29f7c58a 214 return self.playlist_result(entries, collection_id)
3cfeb162 215
3cfeb162 216
29f7c58a 217class NBABaseIE(NBACVPBaseIE):
218 _VALID_URL_BASE = r'''(?x)
219 https?://(?:www\.)?nba\.com/
220 (?P<team>
221 blazers|
222 bucks|
223 bulls|
224 cavaliers|
225 celtics|
226 clippers|
227 grizzlies|
228 hawks|
229 heat|
230 hornets|
231 jazz|
232 kings|
233 knicks|
234 lakers|
235 magic|
236 mavericks|
237 nets|
238 nuggets|
239 pacers|
240 pelicans|
241 pistons|
242 raptors|
243 rockets|
244 sixers|
245 spurs|
246 suns|
247 thunder|
248 timberwolves|
249 warriors|
250 wizards
251 )
252 (?:/play\#)?/'''
253 _CHANNEL_PATH_REGEX = r'video/channel|series'
86a7dbe6 254
29f7c58a 255 def _embed_url_result(self, team, content_id):
256 return self.url_result(update_url_query(
257 'https://secure.nba.com/assets/amp/include/video/iframe.html', {
258 'contentId': content_id,
259 'team': team,
260 }), NBAEmbedIE.ie_key())
3cfeb162 261
29f7c58a 262 def _call_api(self, team, content_id, query, resource):
263 return self._download_json(
264 'https://api.nba.net/2/%s/video,imported_video,wsc/' % team,
265 content_id, 'Download %s JSON metadata' % resource,
266 query=query, headers={
267 'accessToken': 'internal|bb88df6b4c2244e78822812cecf1ee1b',
268 })['response']['result']
3cfeb162 269
29f7c58a 270 def _extract_video(self, video, team, extract_all=True):
271 video_id = compat_str(video['nid'])
272 team = video['brand']
86a7dbe6 273
29f7c58a 274 info = {
275 'id': video_id,
276 'title': video.get('title') or video.get('headline') or video['shortHeadline'],
277 'description': video.get('description'),
278 'timestamp': parse_iso8601(video.get('published')),
279 }
280
281 subtitles = {}
282 captions = try_get(video, lambda x: x['videoCaptions']['sidecars'], dict) or {}
283 for caption_url in captions.values():
284 subtitles.setdefault('en', []).append({'url': caption_url})
285
286 formats = []
287 mp4_url = video.get('mp4')
288 if mp4_url:
289 formats.append({
290 'url': mp4_url,
c233e6bc 291 })
29f7c58a 292
293 if extract_all:
294 source_url = video.get('videoSource')
295 if source_url and not source_url.startswith('s3://') and self._is_valid_url(source_url, video_id, 'source'):
296 formats.append({
297 'format_id': 'source',
298 'url': source_url,
f983b875 299 'quality': 1,
29f7c58a 300 })
301
302 m3u8_url = video.get('m3u8')
303 if m3u8_url:
304 if '.akamaihd.net/i/' in m3u8_url:
305 formats.extend(self._extract_akamai_formats(
306 m3u8_url, video_id, {'http': 'pmd.cdn.turner.com'}))
307 else:
308 formats.extend(self._extract_m3u8_formats(
309 m3u8_url, video_id, 'mp4',
310 'm3u8_native', m3u8_id='hls', fatal=False))
311
312 content_xml = video.get('contentXml')
313 if team and content_xml:
314 cvp_info = self._extract_nba_cvp_info(
315 team + content_xml, video_id, fatal=False)
316 if cvp_info:
317 formats.extend(cvp_info['formats'])
318 subtitles = self._merge_subtitles(subtitles, cvp_info['subtitles'])
319 info = merge_dicts(info, cvp_info)
320
321 self._sort_formats(formats)
322 else:
323 info.update(self._embed_url_result(team, video['videoId']))
324
325 info.update({
326 'formats': formats,
327 'subtitles': subtitles,
328 })
329
330 return info
331
332 def _real_extract(self, url):
5ad28e7f 333 team, display_id = self._match_valid_url(url).groups()
29f7c58a 334 if '/play#/' in url:
335 display_id = compat_urllib_parse_unquote(display_id)
336 else:
337 webpage = self._download_webpage(url, display_id)
338 display_id = self._search_regex(
339 self._CONTENT_ID_REGEX + r'\s*:\s*"([^"]+)"', webpage, 'video id')
340 return self._extract_url_results(team, display_id)
341
342
343class NBAEmbedIE(NBABaseIE):
344 IENAME = 'nba:embed'
345 _VALID_URL = r'https?://secure\.nba\.com/assets/amp/include/video/(?:topI|i)frame\.html\?.*?\bcontentId=(?P<id>[^?#&]+)'
346 _TESTS = [{
347 'url': 'https://secure.nba.com/assets/amp/include/video/topIframe.html?contentId=teams/bulls/2020/12/04/3478774/1607105587854-20201204_SCHEDULE_RELEASE_FINAL_DRUPAL-3478774&team=bulls&adFree=false&profile=71&videoPlayerName=TAMPCVP&baseUrl=&videoAdsection=nba.com_mobile_web_teamsites_chicagobulls&ampEnv=',
348 'only_matching': True,
349 }, {
350 'url': 'https://secure.nba.com/assets/amp/include/video/iframe.html?contentId=2016/10/29/0021600027boschaplay7&adFree=false&profile=71&team=&videoPlayerName=LAMPCVP',
351 'only_matching': True,
352 }]
353
354 def _real_extract(self, url):
4dfbf869 355 qs = parse_qs(url)
29f7c58a 356 content_id = qs['contentId'][0]
357 team = qs.get('team', [None])[0]
358 if not team:
359 return self.url_result(
360 'https://watch.nba.com/video/' + content_id, NBAWatchIE.ie_key())
361 video = self._call_api(team, content_id, {'videoid': content_id}, 'video')[0]
362 return self._extract_video(video, team)
363
364
365class NBAIE(NBABaseIE):
366 IENAME = 'nba'
367 _VALID_URL = NBABaseIE._VALID_URL_BASE + '(?!%s)video/(?P<id>(?:[^/]+/)*[^/?#&]+)' % NBABaseIE._CHANNEL_PATH_REGEX
368 _TESTS = [{
369 'url': 'https://www.nba.com/bulls/video/teams/bulls/2020/12/04/3478774/1607105587854-20201204schedulereleasefinaldrupal-3478774',
370 'info_dict': {
371 'id': '45039',
372 'ext': 'mp4',
373 'title': 'AND WE BACK.',
374 'description': 'Part 1 of our 2020-21 schedule is here! Watch our games on NBC Sports Chicago.',
375 'duration': 94,
376 'timestamp': 1607112000,
377 'upload_date': '20201218',
378 },
379 }, {
380 'url': 'https://www.nba.com/bucks/play#/video/teams%2Fbucks%2F2020%2F12%2F17%2F64860%2F1608252863446-Op_Dream_16x9-64860',
381 'only_matching': True,
382 }, {
383 'url': 'https://www.nba.com/bucks/play#/video/wsc%2Fteams%2F2787C911AA1ACD154B5377F7577CCC7134B2A4B0',
384 'only_matching': True,
385 }]
386 _CONTENT_ID_REGEX = r'videoID'
387
388 def _extract_url_results(self, team, content_id):
389 return self._embed_url_result(team, content_id)
390
391
392class NBAChannelIE(NBABaseIE):
393 IENAME = 'nba:channel'
394 _VALID_URL = NBABaseIE._VALID_URL_BASE + '(?:%s)/(?P<id>[^/?#&]+)' % NBABaseIE._CHANNEL_PATH_REGEX
395 _TESTS = [{
396 'url': 'https://www.nba.com/blazers/video/channel/summer_league',
397 'info_dict': {
398 'title': 'Summer League',
399 },
400 'playlist_mincount': 138,
401 }, {
402 'url': 'https://www.nba.com/bucks/play#/series/On%20This%20Date',
403 'only_matching': True,
404 }]
405 _CONTENT_ID_REGEX = r'videoSubCategory'
406 _PAGE_SIZE = 100
407
408 def _fetch_page(self, team, channel, page):
409 results = self._call_api(team, channel, {
410 'channels': channel,
411 'count': self._PAGE_SIZE,
412 'offset': page * self._PAGE_SIZE,
413 }, 'page %d' % (page + 1))
414 for video in results:
415 yield self._extract_video(video, team, False)
416
417 def _extract_url_results(self, team, content_id):
418 entries = OnDemandPagedList(
419 functools.partial(self._fetch_page, team, content_id),
420 self._PAGE_SIZE)
421 return self.playlist_result(entries, playlist_title=content_id)