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.

368 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. # MD5 sums omitted as values are different on Travis CI and my machine
  103. 'url': 'http://www.iqiyi.com/v_19rrny4w8w.html',
  104. 'info_dict': {
  105. 'id': 'f3cf468b39dddb30d676f89a91200dc1',
  106. 'title': '泰坦尼克号',
  107. },
  108. 'playlist': [{
  109. 'info_dict': {
  110. 'id': 'f3cf468b39dddb30d676f89a91200dc1_part1',
  111. 'ext': 'f4v',
  112. 'title': '泰坦尼克号',
  113. },
  114. }, {
  115. 'info_dict': {
  116. 'id': 'f3cf468b39dddb30d676f89a91200dc1_part2',
  117. 'ext': 'f4v',
  118. 'title': '泰坦尼克号',
  119. },
  120. }],
  121. 'expected_warnings': ['Needs a VIP account for full video'],
  122. }]
  123. _FORMATS_MAP = [
  124. ('1', 'h6'),
  125. ('2', 'h5'),
  126. ('3', 'h4'),
  127. ('4', 'h3'),
  128. ('5', 'h2'),
  129. ('10', 'h1'),
  130. ]
  131. @staticmethod
  132. def md5_text(text):
  133. return hashlib.md5(text.encode('utf-8')).hexdigest()
  134. def _authenticate_vip_video(self, api_video_url, video_id, tvid, _uuid, do_report_warning):
  135. auth_params = {
  136. # version and platform hard-coded in com/qiyi/player/core/model/remote/AuthenticationRemote.as
  137. 'version': '2.0',
  138. 'platform': 'b6c13e26323c537d',
  139. 'aid': tvid,
  140. 'tvid': tvid,
  141. 'uid': '',
  142. 'deviceId': _uuid,
  143. 'playType': 'main', # XXX: always main?
  144. 'filename': os.path.splitext(url_basename(api_video_url))[0],
  145. }
  146. qd_items = compat_parse_qs(compat_urllib_parse_urlparse(api_video_url).query)
  147. for key, val in qd_items.items():
  148. auth_params[key] = val[0]
  149. auth_req = sanitized_Request(
  150. 'http://api.vip.iqiyi.com/services/ckn.action',
  151. urlencode_postdata(auth_params))
  152. # iQiyi server throws HTTP 405 error without the following header
  153. auth_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  154. auth_result = self._download_json(
  155. auth_req, video_id,
  156. note='Downloading video authentication JSON',
  157. errnote='Unable to download video authentication JSON')
  158. if auth_result['code'] == 'Q00506': # requires a VIP account
  159. if do_report_warning:
  160. self.report_warning('Needs a VIP account for full video')
  161. return False
  162. return auth_result
  163. def construct_video_urls(self, data, video_id, _uuid, tvid):
  164. def do_xor(x, y):
  165. a = y % 3
  166. if a == 1:
  167. return x ^ 121
  168. if a == 2:
  169. return x ^ 72
  170. return x ^ 103
  171. def get_encode_code(l):
  172. a = 0
  173. b = l.split('-')
  174. c = len(b)
  175. s = ''
  176. for i in range(c - 1, -1, -1):
  177. a = do_xor(int(b[c - i - 1], 16), i)
  178. s += chr(a)
  179. return s[::-1]
  180. def get_path_key(x, format_id, segment_index):
  181. mg = ')(*&^flash@#$%a'
  182. tm = self._download_json(
  183. 'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id,
  184. note='Download path key of segment %d for format %s' % (segment_index + 1, format_id)
  185. )['t']
  186. t = str(int(math.floor(int(tm) / (600.0))))
  187. return self.md5_text(t + mg + x)
  188. video_urls_dict = {}
  189. need_vip_warning_report = True
  190. for format_item in data['vp']['tkl'][0]['vs']:
  191. if 0 < int(format_item['bid']) <= 10:
  192. format_id = self.get_format(format_item['bid'])
  193. else:
  194. continue
  195. video_urls = []
  196. video_urls_info = format_item['fs']
  197. if not format_item['fs'][0]['l'].startswith('/'):
  198. t = get_encode_code(format_item['fs'][0]['l'])
  199. if t.endswith('mp4'):
  200. video_urls_info = format_item['flvs']
  201. for segment_index, segment in enumerate(video_urls_info):
  202. vl = segment['l']
  203. if not vl.startswith('/'):
  204. vl = get_encode_code(vl)
  205. is_vip_video = '/vip/' in vl
  206. filesize = segment['b']
  207. base_url = data['vp']['du'].split('/')
  208. if not is_vip_video:
  209. key = get_path_key(
  210. vl.split('/')[-1].split('.')[0], format_id, segment_index)
  211. base_url.insert(-1, key)
  212. base_url = '/'.join(base_url)
  213. param = {
  214. 'su': _uuid,
  215. 'qyid': uuid.uuid4().hex,
  216. 'client': '',
  217. 'z': '',
  218. 'bt': '',
  219. 'ct': '',
  220. 'tn': str(int(time.time()))
  221. }
  222. api_video_url = base_url + vl
  223. if is_vip_video:
  224. api_video_url = api_video_url.replace('.f4v', '.hml')
  225. auth_result = self._authenticate_vip_video(
  226. api_video_url, video_id, tvid, _uuid, need_vip_warning_report)
  227. if auth_result is False:
  228. need_vip_warning_report = False
  229. break
  230. param.update({
  231. 't': auth_result['data']['t'],
  232. # cid is hard-coded in com/qiyi/player/core/player/RuntimeData.as
  233. 'cid': 'afbe8fd3d73448c9',
  234. 'vid': video_id,
  235. 'QY00001': auth_result['data']['u'],
  236. })
  237. api_video_url += '?' if '?' not in api_video_url else '&'
  238. api_video_url += compat_urllib_parse.urlencode(param)
  239. js = self._download_json(
  240. api_video_url, video_id,
  241. note='Download video info of segment %d for format %s' % (segment_index + 1, format_id))
  242. video_url = js['l']
  243. video_urls.append(
  244. (video_url, filesize))
  245. video_urls_dict[format_id] = video_urls
  246. return video_urls_dict
  247. def get_format(self, bid):
  248. matched_format_ids = [_format_id for _bid, _format_id in self._FORMATS_MAP if _bid == str(bid)]
  249. return matched_format_ids[0] if len(matched_format_ids) else None
  250. def get_bid(self, format_id):
  251. matched_bids = [_bid for _bid, _format_id in self._FORMATS_MAP if _format_id == format_id]
  252. return matched_bids[0] if len(matched_bids) else None
  253. def get_raw_data(self, tvid, video_id, enc_key, _uuid):
  254. tm = str(int(time.time()))
  255. tail = tm + tvid
  256. param = {
  257. 'key': 'fvip',
  258. 'src': self.md5_text('youtube-dl'),
  259. 'tvId': tvid,
  260. 'vid': video_id,
  261. 'vinfo': 1,
  262. 'tm': tm,
  263. 'enc': self.md5_text(enc_key + tail),
  264. 'qyid': _uuid,
  265. 'tn': random.random(),
  266. 'um': 0,
  267. 'authkey': self.md5_text(self.md5_text('') + tail),
  268. 'k_tag': 1,
  269. }
  270. api_url = 'http://cache.video.qiyi.com/vms' + '?' + \
  271. compat_urllib_parse.urlencode(param)
  272. raw_data = self._download_json(api_url, video_id)
  273. return raw_data
  274. def get_enc_key(self, swf_url, video_id):
  275. # TODO: automatic key extraction
  276. # last update at 2016-01-22 for Zombie::bite
  277. enc_key = '6ab6d0280511493ba85594779759d4ed'
  278. return enc_key
  279. def _real_extract(self, url):
  280. webpage = self._download_webpage(
  281. url, 'temp_id', note='download video page')
  282. tvid = self._search_regex(
  283. r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
  284. video_id = self._search_regex(
  285. r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
  286. swf_url = self._search_regex(
  287. r'(http://[^\'"]+MainPlayer[^.]+\.swf)', webpage, 'swf player URL')
  288. _uuid = uuid.uuid4().hex
  289. enc_key = self.get_enc_key(swf_url, video_id)
  290. raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid)
  291. if raw_data['code'] != 'A000000':
  292. raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
  293. data = raw_data['data']
  294. title = data['vi']['vn']
  295. # generate video_urls_dict
  296. video_urls_dict = self.construct_video_urls(
  297. data, video_id, _uuid, tvid)
  298. # construct info
  299. entries = []
  300. for format_id in video_urls_dict:
  301. video_urls = video_urls_dict[format_id]
  302. for i, video_url_info in enumerate(video_urls):
  303. if len(entries) < i + 1:
  304. entries.append({'formats': []})
  305. entries[i]['formats'].append(
  306. {
  307. 'url': video_url_info[0],
  308. 'filesize': video_url_info[-1],
  309. 'format_id': format_id,
  310. 'preference': int(self.get_bid(format_id))
  311. }
  312. )
  313. for i in range(len(entries)):
  314. self._sort_formats(entries[i]['formats'])
  315. entries[i].update(
  316. {
  317. 'id': '%s_part%d' % (video_id, i + 1),
  318. 'title': title,
  319. }
  320. )
  321. if len(entries) > 1:
  322. info = {
  323. '_type': 'multi_video',
  324. 'id': video_id,
  325. 'title': title,
  326. 'entries': entries,
  327. }
  328. else:
  329. info = entries[0]
  330. info['id'] = video_id
  331. info['title'] = title
  332. return info