You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

460 lines
15 KiB

10 years ago
10 years ago
10 years ago
10 years ago
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import binascii
  4. import hashlib
  5. import itertools
  6. import math
  7. import re
  8. import time
  9. from .common import InfoExtractor
  10. from ..compat import (
  11. compat_str,
  12. compat_urllib_parse_urlencode,
  13. )
  14. from ..utils import (
  15. decode_packed_codes,
  16. ExtractorError,
  17. intlist_to_bytes,
  18. ohdave_rsa_encrypt,
  19. remove_start,
  20. urshift,
  21. )
  22. def md5_text(text):
  23. return hashlib.md5(text.encode('utf-8')).hexdigest()
  24. class IqiyiSDK(object):
  25. def __init__(self, target, ip, timestamp):
  26. self.target = target
  27. self.ip = ip
  28. self.timestamp = timestamp
  29. @staticmethod
  30. def split_sum(data):
  31. return compat_str(sum(map(lambda p: int(p, 16), list(data))))
  32. @staticmethod
  33. def digit_sum(num):
  34. if isinstance(num, int):
  35. num = compat_str(num)
  36. return compat_str(sum(map(int, num)))
  37. def even_odd(self):
  38. even = self.digit_sum(compat_str(self.timestamp)[::2])
  39. odd = self.digit_sum(compat_str(self.timestamp)[1::2])
  40. return even, odd
  41. def preprocess(self, chunksize):
  42. self.target = md5_text(self.target)
  43. chunks = []
  44. for i in range(32 // chunksize):
  45. chunks.append(self.target[chunksize * i:chunksize * (i + 1)])
  46. if 32 % chunksize:
  47. chunks.append(self.target[32 - 32 % chunksize:])
  48. return chunks, list(map(int, self.ip.split('.')))
  49. def mod(self, modulus):
  50. chunks, ip = self.preprocess(32)
  51. self.target = chunks[0] + ''.join(map(lambda p: compat_str(p % modulus), ip))
  52. def split(self, chunksize):
  53. modulus_map = {
  54. 4: 256,
  55. 5: 10,
  56. 8: 100,
  57. }
  58. chunks, ip = self.preprocess(chunksize)
  59. ret = ''
  60. for i in range(len(chunks)):
  61. ip_part = compat_str(ip[i] % modulus_map[chunksize]) if i < 4 else ''
  62. if chunksize == 8:
  63. ret += ip_part + chunks[i]
  64. else:
  65. ret += chunks[i] + ip_part
  66. self.target = ret
  67. def handle_input16(self):
  68. self.target = md5_text(self.target)
  69. self.target = self.split_sum(self.target[:16]) + self.target + self.split_sum(self.target[16:])
  70. def handle_input8(self):
  71. self.target = md5_text(self.target)
  72. ret = ''
  73. for i in range(4):
  74. part = self.target[8 * i:8 * (i + 1)]
  75. ret += self.split_sum(part) + part
  76. self.target = ret
  77. def handleSum(self):
  78. self.target = md5_text(self.target)
  79. self.target = self.split_sum(self.target) + self.target
  80. def date(self, scheme):
  81. self.target = md5_text(self.target)
  82. d = time.localtime(self.timestamp)
  83. strings = {
  84. 'y': compat_str(d.tm_year),
  85. 'm': '%02d' % d.tm_mon,
  86. 'd': '%02d' % d.tm_mday,
  87. }
  88. self.target += ''.join(map(lambda c: strings[c], list(scheme)))
  89. def split_time_even_odd(self):
  90. even, odd = self.even_odd()
  91. self.target = odd + md5_text(self.target) + even
  92. def split_time_odd_even(self):
  93. even, odd = self.even_odd()
  94. self.target = even + md5_text(self.target) + odd
  95. def split_ip_time_sum(self):
  96. chunks, ip = self.preprocess(32)
  97. self.target = compat_str(sum(ip)) + chunks[0] + self.digit_sum(self.timestamp)
  98. def split_time_ip_sum(self):
  99. chunks, ip = self.preprocess(32)
  100. self.target = self.digit_sum(self.timestamp) + chunks[0] + compat_str(sum(ip))
  101. class IqiyiSDKInterpreter(object):
  102. def __init__(self, sdk_code):
  103. self.sdk_code = sdk_code
  104. def run(self, target, ip, timestamp):
  105. self.sdk_code = decode_packed_codes(self.sdk_code)
  106. functions = re.findall(r'input=([a-zA-Z0-9]+)\(input', self.sdk_code)
  107. sdk = IqiyiSDK(target, ip, timestamp)
  108. other_functions = {
  109. 'handleSum': sdk.handleSum,
  110. 'handleInput8': sdk.handle_input8,
  111. 'handleInput16': sdk.handle_input16,
  112. 'splitTimeEvenOdd': sdk.split_time_even_odd,
  113. 'splitTimeOddEven': sdk.split_time_odd_even,
  114. 'splitIpTimeSum': sdk.split_ip_time_sum,
  115. 'splitTimeIpSum': sdk.split_time_ip_sum,
  116. }
  117. for function in functions:
  118. if re.match(r'mod\d+', function):
  119. sdk.mod(int(function[3:]))
  120. elif re.match(r'date[ymd]{3}', function):
  121. sdk.date(function[4:])
  122. elif re.match(r'split\d+', function):
  123. sdk.split(int(function[5:]))
  124. elif function in other_functions:
  125. other_functions[function]()
  126. else:
  127. raise ExtractorError('Unknown funcion %s' % function)
  128. return sdk.target
  129. class IqiyiIE(InfoExtractor):
  130. IE_NAME = 'iqiyi'
  131. IE_DESC = '爱奇艺'
  132. _VALID_URL = r'https?://(?:(?:[^.]+\.)?iqiyi\.com|www\.pps\.tv)/.+\.html'
  133. _NETRC_MACHINE = 'iqiyi'
  134. _TESTS = [{
  135. 'url': 'http://www.iqiyi.com/v_19rrojlavg.html',
  136. 'md5': '470a6c160618577166db1a7aac5a3606',
  137. 'info_dict': {
  138. 'id': '9c1fb1b99d192b21c559e5a1a2cb3c73',
  139. 'ext': 'mp4',
  140. 'title': '美国德州空中惊现奇异云团 酷似UFO',
  141. }
  142. }, {
  143. 'url': 'http://www.iqiyi.com/v_19rrhnnclk.html',
  144. 'md5': 'f09f0a6a59b2da66a26bf4eda669a4cc',
  145. 'info_dict': {
  146. 'id': 'e3f585b550a280af23c98b6cb2be19fb',
  147. 'ext': 'mp4',
  148. 'title': '名侦探柯南 国语版',
  149. },
  150. 'skip': 'Geo-restricted to China',
  151. }, {
  152. 'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html',
  153. 'only_matching': True,
  154. }, {
  155. 'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html',
  156. 'only_matching': True,
  157. }, {
  158. 'url': 'http://yule.iqiyi.com/pcb.html',
  159. 'only_matching': True,
  160. }, {
  161. # VIP-only video. The first 2 parts (6 minutes) are available without login
  162. # MD5 sums omitted as values are different on Travis CI and my machine
  163. 'url': 'http://www.iqiyi.com/v_19rrny4w8w.html',
  164. 'info_dict': {
  165. 'id': 'f3cf468b39dddb30d676f89a91200dc1',
  166. 'title': '泰坦尼克号',
  167. },
  168. 'playlist': [{
  169. 'info_dict': {
  170. 'id': 'f3cf468b39dddb30d676f89a91200dc1_part1',
  171. 'ext': 'f4v',
  172. 'title': '泰坦尼克号',
  173. },
  174. }, {
  175. 'info_dict': {
  176. 'id': 'f3cf468b39dddb30d676f89a91200dc1_part2',
  177. 'ext': 'f4v',
  178. 'title': '泰坦尼克号',
  179. },
  180. }],
  181. 'expected_warnings': ['Needs a VIP account for full video'],
  182. }, {
  183. 'url': 'http://www.iqiyi.com/a_19rrhb8ce1.html',
  184. 'info_dict': {
  185. 'id': '202918101',
  186. 'title': '灌篮高手 国语版',
  187. },
  188. 'playlist_count': 101,
  189. }, {
  190. 'url': 'http://www.pps.tv/w_19rrbav0ph.html',
  191. 'only_matching': True,
  192. }]
  193. _FORMATS_MAP = [
  194. ('1', 'h6'),
  195. ('2', 'h5'),
  196. ('3', 'h4'),
  197. ('4', 'h3'),
  198. ('5', 'h2'),
  199. ('10', 'h1'),
  200. ]
  201. def _real_initialize(self):
  202. self._login()
  203. @staticmethod
  204. def _rsa_fun(data):
  205. # public key extracted from http://static.iqiyi.com/js/qiyiV2/20160129180840/jobs/i18n/i18nIndex.js
  206. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  207. e = 65537
  208. return ohdave_rsa_encrypt(data, e, N)
  209. def _login(self):
  210. (username, password) = self._get_login_info()
  211. # No authentication to be performed
  212. if not username:
  213. return True
  214. data = self._download_json(
  215. 'http://kylin.iqiyi.com/get_token', None,
  216. note='Get token for logging', errnote='Unable to get token for logging')
  217. sdk = data['sdk']
  218. timestamp = int(time.time())
  219. 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' % (
  220. username, self._rsa_fun(password.encode('utf-8')))
  221. interp = IqiyiSDKInterpreter(sdk)
  222. sign = interp.run(target, data['ip'], timestamp)
  223. validation_params = {
  224. 'target': target,
  225. 'server': 'BEA3AA1908656AABCCFF76582C4C6660',
  226. 'token': data['token'],
  227. 'bird_src': 'f8d91d57af224da7893dd397d52d811a',
  228. 'sign': sign,
  229. 'bird_t': timestamp,
  230. }
  231. validation_result = self._download_json(
  232. 'http://kylin.iqiyi.com/validate?' + compat_urllib_parse_urlencode(validation_params), None,
  233. note='Validate credentials', errnote='Unable to validate credentials')
  234. MSG_MAP = {
  235. 'P00107': 'please login via the web interface and enter the CAPTCHA code',
  236. 'P00117': 'bad username or password',
  237. }
  238. code = validation_result['code']
  239. if code != 'A00000':
  240. msg = MSG_MAP.get(code)
  241. if not msg:
  242. msg = 'error %s' % code
  243. if validation_result.get('msg'):
  244. msg += ': ' + validation_result['msg']
  245. self._downloader.report_warning('unable to log in: ' + msg)
  246. return False
  247. return True
  248. @staticmethod
  249. def _gen_sc(tvid, timestamp):
  250. M = [1732584193, -271733879]
  251. M.extend([~M[0], ~M[1]])
  252. I_table = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]
  253. C_base = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8388608, 432]
  254. def L(n, t):
  255. if t is None:
  256. t = 0
  257. return trunc(((n >> 1) + (t >> 1) << 1) + (n & 1) + (t & 1))
  258. def trunc(n):
  259. n = n % 0x100000000
  260. if n > 0x7fffffff:
  261. n -= 0x100000000
  262. return n
  263. def transform(string, mod):
  264. num = int(string, 16)
  265. return (num >> 8 * (i % 4) & 255 ^ i % mod) << ((a & 3) << 3)
  266. C = list(C_base)
  267. o = list(M)
  268. k = str(timestamp - 7)
  269. for i in range(13):
  270. a = i
  271. C[a >> 2] |= ord(k[a]) << 8 * (a % 4)
  272. for i in range(16):
  273. a = i + 13
  274. start = (i >> 2) * 8
  275. r = '03967743b643f66763d623d637e30733'
  276. C[a >> 2] |= transform(''.join(reversed(r[start:start + 8])), 7)
  277. for i in range(16):
  278. a = i + 29
  279. start = (i >> 2) * 8
  280. r = '7038766939776a32776a32706b337139'
  281. C[a >> 2] |= transform(r[start:start + 8], 1)
  282. for i in range(9):
  283. a = i + 45
  284. if i < len(tvid):
  285. C[a >> 2] |= ord(tvid[i]) << 8 * (a % 4)
  286. for a in range(64):
  287. i = a
  288. I = i >> 4
  289. C_index = [i, 5 * i + 1, 3 * i + 5, 7 * i][I] % 16 + urshift(a, 6)
  290. m = L(L(o[0], [
  291. trunc(o[1] & o[2]) | trunc(~o[1] & o[3]),
  292. trunc(o[3] & o[1]) | trunc(~o[3] & o[2]),
  293. o[1] ^ o[2] ^ o[3],
  294. o[2] ^ trunc(o[1] | ~o[3])
  295. ][I]), L(
  296. trunc(int(abs(math.sin(i + 1)) * 4294967296)),
  297. C[C_index] if C_index < len(C) else None))
  298. I = I_table[4 * I + i % 4]
  299. o = [o[3],
  300. L(o[1], trunc(trunc(m << I) | urshift(m, 32 - I))),
  301. o[1],
  302. o[2]]
  303. new_M = [L(o[0], M[0]), L(o[1], M[1]), L(o[2], M[2]), L(o[3], M[3])]
  304. s = [new_M[a >> 3] >> (1 ^ a & 7) * 4 & 15 for a in range(32)]
  305. return binascii.hexlify(intlist_to_bytes(s))[1::2].decode('ascii')
  306. def get_raw_data(self, tvid, video_id):
  307. tm = int(time.time() * 1000)
  308. sc = self._gen_sc(tvid, tm)
  309. params = {
  310. 'platForm': 'h5',
  311. 'rate': 1,
  312. 'tvid': tvid,
  313. 'vid': video_id,
  314. 'cupid': 'qc_100001_100186',
  315. 'type': 'mp4',
  316. 'nolimit': 0,
  317. 'agenttype': 13,
  318. 'src': 'd846d0c32d664d32b6b54ea48997a589',
  319. 'sc': sc,
  320. 't': tm - 7,
  321. '__jsT': None,
  322. }
  323. headers = {}
  324. cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
  325. if cn_verification_proxy:
  326. headers['Ytdl-request-proxy'] = cn_verification_proxy
  327. return self._download_json(
  328. 'http://cache.m.iqiyi.com/jp/tmts/%s/%s/' % (tvid, video_id),
  329. video_id, transform_source=lambda s: remove_start(s, 'var tvInfoJs='),
  330. query=params, headers=headers)
  331. def _extract_playlist(self, webpage):
  332. PAGE_SIZE = 50
  333. links = re.findall(
  334. r'<a[^>]+class="site-piclist_pic_link"[^>]+href="(http://www\.iqiyi\.com/.+\.html)"',
  335. webpage)
  336. if not links:
  337. return
  338. album_id = self._search_regex(
  339. r'albumId\s*:\s*(\d+),', webpage, 'album ID')
  340. album_title = self._search_regex(
  341. r'data-share-title="([^"]+)"', webpage, 'album title', fatal=False)
  342. entries = list(map(self.url_result, links))
  343. # Start from 2 because links in the first page are already on webpage
  344. for page_num in itertools.count(2):
  345. pagelist_page = self._download_webpage(
  346. 'http://cache.video.qiyi.com/jp/avlist/%s/%d/%d/' % (album_id, page_num, PAGE_SIZE),
  347. album_id,
  348. note='Download playlist page %d' % page_num,
  349. errnote='Failed to download playlist page %d' % page_num)
  350. pagelist = self._parse_json(
  351. remove_start(pagelist_page, 'var tvInfoJs='), album_id)
  352. vlist = pagelist['data']['vlist']
  353. for item in vlist:
  354. entries.append(self.url_result(item['vurl']))
  355. if len(vlist) < PAGE_SIZE:
  356. break
  357. return self.playlist_result(entries, album_id, album_title)
  358. def _real_extract(self, url):
  359. webpage = self._download_webpage(
  360. url, 'temp_id', note='download video page')
  361. # There's no simple way to determine whether an URL is a playlist or not
  362. # So detect it
  363. playlist_result = self._extract_playlist(webpage)
  364. if playlist_result:
  365. return playlist_result
  366. tvid = self._search_regex(
  367. r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
  368. video_id = self._search_regex(
  369. r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
  370. for _ in range(5):
  371. raw_data = self.get_raw_data(tvid, video_id)
  372. if raw_data['code'] != 'A00000':
  373. if raw_data['code'] == 'A00111':
  374. self.raise_geo_restricted()
  375. raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
  376. data = raw_data['data']
  377. # iQiYi sometimes returns Ads
  378. if not isinstance(data['playInfo'], dict):
  379. self._sleep(5, video_id)
  380. continue
  381. title = data['playInfo']['an']
  382. break
  383. return {
  384. 'id': video_id,
  385. 'title': title,
  386. 'url': data['m3u'],
  387. }