2 from __future__ import unicode_literals
11 from .common import InfoExtractor
12 from ..compat import (
15 compat_urllib_parse_urlparse,
25 class IqiyiIE(InfoExtractor):
29 _VALID_URL = r'http://(?:[^.]+\.)?iqiyi\.com/.+\.html'
32 'url': 'http://www.iqiyi.com/v_19rrojlavg.html',
33 'md5': '2cb594dc2781e6c941a110d8f358118b',
35 'id': '9c1fb1b99d192b21c559e5a1a2cb3c73',
36 'title': '美国德州空中惊现奇异云团 酷似UFO',
40 'url': 'http://www.iqiyi.com/v_19rrhnnclk.html',
42 'id': 'e3f585b550a280af23c98b6cb2be19fb',
43 'title': '名侦探柯南第752集',
47 'id': 'e3f585b550a280af23c98b6cb2be19fb_part1',
49 'title': '名侦探柯南第752集',
53 'id': 'e3f585b550a280af23c98b6cb2be19fb_part2',
55 'title': '名侦探柯南第752集',
59 'id': 'e3f585b550a280af23c98b6cb2be19fb_part3',
61 'title': '名侦探柯南第752集',
65 'id': 'e3f585b550a280af23c98b6cb2be19fb_part4',
67 'title': '名侦探柯南第752集',
71 'id': 'e3f585b550a280af23c98b6cb2be19fb_part5',
73 'title': '名侦探柯南第752集',
77 'id': 'e3f585b550a280af23c98b6cb2be19fb_part6',
79 'title': '名侦探柯南第752集',
83 'id': 'e3f585b550a280af23c98b6cb2be19fb_part7',
85 'title': '名侦探柯南第752集',
89 'id': 'e3f585b550a280af23c98b6cb2be19fb_part8',
91 'title': '名侦探柯南第752集',
95 'skip_download': True,
98 'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html',
99 'only_matching': True,
101 'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html',
102 'only_matching': True,
104 'url': 'http://yule.iqiyi.com/pcb.html',
105 'only_matching': True,
107 # VIP-only video. The first 2 parts (6 minutes) are available without login
108 'url': 'http://www.iqiyi.com/v_19rrny4w8w.html',
110 'id': 'f3cf468b39dddb30d676f89a91200dc1',
114 'md5': '436bcde6e1307307d5ba1549715b0bbd',
116 'id': 'f3cf468b39dddb30d676f89a91200dc1_part1',
121 'md5': 'bfc5e332f4900fde547c69372385649e',
123 'id': 'f3cf468b39dddb30d676f89a91200dc1_part2',
128 'expected_warnings': ['Needs a VIP account for full video'],
142 return hashlib.md5(text.encode('utf-8')).hexdigest()
144 def _authenticate_vip_video(self, api_video_url, video_id, tvid, _uuid, do_report_warning):
146 # version and platform hard-coded in com/qiyi/player/core/model/remote/AuthenticationRemote.as
148 'platform': 'b6c13e26323c537d',
153 'playType': 'main', # XXX: always main?
154 'filename': os.path.splitext(url_basename(api_video_url))[0],
157 qd_items = compat_parse_qs(compat_urllib_parse_urlparse(api_video_url).query)
158 for key, val in qd_items.items():
159 auth_params[key] = val[0]
161 auth_req = sanitized_Request(
162 'http://api.vip.iqiyi.com/services/ckn.action',
163 urlencode_postdata(auth_params))
164 # iQiyi server throws HTTP 405 error without the following header
165 auth_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
166 auth_result = self._download_json(
168 note='Downloading video authentication JSON',
169 errnote='Unable to download video authentication JSON')
170 if auth_result['code'] == 'Q00506': # requires a VIP account
171 if do_report_warning:
172 self.report_warning('Needs a VIP account for full video')
177 def construct_video_urls(self, data, video_id, _uuid, tvid):
186 def get_encode_code(l):
191 for i in range(c - 1, -1, -1):
192 a = do_xor(int(b[c - i - 1], 16), i)
196 def get_path_key(x, format_id, segment_index):
197 mg = ')(*&^flash@#$%a'
198 tm = self._download_json(
199 'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id,
200 note='Download path key of segment %d for format %s' % (segment_index + 1, format_id)
202 t = str(int(math.floor(int(tm) / (600.0))))
203 return self.md5_text(t + mg + x)
206 need_vip_warning_report = True
207 for format_item in data['vp']['tkl'][0]['vs']:
208 if 0 < int(format_item['bid']) <= 10:
209 format_id = self.get_format(format_item['bid'])
215 video_urls_info = format_item['fs']
216 if not format_item['fs'][0]['l'].startswith('/'):
217 t = get_encode_code(format_item['fs'][0]['l'])
218 if t.endswith('mp4'):
219 video_urls_info = format_item['flvs']
221 for segment_index, segment in enumerate(video_urls_info):
223 if not vl.startswith('/'):
224 vl = get_encode_code(vl)
225 is_vip_video = '/vip/' in vl
226 filesize = segment['b']
227 base_url = data['vp']['du'].split('/')
230 vl.split('/')[-1].split('.')[0], format_id, segment_index)
231 base_url.insert(-1, key)
232 base_url = '/'.join(base_url)
235 'qyid': uuid.uuid4().hex,
240 'tn': str(int(time.time()))
242 api_video_url = base_url + vl
244 api_video_url = api_video_url.replace('.f4v', '.hml')
245 auth_result = self._authenticate_vip_video(
246 api_video_url, video_id, tvid, _uuid, need_vip_warning_report)
247 if auth_result is False:
248 need_vip_warning_report = False
251 't': auth_result['data']['t'],
252 # cid is hard-coded in com/qiyi/player/core/player/RuntimeData.as
253 'cid': 'afbe8fd3d73448c9',
255 'QY00001': auth_result['data']['u'],
257 api_video_url += '?' if '?' not in api_video_url else '&'
258 api_video_url += compat_urllib_parse.urlencode(param)
259 js = self._download_json(
260 api_video_url, video_id,
261 note='Download video info of segment %d for format %s' % (segment_index + 1, format_id))
264 (video_url, filesize))
266 video_urls_dict[format_id] = video_urls
267 return video_urls_dict
269 def get_format(self, bid):
270 matched_format_ids = [_format_id for _bid, _format_id in self._FORMATS_MAP if _bid == str(bid)]
271 return matched_format_ids[0] if len(matched_format_ids) else None
273 def get_bid(self, format_id):
274 matched_bids = [_bid for _bid, _format_id in self._FORMATS_MAP if _format_id == format_id]
275 return matched_bids[0] if len(matched_bids) else None
277 def get_raw_data(self, tvid, video_id, enc_key, _uuid):
278 tm = str(int(time.time()))
282 'src': self.md5_text('youtube-dl'),
287 'enc': self.md5_text(enc_key + tail),
289 'tn': random.random(),
291 'authkey': self.md5_text(self.md5_text('') + tail),
295 api_url = 'http://cache.video.qiyi.com/vms' + '?' + \
296 compat_urllib_parse.urlencode(param)
297 raw_data = self._download_json(api_url, video_id)
300 def get_enc_key(self, swf_url, video_id):
301 # TODO: automatic key extraction
302 # last update at 2016-01-22 for Zombie::bite
303 enc_key = '6ab6d0280511493ba85594779759d4ed'
306 def _real_extract(self, url):
307 webpage = self._download_webpage(
308 url, 'temp_id', note='download video page')
309 tvid = self._search_regex(
310 r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
311 video_id = self._search_regex(
312 r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
313 swf_url = self._search_regex(
314 r'(http://[^\'"]+MainPlayer[^.]+\.swf)', webpage, 'swf player URL')
315 _uuid = uuid.uuid4().hex
317 enc_key = self.get_enc_key(swf_url, video_id)
319 raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid)
321 if raw_data['code'] != 'A000000':
322 raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
324 data = raw_data['data']
326 title = data['vi']['vn']
328 # generate video_urls_dict
329 video_urls_dict = self.construct_video_urls(
330 data, video_id, _uuid, tvid)
334 for format_id in video_urls_dict:
335 video_urls = video_urls_dict[format_id]
336 for i, video_url_info in enumerate(video_urls):
337 if len(entries) < i + 1:
338 entries.append({'formats': []})
339 entries[i]['formats'].append(
341 'url': video_url_info[0],
342 'filesize': video_url_info[-1],
343 'format_id': format_id,
344 'preference': int(self.get_bid(format_id))
348 for i in range(len(entries)):
349 self._sort_formats(entries[i]['formats'])
352 'id': '%s_part%d' % (video_id, i + 1),
359 '_type': 'multi_video',
366 info['id'] = video_id
367 info['title'] = title