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