mlb.py 15 KB

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