]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/youku.py
[extractor/youku] Fix extractor (#5622)
[yt-dlp.git] / yt_dlp / extractor / youku.py
1 import random
2 import re
3 import string
4 import time
5
6 from .common import InfoExtractor
7 from ..utils import (
8 ExtractorError,
9 get_element_by_class,
10 js_to_json,
11 str_or_none,
12 strip_jsonp,
13 )
14
15
16 class YoukuIE(InfoExtractor):
17 IE_NAME = 'youku'
18 IE_DESC = '优酷'
19 _VALID_URL = r'''(?x)
20 (?:
21 https?://(
22 (?:v|player)\.youku\.com/(?:v_show/id_|player\.php/sid/)|
23 video\.tudou\.com/v/)|
24 youku:)
25 (?P<id>[A-Za-z0-9]+)(?:\.html|/v\.swf|)
26 '''
27
28 _TESTS = [{
29 # MD5 is unstable
30 'url': 'http://v.youku.com/v_show/id_XMTc1ODE5Njcy.html',
31 'info_dict': {
32 'id': 'XMTc1ODE5Njcy',
33 'title': '★Smile﹗♡ Git Fresh -Booty Music舞蹈.',
34 'ext': 'mp4',
35 'duration': 74.73,
36 'thumbnail': r're:^https?://.*',
37 'uploader': '。躲猫猫、',
38 'uploader_id': '36017967',
39 'uploader_url': 'http://i.youku.com/u/UMTQ0MDcxODY4',
40 'tags': list,
41 }
42 }, {
43 'url': 'http://player.youku.com/player.php/sid/XNDgyMDQ2NTQw/v.swf',
44 'only_matching': True,
45 }, {
46 'url': 'http://v.youku.com/v_show/id_XODgxNjg1Mzk2_ev_1.html',
47 'info_dict': {
48 'id': 'XODgxNjg1Mzk2',
49 'ext': 'mp4',
50 'title': '武媚娘传奇 85',
51 'duration': 1999.61,
52 'thumbnail': r're:^https?://.*',
53 'uploader': '疯狂豆花',
54 'uploader_id': '62583473',
55 'uploader_url': 'http://i.youku.com/u/UMjUwMzMzODky',
56 'tags': list,
57 },
58 }, {
59 'url': 'http://v.youku.com/v_show/id_XMTI1OTczNDM5Mg==.html',
60 'info_dict': {
61 'id': 'XMTI1OTczNDM5Mg',
62 'ext': 'mp4',
63 'title': '花千骨 04',
64 'duration': 2363,
65 'thumbnail': r're:^https?://.*',
66 'uploader': '放剧场-花千骨',
67 'uploader_id': '772849359',
68 'uploader_url': 'http://i.youku.com/u/UMzA5MTM5NzQzNg==',
69 'tags': list,
70 },
71 }, {
72 'url': 'http://v.youku.com/v_show/id_XNjA1NzA2Njgw.html',
73 'note': 'Video protected with password',
74 'info_dict': {
75 'id': 'XNjA1NzA2Njgw',
76 'ext': 'mp4',
77 'title': '邢義田复旦讲座之想象中的胡人—从“左衽孔子”说起',
78 'duration': 7264.5,
79 'thumbnail': r're:^https?://.*',
80 'uploader': 'FoxJin1006',
81 'uploader_id': '322014285',
82 'uploader_url': 'http://i.youku.com/u/UMTI4ODA1NzE0MA==',
83 'tags': list,
84 },
85 'params': {
86 'videopassword': '100600',
87 },
88 }, {
89 # /play/get.json contains streams with "channel_type":"tail"
90 'url': 'http://v.youku.com/v_show/id_XOTUxMzg4NDMy.html',
91 'info_dict': {
92 'id': 'XOTUxMzg4NDMy',
93 'ext': 'mp4',
94 'title': '我的世界☆明月庄主☆车震猎杀☆杀人艺术Minecraft',
95 'duration': 702.08,
96 'thumbnail': r're:^https?://.*',
97 'uploader': '明月庄主moon',
98 'uploader_id': '38465621',
99 'uploader_url': 'https://www.youku.com/profile/index/?uid=UMTUzODYyNDg0',
100 'tags': list,
101 },
102 }, {
103 'url': 'https://v.youku.com/v_show/id_XNTA2NTA0MjA1Mg==.html',
104 'info_dict': {
105 'id': 'XNTA2NTA0MjA1Mg',
106 'ext': 'mp4',
107 'title': 'Minecraft我的世界:建造超大巨型航空飞机,菜鸟vs高手vs黑客',
108 'duration': 542.13,
109 'thumbnail': r're:^https?://.*',
110 'uploader': '波哥游戏解说',
111 'uploader_id': '156688084',
112 'uploader_url': 'https://www.youku.com/profile/index/?uid=UNjI2NzUyMzM2',
113 'tags': list,
114 },
115 }, {
116 'url': 'https://v.youku.com/v_show/id_XNTE1MzczOTg4MA==.html',
117 'info_dict': {
118 'id': 'XNTE1MzczOTg4MA',
119 'ext': 'mp4',
120 'title': '国产超A特工片',
121 'duration': 362.97,
122 'thumbnail': r're:^https?://.*',
123 'uploader': '陈晓娟说历史',
124 'uploader_id': '1640913339',
125 'uploader_url': 'https://www.youku.com/profile/index/?uid=UNjU2MzY1MzM1Ng==',
126 'tags': list,
127 },
128 }]
129
130 @staticmethod
131 def get_ysuid():
132 return '%d%s' % (int(time.time()), ''.join([
133 random.choice(string.ascii_letters) for i in range(3)]))
134
135 def get_format_name(self, fm):
136 _dict = {
137 '3gp': 'h6',
138 '3gphd': 'h5',
139 'flv': 'h4',
140 'flvhd': 'h4',
141 'mp4': 'h3',
142 'mp4hd': 'h3',
143 'mp4hd2': 'h4',
144 'mp4hd3': 'h4',
145 'hd2': 'h2',
146 'hd3': 'h1',
147 }
148 return _dict.get(fm)
149
150 def _real_extract(self, url):
151 video_id = self._match_id(url)
152
153 self._set_cookie('youku.com', '__ysuid', self.get_ysuid())
154 self._set_cookie('youku.com', 'xreferrer', 'http://www.youku.com')
155
156 _, urlh = self._download_webpage_handle(
157 'https://log.mmstat.com/eg.js', video_id, 'Retrieving cna info')
158 # The etag header is '"foobar"'; let's remove the double quotes
159 cna = urlh.headers['etag'][1:-1]
160
161 # request basic data
162 basic_data_params = {
163 'vid': video_id,
164 'ccode': '0524',
165 'client_ip': '192.168.1.1',
166 'utid': cna,
167 'client_ts': time.time() / 1000,
168 }
169
170 video_password = self.get_param('videopassword')
171 if video_password:
172 basic_data_params['password'] = video_password
173
174 headers = {
175 'Referer': url,
176 }
177 headers.update(self.geo_verification_headers())
178 data = self._download_json(
179 'https://ups.youku.com/ups/get.json', video_id,
180 'Downloading JSON metadata',
181 query=basic_data_params, headers=headers)['data']
182
183 error = data.get('error')
184 if error:
185 error_note = error.get('note')
186 if error_note is not None and '因版权原因无法观看此视频' in error_note:
187 raise ExtractorError(
188 'Youku said: Sorry, this video is available in China only', expected=True)
189 elif error_note and '该视频被设为私密' in error_note:
190 raise ExtractorError(
191 'Youku said: Sorry, this video is private', expected=True)
192 else:
193 msg = 'Youku server reported error %i' % error.get('code')
194 if error_note is not None:
195 msg += ': ' + error_note
196 raise ExtractorError(msg)
197
198 # get video title
199 video_data = data['video']
200 title = video_data['title']
201
202 formats = [{
203 'url': stream['m3u8_url'],
204 'format_id': self.get_format_name(stream.get('stream_type')),
205 'ext': 'mp4',
206 'protocol': 'm3u8_native',
207 'filesize': int(stream.get('size')),
208 'width': stream.get('width'),
209 'height': stream.get('height'),
210 } for stream in data['stream'] if stream.get('channel_type') != 'tail']
211
212 return {
213 'id': video_id,
214 'title': title,
215 'formats': formats,
216 'duration': video_data.get('seconds'),
217 'thumbnail': video_data.get('logo'),
218 'uploader': video_data.get('username'),
219 'uploader_id': str_or_none(video_data.get('userid')),
220 'uploader_url': data.get('uploader', {}).get('homepage'),
221 'tags': video_data.get('tags'),
222 }
223
224
225 class YoukuShowIE(InfoExtractor):
226 _VALID_URL = r'https?://list\.youku\.com/show/id_(?P<id>[0-9a-z]+)\.html'
227 IE_NAME = 'youku:show'
228
229 _TESTS = [{
230 'url': 'http://list.youku.com/show/id_zc7c670be07ff11e48b3f.html',
231 'info_dict': {
232 'id': 'zc7c670be07ff11e48b3f',
233 'title': '花千骨 DVD版',
234 'description': 'md5:a1ae6f5618571bbeb5c9821f9c81b558',
235 },
236 'playlist_count': 50,
237 }, {
238 # Episode number not starting from 1
239 'url': 'http://list.youku.com/show/id_zefbfbd70efbfbd780bef.html',
240 'info_dict': {
241 'id': 'zefbfbd70efbfbd780bef',
242 'title': '超级飞侠3',
243 'description': 'md5:275715156abebe5ccc2a1992e9d56b98',
244 },
245 'playlist_count': 24,
246 }, {
247 # Ongoing playlist. The initial page is the last one
248 'url': 'http://list.youku.com/show/id_za7c275ecd7b411e1a19e.html',
249 'only_matching': True,
250 }, {
251 # No data-id value.
252 'url': 'http://list.youku.com/show/id_zefbfbd61237fefbfbdef.html',
253 'only_matching': True,
254 }, {
255 # Wrong number of reload_id.
256 'url': 'http://list.youku.com/show/id_z20eb4acaf5c211e3b2ad.html',
257 'only_matching': True,
258 }]
259
260 def _extract_entries(self, playlist_data_url, show_id, note, query):
261 query['callback'] = 'cb'
262 playlist_data = self._download_json(
263 playlist_data_url, show_id, query=query, note=note,
264 transform_source=lambda s: js_to_json(strip_jsonp(s))).get('html')
265 if playlist_data is None:
266 return [None, None]
267 drama_list = (get_element_by_class('p-drama-grid', playlist_data)
268 or get_element_by_class('p-drama-half-row', playlist_data))
269 if drama_list is None:
270 raise ExtractorError('No episodes found')
271 video_urls = re.findall(r'<a[^>]+href="([^"]+)"', drama_list)
272 return playlist_data, [
273 self.url_result(self._proto_relative_url(video_url, 'http:'), YoukuIE.ie_key())
274 for video_url in video_urls]
275
276 def _real_extract(self, url):
277 show_id = self._match_id(url)
278 webpage = self._download_webpage(url, show_id)
279
280 entries = []
281 page_config = self._parse_json(self._search_regex(
282 r'var\s+PageConfig\s*=\s*({.+});', webpage, 'page config'),
283 show_id, transform_source=js_to_json)
284 first_page, initial_entries = self._extract_entries(
285 'http://list.youku.com/show/module', show_id,
286 note='Downloading initial playlist data page',
287 query={
288 'id': page_config['showid'],
289 'tab': 'showInfo',
290 })
291 first_page_reload_id = self._html_search_regex(
292 r'<div[^>]+id="(reload_\d+)', first_page, 'first page reload id')
293 # The first reload_id has the same items as first_page
294 reload_ids = re.findall('<li[^>]+data-id="([^"]+)">', first_page)
295 entries.extend(initial_entries)
296 for idx, reload_id in enumerate(reload_ids):
297 if reload_id == first_page_reload_id:
298 continue
299 _, new_entries = self._extract_entries(
300 'http://list.youku.com/show/episode', show_id,
301 note='Downloading playlist data page %d' % (idx + 1),
302 query={
303 'id': page_config['showid'],
304 'stage': reload_id,
305 })
306 if new_entries is not None:
307 entries.extend(new_entries)
308 desc = self._html_search_meta('description', webpage, fatal=False)
309 playlist_title = desc.split(',')[0] if desc else None
310 detail_li = get_element_by_class('p-intro', webpage)
311 playlist_description = get_element_by_class(
312 'intro-more', detail_li) if detail_li else None
313
314 return self.playlist_result(
315 entries, show_id, playlist_title, playlist_description)