[youku:show] Fix extraction
[youtube-dl] / youtube_dl / extractor / youku.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import itertools
5 import random
6 import re
7 import string
8 import time
9
10 from .common import InfoExtractor
11 from ..utils import (
12     ExtractorError,
13     get_element_by_class,
14     js_to_json,
15     strip_jsonp,
16     urljoin,
17 )
18
19
20 class YoukuIE(InfoExtractor):
21     IE_NAME = 'youku'
22     IE_DESC = '优酷'
23     _VALID_URL = r'''(?x)
24         (?:
25             http://(?:v|player)\.youku\.com/(?:v_show/id_|player\.php/sid/)|
26             youku:)
27         (?P<id>[A-Za-z0-9]+)(?:\.html|/v\.swf|)
28     '''
29
30     _TESTS = [{
31         # MD5 is unstable
32         'url': 'http://v.youku.com/v_show/id_XMTc1ODE5Njcy.html',
33         'info_dict': {
34             'id': 'XMTc1ODE5Njcy',
35             'title': '★Smile﹗♡ Git Fresh -Booty Music舞蹈.',
36             'ext': 'mp4',
37         }
38     }, {
39         'url': 'http://player.youku.com/player.php/sid/XNDgyMDQ2NTQw/v.swf',
40         'only_matching': True,
41     }, {
42         'url': 'http://v.youku.com/v_show/id_XODgxNjg1Mzk2_ev_1.html',
43         'info_dict': {
44             'id': 'XODgxNjg1Mzk2',
45             'ext': 'mp4',
46             'title': '武媚娘传奇 85',
47         },
48     }, {
49         'url': 'http://v.youku.com/v_show/id_XMTI1OTczNDM5Mg==.html',
50         'info_dict': {
51             'id': 'XMTI1OTczNDM5Mg',
52             'ext': 'mp4',
53             'title': '花千骨 04',
54         },
55     }, {
56         'url': 'http://v.youku.com/v_show/id_XNjA1NzA2Njgw.html',
57         'note': 'Video protected with password',
58         'info_dict': {
59             'id': 'XNjA1NzA2Njgw',
60             'ext': 'mp4',
61             'title': '邢義田复旦讲座之想象中的胡人—从“左衽孔子”说起',
62         },
63         'params': {
64             'videopassword': '100600',
65         },
66     }, {
67         # /play/get.json contains streams with "channel_type":"tail"
68         'url': 'http://v.youku.com/v_show/id_XOTUxMzg4NDMy.html',
69         'info_dict': {
70             'id': 'XOTUxMzg4NDMy',
71             'ext': 'mp4',
72             'title': '我的世界☆明月庄主☆车震猎杀☆杀人艺术Minecraft',
73         },
74     }]
75
76     @staticmethod
77     def get_ysuid():
78         return '%d%s' % (int(time.time()), ''.join([
79             random.choice(string.ascii_letters) for i in range(3)]))
80
81     def get_format_name(self, fm):
82         _dict = {
83             '3gp': 'h6',
84             '3gphd': 'h5',
85             'flv': 'h4',
86             'flvhd': 'h4',
87             'mp4': 'h3',
88             'mp4hd': 'h3',
89             'mp4hd2': 'h4',
90             'mp4hd3': 'h4',
91             'hd2': 'h2',
92             'hd3': 'h1',
93         }
94         return _dict.get(fm)
95
96     def _real_extract(self, url):
97         video_id = self._match_id(url)
98
99         self._set_cookie('youku.com', '__ysuid', self.get_ysuid())
100         self._set_cookie('youku.com', 'xreferrer', 'http://www.youku.com')
101
102         _, urlh = self._download_webpage_handle(
103             'https://log.mmstat.com/eg.js', video_id, 'Retrieving cna info')
104         # The etag header is '"foobar"'; let's remove the double quotes
105         cna = urlh.headers['etag'][1:-1]
106
107         # request basic data
108         basic_data_params = {
109             'vid': video_id,
110             'ccode': '0401',
111             'client_ip': '192.168.1.1',
112             'utid': cna,
113             'client_ts': time.time() / 1000,
114         }
115
116         video_password = self._downloader.params.get('videopassword')
117         if video_password:
118             basic_data_params['password'] = video_password
119
120         headers = {
121             'Referer': url,
122         }
123         headers.update(self.geo_verification_headers())
124         data = self._download_json(
125             'https://ups.youku.com/ups/get.json', video_id,
126             'Downloading JSON metadata',
127             query=basic_data_params, headers=headers)['data']
128
129         error = data.get('error')
130         if error:
131             error_note = error.get('note')
132             if error_note is not None and '因版权原因无法观看此视频' in error_note:
133                 raise ExtractorError(
134                     'Youku said: Sorry, this video is available in China only', expected=True)
135             elif error_note and '该视频被设为私密' in error_note:
136                 raise ExtractorError(
137                     'Youku said: Sorry, this video is private', expected=True)
138             else:
139                 msg = 'Youku server reported error %i' % error.get('code')
140                 if error_note is not None:
141                     msg += ': ' + error_note
142                 raise ExtractorError(msg)
143
144         # get video title
145         title = data['video']['title']
146
147         formats = [{
148             'url': stream['m3u8_url'],
149             'format_id': self.get_format_name(stream.get('stream_type')),
150             'ext': 'mp4',
151             'protocol': 'm3u8_native',
152             'filesize': int(stream.get('size')),
153             'width': stream.get('width'),
154             'height': stream.get('height'),
155         } for stream in data['stream'] if stream.get('channel_type') != 'tail']
156         self._sort_formats(formats)
157
158         return {
159             'id': video_id,
160             'title': title,
161             'formats': formats,
162         }
163
164
165 class YoukuShowIE(InfoExtractor):
166     _VALID_URL = r'https?://list\.youku\.com/show/id_(?P<id>[0-9a-z]+)\.html'
167     IE_NAME = 'youku:show'
168
169     _TEST = {
170         'url': 'http://list.youku.com/show/id_zc7c670be07ff11e48b3f.html',
171         'info_dict': {
172             'id': 'zc7c670be07ff11e48b3f',
173             'title': '花千骨 未删减版',
174             'description': 'md5:a1ae6f5618571bbeb5c9821f9c81b558',
175         },
176         'playlist_count': 50,
177     }
178
179     _PAGE_SIZE = 40
180
181     def _real_extract(self, url):
182         show_id = self._match_id(url)
183         webpage = self._download_webpage(url, show_id)
184
185         entries = []
186         page_config = self._parse_json(self._search_regex(
187             r'var\s+PageConfig\s*=\s*({.+});', webpage, 'page config'),
188             show_id, transform_source=js_to_json)
189         for idx in itertools.count(0):
190             if idx == 0:
191                 playlist_data_url = 'http://list.youku.com/show/module'
192                 query = {'id': page_config['showid'], 'tab': 'point'}
193             else:
194                 playlist_data_url = 'http://list.youku.com/show/point'
195                 query = {
196                     'id': page_config['showid'],
197                     'stage': 'reload_%d' % (self._PAGE_SIZE * idx + 1),
198                 }
199             query['callback'] = 'cb'
200             playlist_data = self._download_json(
201                 playlist_data_url, show_id, query=query,
202                 note='Downloading playlist data page %d' % (idx + 1),
203                 transform_source=lambda s: js_to_json(strip_jsonp(s)))['html']
204             video_urls = re.findall(
205                 r'<div[^>]+class="p-thumb"[^<]+<a[^>]+href="([^"]+)"',
206                 playlist_data)
207             new_entries = [
208                 self.url_result(urljoin(url, video_url), YoukuIE.ie_key())
209                 for video_url in video_urls]
210             entries.extend(new_entries)
211             if len(new_entries) < self._PAGE_SIZE:
212                 break
213
214         desc = self._html_search_meta('description', webpage, fatal=False)
215         playlist_title = desc.split(',')[0] if desc else None
216         detail_li = get_element_by_class('p-intro', webpage)
217         playlist_description = get_element_by_class(
218             'intro-more', detail_li) if detail_li else None
219
220         return self.playlist_result(
221             entries, show_id, playlist_title, playlist_description)