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