[yahoo] Add an extractor for yahoo news (closes #1849)
[youtube-dl] / youtube_dl / extractor / yahoo.py
1 import itertools
2 import json
3 import re
4
5 from .common import InfoExtractor, SearchInfoExtractor
6 from ..utils import (
7     compat_urllib_parse,
8     compat_urlparse,
9     determine_ext,
10     clean_html,
11 )
12
13
14 class YahooIE(InfoExtractor):
15     IE_DESC = u'Yahoo screen'
16     _VALID_URL = r'http://screen\.yahoo\.com/.*?-(?P<id>\d*?)\.html'
17     _TESTS = [
18         {
19             u'url': u'http://screen.yahoo.com/julian-smith-travis-legg-watch-214727115.html',
20             u'file': u'214727115.flv',
21             u'info_dict': {
22                 u'title': u'Julian Smith & Travis Legg Watch Julian Smith',
23                 u'description': u'Julian and Travis watch Julian Smith',
24             },
25             u'params': {
26                 # Requires rtmpdump
27                 u'skip_download': True,
28             },
29         },
30         {
31             u'url': u'http://screen.yahoo.com/wired/codefellas-s1-ep12-cougar-lies-103000935.html',
32             u'file': u'103000935.flv',
33             u'info_dict': {
34                 u'title': u'Codefellas - The Cougar Lies with Spanish Moss',
35                 u'description': u'Agent Topple\'s mustache does its dirty work, and Nicole brokers a deal for peace. But why is the NSA collecting millions of Instagram brunch photos? And if your waffles have nothing to hide, what are they so worried about?',
36             },
37             u'params': {
38                 # Requires rtmpdump
39                 u'skip_download': True,
40             },
41         },
42     ]
43
44     def _real_extract(self, url):
45         mobj = re.match(self._VALID_URL, url)
46         video_id = mobj.group('id')
47         webpage = self._download_webpage(url, video_id)
48
49         items_json = self._search_regex(r'mediaItems: ({.*?})$',
50             webpage, u'items', flags=re.MULTILINE)
51         items = json.loads(items_json)
52         info = items['mediaItems']['query']['results']['mediaObj'][0]
53         # The 'meta' field is not always in the video webpage, we request it
54         # from another page
55         long_id = info['id']
56         return self._get_info(info['id'], video_id)
57
58     def _get_info(self, long_id, video_id):
59         query = ('SELECT * FROM yahoo.media.video.streams WHERE id="%s"'
60                  ' AND plrs="86Gj0vCaSzV_Iuf6hNylf2" AND region="US"' % long_id)
61         data = compat_urllib_parse.urlencode({
62             'q': query,
63             'env': 'prod',
64             'format': 'json',
65         })
66         query_result_json = self._download_webpage(
67             'http://video.query.yahoo.com/v1/public/yql?' + data,
68             video_id, u'Downloading video info')
69         query_result = json.loads(query_result_json)
70         info = query_result['query']['results']['mediaObj'][0]
71         meta = info['meta']
72
73         formats = []
74         for s in info['streams']:
75             format_info = {
76                 'width': s.get('width'),
77                 'height': s.get('height'),
78                 'bitrate': s.get('bitrate'),
79             }
80
81             host = s['host']
82             path = s['path']
83             if host.startswith('rtmp'):
84                 format_info.update({
85                     'url': host,
86                     'play_path': path,
87                     'ext': 'flv',
88                 })
89             else:
90                 format_url = compat_urlparse.urljoin(host, path)
91                 format_info['url'] = format_url
92                 format_info['ext'] = determine_ext(format_url)
93                 
94             formats.append(format_info)
95         formats = sorted(formats, key=lambda f:(f['height'], f['width']))
96
97         return {
98             'id': video_id,
99             'title': meta['title'],
100             'formats': formats,
101             'description': clean_html(meta['description']),
102             'thumbnail': meta['thumbnail'],
103         }
104
105
106 class YahooNewsIE(YahooIE):
107     IE_NAME = 'yahoo:news'
108     _VALID_URL = r'http://news\.yahoo\.com/video/.*?-(?P<id>\d*?)\.html'
109
110     _TEST = {
111         u'url': u'http://news.yahoo.com/video/china-moses-crazy-blues-104538833.html',
112         u'info_dict': {
113             u'id': u'104538833',
114             u'ext': u'flv',
115             u'title': u'China Moses Is Crazy About the Blues',
116             u'description': u'md5:9900ab8cd5808175c7b3fe55b979bed0',
117         },
118         u'params': {
119             # Requires rtmpdump
120             u'skip_download': True,
121         },
122     }
123
124     # Overwrite YahooIE properties we don't want
125     _TESTS = []
126
127     def _real_extract(self, url):
128         mobj = re.match(self._VALID_URL, url)
129         video_id = mobj.group('id')
130         webpage = self._download_webpage(url, video_id)
131         long_id = self._search_regex(r'contentId: \'(.+?)\',', webpage, u'long id')
132         return self._get_info(long_id, video_id)
133
134
135 class YahooSearchIE(SearchInfoExtractor):
136     IE_DESC = u'Yahoo screen search'
137     _MAX_RESULTS = 1000
138     IE_NAME = u'screen.yahoo:search'
139     _SEARCH_KEY = 'yvsearch'
140
141     def _get_n_results(self, query, n):
142         """Get a specified number of results for a query"""
143
144         res = {
145             '_type': 'playlist',
146             'id': query,
147             'entries': []
148         }
149         for pagenum in itertools.count(0): 
150             result_url = u'http://video.search.yahoo.com/search/?p=%s&fr=screen&o=js&gs=0&b=%d' % (compat_urllib_parse.quote_plus(query), pagenum * 30)
151             webpage = self._download_webpage(result_url, query,
152                                              note='Downloading results page '+str(pagenum+1))
153             info = json.loads(webpage)
154             m = info[u'm']
155             results = info[u'results']
156
157             for (i, r) in enumerate(results):
158                 if (pagenum * 30) +i >= n:
159                     break
160                 mobj = re.search(r'(?P<url>screen\.yahoo\.com/.*?-\d*?\.html)"', r)
161                 e = self.url_result('http://' + mobj.group('url'), 'Yahoo')
162                 res['entries'].append(e)
163             if (pagenum * 30 +i >= n) or (m[u'last'] >= (m[u'total'] -1)):
164                 break
165
166         return res