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.

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