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