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.

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