2 from __future__ import unicode_literals
11 from .common import InfoExtractor
12 from ..compat import (
14 compat_urllib_parse_urlencode,
27 return hashlib.md5(text.encode('utf-8')).hexdigest()
30 class IqiyiSDK(object):
31 def __init__(self, target, ip, timestamp):
34 self.timestamp = timestamp
38 return compat_str(sum(map(lambda p: int(p, 16), list(data))))
42 if isinstance(num, int):
44 return compat_str(sum(map(int, num)))
47 even = self.digit_sum(compat_str(self.timestamp)[::2])
48 odd = self.digit_sum(compat_str(self.timestamp)[1::2])
51 def preprocess(self, chunksize):
52 self.target = md5_text(self.target)
54 for i in range(32 // chunksize):
55 chunks.append(self.target[chunksize * i:chunksize * (i + 1)])
57 chunks.append(self.target[32 - 32 % chunksize:])
58 return chunks, list(map(int, self.ip.split('.')))
60 def mod(self, modulus):
61 chunks, ip = self.preprocess(32)
62 self.target = chunks[0] + ''.join(map(lambda p: compat_str(p % modulus), ip))
64 def split(self, chunksize):
71 chunks, ip = self.preprocess(chunksize)
73 for i in range(len(chunks)):
74 ip_part = compat_str(ip[i] % modulus_map[chunksize]) if i < 4 else ''
76 ret += ip_part + chunks[i]
78 ret += chunks[i] + ip_part
81 def handle_input16(self):
82 self.target = md5_text(self.target)
83 self.target = self.split_sum(self.target[:16]) + self.target + self.split_sum(self.target[16:])
85 def handle_input8(self):
86 self.target = md5_text(self.target)
89 part = self.target[8 * i:8 * (i + 1)]
90 ret += self.split_sum(part) + part
94 self.target = md5_text(self.target)
95 self.target = self.split_sum(self.target) + self.target
97 def date(self, scheme):
98 self.target = md5_text(self.target)
99 d = time.localtime(self.timestamp)
101 'y': compat_str(d.tm_year),
102 'm': '%02d' % d.tm_mon,
103 'd': '%02d' % d.tm_mday,
105 self.target += ''.join(map(lambda c: strings[c], list(scheme)))
107 def split_time_even_odd(self):
108 even, odd = self.even_odd()
109 self.target = odd + md5_text(self.target) + even
111 def split_time_odd_even(self):
112 even, odd = self.even_odd()
113 self.target = even + md5_text(self.target) + odd
115 def split_ip_time_sum(self):
116 chunks, ip = self.preprocess(32)
117 self.target = compat_str(sum(ip)) + chunks[0] + self.digit_sum(self.timestamp)
119 def split_time_ip_sum(self):
120 chunks, ip = self.preprocess(32)
121 self.target = self.digit_sum(self.timestamp) + chunks[0] + compat_str(sum(ip))
124 class IqiyiSDKInterpreter(object):
125 def __init__(self, sdk_code):
126 self.sdk_code = sdk_code
128 def run(self, target, ip, timestamp):
129 self.sdk_code = decode_packed_codes(self.sdk_code)
131 functions = re.findall(r'input=([a-zA-Z0-9]+)\(input', self.sdk_code)
133 sdk = IqiyiSDK(target, ip, timestamp)
136 'handleSum': sdk.handleSum,
137 'handleInput8': sdk.handle_input8,
138 'handleInput16': sdk.handle_input16,
139 'splitTimeEvenOdd': sdk.split_time_even_odd,
140 'splitTimeOddEven': sdk.split_time_odd_even,
141 'splitIpTimeSum': sdk.split_ip_time_sum,
142 'splitTimeIpSum': sdk.split_time_ip_sum,
144 for function in functions:
145 if re.match(r'mod\d+', function):
146 sdk.mod(int(function[3:]))
147 elif re.match(r'date[ymd]{3}', function):
148 sdk.date(function[4:])
149 elif re.match(r'split\d+', function):
150 sdk.split(int(function[5:]))
151 elif function in other_functions:
152 other_functions[function]()
154 raise ExtractorError('Unknown funcion %s' % function)
159 class IqiyiIE(InfoExtractor):
163 _VALID_URL = r'https?://(?:(?:[^.]+\.)?iqiyi\.com|www\.pps\.tv)/.+\.html'
165 _NETRC_MACHINE = 'iqiyi'
168 'url': 'http://www.iqiyi.com/v_19rrojlavg.html',
169 'md5': '470a6c160618577166db1a7aac5a3606',
171 'id': '9c1fb1b99d192b21c559e5a1a2cb3c73',
173 'title': '美国德州空中惊现奇异云团 酷似UFO',
176 'url': 'http://www.iqiyi.com/v_19rrhnnclk.html',
177 'md5': 'f09f0a6a59b2da66a26bf4eda669a4cc',
179 'id': 'e3f585b550a280af23c98b6cb2be19fb',
181 'title': '名侦探柯南 国语版',
183 'skip': 'Geo-restricted to China',
185 'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html',
186 'only_matching': True,
188 'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html',
189 'only_matching': True,
191 'url': 'http://yule.iqiyi.com/pcb.html',
192 'only_matching': True,
194 # VIP-only video. The first 2 parts (6 minutes) are available without login
195 # MD5 sums omitted as values are different on Travis CI and my machine
196 'url': 'http://www.iqiyi.com/v_19rrny4w8w.html',
198 'id': 'f3cf468b39dddb30d676f89a91200dc1',
203 'id': 'f3cf468b39dddb30d676f89a91200dc1_part1',
209 'id': 'f3cf468b39dddb30d676f89a91200dc1_part2',
214 'expected_warnings': ['Needs a VIP account for full video'],
216 'url': 'http://www.iqiyi.com/a_19rrhb8ce1.html',
221 'playlist_count': 101,
223 'url': 'http://www.pps.tv/w_19rrbav0ph.html',
224 'only_matching': True,
236 def _real_initialize(self):
241 # public key extracted from http://static.iqiyi.com/js/qiyiV2/20160129180840/jobs/i18n/i18nIndex.js
242 N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
245 return ohdave_rsa_encrypt(data, e, N)
248 (username, password) = self._get_login_info()
250 # No authentication to be performed
254 data = self._download_json(
255 'http://kylin.iqiyi.com/get_token', None,
256 note='Get token for logging', errnote='Unable to get token for logging')
258 timestamp = int(time.time())
259 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' % (
260 username, self._rsa_fun(password.encode('utf-8')))
262 interp = IqiyiSDKInterpreter(sdk)
263 sign = interp.run(target, data['ip'], timestamp)
265 validation_params = {
267 'server': 'BEA3AA1908656AABCCFF76582C4C6660',
268 'token': data['token'],
269 'bird_src': 'f8d91d57af224da7893dd397d52d811a',
273 validation_result = self._download_json(
274 'http://kylin.iqiyi.com/validate?' + compat_urllib_parse_urlencode(validation_params), None,
275 note='Validate credentials', errnote='Unable to validate credentials')
278 'P00107': 'please login via the web interface and enter the CAPTCHA code',
279 'P00117': 'bad username or password',
282 code = validation_result['code']
284 msg = MSG_MAP.get(code)
286 msg = 'error %s' % code
287 if validation_result.get('msg'):
288 msg += ': ' + validation_result['msg']
289 self._downloader.report_warning('unable to log in: ' + msg)
295 def _gen_sc(tvid, timestamp):
296 M = [1732584193, -271733879]
297 M.extend([~M[0], ~M[1]])
298 I_table = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]
299 C_base = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8388608, 432]
304 return trunc(((n >> 1) + (t >> 1) << 1) + (n & 1) + (t & 1))
312 def transform(string, mod):
313 num = int(string, 16)
314 return (num >> 8 * (i % 4) & 255 ^ i % mod) << ((a & 3) << 3)
318 k = str(timestamp - 7)
321 C[a >> 2] |= ord(k[a]) << 8 * (a % 4)
326 r = '03967743b643f66763d623d637e30733'
327 C[a >> 2] |= transform(''.join(reversed(r[start:start + 8])), 7)
332 r = '7038766939776a32776a32706b337139'
333 C[a >> 2] |= transform(r[start:start + 8], 1)
338 C[a >> 2] |= ord(tvid[i]) << 8 * (a % 4)
343 C_index = [i, 5 * i + 1, 3 * i + 5, 7 * i][I] % 16 + urshift(a, 6)
345 trunc(o[1] & o[2]) | trunc(~o[1] & o[3]),
346 trunc(o[3] & o[1]) | trunc(~o[3] & o[2]),
348 o[2] ^ trunc(o[1] | ~o[3])
350 trunc(int(abs(math.sin(i + 1)) * 4294967296)),
351 C[C_index] if C_index < len(C) else None))
352 I = I_table[4 * I + i % 4]
354 L(o[1], trunc(trunc(m << I) | urshift(m, 32 - I))),
358 new_M = [L(o[0], M[0]), L(o[1], M[1]), L(o[2], M[2]), L(o[3], M[3])]
359 s = [new_M[a >> 3] >> (1 ^ a & 7) * 4 & 15 for a in range(32)]
360 return binascii.hexlify(intlist_to_bytes(s))[1::2].decode('ascii')
362 def get_raw_data(self, tvid, video_id):
363 tm = int(time.time() * 1000)
365 sc = self._gen_sc(tvid, tm)
371 'cupid': 'qc_100001_100186',
375 'src': 'd846d0c32d664d32b6b54ea48997a589',
382 cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
383 if cn_verification_proxy:
384 headers['Ytdl-request-proxy'] = cn_verification_proxy
385 return self._download_json(
386 'http://cache.m.iqiyi.com/jp/tmts/%s/%s/' % (tvid, video_id),
387 video_id, transform_source=lambda s: remove_start(s, 'var tvInfoJs='),
388 query=params, headers=headers)
390 def _extract_playlist(self, webpage):
394 r'<a[^>]+class="site-piclist_pic_link"[^>]+href="(http://www\.iqiyi\.com/.+\.html)"',
399 album_id = self._search_regex(
400 r'albumId\s*:\s*(\d+),', webpage, 'album ID')
401 album_title = self._search_regex(
402 r'data-share-title="([^"]+)"', webpage, 'album title', fatal=False)
404 entries = list(map(self.url_result, links))
406 # Start from 2 because links in the first page are already on webpage
407 for page_num in itertools.count(2):
408 pagelist_page = self._download_webpage(
409 'http://cache.video.qiyi.com/jp/avlist/%s/%d/%d/' % (album_id, page_num, PAGE_SIZE),
411 note='Download playlist page %d' % page_num,
412 errnote='Failed to download playlist page %d' % page_num)
413 pagelist = self._parse_json(
414 remove_start(pagelist_page, 'var tvInfoJs='), album_id)
415 vlist = pagelist['data']['vlist']
417 entries.append(self.url_result(item['vurl']))
418 if len(vlist) < PAGE_SIZE:
421 return self.playlist_result(entries, album_id, album_title)
423 def _real_extract(self, url):
424 webpage = self._download_webpage(
425 url, 'temp_id', note='download video page')
427 # There's no simple way to determine whether an URL is a playlist or not
429 playlist_result = self._extract_playlist(webpage)
431 return playlist_result
433 tvid = self._search_regex(
434 r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
435 video_id = self._search_regex(
436 r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
439 raw_data = self.get_raw_data(tvid, video_id)
441 if raw_data['code'] != 'A00000':
442 if raw_data['code'] == 'A00111':
443 self.raise_geo_restricted()
444 raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
446 data = raw_data['data']
448 # iQiYi sometimes returns Ads
449 if not isinstance(data['playInfo'], dict):
450 self._sleep(5, video_id)
453 title = data['playInfo']['an']