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