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.

641 lines
22 KiB

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