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.

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