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