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