iqiyi.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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/v_.+?\.html'
  16. _TESTS = [{
  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. 'url': 'http://www.iqiyi.com/v_19rrhnnclk.html',
  26. 'info_dict': {
  27. 'id': 'e3f585b550a280af23c98b6cb2be19fb',
  28. 'title': '名侦探柯南第752集',
  29. },
  30. 'playlist': [{
  31. 'md5': '7e49376fecaffa115d951634917fe105',
  32. 'info_dict': {
  33. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part1',
  34. 'ext': 'f4v',
  35. 'title': '名侦探柯南第752集',
  36. },
  37. }, {
  38. 'md5': '41b75ba13bb7ac0e411131f92bc4f6ca',
  39. 'info_dict': {
  40. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part2',
  41. 'ext': 'f4v',
  42. 'title': '名侦探柯南第752集',
  43. },
  44. }, {
  45. 'md5': '0cee1dd0a3d46a83e71e2badeae2aab0',
  46. 'info_dict': {
  47. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part3',
  48. 'ext': 'f4v',
  49. 'title': '名侦探柯南第752集',
  50. },
  51. }, {
  52. 'md5': '4f8ad72373b0c491b582e7c196b0b1f9',
  53. 'info_dict': {
  54. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part4',
  55. 'ext': 'f4v',
  56. 'title': '名侦探柯南第752集',
  57. },
  58. }, {
  59. 'md5': 'd89ad028bcfad282918e8098e811711d',
  60. 'info_dict': {
  61. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part5',
  62. 'ext': 'f4v',
  63. 'title': '名侦探柯南第752集',
  64. },
  65. }, {
  66. 'md5': '9cb1e5c95da25dff0660c32ae50903b7',
  67. 'info_dict': {
  68. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part6',
  69. 'ext': 'f4v',
  70. 'title': '名侦探柯南第752集',
  71. },
  72. }, {
  73. 'md5': '155116e0ff1867bbc9b98df294faabc9',
  74. 'info_dict': {
  75. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part7',
  76. 'ext': 'f4v',
  77. 'title': '名侦探柯南第752集',
  78. },
  79. }, {
  80. 'md5': '53f5db77622ae14fa493ed2a278a082b',
  81. 'info_dict': {
  82. 'id': 'e3f585b550a280af23c98b6cb2be19fb_part8',
  83. 'ext': 'f4v',
  84. 'title': '名侦探柯南第752集',
  85. },
  86. }],
  87. }]
  88. _FORMATS_MAP = [
  89. ('1', 'h6'),
  90. ('2', 'h5'),
  91. ('3', 'h4'),
  92. ('4', 'h3'),
  93. ('5', 'h2'),
  94. ('10', 'h1'),
  95. ]
  96. def construct_video_urls(self, data, video_id, _uuid):
  97. def do_xor(x, y):
  98. a = y % 3
  99. if a == 1:
  100. return x ^ 121
  101. if a == 2:
  102. return x ^ 72
  103. return x ^ 103
  104. def get_encode_code(l):
  105. a = 0
  106. b = l.split('-')
  107. c = len(b)
  108. s = ''
  109. for i in range(c - 1, -1, -1):
  110. a = do_xor(int(b[c - i - 1], 16), i)
  111. s += chr(a)
  112. return s[::-1]
  113. def get_path_key(x, format_id, segment_index):
  114. mg = ')(*&^flash@#$%a'
  115. tm = self._download_json(
  116. 'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id,
  117. note='Download path key of segment %d for format %s' % (segment_index + 1, format_id)
  118. )['t']
  119. t = str(int(math.floor(int(tm) / (600.0))))
  120. return hashlib.md5((t + mg + x).encode('utf8')).hexdigest()
  121. video_urls_dict = {}
  122. for format_item in data['vp']['tkl'][0]['vs']:
  123. if 0 < int(format_item['bid']) <= 10:
  124. format_id = self.get_format(format_item['bid'])
  125. else:
  126. continue
  127. video_urls = []
  128. video_urls_info = format_item['fs']
  129. if not format_item['fs'][0]['l'].startswith('/'):
  130. t = get_encode_code(format_item['fs'][0]['l'])
  131. if t.endswith('mp4'):
  132. video_urls_info = format_item['flvs']
  133. for segment_index, segment in enumerate(video_urls_info):
  134. vl = segment['l']
  135. if not vl.startswith('/'):
  136. vl = get_encode_code(vl)
  137. key = get_path_key(
  138. vl.split('/')[-1].split('.')[0], format_id, segment_index)
  139. filesize = segment['b']
  140. base_url = data['vp']['du'].split('/')
  141. base_url.insert(-1, key)
  142. base_url = '/'.join(base_url)
  143. param = {
  144. 'su': _uuid,
  145. 'qyid': uuid.uuid4().hex,
  146. 'client': '',
  147. 'z': '',
  148. 'bt': '',
  149. 'ct': '',
  150. 'tn': str(int(time.time()))
  151. }
  152. api_video_url = base_url + vl + '?' + \
  153. compat_urllib_parse.urlencode(param)
  154. js = self._download_json(
  155. api_video_url, video_id,
  156. note='Download video info of segment %d for format %s' % (segment_index + 1, format_id))
  157. video_url = js['l']
  158. video_urls.append(
  159. (video_url, filesize))
  160. video_urls_dict[format_id] = video_urls
  161. return video_urls_dict
  162. def get_format(self, bid):
  163. matched_format_ids = [_format_id for _bid, _format_id in self._FORMATS_MAP if _bid == str(bid)]
  164. return matched_format_ids[0] if len(matched_format_ids) else None
  165. def get_bid(self, format_id):
  166. matched_bids = [_bid for _bid, _format_id in self._FORMATS_MAP if _format_id == format_id]
  167. return matched_bids[0] if len(matched_bids) else None
  168. def get_raw_data(self, tvid, video_id, enc_key, _uuid):
  169. tm = str(int(time.time()))
  170. param = {
  171. 'key': 'fvip',
  172. 'src': hashlib.md5(b'youtube-dl').hexdigest(),
  173. 'tvId': tvid,
  174. 'vid': video_id,
  175. 'vinfo': 1,
  176. 'tm': tm,
  177. 'enc': hashlib.md5(
  178. (enc_key + tm + tvid).encode('utf8')).hexdigest(),
  179. 'qyid': _uuid,
  180. 'tn': random.random(),
  181. 'um': 0,
  182. 'authkey': hashlib.md5(
  183. (tm + tvid).encode('utf8')).hexdigest()
  184. }
  185. api_url = 'http://cache.video.qiyi.com/vms' + '?' + \
  186. compat_urllib_parse.urlencode(param)
  187. raw_data = self._download_json(api_url, video_id)
  188. return raw_data
  189. def get_enc_key(self, swf_url, video_id):
  190. req = self._request_webpage(
  191. swf_url, video_id, note='download swf content')
  192. cn = req.read()
  193. cn = zlib.decompress(cn[8:])
  194. pt = re.compile(b'MixerRemote\x08(?P<enc_key>.+?)\$&vv')
  195. enc_key = self._search_regex(pt, cn, 'enc_key').decode('utf8')
  196. return enc_key
  197. def _real_extract(self, url):
  198. webpage = self._download_webpage(
  199. url, 'temp_id', note='download video page')
  200. tvid = self._search_regex(
  201. r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
  202. video_id = self._search_regex(
  203. r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
  204. swf_url = self._search_regex(
  205. r'(http://[^\'"]+MainPlayer[^.]+\.swf)', webpage, 'swf player URL')
  206. _uuid = uuid.uuid4().hex
  207. enc_key = self.get_enc_key(swf_url, video_id)
  208. raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid)
  209. if raw_data['code'] != 'A000000':
  210. raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
  211. if not raw_data['data']['vp']['tkl']:
  212. raise ExtractorError('No support iQiqy VIP video')
  213. data = raw_data['data']
  214. title = data['vi']['vn']
  215. # generate video_urls_dict
  216. video_urls_dict = self.construct_video_urls(
  217. data, video_id, _uuid)
  218. # construct info
  219. entries = []
  220. for format_id in video_urls_dict:
  221. video_urls = video_urls_dict[format_id]
  222. for i, video_url_info in enumerate(video_urls):
  223. if len(entries) < i + 1:
  224. entries.append({'formats': []})
  225. entries[i]['formats'].append(
  226. {
  227. 'url': video_url_info[0],
  228. 'filesize': video_url_info[-1],
  229. 'format_id': format_id,
  230. 'preference': int(self.get_bid(format_id))
  231. }
  232. )
  233. for i in range(len(entries)):
  234. self._sort_formats(entries[i]['formats'])
  235. entries[i].update(
  236. {
  237. 'id': '%s_part%d' % (video_id, i + 1),
  238. 'title': title,
  239. }
  240. )
  241. if len(entries) > 1:
  242. info = {
  243. '_type': 'multi_video',
  244. 'id': video_id,
  245. 'title': title,
  246. 'entries': entries,
  247. }
  248. else:
  249. info = entries[0]
  250. info['id'] = video_id
  251. info['title'] = title
  252. return info