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.

369 lines
13 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 math
  5. import os
  6. import random
  7. import time
  8. import uuid
  9. from .common import InfoExtractor
  10. from ..compat import (
  11. compat_parse_qs,
  12. compat_urllib_parse,
  13. compat_urllib_parse_urlparse,
  14. )
  15. from ..utils import (
  16. ExtractorError,
  17. sanitized_Request,
  18. urlencode_postdata,
  19. url_basename,
  20. )
  21. class IqiyiIE(InfoExtractor):
  22. IE_NAME = 'iqiyi'
  23. IE_DESC = '爱奇艺'
  24. _VALID_URL = r'http://(?:[^.]+\.)?iqiyi\.com/.+\.html'
  25. _TESTS = [{
  26. 'url': 'http://www.iqiyi.com/v_19rrojlavg.html',
  27. 'md5': '2cb594dc2781e6c941a110d8f358118b',
  28. 'info_dict': {
  29. 'id': '9c1fb1b99d192b21c559e5a1a2cb3c73',
  30. 'title': '美国德州空中惊现奇异云团 酷似UFO',
  31. 'ext': 'f4v',
  32. }
  33. }, {
  34. 'url': 'http://www.iqiyi.com/v_19rrhnnclk.html',
  35. 'info_dict': {
  36. 'id': 'e3f585b550a280af23c98b6cb2be19fb',
  37. 'title': '名侦探柯南第752集',
  38. },
  39. 'playlist': [{
  40. 'info_dict': {
  41. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part1',
  42. 'ext': 'f4v',
  43. 'title': '名侦探柯南第752集',
  44. },
  45. }, {
  46. 'info_dict': {
  47. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part2',
  48. 'ext': 'f4v',
  49. 'title': '名侦探柯南第752集',
  50. },
  51. }, {
  52. 'info_dict': {
  53. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part3',
  54. 'ext': 'f4v',
  55. 'title': '名侦探柯南第752集',
  56. },
  57. }, {
  58. 'info_dict': {
  59. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part4',
  60. 'ext': 'f4v',
  61. 'title': '名侦探柯南第752集',
  62. },
  63. }, {
  64. 'info_dict': {
  65. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part5',
  66. 'ext': 'f4v',
  67. 'title': '名侦探柯南第752集',
  68. },
  69. }, {
  70. 'info_dict': {
  71. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part6',
  72. 'ext': 'f4v',
  73. 'title': '名侦探柯南第752集',
  74. },
  75. }, {
  76. 'info_dict': {
  77. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part7',
  78. 'ext': 'f4v',
  79. 'title': '名侦探柯南第752集',
  80. },
  81. }, {
  82. 'info_dict': {
  83. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part8',
  84. 'ext': 'f4v',
  85. 'title': '名侦探柯南第752集',
  86. },
  87. }],
  88. 'params': {
  89. 'skip_download': True,
  90. },
  91. }, {
  92. 'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html',
  93. 'only_matching': True,
  94. }, {
  95. 'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html',
  96. 'only_matching': True,
  97. }, {
  98. 'url': 'http://yule.iqiyi.com/pcb.html',
  99. 'only_matching': True,
  100. }, {
  101. # VIP-only video. The first 2 parts (6 minutes) are available without login
  102. 'url': 'http://www.iqiyi.com/v_19rrny4w8w.html',
  103. 'info_dict': {
  104. 'id': 'f3cf468b39dddb30d676f89a91200dc1',
  105. 'title': '泰坦尼克号',
  106. },
  107. 'playlist': [{
  108. 'md5': '436bcde6e1307307d5ba1549715b0bbd',
  109. 'info_dict': {
  110. 'id': 'f3cf468b39dddb30d676f89a91200dc1_part1',
  111. 'ext': 'f4v',
  112. 'title': '泰坦尼克号',
  113. },
  114. }, {
  115. 'md5': 'bfc5e332f4900fde547c69372385649e',
  116. 'info_dict': {
  117. 'id': 'f3cf468b39dddb30d676f89a91200dc1_part2',
  118. 'ext': 'f4v',
  119. 'title': '泰坦尼克号',
  120. },
  121. }],
  122. 'expected_warnings': ['Needs a VIP account for full video'],
  123. }]
  124. _FORMATS_MAP = [
  125. ('1', 'h6'),
  126. ('2', 'h5'),
  127. ('3', 'h4'),
  128. ('4', 'h3'),
  129. ('5', 'h2'),
  130. ('10', 'h1'),
  131. ]
  132. @staticmethod
  133. def md5_text(text):
  134. return hashlib.md5(text.encode('utf-8')).hexdigest()
  135. def _authenticate_vip_video(self, api_video_url, video_id, tvid, _uuid, do_report_warning):
  136. auth_params = {
  137. # version and platform hard-coded in com/qiyi/player/core/model/remote/AuthenticationRemote.as
  138. 'version': '2.0',
  139. 'platform': 'b6c13e26323c537d',
  140. 'aid': tvid,
  141. 'tvid': tvid,
  142. 'uid': '',
  143. 'deviceId': _uuid,
  144. 'playType': 'main', # XXX: always main?
  145. 'filename': os.path.splitext(url_basename(api_video_url))[0],
  146. }
  147. qd_items = compat_parse_qs(compat_urllib_parse_urlparse(api_video_url).query)
  148. for key, val in qd_items.items():
  149. auth_params[key] = val[0]
  150. auth_req = sanitized_Request(
  151. 'http://api.vip.iqiyi.com/services/ckn.action',
  152. urlencode_postdata(auth_params))
  153. # iQiyi server throws HTTP 405 error without the following header
  154. auth_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  155. auth_result = self._download_json(
  156. auth_req, video_id,
  157. note='Downloading video authentication JSON',
  158. errnote='Unable to download video authentication JSON')
  159. if auth_result['code'] == 'Q00506': # requires a VIP account
  160. if do_report_warning:
  161. self.report_warning('Needs a VIP account for full video')
  162. return False
  163. return auth_result
  164. def construct_video_urls(self, data, video_id, _uuid, tvid):
  165. def do_xor(x, y):
  166. a = y % 3
  167. if a == 1:
  168. return x ^ 121
  169. if a == 2:
  170. return x ^ 72
  171. return x ^ 103
  172. def get_encode_code(l):
  173. a = 0
  174. b = l.split('-')
  175. c = len(b)
  176. s = ''
  177. for i in range(c - 1, -1, -1):
  178. a = do_xor(int(b[c - i - 1], 16), i)
  179. s += chr(a)
  180. return s[::-1]
  181. def get_path_key(x, format_id, segment_index):
  182. mg = ')(*&^flash@#$%a'
  183. tm = self._download_json(
  184. 'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id,
  185. note='Download path key of segment %d for format %s' % (segment_index + 1, format_id)
  186. )['t']
  187. t = str(int(math.floor(int(tm) / (600.0))))
  188. return self.md5_text(t + mg + x)
  189. video_urls_dict = {}
  190. need_vip_warning_report = True
  191. for format_item in data['vp']['tkl'][0]['vs']:
  192. if 0 < int(format_item['bid']) <= 10:
  193. format_id = self.get_format(format_item['bid'])
  194. else:
  195. continue
  196. video_urls = []
  197. video_urls_info = format_item['fs']
  198. if not format_item['fs'][0]['l'].startswith('/'):
  199. t = get_encode_code(format_item['fs'][0]['l'])
  200. if t.endswith('mp4'):
  201. video_urls_info = format_item['flvs']
  202. for segment_index, segment in enumerate(video_urls_info):
  203. vl = segment['l']
  204. if not vl.startswith('/'):
  205. vl = get_encode_code(vl)
  206. is_vip_video = '/vip/' in vl
  207. filesize = segment['b']
  208. base_url = data['vp']['du'].split('/')
  209. if not is_vip_video:
  210. key = get_path_key(
  211. vl.split('/')[-1].split('.')[0], format_id, segment_index)
  212. base_url.insert(-1, key)
  213. base_url = '/'.join(base_url)
  214. param = {
  215. 'su': _uuid,
  216. 'qyid': uuid.uuid4().hex,
  217. 'client': '',
  218. 'z': '',
  219. 'bt': '',
  220. 'ct': '',
  221. 'tn': str(int(time.time()))
  222. }
  223. api_video_url = base_url + vl
  224. if is_vip_video:
  225. api_video_url = api_video_url.replace('.f4v', '.hml')
  226. auth_result = self._authenticate_vip_video(
  227. api_video_url, video_id, tvid, _uuid, need_vip_warning_report)
  228. if auth_result is False:
  229. need_vip_warning_report = False
  230. break
  231. param.update({
  232. 't': auth_result['data']['t'],
  233. # cid is hard-coded in com/qiyi/player/core/player/RuntimeData.as
  234. 'cid': 'afbe8fd3d73448c9',
  235. 'vid': video_id,
  236. 'QY00001': auth_result['data']['u'],
  237. })
  238. api_video_url += '?' if '?' not in api_video_url else '&'
  239. api_video_url += compat_urllib_parse.urlencode(param)
  240. js = self._download_json(
  241. api_video_url, video_id,
  242. note='Download video info of segment %d for format %s' % (segment_index + 1, format_id))
  243. video_url = js['l']
  244. video_urls.append(
  245. (video_url, filesize))
  246. video_urls_dict[format_id] = video_urls
  247. return video_urls_dict
  248. def get_format(self, bid):
  249. matched_format_ids = [_format_id for _bid, _format_id in self._FORMATS_MAP if _bid == str(bid)]
  250. return matched_format_ids[0] if len(matched_format_ids) else None
  251. def get_bid(self, format_id):
  252. matched_bids = [_bid for _bid, _format_id in self._FORMATS_MAP if _format_id == format_id]
  253. return matched_bids[0] if len(matched_bids) else None
  254. def get_raw_data(self, tvid, video_id, enc_key, _uuid):
  255. tm = str(int(time.time()))
  256. tail = tm + tvid
  257. param = {
  258. 'key': 'fvip',
  259. 'src': self.md5_text('youtube-dl'),
  260. 'tvId': tvid,
  261. 'vid': video_id,
  262. 'vinfo': 1,
  263. 'tm': tm,
  264. 'enc': self.md5_text(enc_key + tail),
  265. 'qyid': _uuid,
  266. 'tn': random.random(),
  267. 'um': 0,
  268. 'authkey': self.md5_text(self.md5_text('') + tail),
  269. 'k_tag': 1,
  270. }
  271. api_url = 'http://cache.video.qiyi.com/vms' + '?' + \
  272. compat_urllib_parse.urlencode(param)
  273. raw_data = self._download_json(api_url, video_id)
  274. return raw_data
  275. def get_enc_key(self, swf_url, video_id):
  276. # TODO: automatic key extraction
  277. # last update at 2016-01-22 for Zombie::bite
  278. enc_key = '6ab6d0280511493ba85594779759d4ed'
  279. return enc_key
  280. def _real_extract(self, url):
  281. webpage = self._download_webpage(
  282. url, 'temp_id', note='download video page')
  283. tvid = self._search_regex(
  284. r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
  285. video_id = self._search_regex(
  286. r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
  287. swf_url = self._search_regex(
  288. r'(http://[^\'"]+MainPlayer[^.]+\.swf)', webpage, 'swf player URL')
  289. _uuid = uuid.uuid4().hex
  290. enc_key = self.get_enc_key(swf_url, video_id)
  291. raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid)
  292. if raw_data['code'] != 'A000000':
  293. raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
  294. data = raw_data['data']
  295. title = data['vi']['vn']
  296. # generate video_urls_dict
  297. video_urls_dict = self.construct_video_urls(
  298. data, video_id, _uuid, tvid)
  299. # construct info
  300. entries = []
  301. for format_id in video_urls_dict:
  302. video_urls = video_urls_dict[format_id]
  303. for i, video_url_info in enumerate(video_urls):
  304. if len(entries) < i + 1:
  305. entries.append({'formats': []})
  306. entries[i]['formats'].append(
  307. {
  308. 'url': video_url_info[0],
  309. 'filesize': video_url_info[-1],
  310. 'format_id': format_id,
  311. 'preference': int(self.get_bid(format_id))
  312. }
  313. )
  314. for i in range(len(entries)):
  315. self._sort_formats(entries[i]['formats'])
  316. entries[i].update(
  317. {
  318. 'id': '%s_part%d' % (video_id, i + 1),
  319. 'title': title,
  320. }
  321. )
  322. if len(entries) > 1:
  323. info = {
  324. '_type': 'multi_video',
  325. 'id': video_id,
  326. 'title': title,
  327. 'entries': entries,
  328. }
  329. else:
  330. info = entries[0]
  331. info['id'] = video_id
  332. info['title'] = title
  333. return info