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.

385 lines
13 KiB

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 re
  6. import time
  7. from .common import InfoExtractor
  8. from ..compat import (
  9. compat_str,
  10. compat_urllib_parse_urlencode,
  11. )
  12. from ..utils import (
  13. clean_html,
  14. decode_packed_codes,
  15. get_element_by_id,
  16. get_element_by_attribute,
  17. ExtractorError,
  18. ohdave_rsa_encrypt,
  19. remove_start,
  20. )
  21. def md5_text(text):
  22. return hashlib.md5(text.encode('utf-8')).hexdigest()
  23. class IqiyiSDK(object):
  24. def __init__(self, target, ip, timestamp):
  25. self.target = target
  26. self.ip = ip
  27. self.timestamp = timestamp
  28. @staticmethod
  29. def split_sum(data):
  30. return compat_str(sum(map(lambda p: int(p, 16), list(data))))
  31. @staticmethod
  32. def digit_sum(num):
  33. if isinstance(num, int):
  34. num = compat_str(num)
  35. return compat_str(sum(map(int, num)))
  36. def even_odd(self):
  37. even = self.digit_sum(compat_str(self.timestamp)[::2])
  38. odd = self.digit_sum(compat_str(self.timestamp)[1::2])
  39. return even, odd
  40. def preprocess(self, chunksize):
  41. self.target = md5_text(self.target)
  42. chunks = []
  43. for i in range(32 // chunksize):
  44. chunks.append(self.target[chunksize * i:chunksize * (i + 1)])
  45. if 32 % chunksize:
  46. chunks.append(self.target[32 - 32 % chunksize:])
  47. return chunks, list(map(int, self.ip.split('.')))
  48. def mod(self, modulus):
  49. chunks, ip = self.preprocess(32)
  50. self.target = chunks[0] + ''.join(map(lambda p: compat_str(p % modulus), ip))
  51. def split(self, chunksize):
  52. modulus_map = {
  53. 4: 256,
  54. 5: 10,
  55. 8: 100,
  56. }
  57. chunks, ip = self.preprocess(chunksize)
  58. ret = ''
  59. for i in range(len(chunks)):
  60. ip_part = compat_str(ip[i] % modulus_map[chunksize]) if i < 4 else ''
  61. if chunksize == 8:
  62. ret += ip_part + chunks[i]
  63. else:
  64. ret += chunks[i] + ip_part
  65. self.target = ret
  66. def handle_input16(self):
  67. self.target = md5_text(self.target)
  68. self.target = self.split_sum(self.target[:16]) + self.target + self.split_sum(self.target[16:])
  69. def handle_input8(self):
  70. self.target = md5_text(self.target)
  71. ret = ''
  72. for i in range(4):
  73. part = self.target[8 * i:8 * (i + 1)]
  74. ret += self.split_sum(part) + part
  75. self.target = ret
  76. def handleSum(self):
  77. self.target = md5_text(self.target)
  78. self.target = self.split_sum(self.target) + self.target
  79. def date(self, scheme):
  80. self.target = md5_text(self.target)
  81. d = time.localtime(self.timestamp)
  82. strings = {
  83. 'y': compat_str(d.tm_year),
  84. 'm': '%02d' % d.tm_mon,
  85. 'd': '%02d' % d.tm_mday,
  86. }
  87. self.target += ''.join(map(lambda c: strings[c], list(scheme)))
  88. def split_time_even_odd(self):
  89. even, odd = self.even_odd()
  90. self.target = odd + md5_text(self.target) + even
  91. def split_time_odd_even(self):
  92. even, odd = self.even_odd()
  93. self.target = even + md5_text(self.target) + odd
  94. def split_ip_time_sum(self):
  95. chunks, ip = self.preprocess(32)
  96. self.target = compat_str(sum(ip)) + chunks[0] + self.digit_sum(self.timestamp)
  97. def split_time_ip_sum(self):
  98. chunks, ip = self.preprocess(32)
  99. self.target = self.digit_sum(self.timestamp) + chunks[0] + compat_str(sum(ip))
  100. class IqiyiSDKInterpreter(object):
  101. def __init__(self, sdk_code):
  102. self.sdk_code = sdk_code
  103. def run(self, target, ip, timestamp):
  104. self.sdk_code = decode_packed_codes(self.sdk_code)
  105. functions = re.findall(r'input=([a-zA-Z0-9]+)\(input', self.sdk_code)
  106. sdk = IqiyiSDK(target, ip, timestamp)
  107. other_functions = {
  108. 'handleSum': sdk.handleSum,
  109. 'handleInput8': sdk.handle_input8,
  110. 'handleInput16': sdk.handle_input16,
  111. 'splitTimeEvenOdd': sdk.split_time_even_odd,
  112. 'splitTimeOddEven': sdk.split_time_odd_even,
  113. 'splitIpTimeSum': sdk.split_ip_time_sum,
  114. 'splitTimeIpSum': sdk.split_time_ip_sum,
  115. }
  116. for function in functions:
  117. if re.match(r'mod\d+', function):
  118. sdk.mod(int(function[3:]))
  119. elif re.match(r'date[ymd]{3}', function):
  120. sdk.date(function[4:])
  121. elif re.match(r'split\d+', function):
  122. sdk.split(int(function[5:]))
  123. elif function in other_functions:
  124. other_functions[function]()
  125. else:
  126. raise ExtractorError('Unknown funcion %s' % function)
  127. return sdk.target
  128. class IqiyiIE(InfoExtractor):
  129. IE_NAME = 'iqiyi'
  130. IE_DESC = '爱奇艺'
  131. _VALID_URL = r'https?://(?:(?:[^.]+\.)?iqiyi\.com|www\.pps\.tv)/.+\.html'
  132. _NETRC_MACHINE = 'iqiyi'
  133. _TESTS = [{
  134. 'url': 'http://www.iqiyi.com/v_19rrojlavg.html',
  135. # MD5 checksum differs on my machine and Travis CI
  136. 'info_dict': {
  137. 'id': '9c1fb1b99d192b21c559e5a1a2cb3c73',
  138. 'ext': 'mp4',
  139. 'title': '美国德州空中惊现奇异云团 酷似UFO',
  140. }
  141. }, {
  142. 'url': 'http://www.iqiyi.com/v_19rrhnnclk.html',
  143. 'md5': '667171934041350c5de3f5015f7f1152',
  144. 'info_dict': {
  145. 'id': 'e3f585b550a280af23c98b6cb2be19fb',
  146. 'ext': 'mp4',
  147. 'title': '名侦探柯南 国语版:第752集 迫近灰原秘密的黑影 下篇',
  148. },
  149. 'skip': 'Geo-restricted to China',
  150. }, {
  151. 'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html',
  152. 'only_matching': True,
  153. }, {
  154. 'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html',
  155. 'only_matching': True,
  156. }, {
  157. 'url': 'http://yule.iqiyi.com/pcb.html',
  158. 'only_matching': True,
  159. }, {
  160. # VIP-only video. The first 2 parts (6 minutes) are available without login
  161. # MD5 sums omitted as values are different on Travis CI and my machine
  162. 'url': 'http://www.iqiyi.com/v_19rrny4w8w.html',
  163. 'info_dict': {
  164. 'id': 'f3cf468b39dddb30d676f89a91200dc1',
  165. 'ext': 'mp4',
  166. 'title': '泰坦尼克号',
  167. },
  168. 'skip': 'Geo-restricted to China',
  169. }, {
  170. 'url': 'http://www.iqiyi.com/a_19rrhb8ce1.html',
  171. 'info_dict': {
  172. 'id': '202918101',
  173. 'title': '灌篮高手 国语版',
  174. },
  175. 'playlist_count': 101,
  176. }, {
  177. 'url': 'http://www.pps.tv/w_19rrbav0ph.html',
  178. 'only_matching': True,
  179. }]
  180. _FORMATS_MAP = {
  181. '96': 1, # 216p, 240p
  182. '1': 2, # 336p, 360p
  183. '2': 3, # 480p, 504p
  184. '21': 4, # 504p
  185. '4': 5, # 720p
  186. '17': 5, # 720p
  187. '5': 6, # 1072p, 1080p
  188. '18': 7, # 1080p
  189. }
  190. def _real_initialize(self):
  191. self._login()
  192. @staticmethod
  193. def _rsa_fun(data):
  194. # public key extracted from http://static.iqiyi.com/js/qiyiV2/20160129180840/jobs/i18n/i18nIndex.js
  195. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  196. e = 65537
  197. return ohdave_rsa_encrypt(data, e, N)
  198. def _login(self):
  199. (username, password) = self._get_login_info()
  200. # No authentication to be performed
  201. if not username:
  202. return True
  203. data = self._download_json(
  204. 'http://kylin.iqiyi.com/get_token', None,
  205. note='Get token for logging', errnote='Unable to get token for logging')
  206. sdk = data['sdk']
  207. timestamp = int(time.time())
  208. 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' % (
  209. username, self._rsa_fun(password.encode('utf-8')))
  210. interp = IqiyiSDKInterpreter(sdk)
  211. sign = interp.run(target, data['ip'], timestamp)
  212. validation_params = {
  213. 'target': target,
  214. 'server': 'BEA3AA1908656AABCCFF76582C4C6660',
  215. 'token': data['token'],
  216. 'bird_src': 'f8d91d57af224da7893dd397d52d811a',
  217. 'sign': sign,
  218. 'bird_t': timestamp,
  219. }
  220. validation_result = self._download_json(
  221. 'http://kylin.iqiyi.com/validate?' + compat_urllib_parse_urlencode(validation_params), None,
  222. note='Validate credentials', errnote='Unable to validate credentials')
  223. MSG_MAP = {
  224. 'P00107': 'please login via the web interface and enter the CAPTCHA code',
  225. 'P00117': 'bad username or password',
  226. }
  227. code = validation_result['code']
  228. if code != 'A00000':
  229. msg = MSG_MAP.get(code)
  230. if not msg:
  231. msg = 'error %s' % code
  232. if validation_result.get('msg'):
  233. msg += ': ' + validation_result['msg']
  234. self._downloader.report_warning('unable to log in: ' + msg)
  235. return False
  236. return True
  237. def get_raw_data(self, tvid, video_id):
  238. tm = int(time.time() * 1000)
  239. key = 'd5fb4bd9d50c4be6948c97edd7254b0e'
  240. sc = md5_text(compat_str(tm) + key + tvid)
  241. params = {
  242. 'tvid': tvid,
  243. 'vid': video_id,
  244. 'src': '76f90cbd92f94a2e925d83e8ccd22cb7',
  245. 'sc': sc,
  246. 't': tm,
  247. }
  248. return self._download_json(
  249. 'http://cache.m.iqiyi.com/jp/tmts/%s/%s/' % (tvid, video_id),
  250. video_id, transform_source=lambda s: remove_start(s, 'var tvInfoJs='),
  251. query=params, headers=self.geo_verification_headers())
  252. def _extract_playlist(self, webpage):
  253. PAGE_SIZE = 50
  254. links = re.findall(
  255. r'<a[^>]+class="site-piclist_pic_link"[^>]+href="(http://www\.iqiyi\.com/.+\.html)"',
  256. webpage)
  257. if not links:
  258. return
  259. album_id = self._search_regex(
  260. r'albumId\s*:\s*(\d+),', webpage, 'album ID')
  261. album_title = self._search_regex(
  262. r'data-share-title="([^"]+)"', webpage, 'album title', fatal=False)
  263. entries = list(map(self.url_result, links))
  264. # Start from 2 because links in the first page are already on webpage
  265. for page_num in itertools.count(2):
  266. pagelist_page = self._download_webpage(
  267. 'http://cache.video.qiyi.com/jp/avlist/%s/%d/%d/' % (album_id, page_num, PAGE_SIZE),
  268. album_id,
  269. note='Download playlist page %d' % page_num,
  270. errnote='Failed to download playlist page %d' % page_num)
  271. pagelist = self._parse_json(
  272. remove_start(pagelist_page, 'var tvInfoJs='), album_id)
  273. vlist = pagelist['data']['vlist']
  274. for item in vlist:
  275. entries.append(self.url_result(item['vurl']))
  276. if len(vlist) < PAGE_SIZE:
  277. break
  278. return self.playlist_result(entries, album_id, album_title)
  279. def _real_extract(self, url):
  280. webpage = self._download_webpage(
  281. url, 'temp_id', note='download video page')
  282. # There's no simple way to determine whether an URL is a playlist or not
  283. # So detect it
  284. playlist_result = self._extract_playlist(webpage)
  285. if playlist_result:
  286. return playlist_result
  287. tvid = self._search_regex(
  288. r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
  289. video_id = self._search_regex(
  290. r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
  291. formats = []
  292. for _ in range(5):
  293. raw_data = self.get_raw_data(tvid, video_id)
  294. if raw_data['code'] != 'A00000':
  295. if raw_data['code'] == 'A00111':
  296. self.raise_geo_restricted()
  297. raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
  298. data = raw_data['data']
  299. for stream in data['vidl']:
  300. if 'm3utx' not in stream:
  301. continue
  302. vd = compat_str(stream['vd'])
  303. formats.append({
  304. 'url': stream['m3utx'],
  305. 'format_id': vd,
  306. 'ext': 'mp4',
  307. 'preference': self._FORMATS_MAP.get(vd, -1),
  308. 'protocol': 'm3u8_native',
  309. })
  310. if formats:
  311. break
  312. self._sleep(5, video_id)
  313. self._sort_formats(formats)
  314. title = (get_element_by_id('widget-videotitle', webpage) or
  315. clean_html(get_element_by_attribute('class', 'mod-play-tit', webpage)))
  316. return {
  317. 'id': video_id,
  318. 'title': title,
  319. 'formats': formats,
  320. }