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.

386 lines
13 KiB

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 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': 'b7dc800a4004b1b57749d9abae0472da',
  144. 'info_dict': {
  145. 'id': 'e3f585b550a280af23c98b6cb2be19fb',
  146. 'ext': 'mp4',
  147. # This can be either Simplified Chinese or Traditional Chinese
  148. 'title': r're:^(?:名侦探柯南 国语版:第752集 迫近灰原秘密的黑影 下篇|名偵探柯南 國語版:第752集 迫近灰原秘密的黑影 下篇)$',
  149. },
  150. 'skip': 'Geo-restricted to China',
  151. }, {
  152. 'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html',
  153. 'only_matching': True,
  154. }, {
  155. 'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html',
  156. 'only_matching': True,
  157. }, {
  158. 'url': 'http://yule.iqiyi.com/pcb.html',
  159. 'only_matching': True,
  160. }, {
  161. # VIP-only video. The first 2 parts (6 minutes) are available without login
  162. # MD5 sums omitted as values are different on Travis CI and my machine
  163. 'url': 'http://www.iqiyi.com/v_19rrny4w8w.html',
  164. 'info_dict': {
  165. 'id': 'f3cf468b39dddb30d676f89a91200dc1',
  166. 'ext': 'mp4',
  167. 'title': '泰坦尼克号',
  168. },
  169. 'skip': 'Geo-restricted to China',
  170. }, {
  171. 'url': 'http://www.iqiyi.com/a_19rrhb8ce1.html',
  172. 'info_dict': {
  173. 'id': '202918101',
  174. 'title': '灌篮高手 国语版',
  175. },
  176. 'playlist_count': 101,
  177. }, {
  178. 'url': 'http://www.pps.tv/w_19rrbav0ph.html',
  179. 'only_matching': True,
  180. }]
  181. _FORMATS_MAP = {
  182. '96': 1, # 216p, 240p
  183. '1': 2, # 336p, 360p
  184. '2': 3, # 480p, 504p
  185. '21': 4, # 504p
  186. '4': 5, # 720p
  187. '17': 5, # 720p
  188. '5': 6, # 1072p, 1080p
  189. '18': 7, # 1080p
  190. }
  191. def _real_initialize(self):
  192. self._login()
  193. @staticmethod
  194. def _rsa_fun(data):
  195. # public key extracted from http://static.iqiyi.com/js/qiyiV2/20160129180840/jobs/i18n/i18nIndex.js
  196. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  197. e = 65537
  198. return ohdave_rsa_encrypt(data, e, N)
  199. def _login(self):
  200. (username, password) = self._get_login_info()
  201. # No authentication to be performed
  202. if not username:
  203. return True
  204. data = self._download_json(
  205. 'http://kylin.iqiyi.com/get_token', None,
  206. note='Get token for logging', errnote='Unable to get token for logging')
  207. sdk = data['sdk']
  208. timestamp = int(time.time())
  209. 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' % (
  210. username, self._rsa_fun(password.encode('utf-8')))
  211. interp = IqiyiSDKInterpreter(sdk)
  212. sign = interp.run(target, data['ip'], timestamp)
  213. validation_params = {
  214. 'target': target,
  215. 'server': 'BEA3AA1908656AABCCFF76582C4C6660',
  216. 'token': data['token'],
  217. 'bird_src': 'f8d91d57af224da7893dd397d52d811a',
  218. 'sign': sign,
  219. 'bird_t': timestamp,
  220. }
  221. validation_result = self._download_json(
  222. 'http://kylin.iqiyi.com/validate?' + compat_urllib_parse_urlencode(validation_params), None,
  223. note='Validate credentials', errnote='Unable to validate credentials')
  224. MSG_MAP = {
  225. 'P00107': 'please login via the web interface and enter the CAPTCHA code',
  226. 'P00117': 'bad username or password',
  227. }
  228. code = validation_result['code']
  229. if code != 'A00000':
  230. msg = MSG_MAP.get(code)
  231. if not msg:
  232. msg = 'error %s' % code
  233. if validation_result.get('msg'):
  234. msg += ': ' + validation_result['msg']
  235. self._downloader.report_warning('unable to log in: ' + msg)
  236. return False
  237. return True
  238. def get_raw_data(self, tvid, video_id):
  239. tm = int(time.time() * 1000)
  240. key = 'd5fb4bd9d50c4be6948c97edd7254b0e'
  241. sc = md5_text(compat_str(tm) + key + tvid)
  242. params = {
  243. 'tvid': tvid,
  244. 'vid': video_id,
  245. 'src': '76f90cbd92f94a2e925d83e8ccd22cb7',
  246. 'sc': sc,
  247. 't': tm,
  248. }
  249. return self._download_json(
  250. 'http://cache.m.iqiyi.com/jp/tmts/%s/%s/' % (tvid, video_id),
  251. video_id, transform_source=lambda s: remove_start(s, 'var tvInfoJs='),
  252. query=params, headers=self.geo_verification_headers())
  253. def _extract_playlist(self, webpage):
  254. PAGE_SIZE = 50
  255. links = re.findall(
  256. r'<a[^>]+class="site-piclist_pic_link"[^>]+href="(http://www\.iqiyi\.com/.+\.html)"',
  257. webpage)
  258. if not links:
  259. return
  260. album_id = self._search_regex(
  261. r'albumId\s*:\s*(\d+),', webpage, 'album ID')
  262. album_title = self._search_regex(
  263. r'data-share-title="([^"]+)"', webpage, 'album title', fatal=False)
  264. entries = list(map(self.url_result, links))
  265. # Start from 2 because links in the first page are already on webpage
  266. for page_num in itertools.count(2):
  267. pagelist_page = self._download_webpage(
  268. 'http://cache.video.qiyi.com/jp/avlist/%s/%d/%d/' % (album_id, page_num, PAGE_SIZE),
  269. album_id,
  270. note='Download playlist page %d' % page_num,
  271. errnote='Failed to download playlist page %d' % page_num)
  272. pagelist = self._parse_json(
  273. remove_start(pagelist_page, 'var tvInfoJs='), album_id)
  274. vlist = pagelist['data']['vlist']
  275. for item in vlist:
  276. entries.append(self.url_result(item['vurl']))
  277. if len(vlist) < PAGE_SIZE:
  278. break
  279. return self.playlist_result(entries, album_id, album_title)
  280. def _real_extract(self, url):
  281. webpage = self._download_webpage(
  282. url, 'temp_id', note='download video page')
  283. # There's no simple way to determine whether an URL is a playlist or not
  284. # So detect it
  285. playlist_result = self._extract_playlist(webpage)
  286. if playlist_result:
  287. return playlist_result
  288. tvid = self._search_regex(
  289. r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
  290. video_id = self._search_regex(
  291. r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
  292. formats = []
  293. for _ in range(5):
  294. raw_data = self.get_raw_data(tvid, video_id)
  295. if raw_data['code'] != 'A00000':
  296. if raw_data['code'] == 'A00111':
  297. self.raise_geo_restricted()
  298. raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
  299. data = raw_data['data']
  300. for stream in data['vidl']:
  301. if 'm3utx' not in stream:
  302. continue
  303. vd = compat_str(stream['vd'])
  304. formats.append({
  305. 'url': stream['m3utx'],
  306. 'format_id': vd,
  307. 'ext': 'mp4',
  308. 'preference': self._FORMATS_MAP.get(vd, -1),
  309. 'protocol': 'm3u8_native',
  310. })
  311. if formats:
  312. break
  313. self._sleep(5, video_id)
  314. self._sort_formats(formats)
  315. title = (get_element_by_id('widget-videotitle', webpage) or
  316. clean_html(get_element_by_attribute('class', 'mod-play-tit', webpage)))
  317. return {
  318. 'id': video_id,
  319. 'title': title,
  320. 'formats': formats,
  321. }