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.

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