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.

608 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,
  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'] == 'Q00506': # requires a VIP account
  324. if do_report_warning:
  325. self.report_warning('Needs a VIP account for full video')
  326. return False
  327. return auth_result
  328. def construct_video_urls(self, data, video_id, _uuid, tvid):
  329. def do_xor(x, y):
  330. a = y % 3
  331. if a == 1:
  332. return x ^ 121
  333. if a == 2:
  334. return x ^ 72
  335. return x ^ 103
  336. def get_encode_code(l):
  337. a = 0
  338. b = l.split('-')
  339. c = len(b)
  340. s = ''
  341. for i in range(c - 1, -1, -1):
  342. a = do_xor(int(b[c - i - 1], 16), i)
  343. s += chr(a)
  344. return s[::-1]
  345. def get_path_key(x, format_id, segment_index):
  346. mg = ')(*&^flash@#$%a'
  347. tm = self._download_json(
  348. 'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id,
  349. note='Download path key of segment %d for format %s' % (segment_index + 1, format_id)
  350. )['t']
  351. t = str(int(math.floor(int(tm) / (600.0))))
  352. return md5_text(t + mg + x)
  353. video_urls_dict = {}
  354. need_vip_warning_report = True
  355. for format_item in data['vp']['tkl'][0]['vs']:
  356. if 0 < int(format_item['bid']) <= 10:
  357. format_id = self.get_format(format_item['bid'])
  358. else:
  359. continue
  360. video_urls = []
  361. video_urls_info = format_item['fs']
  362. if not format_item['fs'][0]['l'].startswith('/'):
  363. t = get_encode_code(format_item['fs'][0]['l'])
  364. if t.endswith('mp4'):
  365. video_urls_info = format_item['flvs']
  366. for segment_index, segment in enumerate(video_urls_info):
  367. vl = segment['l']
  368. if not vl.startswith('/'):
  369. vl = get_encode_code(vl)
  370. is_vip_video = '/vip/' in vl
  371. filesize = segment['b']
  372. base_url = data['vp']['du'].split('/')
  373. if not is_vip_video:
  374. key = get_path_key(
  375. vl.split('/')[-1].split('.')[0], format_id, segment_index)
  376. base_url.insert(-1, key)
  377. base_url = '/'.join(base_url)
  378. param = {
  379. 'su': _uuid,
  380. 'qyid': uuid.uuid4().hex,
  381. 'client': '',
  382. 'z': '',
  383. 'bt': '',
  384. 'ct': '',
  385. 'tn': str(int(time.time()))
  386. }
  387. api_video_url = base_url + vl
  388. if is_vip_video:
  389. api_video_url = api_video_url.replace('.f4v', '.hml')
  390. auth_result = self._authenticate_vip_video(
  391. api_video_url, video_id, tvid, _uuid, need_vip_warning_report)
  392. if auth_result is False:
  393. need_vip_warning_report = False
  394. break
  395. param.update({
  396. 't': auth_result['data']['t'],
  397. # cid is hard-coded in com/qiyi/player/core/player/RuntimeData.as
  398. 'cid': 'afbe8fd3d73448c9',
  399. 'vid': video_id,
  400. 'QY00001': auth_result['data']['u'],
  401. })
  402. api_video_url += '?' if '?' not in api_video_url else '&'
  403. api_video_url += compat_urllib_parse.urlencode(param)
  404. js = self._download_json(
  405. api_video_url, video_id,
  406. note='Download video info of segment %d for format %s' % (segment_index + 1, format_id))
  407. video_url = js['l']
  408. video_urls.append(
  409. (video_url, filesize))
  410. video_urls_dict[format_id] = video_urls
  411. return video_urls_dict
  412. def get_format(self, bid):
  413. matched_format_ids = [_format_id for _bid, _format_id in self._FORMATS_MAP if _bid == str(bid)]
  414. return matched_format_ids[0] if len(matched_format_ids) else None
  415. def get_bid(self, format_id):
  416. matched_bids = [_bid for _bid, _format_id in self._FORMATS_MAP if _format_id == format_id]
  417. return matched_bids[0] if len(matched_bids) else None
  418. def get_raw_data(self, tvid, video_id, enc_key, _uuid):
  419. tm = str(int(time.time()))
  420. tail = tm + tvid
  421. param = {
  422. 'key': 'fvip',
  423. 'src': md5_text('youtube-dl'),
  424. 'tvId': tvid,
  425. 'vid': video_id,
  426. 'vinfo': 1,
  427. 'tm': tm,
  428. 'enc': md5_text(enc_key + tail),
  429. 'qyid': _uuid,
  430. 'tn': random.random(),
  431. 'um': 0,
  432. 'authkey': md5_text(md5_text('') + tail),
  433. 'k_tag': 1,
  434. }
  435. api_url = 'http://cache.video.qiyi.com/vms' + '?' + \
  436. compat_urllib_parse.urlencode(param)
  437. raw_data = self._download_json(api_url, video_id)
  438. return raw_data
  439. def get_enc_key(self, video_id):
  440. # TODO: automatic key extraction
  441. # last update at 2016-01-22 for Zombie::bite
  442. enc_key = '8ed797d224d043e7ac23d95b70227d32'
  443. return enc_key
  444. def _extract_playlist(self, webpage):
  445. PAGE_SIZE = 50
  446. links = re.findall(
  447. r'<a[^>]+class="site-piclist_pic_link"[^>]+href="(http://www\.iqiyi\.com/.+\.html)"',
  448. webpage)
  449. if not links:
  450. return
  451. album_id = self._search_regex(
  452. r'albumId\s*:\s*(\d+),', webpage, 'album ID')
  453. album_title = self._search_regex(
  454. r'data-share-title="([^"]+)"', webpage, 'album title', fatal=False)
  455. entries = list(map(self.url_result, links))
  456. # Start from 2 because links in the first page are already on webpage
  457. for page_num in itertools.count(2):
  458. pagelist_page = self._download_webpage(
  459. 'http://cache.video.qiyi.com/jp/avlist/%s/%d/%d/' % (album_id, page_num, PAGE_SIZE),
  460. album_id,
  461. note='Download playlist page %d' % page_num,
  462. errnote='Failed to download playlist page %d' % page_num)
  463. pagelist = self._parse_json(
  464. remove_start(pagelist_page, 'var tvInfoJs='), album_id)
  465. vlist = pagelist['data']['vlist']
  466. for item in vlist:
  467. entries.append(self.url_result(item['vurl']))
  468. if len(vlist) < PAGE_SIZE:
  469. break
  470. return self.playlist_result(entries, album_id, album_title)
  471. def _real_extract(self, url):
  472. webpage = self._download_webpage(
  473. url, 'temp_id', note='download video page')
  474. # There's no simple way to determine whether an URL is a playlist or not
  475. # So detect it
  476. playlist_result = self._extract_playlist(webpage)
  477. if playlist_result:
  478. return playlist_result
  479. tvid = self._search_regex(
  480. r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
  481. video_id = self._search_regex(
  482. r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
  483. _uuid = uuid.uuid4().hex
  484. enc_key = self.get_enc_key(video_id)
  485. raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid)
  486. if raw_data['code'] != 'A000000':
  487. raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
  488. data = raw_data['data']
  489. title = data['vi']['vn']
  490. # generate video_urls_dict
  491. video_urls_dict = self.construct_video_urls(
  492. data, video_id, _uuid, tvid)
  493. # construct info
  494. entries = []
  495. for format_id in video_urls_dict:
  496. video_urls = video_urls_dict[format_id]
  497. for i, video_url_info in enumerate(video_urls):
  498. if len(entries) < i + 1:
  499. entries.append({'formats': []})
  500. entries[i]['formats'].append(
  501. {
  502. 'url': video_url_info[0],
  503. 'filesize': video_url_info[-1],
  504. 'format_id': format_id,
  505. 'preference': int(self.get_bid(format_id))
  506. }
  507. )
  508. for i in range(len(entries)):
  509. self._sort_formats(entries[i]['formats'])
  510. entries[i].update(
  511. {
  512. 'id': '%s_part%d' % (video_id, i + 1),
  513. 'title': title,
  514. }
  515. )
  516. if len(entries) > 1:
  517. info = {
  518. '_type': 'multi_video',
  519. 'id': video_id,
  520. 'title': title,
  521. 'entries': entries,
  522. }
  523. else:
  524. info = entries[0]
  525. info['id'] = video_id
  526. info['title'] = title
  527. return info