[iqiyi] Mark broken
[youtube-dl] / youtube_dl / extractor / iqiyi.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import hashlib
5 import itertools
6 import math
7 import os
8 import random
9 import re
10 import time
11 import uuid
12
13 from .common import InfoExtractor
14 from ..compat import (
15     compat_parse_qs,
16     compat_str,
17     compat_urllib_parse_urlencode,
18     compat_urllib_parse_urlparse,
19 )
20 from ..utils import (
21     decode_packed_codes,
22     ExtractorError,
23     ohdave_rsa_encrypt,
24     remove_start,
25     sanitized_Request,
26     urlencode_postdata,
27     url_basename,
28 )
29
30
31 def md5_text(text):
32     return hashlib.md5(text.encode('utf-8')).hexdigest()
33
34
35 class IqiyiSDK(object):
36     def __init__(self, target, ip, timestamp):
37         self.target = target
38         self.ip = ip
39         self.timestamp = timestamp
40
41     @staticmethod
42     def split_sum(data):
43         return compat_str(sum(map(lambda p: int(p, 16), list(data))))
44
45     @staticmethod
46     def digit_sum(num):
47         if isinstance(num, int):
48             num = compat_str(num)
49         return compat_str(sum(map(int, num)))
50
51     def even_odd(self):
52         even = self.digit_sum(compat_str(self.timestamp)[::2])
53         odd = self.digit_sum(compat_str(self.timestamp)[1::2])
54         return even, odd
55
56     def preprocess(self, chunksize):
57         self.target = md5_text(self.target)
58         chunks = []
59         for i in range(32 // chunksize):
60             chunks.append(self.target[chunksize * i:chunksize * (i + 1)])
61         if 32 % chunksize:
62             chunks.append(self.target[32 - 32 % chunksize:])
63         return chunks, list(map(int, self.ip.split('.')))
64
65     def mod(self, modulus):
66         chunks, ip = self.preprocess(32)
67         self.target = chunks[0] + ''.join(map(lambda p: compat_str(p % modulus), ip))
68
69     def split(self, chunksize):
70         modulus_map = {
71             4: 256,
72             5: 10,
73             8: 100,
74         }
75
76         chunks, ip = self.preprocess(chunksize)
77         ret = ''
78         for i in range(len(chunks)):
79             ip_part = compat_str(ip[i] % modulus_map[chunksize]) if i < 4 else ''
80             if chunksize == 8:
81                 ret += ip_part + chunks[i]
82             else:
83                 ret += chunks[i] + ip_part
84         self.target = ret
85
86     def handle_input16(self):
87         self.target = md5_text(self.target)
88         self.target = self.split_sum(self.target[:16]) + self.target + self.split_sum(self.target[16:])
89
90     def handle_input8(self):
91         self.target = md5_text(self.target)
92         ret = ''
93         for i in range(4):
94             part = self.target[8 * i:8 * (i + 1)]
95             ret += self.split_sum(part) + part
96         self.target = ret
97
98     def handleSum(self):
99         self.target = md5_text(self.target)
100         self.target = self.split_sum(self.target) + self.target
101
102     def date(self, scheme):
103         self.target = md5_text(self.target)
104         d = time.localtime(self.timestamp)
105         strings = {
106             'y': compat_str(d.tm_year),
107             'm': '%02d' % d.tm_mon,
108             'd': '%02d' % d.tm_mday,
109         }
110         self.target += ''.join(map(lambda c: strings[c], list(scheme)))
111
112     def split_time_even_odd(self):
113         even, odd = self.even_odd()
114         self.target = odd + md5_text(self.target) + even
115
116     def split_time_odd_even(self):
117         even, odd = self.even_odd()
118         self.target = even + md5_text(self.target) + odd
119
120     def split_ip_time_sum(self):
121         chunks, ip = self.preprocess(32)
122         self.target = compat_str(sum(ip)) + chunks[0] + self.digit_sum(self.timestamp)
123
124     def split_time_ip_sum(self):
125         chunks, ip = self.preprocess(32)
126         self.target = self.digit_sum(self.timestamp) + chunks[0] + compat_str(sum(ip))
127
128
129 class IqiyiSDKInterpreter(object):
130     def __init__(self, sdk_code):
131         self.sdk_code = sdk_code
132
133     def run(self, target, ip, timestamp):
134         self.sdk_code = decode_packed_codes(self.sdk_code)
135
136         functions = re.findall(r'input=([a-zA-Z0-9]+)\(input', self.sdk_code)
137
138         sdk = IqiyiSDK(target, ip, timestamp)
139
140         other_functions = {
141             'handleSum': sdk.handleSum,
142             'handleInput8': sdk.handle_input8,
143             'handleInput16': sdk.handle_input16,
144             'splitTimeEvenOdd': sdk.split_time_even_odd,
145             'splitTimeOddEven': sdk.split_time_odd_even,
146             'splitIpTimeSum': sdk.split_ip_time_sum,
147             'splitTimeIpSum': sdk.split_time_ip_sum,
148         }
149         for function in functions:
150             if re.match(r'mod\d+', function):
151                 sdk.mod(int(function[3:]))
152             elif re.match(r'date[ymd]{3}', function):
153                 sdk.date(function[4:])
154             elif re.match(r'split\d+', function):
155                 sdk.split(int(function[5:]))
156             elif function in other_functions:
157                 other_functions[function]()
158             else:
159                 raise ExtractorError('Unknown funcion %s' % function)
160
161         return sdk.target
162
163
164 class IqiyiIE(InfoExtractor):
165     IE_NAME = 'iqiyi'
166     IE_DESC = '爱奇艺'
167
168     _WORKING = False
169
170     _VALID_URL = r'https?://(?:(?:[^.]+\.)?iqiyi\.com|www\.pps\.tv)/.+\.html'
171
172     _NETRC_MACHINE = 'iqiyi'
173
174     _TESTS = [{
175         'url': 'http://www.iqiyi.com/v_19rrojlavg.html',
176         'md5': '2cb594dc2781e6c941a110d8f358118b',
177         'info_dict': {
178             'id': '9c1fb1b99d192b21c559e5a1a2cb3c73',
179             'title': '美国德州空中惊现奇异云团 酷似UFO',
180             'ext': 'f4v',
181         }
182     }, {
183         'url': 'http://www.iqiyi.com/v_19rrhnnclk.html',
184         'info_dict': {
185             'id': 'e3f585b550a280af23c98b6cb2be19fb',
186             'title': '名侦探柯南第752集',
187         },
188         'playlist': [{
189             'info_dict': {
190                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part1',
191                 'ext': 'f4v',
192                 'title': '名侦探柯南第752集',
193             },
194         }, {
195             'info_dict': {
196                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part2',
197                 'ext': 'f4v',
198                 'title': '名侦探柯南第752集',
199             },
200         }, {
201             'info_dict': {
202                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part3',
203                 'ext': 'f4v',
204                 'title': '名侦探柯南第752集',
205             },
206         }, {
207             'info_dict': {
208                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part4',
209                 'ext': 'f4v',
210                 'title': '名侦探柯南第752集',
211             },
212         }, {
213             'info_dict': {
214                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part5',
215                 'ext': 'f4v',
216                 'title': '名侦探柯南第752集',
217             },
218         }, {
219             'info_dict': {
220                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part6',
221                 'ext': 'f4v',
222                 'title': '名侦探柯南第752集',
223             },
224         }, {
225             'info_dict': {
226                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part7',
227                 'ext': 'f4v',
228                 'title': '名侦探柯南第752集',
229             },
230         }, {
231             'info_dict': {
232                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part8',
233                 'ext': 'f4v',
234                 'title': '名侦探柯南第752集',
235             },
236         }],
237         'params': {
238             'skip_download': True,
239         },
240     }, {
241         'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html',
242         'only_matching': True,
243     }, {
244         'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html',
245         'only_matching': True,
246     }, {
247         'url': 'http://yule.iqiyi.com/pcb.html',
248         'only_matching': True,
249     }, {
250         # VIP-only video. The first 2 parts (6 minutes) are available without login
251         # MD5 sums omitted as values are different on Travis CI and my machine
252         'url': 'http://www.iqiyi.com/v_19rrny4w8w.html',
253         'info_dict': {
254             'id': 'f3cf468b39dddb30d676f89a91200dc1',
255             'title': '泰坦尼克号',
256         },
257         'playlist': [{
258             'info_dict': {
259                 'id': 'f3cf468b39dddb30d676f89a91200dc1_part1',
260                 'ext': 'f4v',
261                 'title': '泰坦尼克号',
262             },
263         }, {
264             'info_dict': {
265                 'id': 'f3cf468b39dddb30d676f89a91200dc1_part2',
266                 'ext': 'f4v',
267                 'title': '泰坦尼克号',
268             },
269         }],
270         'expected_warnings': ['Needs a VIP account for full video'],
271     }, {
272         'url': 'http://www.iqiyi.com/a_19rrhb8ce1.html',
273         'info_dict': {
274             'id': '202918101',
275             'title': '灌篮高手 国语版',
276         },
277         'playlist_count': 101,
278     }, {
279         'url': 'http://www.pps.tv/w_19rrbav0ph.html',
280         'only_matching': True,
281     }]
282
283     _FORMATS_MAP = [
284         ('1', 'h6'),
285         ('2', 'h5'),
286         ('3', 'h4'),
287         ('4', 'h3'),
288         ('5', 'h2'),
289         ('10', 'h1'),
290     ]
291
292     AUTH_API_ERRORS = {
293         # No preview available (不允许试看鉴权失败)
294         'Q00505': 'This video requires a VIP account',
295         # End of preview time (试看结束鉴权失败)
296         'Q00506': 'Needs a VIP account for full video',
297     }
298
299     def _real_initialize(self):
300         self._login()
301
302     @staticmethod
303     def _rsa_fun(data):
304         # public key extracted from http://static.iqiyi.com/js/qiyiV2/20160129180840/jobs/i18n/i18nIndex.js
305         N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
306         e = 65537
307
308         return ohdave_rsa_encrypt(data, e, N)
309
310     def _login(self):
311         (username, password) = self._get_login_info()
312
313         # No authentication to be performed
314         if not username:
315             return True
316
317         data = self._download_json(
318             'http://kylin.iqiyi.com/get_token', None,
319             note='Get token for logging', errnote='Unable to get token for logging')
320         sdk = data['sdk']
321         timestamp = int(time.time())
322         target = '/apis/reglogin/login.action?lang=zh_TW&area_code=null&email=%s&passwd=%s&agenttype=1&from=undefined&keeplogin=0&piccode=&fromurl=&_pos=1' % (
323             username, self._rsa_fun(password.encode('utf-8')))
324
325         interp = IqiyiSDKInterpreter(sdk)
326         sign = interp.run(target, data['ip'], timestamp)
327
328         validation_params = {
329             'target': target,
330             'server': 'BEA3AA1908656AABCCFF76582C4C6660',
331             'token': data['token'],
332             'bird_src': 'f8d91d57af224da7893dd397d52d811a',
333             'sign': sign,
334             'bird_t': timestamp,
335         }
336         validation_result = self._download_json(
337             'http://kylin.iqiyi.com/validate?' + compat_urllib_parse_urlencode(validation_params), None,
338             note='Validate credentials', errnote='Unable to validate credentials')
339
340         MSG_MAP = {
341             'P00107': 'please login via the web interface and enter the CAPTCHA code',
342             'P00117': 'bad username or password',
343         }
344
345         code = validation_result['code']
346         if code != 'A00000':
347             msg = MSG_MAP.get(code)
348             if not msg:
349                 msg = 'error %s' % code
350                 if validation_result.get('msg'):
351                     msg += ': ' + validation_result['msg']
352             self._downloader.report_warning('unable to log in: ' + msg)
353             return False
354
355         return True
356
357     def _authenticate_vip_video(self, api_video_url, video_id, tvid, _uuid, do_report_warning):
358         auth_params = {
359             # version and platform hard-coded in com/qiyi/player/core/model/remote/AuthenticationRemote.as
360             'version': '2.0',
361             'platform': 'b6c13e26323c537d',
362             'aid': tvid,
363             'tvid': tvid,
364             'uid': '',
365             'deviceId': _uuid,
366             'playType': 'main',  # XXX: always main?
367             'filename': os.path.splitext(url_basename(api_video_url))[0],
368         }
369
370         qd_items = compat_parse_qs(compat_urllib_parse_urlparse(api_video_url).query)
371         for key, val in qd_items.items():
372             auth_params[key] = val[0]
373
374         auth_req = sanitized_Request(
375             'http://api.vip.iqiyi.com/services/ckn.action',
376             urlencode_postdata(auth_params))
377         # iQiyi server throws HTTP 405 error without the following header
378         auth_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
379         auth_result = self._download_json(
380             auth_req, video_id,
381             note='Downloading video authentication JSON',
382             errnote='Unable to download video authentication JSON')
383
384         code = auth_result.get('code')
385         msg = self.AUTH_API_ERRORS.get(code) or auth_result.get('msg') or code
386         if code == 'Q00506':
387             if do_report_warning:
388                 self.report_warning(msg)
389             return False
390         if 'data' not in auth_result:
391             if msg is not None:
392                 raise ExtractorError('%s said: %s' % (self.IE_NAME, msg), expected=True)
393             raise ExtractorError('Unexpected error from Iqiyi auth API')
394
395         return auth_result['data']
396
397     def construct_video_urls(self, data, video_id, _uuid, tvid):
398         def do_xor(x, y):
399             a = y % 3
400             if a == 1:
401                 return x ^ 121
402             if a == 2:
403                 return x ^ 72
404             return x ^ 103
405
406         def get_encode_code(l):
407             a = 0
408             b = l.split('-')
409             c = len(b)
410             s = ''
411             for i in range(c - 1, -1, -1):
412                 a = do_xor(int(b[c - i - 1], 16), i)
413                 s += chr(a)
414             return s[::-1]
415
416         def get_path_key(x, format_id, segment_index):
417             mg = ')(*&^flash@#$%a'
418             tm = self._download_json(
419                 'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id,
420                 note='Download path key of segment %d for format %s' % (segment_index + 1, format_id)
421             )['t']
422             t = str(int(math.floor(int(tm) / (600.0))))
423             return md5_text(t + mg + x)
424
425         video_urls_dict = {}
426         need_vip_warning_report = True
427         for format_item in data['vp']['tkl'][0]['vs']:
428             if 0 < int(format_item['bid']) <= 10:
429                 format_id = self.get_format(format_item['bid'])
430             else:
431                 continue
432
433             video_urls = []
434
435             video_urls_info = format_item['fs']
436             if not format_item['fs'][0]['l'].startswith('/'):
437                 t = get_encode_code(format_item['fs'][0]['l'])
438                 if t.endswith('mp4'):
439                     video_urls_info = format_item['flvs']
440
441             for segment_index, segment in enumerate(video_urls_info):
442                 vl = segment['l']
443                 if not vl.startswith('/'):
444                     vl = get_encode_code(vl)
445                 is_vip_video = '/vip/' in vl
446                 filesize = segment['b']
447                 base_url = data['vp']['du'].split('/')
448                 if not is_vip_video:
449                     key = get_path_key(
450                         vl.split('/')[-1].split('.')[0], format_id, segment_index)
451                     base_url.insert(-1, key)
452                 base_url = '/'.join(base_url)
453                 param = {
454                     'su': _uuid,
455                     'qyid': uuid.uuid4().hex,
456                     'client': '',
457                     'z': '',
458                     'bt': '',
459                     'ct': '',
460                     'tn': str(int(time.time()))
461                 }
462                 api_video_url = base_url + vl
463                 if is_vip_video:
464                     api_video_url = api_video_url.replace('.f4v', '.hml')
465                     auth_result = self._authenticate_vip_video(
466                         api_video_url, video_id, tvid, _uuid, need_vip_warning_report)
467                     if auth_result is False:
468                         need_vip_warning_report = False
469                         break
470                     param.update({
471                         't': auth_result['t'],
472                         # cid is hard-coded in com/qiyi/player/core/player/RuntimeData.as
473                         'cid': 'afbe8fd3d73448c9',
474                         'vid': video_id,
475                         'QY00001': auth_result['u'],
476                     })
477                 api_video_url += '?' if '?' not in api_video_url else '&'
478                 api_video_url += compat_urllib_parse_urlencode(param)
479                 js = self._download_json(
480                     api_video_url, video_id,
481                     note='Download video info of segment %d for format %s' % (segment_index + 1, format_id))
482                 video_url = js['l']
483                 video_urls.append(
484                     (video_url, filesize))
485
486             video_urls_dict[format_id] = video_urls
487         return video_urls_dict
488
489     def get_format(self, bid):
490         matched_format_ids = [_format_id for _bid, _format_id in self._FORMATS_MAP if _bid == str(bid)]
491         return matched_format_ids[0] if len(matched_format_ids) else None
492
493     def get_bid(self, format_id):
494         matched_bids = [_bid for _bid, _format_id in self._FORMATS_MAP if _format_id == format_id]
495         return matched_bids[0] if len(matched_bids) else None
496
497     def get_raw_data(self, tvid, video_id, enc_key, _uuid):
498         tm = str(int(time.time()))
499         tail = tm + tvid
500         param = {
501             'key': 'fvip',
502             'src': md5_text('youtube-dl'),
503             'tvId': tvid,
504             'vid': video_id,
505             'vinfo': 1,
506             'tm': tm,
507             'enc': md5_text(enc_key + tail),
508             'qyid': _uuid,
509             'tn': random.random(),
510             # In iQiyi's flash player, um is set to 1 if there's a logged user
511             # Some 1080P formats are only available with a logged user.
512             # Here force um=1 to trick the iQiyi server
513             'um': 1,
514             'authkey': md5_text(md5_text('') + tail),
515             'k_tag': 1,
516         }
517
518         api_url = 'http://cache.video.qiyi.com/vms' + '?' + \
519             compat_urllib_parse_urlencode(param)
520         raw_data = self._download_json(api_url, video_id)
521         return raw_data
522
523     def get_enc_key(self, video_id):
524         # TODO: automatic key extraction
525         # last update at 2016-01-22 for Zombie::bite
526         enc_key = '4a1caba4b4465345366f28da7c117d20'
527         return enc_key
528
529     def _extract_playlist(self, webpage):
530         PAGE_SIZE = 50
531
532         links = re.findall(
533             r'<a[^>]+class="site-piclist_pic_link"[^>]+href="(http://www\.iqiyi\.com/.+\.html)"',
534             webpage)
535         if not links:
536             return
537
538         album_id = self._search_regex(
539             r'albumId\s*:\s*(\d+),', webpage, 'album ID')
540         album_title = self._search_regex(
541             r'data-share-title="([^"]+)"', webpage, 'album title', fatal=False)
542
543         entries = list(map(self.url_result, links))
544
545         # Start from 2 because links in the first page are already on webpage
546         for page_num in itertools.count(2):
547             pagelist_page = self._download_webpage(
548                 'http://cache.video.qiyi.com/jp/avlist/%s/%d/%d/' % (album_id, page_num, PAGE_SIZE),
549                 album_id,
550                 note='Download playlist page %d' % page_num,
551                 errnote='Failed to download playlist page %d' % page_num)
552             pagelist = self._parse_json(
553                 remove_start(pagelist_page, 'var tvInfoJs='), album_id)
554             vlist = pagelist['data']['vlist']
555             for item in vlist:
556                 entries.append(self.url_result(item['vurl']))
557             if len(vlist) < PAGE_SIZE:
558                 break
559
560         return self.playlist_result(entries, album_id, album_title)
561
562     def _real_extract(self, url):
563         webpage = self._download_webpage(
564             url, 'temp_id', note='download video page')
565
566         # There's no simple way to determine whether an URL is a playlist or not
567         # So detect it
568         playlist_result = self._extract_playlist(webpage)
569         if playlist_result:
570             return playlist_result
571
572         tvid = self._search_regex(
573             r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
574         video_id = self._search_regex(
575             r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
576         _uuid = uuid.uuid4().hex
577
578         enc_key = self.get_enc_key(video_id)
579
580         raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid)
581
582         if raw_data['code'] != 'A000000':
583             raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
584
585         data = raw_data['data']
586
587         title = data['vi']['vn']
588
589         # generate video_urls_dict
590         video_urls_dict = self.construct_video_urls(
591             data, video_id, _uuid, tvid)
592
593         # construct info
594         entries = []
595         for format_id in video_urls_dict:
596             video_urls = video_urls_dict[format_id]
597             for i, video_url_info in enumerate(video_urls):
598                 if len(entries) < i + 1:
599                     entries.append({'formats': []})
600                 entries[i]['formats'].append(
601                     {
602                         'url': video_url_info[0],
603                         'filesize': video_url_info[-1],
604                         'format_id': format_id,
605                         'preference': int(self.get_bid(format_id))
606                     }
607                 )
608
609         for i in range(len(entries)):
610             self._sort_formats(entries[i]['formats'])
611             entries[i].update(
612                 {
613                     'id': '%s_part%d' % (video_id, i + 1),
614                     'title': title,
615                 }
616             )
617
618         if len(entries) > 1:
619             info = {
620                 '_type': 'multi_video',
621                 'id': video_id,
622                 'title': title,
623                 'entries': entries,
624             }
625         else:
626             info = entries[0]
627             info['id'] = video_id
628             info['title'] = title
629
630         return info