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': '名侦探柯南 国语版',
184 'cn_verification_proxy': 'http://proxy.uku.im:443/',
187 'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html',
188 'only_matching': True,
190 'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html',
191 'only_matching': True,
193 'url': 'http://yule.iqiyi.com/pcb.html',
194 'only_matching': True,
196 # VIP-only video. The first 2 parts (6 minutes) are available without login
197 # MD5 sums omitted as values are different on Travis CI and my machine
198 'url': 'http://www.iqiyi.com/v_19rrny4w8w.html',
200 'id': 'f3cf468b39dddb30d676f89a91200dc1',
205 'id': 'f3cf468b39dddb30d676f89a91200dc1_part1',
211 'id': 'f3cf468b39dddb30d676f89a91200dc1_part2',
216 'expected_warnings': ['Needs a VIP account for full video'],
218 'url': 'http://www.iqiyi.com/a_19rrhb8ce1.html',
223 'playlist_count': 101,
225 'url': 'http://www.pps.tv/w_19rrbav0ph.html',
226 'only_matching': True,
238 def _real_initialize(self):
243 # public key extracted from http://static.iqiyi.com/js/qiyiV2/20160129180840/jobs/i18n/i18nIndex.js
244 N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
247 return ohdave_rsa_encrypt(data, e, N)
250 (username, password) = self._get_login_info()
252 # No authentication to be performed
256 data = self._download_json(
257 'http://kylin.iqiyi.com/get_token', None,
258 note='Get token for logging', errnote='Unable to get token for logging')
260 timestamp = int(time.time())
261 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' % (
262 username, self._rsa_fun(password.encode('utf-8')))
264 interp = IqiyiSDKInterpreter(sdk)
265 sign = interp.run(target, data['ip'], timestamp)
267 validation_params = {
269 'server': 'BEA3AA1908656AABCCFF76582C4C6660',
270 'token': data['token'],
271 'bird_src': 'f8d91d57af224da7893dd397d52d811a',
275 validation_result = self._download_json(
276 'http://kylin.iqiyi.com/validate?' + compat_urllib_parse_urlencode(validation_params), None,
277 note='Validate credentials', errnote='Unable to validate credentials')
280 'P00107': 'please login via the web interface and enter the CAPTCHA code',
281 'P00117': 'bad username or password',
284 code = validation_result['code']
286 msg = MSG_MAP.get(code)
288 msg = 'error %s' % code
289 if validation_result.get('msg'):
290 msg += ': ' + validation_result['msg']
291 self._downloader.report_warning('unable to log in: ' + msg)
297 def _gen_sc(tvid, timestamp):
298 M = [1732584193, -271733879]
299 M.extend([~M[0], ~M[1]])
300 I_table = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]
301 C_base = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8388608, 432]
306 return trunc(((n >> 1) + (t >> 1) << 1) + (n & 1) + (t & 1))
314 def transform(string, mod):
315 num = int(string, 16)
316 return (num >> 8 * (i % 4) & 255 ^ i % mod) << ((a & 3) << 3)
320 k = str(timestamp - 7)
323 C[a >> 2] |= ord(k[a]) << 8 * (a % 4)
328 r = '03967743b643f66763d623d637e30733'
329 C[a >> 2] |= transform(''.join(reversed(r[start:start + 8])), 7)
334 r = '7038766939776a32776a32706b337139'
335 C[a >> 2] |= transform(r[start:start + 8], 1)
340 C[a >> 2] |= ord(tvid[i]) << 8 * (a % 4)
345 C_index = [i, 5 * i + 1, 3 * i + 5, 7 * i][I] % 16 + urshift(a, 6)
347 trunc(o[1] & o[2]) | trunc(~o[1] & o[3]),
348 trunc(o[3] & o[1]) | trunc(~o[3] & o[2]),
350 o[2] ^ trunc(o[1] | ~o[3])
352 trunc(int(abs(math.sin(i + 1)) * 4294967296)),
353 C[C_index] if C_index < len(C) else None))
354 I = I_table[4 * I + i % 4]
356 L(o[1], trunc(trunc(m << I) | urshift(m, 32 - I))),
360 new_M = [L(o[0], M[0]), L(o[1], M[1]), L(o[2], M[2]), L(o[3], M[3])]
361 s = [new_M[a >> 3] >> (1 ^ a & 7) * 4 & 15 for a in range(32)]
362 return binascii.hexlify(intlist_to_bytes(s))[1::2].decode('ascii')
364 def get_raw_data(self, tvid, video_id):
365 tm = int(time.time() * 1000)
367 sc = self._gen_sc(tvid, tm)
373 'cupid': 'qc_100001_100186',
377 'src': 'd846d0c32d664d32b6b54ea48997a589',
384 cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
385 if cn_verification_proxy:
386 headers['Ytdl-request-proxy'] = cn_verification_proxy
387 return self._download_json(
388 'http://cache.m.iqiyi.com/jp/tmts/%s/%s/' % (tvid, video_id),
389 video_id, transform_source=lambda s: remove_start(s, 'var tvInfoJs='),
390 query=params, headers=headers)
392 def _extract_playlist(self, webpage):
396 r'<a[^>]+class="site-piclist_pic_link"[^>]+href="(http://www\.iqiyi\.com/.+\.html)"',
401 album_id = self._search_regex(
402 r'albumId\s*:\s*(\d+),', webpage, 'album ID')
403 album_title = self._search_regex(
404 r'data-share-title="([^"]+)"', webpage, 'album title', fatal=False)
406 entries = list(map(self.url_result, links))
408 # Start from 2 because links in the first page are already on webpage
409 for page_num in itertools.count(2):
410 pagelist_page = self._download_webpage(
411 'http://cache.video.qiyi.com/jp/avlist/%s/%d/%d/' % (album_id, page_num, PAGE_SIZE),
413 note='Download playlist page %d' % page_num,
414 errnote='Failed to download playlist page %d' % page_num)
415 pagelist = self._parse_json(
416 remove_start(pagelist_page, 'var tvInfoJs='), album_id)
417 vlist = pagelist['data']['vlist']
419 entries.append(self.url_result(item['vurl']))
420 if len(vlist) < PAGE_SIZE:
423 return self.playlist_result(entries, album_id, album_title)
425 def _real_extract(self, url):
426 webpage = self._download_webpage(
427 url, 'temp_id', note='download video page')
429 # There's no simple way to determine whether an URL is a playlist or not
431 playlist_result = self._extract_playlist(webpage)
433 return playlist_result
435 tvid = self._search_regex(
436 r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
437 video_id = self._search_regex(
438 r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
441 raw_data = self.get_raw_data(tvid, video_id)
443 if raw_data['code'] != 'A00000':
444 if raw_data['code'] == 'A00111':
445 self.raise_geo_restricted()
446 raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
448 data = raw_data['data']
450 # iQiYi sometimes returns Ads
451 if not isinstance(data['playInfo'], dict):
452 self._sleep(5, video_id)
455 title = data['playInfo']['an']