[cleanup] Make more playlist entries lazy (#11763)
[yt-dlp.git] / yt_dlp / extractor / yahoo.py
blob35e71209c5ff7519f053b5a34548e008106f5fb1
1 import hashlib
2 import itertools
3 import urllib.parse
5 from .common import InfoExtractor, SearchInfoExtractor
6 from .youtube import YoutubeIE
7 from ..utils import (
8 ExtractorError,
9 clean_html,
10 int_or_none,
11 join_nonempty,
12 mimetype2ext,
13 parse_iso8601,
14 traverse_obj,
15 try_get,
16 url_or_none,
20 class YahooIE(InfoExtractor):
21 IE_DESC = 'Yahoo screen and movies'
22 _VALID_URL = r'(?P<url>https?://(?:(?P<country>[a-zA-Z]{2}(?:-[a-zA-Z]{2})?|malaysia)\.)?(?:[\da-zA-Z_-]+\.)?yahoo\.com/(?:[^/]+/)*(?P<id>[^?&#]*-[0-9]+(?:-[a-z]+)?)\.html)'
23 _EMBED_REGEX = [r'<iframe[^>]+?src=(["\'])(?P<url>https?://(?:screen|movies)\.yahoo\.com/.+?\.html\?format=embed)\1']
25 _TESTS = [{
26 'url': 'http://screen.yahoo.com/julian-smith-travis-legg-watch-214727115.html',
27 'info_dict': {
28 'id': '2d25e626-2378-391f-ada0-ddaf1417e588',
29 'ext': 'mp4',
30 'title': 'Julian Smith & Travis Legg Watch Julian Smith',
31 'description': 'Julian and Travis watch Julian Smith',
32 'duration': 6863,
33 'timestamp': 1369812016,
34 'upload_date': '20130529',
36 'skip': 'No longer exists',
37 }, {
38 'url': 'https://screen.yahoo.com/community/community-sizzle-reel-203225340.html?format=embed',
39 'md5': '7993e572fac98e044588d0b5260f4352',
40 'info_dict': {
41 'id': '4fe78544-8d48-39d8-97cd-13f205d9fcdb',
42 'ext': 'mp4',
43 'title': "Yahoo Saves 'Community'",
44 'description': 'md5:4d4145af2fd3de00cbb6c1d664105053',
45 'duration': 170,
46 'timestamp': 1406838636,
47 'upload_date': '20140731',
49 'skip': 'Unfortunately, this video is not available in your region',
50 }, {
51 'url': 'https://uk.screen.yahoo.com/editor-picks/cute-raccoon-freed-drain-using-091756545.html',
52 'md5': '71298482f7c64cbb7fa064e4553ff1c1',
53 'info_dict': {
54 'id': 'b3affa53-2e14-3590-852b-0e0db6cd1a58',
55 'ext': 'webm',
56 'title': 'Cute Raccoon Freed From Drain\u00a0Using Angle Grinder',
57 'description': 'md5:f66c890e1490f4910a9953c941dee944',
58 'duration': 97,
59 'timestamp': 1414489862,
60 'upload_date': '20141028',
62 'skip': 'No longer exists',
63 }, {
64 'url': 'http://news.yahoo.com/video/china-moses-crazy-blues-104538833.html',
65 'md5': '88e209b417f173d86186bef6e4d1f160',
66 'info_dict': {
67 'id': 'f885cf7f-43d4-3450-9fac-46ac30ece521',
68 'ext': 'mp4',
69 'title': 'China Moses Is Crazy About the Blues',
70 'description': 'md5:9900ab8cd5808175c7b3fe55b979bed0',
71 'duration': 128,
72 'timestamp': 1385722202,
73 'upload_date': '20131129',
75 }, {
76 'url': 'https://www.yahoo.com/movies/v/true-story-trailer-173000497.html',
77 'md5': '2a9752f74cb898af5d1083ea9f661b58',
78 'info_dict': {
79 'id': '071c4013-ce30-3a93-a5b2-e0413cd4a9d1',
80 'ext': 'mp4',
81 'title': '\'True Story\' Trailer',
82 'description': 'True Story',
83 'duration': 150,
84 'timestamp': 1418919206,
85 'upload_date': '20141218',
87 }, {
88 'url': 'https://gma.yahoo.com/pizza-delivery-man-surprised-huge-tip-college-kids-195200785.html',
89 'only_matching': True,
90 }, {
91 'note': 'NBC Sports embeds',
92 'url': 'http://sports.yahoo.com/blogs/ncaab-the-dagger/tyler-kalinoski-s-buzzer-beater-caps-davidson-s-comeback-win-185609842.html?guid=nbc_cbk_davidsonbuzzerbeater_150313',
93 'info_dict': {
94 'id': '9CsDKds0kvHI',
95 'ext': 'flv',
96 'description': 'md5:df390f70a9ba7c95ff1daace988f0d8d',
97 'title': 'Tyler Kalinoski hits buzzer-beater to lift Davidson',
98 'upload_date': '20150313',
99 'uploader': 'NBCU-SPORTS',
100 'timestamp': 1426270238,
102 }, {
103 'url': 'https://tw.news.yahoo.com/-100120367.html',
104 'only_matching': True,
105 }, {
106 # Query result is embedded in webpage, but explicit request to video API fails with geo restriction
107 'url': 'https://screen.yahoo.com/community/communitary-community-episode-1-ladders-154501237.html',
108 'md5': '4fbafb9c9b6f07aa8f870629f6671b35',
109 'info_dict': {
110 'id': '1f32853c-a271-3eef-8cb6-f6d6872cb504',
111 'ext': 'mp4',
112 'title': 'Communitary - Community Episode 1: Ladders',
113 'description': 'md5:8fc39608213295748e1e289807838c97',
114 'duration': 1646,
115 'timestamp': 1440436550,
116 'upload_date': '20150824',
117 'series': 'Communitary',
118 'season_number': 6,
119 'episode_number': 1,
121 'skip': 'No longer exists',
122 }, {
123 # ytwnews://cavideo/
124 'url': 'https://tw.video.yahoo.com/movie-tw/單車天使-中文版預-092316541.html',
125 'info_dict': {
126 'id': 'ba133ff2-0793-3510-b636-59dfe9ff6cff',
127 'ext': 'mp4',
128 'title': '單車天使 - 中文版預',
129 'description': '中文版預',
130 'timestamp': 1476696196,
131 'upload_date': '20161017',
133 'params': {
134 'skip_download': True,
136 }, {
137 # Contains both a Yahoo hosted video and multiple Youtube embeds
138 'url': 'https://www.yahoo.com/entertainment/gwen-stefani-reveals-the-pop-hit-she-passed-on-assigns-it-to-her-voice-contestant-instead-033045672.html',
139 'info_dict': {
140 'id': '46c5d95a-528f-3d03-b732-732fcadd51de',
141 'title': 'Gwen Stefani reveals the pop hit she passed on, assigns it to her \'Voice\' contestant instead',
142 'description': 'Gwen decided not to record this hit herself, but she decided it was the perfect fit for Kyndall Inskeep.',
144 'playlist': [{
145 'info_dict': {
146 'id': '966d4262-4fd1-3aaa-b45b-049ca6e38ba6',
147 'ext': 'mp4',
148 'title': 'Gwen Stefani reveals she turned down one of Sia\'s best songs',
149 'description': 'On "The Voice" Tuesday, Gwen Stefani told Taylor Swift which Sia hit was almost hers.',
150 'timestamp': 1572406500,
151 'upload_date': '20191030',
153 }, {
154 'info_dict': {
155 'id': '352CFDOQrKg',
156 'ext': 'mp4',
157 'title': 'Kyndal Inskeep "Performs the Hell Out of" Sia\'s "Elastic Heart" - The Voice Knockouts 2019',
158 'description': 'md5:7fe8e3d5806f96002e55f190d1d94479',
159 'uploader': 'The Voice',
160 'uploader_id': 'NBCTheVoice',
161 'upload_date': '20191029',
164 'params': {
165 'playlistend': 2,
167 'expected_warnings': ['HTTP Error 404', 'Ignoring subtitle tracks'],
168 }, {
169 'url': 'https://malaysia.news.yahoo.com/video/bystanders-help-ontario-policeman-bust-190932818.html',
170 'only_matching': True,
171 }, {
172 'url': 'https://es-us.noticias.yahoo.com/es-la-puerta-irrompible-que-110539379.html',
173 'only_matching': True,
174 }, {
175 'url': 'https://www.yahoo.com/entertainment/v/longtime-cbs-news-60-minutes-032036500-cbs.html',
176 'only_matching': True,
179 def _extract_yahoo_video(self, video_id, country):
180 video = self._download_json(
181 f'https://{country}.yahoo.com/_td/api/resource/VideoService.videos;view=full;video_ids=["{video_id}"]',
182 video_id, 'Downloading video JSON metadata')[0]
183 title = video['title']
185 if country == 'malaysia':
186 country = 'my'
188 is_live = video.get('live_state') == 'live'
189 fmts = ('m3u8',) if is_live else ('webm', 'mp4')
191 urls = []
192 formats = []
193 subtitles = {}
194 for fmt in fmts:
195 media_obj = self._download_json(
196 'https://video-api.yql.yahoo.com/v1/video/sapi/streams/' + video_id,
197 video_id, f'Downloading {fmt} JSON metadata',
198 headers=self.geo_verification_headers(), query={
199 'format': fmt,
200 'region': country.upper(),
201 })['query']['results']['mediaObj'][0]
202 msg = media_obj.get('status', {}).get('msg')
204 for s in media_obj.get('streams', []):
205 host = s.get('host')
206 path = s.get('path')
207 if not host or not path:
208 continue
209 s_url = host + path
210 if s.get('format') == 'm3u8':
211 formats.extend(self._extract_m3u8_formats(
212 s_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
213 continue
214 tbr = int_or_none(s.get('bitrate'))
215 formats.append({
216 'url': s_url,
217 'format_id': join_nonempty(fmt, tbr),
218 'width': int_or_none(s.get('width')),
219 'height': int_or_none(s.get('height')),
220 'tbr': tbr,
221 'fps': int_or_none(s.get('framerate')),
224 for cc in media_obj.get('closedcaptions', []):
225 cc_url = cc.get('url')
226 if not cc_url or cc_url in urls:
227 continue
228 urls.append(cc_url)
229 subtitles.setdefault(cc.get('lang') or 'en-US', []).append({
230 'url': cc_url,
231 'ext': mimetype2ext(cc.get('content_type')),
234 streaming_url = video.get('streaming_url')
235 if streaming_url and not is_live:
236 formats.extend(self._extract_m3u8_formats(
237 streaming_url, video_id, 'mp4',
238 'm3u8_native', m3u8_id='hls', fatal=False))
240 if not formats and msg == 'geo restricted':
241 self.raise_geo_restricted(metadata_available=True)
243 thumbnails = []
244 for thumb in video.get('thumbnails', []):
245 thumb_url = thumb.get('url')
246 if not thumb_url:
247 continue
248 thumbnails.append({
249 'id': thumb.get('tag'),
250 'url': thumb.get('url'),
251 'width': int_or_none(thumb.get('width')),
252 'height': int_or_none(thumb.get('height')),
255 series_info = video.get('series_info') or {}
257 return {
258 'id': video_id,
259 'title': title,
260 'formats': formats,
261 'thumbnails': thumbnails,
262 'description': clean_html(video.get('description')),
263 'timestamp': parse_iso8601(video.get('publish_time')),
264 'subtitles': subtitles,
265 'duration': int_or_none(video.get('duration')),
266 'view_count': int_or_none(video.get('view_count')),
267 'is_live': is_live,
268 'series': video.get('show_name'),
269 'season_number': int_or_none(series_info.get('season_number')),
270 'episode_number': int_or_none(series_info.get('episode_number')),
273 def _real_extract(self, url):
274 url, country, display_id = self._match_valid_url(url).groups()
275 if not country:
276 country = 'us'
277 else:
278 country = country.split('-')[0]
280 items = self._download_json(
281 f'https://{country}.yahoo.com/caas/content/article', display_id,
282 'Downloading content JSON metadata', query={
283 'url': url,
284 })['items'][0]
286 item = items['data']['partnerData']
287 if item.get('type') != 'video':
288 entries = []
290 cover = item.get('cover') or {}
291 if cover.get('type') == 'yvideo':
292 cover_url = cover.get('url')
293 if cover_url:
294 entries.append(self.url_result(
295 cover_url, 'Yahoo', cover.get('uuid')))
297 for e in (item.get('body') or []):
298 if e.get('type') == 'videoIframe':
299 iframe_url = e.get('url')
300 if iframe_url:
301 entries.append(self.url_result(iframe_url))
303 if item.get('type') == 'storywithleadvideo':
304 iframe_url = try_get(item, lambda x: x['meta']['player']['url'])
305 if iframe_url:
306 entries.append(self.url_result(iframe_url))
307 else:
308 self.report_warning("Yahoo didn't provide an iframe url for this storywithleadvideo")
310 if items.get('markup'):
311 entries.extend(
312 self.url_result(yt_url) for yt_url in YoutubeIE._extract_embed_urls(url, items['markup']))
314 return self.playlist_result(
315 entries, item.get('uuid'),
316 item.get('title'), item.get('summary'))
318 info = self._extract_yahoo_video(item['uuid'], country)
319 info['display_id'] = display_id
320 return info
323 class YahooSearchIE(SearchInfoExtractor):
324 IE_DESC = 'Yahoo screen search'
325 _MAX_RESULTS = 1000
326 IE_NAME = 'screen.yahoo:search'
327 _SEARCH_KEY = 'yvsearch'
329 def _search_results(self, query):
330 for pagenum in itertools.count(0):
331 result_url = f'http://video.search.yahoo.com/search/?p={urllib.parse.quote_plus(query)}&fr=screen&o=js&gs=0&b={pagenum * 30}'
332 info = self._download_json(result_url, query,
333 note='Downloading results page ' + str(pagenum + 1))
334 yield from (self.url_result(result['rurl']) for result in info['results'])
335 if info['m']['last'] >= info['m']['total'] - 1:
336 break
339 class YahooJapanNewsIE(InfoExtractor):
340 IE_NAME = 'yahoo:japannews'
341 IE_DESC = 'Yahoo! Japan News'
342 _VALID_URL = r'https?://news\.yahoo\.co\.jp/(?:articles|feature)/(?P<id>[a-zA-Z0-9]+)'
343 _GEO_COUNTRIES = ['JP']
344 _TESTS = [{
345 'url': 'https://news.yahoo.co.jp/articles/a70fe3a064f1cfec937e2252c7fc6c1ba3201c0e',
346 'info_dict': {
347 'id': 'a70fe3a064f1cfec937e2252c7fc6c1ba3201c0e',
348 'ext': 'mp4',
349 'title': '【独自】安倍元総理「国葬」中止求め“脅迫メール”…「子ども誘拐」“送信者”を追跡',
350 'description': 'md5:1c06974575f930f692d8696fbcfdc546',
351 'thumbnail': r're:https://.+',
353 'params': {
354 'skip_download': True,
356 }, {
357 'url': 'https://news.yahoo.co.jp/feature/1356',
358 'only_matching': True,
361 def _extract_formats(self, json_data, content_id):
362 formats = []
364 for vid in traverse_obj(json_data, ('ResultSet', 'Result', ..., 'VideoUrlSet', 'VideoUrl', ...)) or []:
365 delivery = vid.get('delivery')
366 url = url_or_none(vid.get('Url'))
367 if not delivery or not url:
368 continue
369 elif delivery == 'hls':
370 formats.extend(
371 self._extract_m3u8_formats(
372 url, content_id, 'mp4', 'm3u8_native',
373 m3u8_id='hls', fatal=False))
374 else:
375 bitrate = int_or_none(vid.get('bitrate'))
376 formats.append({
377 'url': url,
378 'format_id': join_nonempty('http', bitrate),
379 'height': int_or_none(vid.get('height')),
380 'width': int_or_none(vid.get('width')),
381 'tbr': bitrate,
383 self._remove_duplicate_formats(formats)
385 return formats
387 def _real_extract(self, url):
388 video_id = self._match_id(url)
389 webpage = self._download_webpage(url, video_id)
390 preloaded_state = self._search_json(r'__PRELOADED_STATE__\s*=', webpage, 'preloaded state', video_id)
392 content_id = traverse_obj(
393 preloaded_state, ('articleDetail', 'paragraphs', ..., 'objectItems', ..., 'video', 'vid'),
394 get_all=False, expected_type=int)
395 if content_id is None:
396 raise ExtractorError('This article does not contain a video', expected=True)
398 HOST = 'news.yahoo.co.jp'
399 space_id = traverse_obj(preloaded_state, ('pageData', 'spaceId'), expected_type=str)
400 json_data = self._download_json(
401 f'https://feapi-yvpub.yahooapis.jp/v1/content/{content_id}',
402 video_id, query={
403 'appid': 'dj0zaiZpPVZMTVFJR0FwZWpiMyZzPWNvbnN1bWVyc2VjcmV0Jng9YjU-',
404 'output': 'json',
405 'domain': HOST,
406 'ak': hashlib.md5('_'.join((space_id, HOST)).encode()).hexdigest() if space_id else '',
407 'device_type': '1100',
410 title = (
411 traverse_obj(preloaded_state,
412 ('articleDetail', 'headline'), ('pageData', 'pageParam', 'title'),
413 expected_type=str)
414 or self._html_search_meta(('og:title', 'twitter:title'), webpage, 'title', default=None)
415 or self._html_extract_title(webpage))
416 description = (
417 traverse_obj(preloaded_state, ('pageData', 'description'), expected_type=str)
418 or self._html_search_meta(
419 ('og:description', 'description', 'twitter:description'),
420 webpage, 'description', default=None))
421 thumbnail = (
422 traverse_obj(preloaded_state, ('pageData', 'ogpImage'), expected_type=str)
423 or self._og_search_thumbnail(webpage, default=None)
424 or self._html_search_meta('twitter:image', webpage, 'thumbnail', default=None))
426 return {
427 'id': video_id,
428 'title': title,
429 'description': description,
430 'thumbnail': thumbnail,
431 'formats': self._extract_formats(json_data, video_id),