nba.py 16 KB

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