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