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.

614 lines
21 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 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|www\.pps\.tv)/.+\.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. 'url': 'http://www.pps.tv/w_19rrbav0ph.html',
  245. 'only_matching': True,
  246. }]
  247. _FORMATS_MAP = [
  248. ('1', 'h6'),
  249. ('2', 'h5'),
  250. ('3', 'h4'),
  251. ('4', 'h3'),
  252. ('5', 'h2'),
  253. ('10', 'h1'),
  254. ]
  255. def _real_initialize(self):
  256. self._login()
  257. @staticmethod
  258. def _rsa_fun(data):
  259. # public key extracted from http://static.iqiyi.com/js/qiyiV2/20160129180840/jobs/i18n/i18nIndex.js
  260. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  261. e = 65537
  262. return ohdave_rsa_encrypt(data, e, N)
  263. def _login(self):
  264. (username, password) = self._get_login_info()
  265. # No authentication to be performed
  266. if not username:
  267. return True
  268. data = self._download_json(
  269. 'http://kylin.iqiyi.com/get_token', None,
  270. note='Get token for logging', errnote='Unable to get token for logging')
  271. sdk = data['sdk']
  272. timestamp = int(time.time())
  273. 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' % (
  274. username, self._rsa_fun(password.encode('utf-8')))
  275. interp = IqiyiSDKInterpreter(sdk)
  276. sign = interp.run(target, data['ip'], timestamp)
  277. validation_params = {
  278. 'target': target,
  279. 'server': 'BEA3AA1908656AABCCFF76582C4C6660',
  280. 'token': data['token'],
  281. 'bird_src': 'f8d91d57af224da7893dd397d52d811a',
  282. 'sign': sign,
  283. 'bird_t': timestamp,
  284. }
  285. validation_result = self._download_json(
  286. 'http://kylin.iqiyi.com/validate?' + compat_urllib_parse_urlencode(validation_params), None,
  287. note='Validate credentials', errnote='Unable to validate credentials')
  288. MSG_MAP = {
  289. 'P00107': 'please login via the web interface and enter the CAPTCHA code',
  290. 'P00117': 'bad username or password',
  291. }
  292. code = validation_result['code']
  293. if code != 'A00000':
  294. msg = MSG_MAP.get(code)
  295. if not msg:
  296. msg = 'error %s' % code
  297. if validation_result.get('msg'):
  298. msg += ': ' + validation_result['msg']
  299. self._downloader.report_warning('unable to log in: ' + msg)
  300. return False
  301. return True
  302. def _authenticate_vip_video(self, api_video_url, video_id, tvid, _uuid, do_report_warning):
  303. auth_params = {
  304. # version and platform hard-coded in com/qiyi/player/core/model/remote/AuthenticationRemote.as
  305. 'version': '2.0',
  306. 'platform': 'b6c13e26323c537d',
  307. 'aid': tvid,
  308. 'tvid': tvid,
  309. 'uid': '',
  310. 'deviceId': _uuid,
  311. 'playType': 'main', # XXX: always main?
  312. 'filename': os.path.splitext(url_basename(api_video_url))[0],
  313. }
  314. qd_items = compat_parse_qs(compat_urllib_parse_urlparse(api_video_url).query)
  315. for key, val in qd_items.items():
  316. auth_params[key] = val[0]
  317. auth_req = sanitized_Request(
  318. 'http://api.vip.iqiyi.com/services/ckn.action',
  319. urlencode_postdata(auth_params))
  320. # iQiyi server throws HTTP 405 error without the following header
  321. auth_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  322. auth_result = self._download_json(
  323. auth_req, video_id,
  324. note='Downloading video authentication JSON',
  325. errnote='Unable to download video authentication JSON')
  326. if auth_result['code'] == 'Q00505': # No preview available (不允许试看鉴权失败)
  327. raise ExtractorError('This video requires a VIP account', expected=True)
  328. if auth_result['code'] == 'Q00506': # End of preview time (试看结束鉴权失败)
  329. if do_report_warning:
  330. self.report_warning('Needs a VIP account for full video')
  331. return False
  332. return auth_result
  333. def construct_video_urls(self, data, video_id, _uuid, tvid):
  334. def do_xor(x, y):
  335. a = y % 3
  336. if a == 1:
  337. return x ^ 121
  338. if a == 2:
  339. return x ^ 72
  340. return x ^ 103
  341. def get_encode_code(l):
  342. a = 0
  343. b = l.split('-')
  344. c = len(b)
  345. s = ''
  346. for i in range(c - 1, -1, -1):
  347. a = do_xor(int(b[c - i - 1], 16), i)
  348. s += chr(a)
  349. return s[::-1]
  350. def get_path_key(x, format_id, segment_index):
  351. mg = ')(*&^flash@#$%a'
  352. tm = self._download_json(
  353. 'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id,
  354. note='Download path key of segment %d for format %s' % (segment_index + 1, format_id)
  355. )['t']
  356. t = str(int(math.floor(int(tm) / (600.0))))
  357. return md5_text(t + mg + x)
  358. video_urls_dict = {}
  359. need_vip_warning_report = True
  360. for format_item in data['vp']['tkl'][0]['vs']:
  361. if 0 < int(format_item['bid']) <= 10:
  362. format_id = self.get_format(format_item['bid'])
  363. else:
  364. continue
  365. video_urls = []
  366. video_urls_info = format_item['fs']
  367. if not format_item['fs'][0]['l'].startswith('/'):
  368. t = get_encode_code(format_item['fs'][0]['l'])
  369. if t.endswith('mp4'):
  370. video_urls_info = format_item['flvs']
  371. for segment_index, segment in enumerate(video_urls_info):
  372. vl = segment['l']
  373. if not vl.startswith('/'):
  374. vl = get_encode_code(vl)
  375. is_vip_video = '/vip/' in vl
  376. filesize = segment['b']
  377. base_url = data['vp']['du'].split('/')
  378. if not is_vip_video:
  379. key = get_path_key(
  380. vl.split('/')[-1].split('.')[0], format_id, segment_index)
  381. base_url.insert(-1, key)
  382. base_url = '/'.join(base_url)
  383. param = {
  384. 'su': _uuid,
  385. 'qyid': uuid.uuid4().hex,
  386. 'client': '',
  387. 'z': '',
  388. 'bt': '',
  389. 'ct': '',
  390. 'tn': str(int(time.time()))
  391. }
  392. api_video_url = base_url + vl
  393. if is_vip_video:
  394. api_video_url = api_video_url.replace('.f4v', '.hml')
  395. auth_result = self._authenticate_vip_video(
  396. api_video_url, video_id, tvid, _uuid, need_vip_warning_report)
  397. if auth_result is False:
  398. need_vip_warning_report = False
  399. break
  400. param.update({
  401. 't': auth_result['data']['t'],
  402. # cid is hard-coded in com/qiyi/player/core/player/RuntimeData.as
  403. 'cid': 'afbe8fd3d73448c9',
  404. 'vid': video_id,
  405. 'QY00001': auth_result['data']['u'],
  406. })
  407. api_video_url += '?' if '?' not in api_video_url else '&'
  408. api_video_url += compat_urllib_parse_urlencode(param)
  409. js = self._download_json(
  410. api_video_url, video_id,
  411. note='Download video info of segment %d for format %s' % (segment_index + 1, format_id))
  412. video_url = js['l']
  413. video_urls.append(
  414. (video_url, filesize))
  415. video_urls_dict[format_id] = video_urls
  416. return video_urls_dict
  417. def get_format(self, bid):
  418. matched_format_ids = [_format_id for _bid, _format_id in self._FORMATS_MAP if _bid == str(bid)]
  419. return matched_format_ids[0] if len(matched_format_ids) else None
  420. def get_bid(self, format_id):
  421. matched_bids = [_bid for _bid, _format_id in self._FORMATS_MAP if _format_id == format_id]
  422. return matched_bids[0] if len(matched_bids) else None
  423. def get_raw_data(self, tvid, video_id, enc_key, _uuid):
  424. tm = str(int(time.time()))
  425. tail = tm + tvid
  426. param = {
  427. 'key': 'fvip',
  428. 'src': md5_text('youtube-dl'),
  429. 'tvId': tvid,
  430. 'vid': video_id,
  431. 'vinfo': 1,
  432. 'tm': tm,
  433. 'enc': md5_text(enc_key + tail),
  434. 'qyid': _uuid,
  435. 'tn': random.random(),
  436. 'um': 0,
  437. 'authkey': md5_text(md5_text('') + tail),
  438. 'k_tag': 1,
  439. }
  440. api_url = 'http://cache.video.qiyi.com/vms' + '?' + \
  441. compat_urllib_parse_urlencode(param)
  442. raw_data = self._download_json(api_url, video_id)
  443. return raw_data
  444. def get_enc_key(self, video_id):
  445. # TODO: automatic key extraction
  446. # last update at 2016-01-22 for Zombie::bite
  447. enc_key = '4a1caba4b4465345366f28da7c117d20'
  448. return enc_key
  449. def _extract_playlist(self, webpage):
  450. PAGE_SIZE = 50
  451. links = re.findall(
  452. r'<a[^>]+class="site-piclist_pic_link"[^>]+href="(http://www\.iqiyi\.com/.+\.html)"',
  453. webpage)
  454. if not links:
  455. return
  456. album_id = self._search_regex(
  457. r'albumId\s*:\s*(\d+),', webpage, 'album ID')
  458. album_title = self._search_regex(
  459. r'data-share-title="([^"]+)"', webpage, 'album title', fatal=False)
  460. entries = list(map(self.url_result, links))
  461. # Start from 2 because links in the first page are already on webpage
  462. for page_num in itertools.count(2):
  463. pagelist_page = self._download_webpage(
  464. 'http://cache.video.qiyi.com/jp/avlist/%s/%d/%d/' % (album_id, page_num, PAGE_SIZE),
  465. album_id,
  466. note='Download playlist page %d' % page_num,
  467. errnote='Failed to download playlist page %d' % page_num)
  468. pagelist = self._parse_json(
  469. remove_start(pagelist_page, 'var tvInfoJs='), album_id)
  470. vlist = pagelist['data']['vlist']
  471. for item in vlist:
  472. entries.append(self.url_result(item['vurl']))
  473. if len(vlist) < PAGE_SIZE:
  474. break
  475. return self.playlist_result(entries, album_id, album_title)
  476. def _real_extract(self, url):
  477. webpage = self._download_webpage(
  478. url, 'temp_id', note='download video page')
  479. # There's no simple way to determine whether an URL is a playlist or not
  480. # So detect it
  481. playlist_result = self._extract_playlist(webpage)
  482. if playlist_result:
  483. return playlist_result
  484. tvid = self._search_regex(
  485. r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
  486. video_id = self._search_regex(
  487. r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
  488. _uuid = uuid.uuid4().hex
  489. enc_key = self.get_enc_key(video_id)
  490. raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid)
  491. if raw_data['code'] != 'A000000':
  492. raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
  493. data = raw_data['data']
  494. title = data['vi']['vn']
  495. # generate video_urls_dict
  496. video_urls_dict = self.construct_video_urls(
  497. data, video_id, _uuid, tvid)
  498. # construct info
  499. entries = []
  500. for format_id in video_urls_dict:
  501. video_urls = video_urls_dict[format_id]
  502. for i, video_url_info in enumerate(video_urls):
  503. if len(entries) < i + 1:
  504. entries.append({'formats': []})
  505. entries[i]['formats'].append(
  506. {
  507. 'url': video_url_info[0],
  508. 'filesize': video_url_info[-1],
  509. 'format_id': format_id,
  510. 'preference': int(self.get_bid(format_id))
  511. }
  512. )
  513. for i in range(len(entries)):
  514. self._sort_formats(entries[i]['formats'])
  515. entries[i].update(
  516. {
  517. 'id': '%s_part%d' % (video_id, i + 1),
  518. 'title': title,
  519. }
  520. )
  521. if len(entries) > 1:
  522. info = {
  523. '_type': 'multi_video',
  524. 'id': video_id,
  525. 'title': title,
  526. 'entries': entries,
  527. }
  528. else:
  529. info = entries[0]
  530. info['id'] = video_id
  531. info['title'] = title
  532. return info