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.

227 lines
7.3 KiB

10 years ago
10 years ago
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 random
  6. import re
  7. import time
  8. import uuid
  9. import zlib
  10. from .common import InfoExtractor
  11. from ..compat import compat_urllib_parse
  12. from ..utils import ExtractorError
  13. class IqiyiIE(InfoExtractor):
  14. IE_NAME = 'iqiyi'
  15. _VALID_URL = r'http://(?:www\.)iqiyi.com/.+?\.html'
  16. _TEST = {
  17. 'url': 'http://www.iqiyi.com/v_19rrojlavg.html',
  18. 'md5': '2cb594dc2781e6c941a110d8f358118b',
  19. 'info_dict': {
  20. 'id': '9c1fb1b99d192b21c559e5a1a2cb3c73',
  21. 'title': '美国德州空中惊现奇异云团 酷似UFO',
  22. 'ext': 'f4v',
  23. }
  24. }
  25. def construct_video_urls(self, data, video_id, _uuid):
  26. def do_xor(x, y):
  27. a = y % 3
  28. if a == 1:
  29. return x ^ 121
  30. if a == 2:
  31. return x ^ 72
  32. return x ^ 103
  33. def get_encode_code(l):
  34. a = 0
  35. b = l.split('-')
  36. c = len(b)
  37. s = ''
  38. for i in range(c - 1, -1, -1):
  39. a = do_xor(int(b[c - i - 1], 16), i)
  40. s += chr(a)
  41. return s[::-1]
  42. def get_path_key(x, format_id, segment_index):
  43. mg = ')(*&^flash@#$%a'
  44. tm = self._download_json(
  45. 'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id,
  46. note='Download path key of segment %d for format %s' % (segment_index + 1, format_id)
  47. )['t']
  48. t = str(int(math.floor(int(tm) / (600.0))))
  49. return hashlib.md5((t + mg + x).encode('utf8')).hexdigest()
  50. video_urls_dict = {}
  51. for format_item in data['vp']['tkl'][0]['vs']:
  52. if 0 < int(format_item['bid']) <= 10:
  53. format_id = self.get_format(format_item['bid'])
  54. else:
  55. continue
  56. video_urls = []
  57. video_urls_info = format_item['fs']
  58. if not format_item['fs'][0]['l'].startswith('/'):
  59. t = get_encode_code(format_item['fs'][0]['l'])
  60. if t.endswith('mp4'):
  61. video_urls_info = format_item['flvs']
  62. for segment_index, segment in enumerate(video_urls_info):
  63. vl = segment['l']
  64. if not vl.startswith('/'):
  65. vl = get_encode_code(vl)
  66. key = get_path_key(
  67. vl.split('/')[-1].split('.')[0], format_id, segment_index)
  68. filesize = segment['b']
  69. base_url = data['vp']['du'].split('/')
  70. base_url.insert(-1, key)
  71. base_url = '/'.join(base_url)
  72. param = {
  73. 'su': _uuid,
  74. 'qyid': uuid.uuid4().hex,
  75. 'client': '',
  76. 'z': '',
  77. 'bt': '',
  78. 'ct': '',
  79. 'tn': str(int(time.time()))
  80. }
  81. api_video_url = base_url + vl + '?' + \
  82. compat_urllib_parse.urlencode(param)
  83. js = self._download_json(
  84. api_video_url, video_id,
  85. note='Download video info of segment %d for format %s' % (segment_index + 1, format_id))
  86. video_url = js['l']
  87. video_urls.append(
  88. (video_url, filesize))
  89. video_urls_dict[format_id] = video_urls
  90. return video_urls_dict
  91. def get_format(self, bid):
  92. _dict = {
  93. '1': 'h6',
  94. '2': 'h5',
  95. '3': 'h4',
  96. '4': 'h3',
  97. '5': 'h2',
  98. '10': 'h1'
  99. }
  100. return _dict.get(str(bid), None)
  101. def get_bid(self, format_id):
  102. _dict = {
  103. 'h6': '1',
  104. 'h5': '2',
  105. 'h4': '3',
  106. 'h3': '4',
  107. 'h2': '5',
  108. 'h1': '10',
  109. 'best': 'best'
  110. }
  111. return _dict.get(format_id, None)
  112. def get_raw_data(self, tvid, video_id, enc_key, _uuid):
  113. tm = str(int(time.time()))
  114. param = {
  115. 'key': 'fvip',
  116. 'src': hashlib.md5(b'youtube-dl').hexdigest(),
  117. 'tvId': tvid,
  118. 'vid': video_id,
  119. 'vinfo': 1,
  120. 'tm': tm,
  121. 'enc': hashlib.md5(
  122. (enc_key + tm + tvid).encode('utf8')).hexdigest(),
  123. 'qyid': _uuid,
  124. 'tn': random.random(),
  125. 'um': 0,
  126. 'authkey': hashlib.md5(
  127. (tm + tvid).encode('utf8')).hexdigest()
  128. }
  129. api_url = 'http://cache.video.qiyi.com/vms' + '?' + \
  130. compat_urllib_parse.urlencode(param)
  131. raw_data = self._download_json(api_url, video_id)
  132. return raw_data
  133. def get_enc_key(self, swf_url, video_id):
  134. req = self._request_webpage(
  135. swf_url, video_id, note='download swf content')
  136. cn = req.read()
  137. cn = zlib.decompress(cn[8:])
  138. pt = re.compile(b'MixerRemote\x08(?P<enc_key>.+?)\$&vv')
  139. enc_key = self._search_regex(pt, cn, 'enc_key').decode('utf8')
  140. return enc_key
  141. def _real_extract(self, url):
  142. webpage = self._download_webpage(
  143. url, 'temp_id', note='download video page')
  144. tvid = self._search_regex(
  145. r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
  146. video_id = self._search_regex(
  147. r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
  148. swf_url = self._search_regex(
  149. r'(http://.+?MainPlayer.+?\.swf)', webpage, 'swf player URL')
  150. _uuid = uuid.uuid4().hex
  151. enc_key = self.get_enc_key(swf_url, video_id)
  152. raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid)
  153. if raw_data['code'] != 'A000000':
  154. raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
  155. if not raw_data['data']['vp']['tkl']:
  156. raise ExtractorError('No support iQiqy VIP video')
  157. data = raw_data['data']
  158. title = data['vi']['vn']
  159. # generate video_urls_dict
  160. video_urls_dict = self.construct_video_urls(
  161. data, video_id, _uuid)
  162. # construct info
  163. entries = []
  164. for format_id in video_urls_dict:
  165. video_urls = video_urls_dict[format_id]
  166. for i, video_url_info in enumerate(video_urls):
  167. if len(entries) < i + 1:
  168. entries.append({'formats': []})
  169. entries[i]['formats'].append(
  170. {
  171. 'url': video_url_info[0],
  172. 'filesize': video_url_info[-1],
  173. 'format_id': format_id,
  174. 'preference': int(self.get_bid(format_id))
  175. }
  176. )
  177. for i in range(len(entries)):
  178. self._sort_formats(entries[i]['formats'])
  179. entries[i].update(
  180. {
  181. 'id': '%s_part%d' % (video_id, i + 1),
  182. 'title': title,
  183. }
  184. )
  185. if len(entries) > 1:
  186. info = {
  187. '_type': 'multi_video',
  188. 'id': video_id,
  189. 'title': title,
  190. 'entries': entries,
  191. }
  192. else:
  193. info = entries[0]
  194. info['id'] = video_id
  195. info['title'] = title
  196. return info