]>
Commit | Line | Data |
---|---|---|
605ec701 | 1 | # coding: utf-8 |
605ec701 P |
2 | from __future__ import unicode_literals |
3 | ||
958d0b65 | 4 | import hashlib |
73f9c286 | 5 | import itertools |
99709cc3 | 6 | import re |
605ec701 | 7 | import time |
958d0b65 YCH |
8 | |
9 | from .common import InfoExtractor | |
8e0548e1 | 10 | from ..compat import ( |
99709cc3 | 11 | compat_str, |
15707c7e | 12 | compat_urllib_parse_urlencode, |
05b23b41 | 13 | compat_urllib_parse_unquote |
8e0548e1 | 14 | ) |
42676437 | 15 | from .openload import PhantomJSwrapper |
8e0548e1 | 16 | from ..utils import ( |
2644e911 | 17 | clean_html, |
f52354a8 | 18 | decode_packed_codes, |
42676437 M |
19 | ExtractorError, |
20 | float_or_none, | |
05b23b41 | 21 | format_field, |
2644e911 YCH |
22 | get_element_by_id, |
23 | get_element_by_attribute, | |
42676437 M |
24 | int_or_none, |
25 | js_to_json, | |
99709cc3 | 26 | ohdave_rsa_encrypt, |
42676437 M |
27 | parse_age_limit, |
28 | parse_duration, | |
29 | parse_iso8601, | |
30 | parse_resolution, | |
31 | qualities, | |
73f9c286 | 32 | remove_start, |
42676437 M |
33 | str_or_none, |
34 | traverse_obj, | |
35 | urljoin, | |
8e0548e1 | 36 | ) |
605ec701 | 37 | |
f1da8610 | 38 | |
99709cc3 YCH |
39 | def md5_text(text): |
40 | return hashlib.md5(text.encode('utf-8')).hexdigest() | |
41 | ||
42 | ||
43 | class IqiyiSDK(object): | |
44 | def __init__(self, target, ip, timestamp): | |
45 | self.target = target | |
46 | self.ip = ip | |
47 | self.timestamp = timestamp | |
48 | ||
49 | @staticmethod | |
50 | def split_sum(data): | |
51 | return compat_str(sum(map(lambda p: int(p, 16), list(data)))) | |
52 | ||
53 | @staticmethod | |
54 | def digit_sum(num): | |
55 | if isinstance(num, int): | |
56 | num = compat_str(num) | |
57 | return compat_str(sum(map(int, num))) | |
58 | ||
59 | def even_odd(self): | |
60 | even = self.digit_sum(compat_str(self.timestamp)[::2]) | |
61 | odd = self.digit_sum(compat_str(self.timestamp)[1::2]) | |
62 | return even, odd | |
63 | ||
64 | def preprocess(self, chunksize): | |
65 | self.target = md5_text(self.target) | |
66 | chunks = [] | |
67 | for i in range(32 // chunksize): | |
68 | chunks.append(self.target[chunksize * i:chunksize * (i + 1)]) | |
69 | if 32 % chunksize: | |
70 | chunks.append(self.target[32 - 32 % chunksize:]) | |
71 | return chunks, list(map(int, self.ip.split('.'))) | |
72 | ||
73 | def mod(self, modulus): | |
74 | chunks, ip = self.preprocess(32) | |
75 | self.target = chunks[0] + ''.join(map(lambda p: compat_str(p % modulus), ip)) | |
76 | ||
77 | def split(self, chunksize): | |
78 | modulus_map = { | |
79 | 4: 256, | |
80 | 5: 10, | |
81 | 8: 100, | |
82 | } | |
83 | ||
84 | chunks, ip = self.preprocess(chunksize) | |
85 | ret = '' | |
86 | for i in range(len(chunks)): | |
87 | ip_part = compat_str(ip[i] % modulus_map[chunksize]) if i < 4 else '' | |
88 | if chunksize == 8: | |
89 | ret += ip_part + chunks[i] | |
90 | else: | |
91 | ret += chunks[i] + ip_part | |
92 | self.target = ret | |
93 | ||
94 | def handle_input16(self): | |
95 | self.target = md5_text(self.target) | |
96 | self.target = self.split_sum(self.target[:16]) + self.target + self.split_sum(self.target[16:]) | |
97 | ||
98 | def handle_input8(self): | |
99 | self.target = md5_text(self.target) | |
100 | ret = '' | |
101 | for i in range(4): | |
102 | part = self.target[8 * i:8 * (i + 1)] | |
103 | ret += self.split_sum(part) + part | |
104 | self.target = ret | |
105 | ||
106 | def handleSum(self): | |
107 | self.target = md5_text(self.target) | |
108 | self.target = self.split_sum(self.target) + self.target | |
109 | ||
110 | def date(self, scheme): | |
111 | self.target = md5_text(self.target) | |
112 | d = time.localtime(self.timestamp) | |
113 | strings = { | |
114 | 'y': compat_str(d.tm_year), | |
115 | 'm': '%02d' % d.tm_mon, | |
116 | 'd': '%02d' % d.tm_mday, | |
117 | } | |
118 | self.target += ''.join(map(lambda c: strings[c], list(scheme))) | |
119 | ||
120 | def split_time_even_odd(self): | |
121 | even, odd = self.even_odd() | |
122 | self.target = odd + md5_text(self.target) + even | |
123 | ||
124 | def split_time_odd_even(self): | |
125 | even, odd = self.even_odd() | |
126 | self.target = even + md5_text(self.target) + odd | |
127 | ||
128 | def split_ip_time_sum(self): | |
129 | chunks, ip = self.preprocess(32) | |
130 | self.target = compat_str(sum(ip)) + chunks[0] + self.digit_sum(self.timestamp) | |
131 | ||
132 | def split_time_ip_sum(self): | |
133 | chunks, ip = self.preprocess(32) | |
134 | self.target = self.digit_sum(self.timestamp) + chunks[0] + compat_str(sum(ip)) | |
135 | ||
136 | ||
137 | class IqiyiSDKInterpreter(object): | |
99709cc3 YCH |
138 | def __init__(self, sdk_code): |
139 | self.sdk_code = sdk_code | |
140 | ||
99709cc3 | 141 | def run(self, target, ip, timestamp): |
f52354a8 | 142 | self.sdk_code = decode_packed_codes(self.sdk_code) |
99709cc3 YCH |
143 | |
144 | functions = re.findall(r'input=([a-zA-Z0-9]+)\(input', self.sdk_code) | |
145 | ||
146 | sdk = IqiyiSDK(target, ip, timestamp) | |
147 | ||
148 | other_functions = { | |
149 | 'handleSum': sdk.handleSum, | |
150 | 'handleInput8': sdk.handle_input8, | |
151 | 'handleInput16': sdk.handle_input16, | |
152 | 'splitTimeEvenOdd': sdk.split_time_even_odd, | |
153 | 'splitTimeOddEven': sdk.split_time_odd_even, | |
154 | 'splitIpTimeSum': sdk.split_ip_time_sum, | |
155 | 'splitTimeIpSum': sdk.split_time_ip_sum, | |
156 | } | |
157 | for function in functions: | |
158 | if re.match(r'mod\d+', function): | |
159 | sdk.mod(int(function[3:])) | |
160 | elif re.match(r'date[ymd]{3}', function): | |
161 | sdk.date(function[4:]) | |
162 | elif re.match(r'split\d+', function): | |
163 | sdk.split(int(function[5:])) | |
164 | elif function in other_functions: | |
165 | other_functions[function]() | |
166 | else: | |
8bdd16b4 | 167 | raise ExtractorError('Unknown function %s' % function) |
99709cc3 YCH |
168 | |
169 | return sdk.target | |
170 | ||
171 | ||
605ec701 P |
172 | class IqiyiIE(InfoExtractor): |
173 | IE_NAME = 'iqiyi' | |
44c514eb | 174 | IE_DESC = '爱奇艺' |
605ec701 | 175 | |
7e176eff | 176 | _VALID_URL = r'https?://(?:(?:[^.]+\.)?iqiyi\.com|www\.pps\.tv)/.+\.html' |
605ec701 | 177 | |
99709cc3 YCH |
178 | _NETRC_MACHINE = 'iqiyi' |
179 | ||
99481135 | 180 | _TESTS = [{ |
f1da8610 | 181 | 'url': 'http://www.iqiyi.com/v_19rrojlavg.html', |
3a212ed6 | 182 | # MD5 checksum differs on my machine and Travis CI |
f1da8610 YCH |
183 | 'info_dict': { |
184 | 'id': '9c1fb1b99d192b21c559e5a1a2cb3c73', | |
5b6ad863 | 185 | 'ext': 'mp4', |
f1da8610 | 186 | 'title': '美国德州空中惊现奇异云团 酷似UFO', |
f1da8610 | 187 | } |
99481135 YCH |
188 | }, { |
189 | 'url': 'http://www.iqiyi.com/v_19rrhnnclk.html', | |
68c22c4c | 190 | 'md5': 'b7dc800a4004b1b57749d9abae0472da', |
99481135 YCH |
191 | 'info_dict': { |
192 | 'id': 'e3f585b550a280af23c98b6cb2be19fb', | |
5b6ad863 | 193 | 'ext': 'mp4', |
68c22c4c YCH |
194 | # This can be either Simplified Chinese or Traditional Chinese |
195 | 'title': r're:^(?:名侦探柯南 国语版:第752集 迫近灰原秘密的黑影 下篇|名偵探柯南 國語版:第752集 迫近灰原秘密的黑影 下篇)$', | |
99481135 | 196 | }, |
fc3996bf | 197 | 'skip': 'Geo-restricted to China', |
59185202 YCH |
198 | }, { |
199 | 'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html', | |
200 | 'only_matching': True, | |
201 | }, { | |
202 | 'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html', | |
203 | 'only_matching': True, | |
204 | }, { | |
205 | 'url': 'http://yule.iqiyi.com/pcb.html', | |
01cb5701 YCH |
206 | 'info_dict': { |
207 | 'id': '4a0af228fddb55ec96398a364248ed7f', | |
208 | 'ext': 'mp4', | |
209 | 'title': '第2017-04-21期 女艺人频遭极端粉丝骚扰', | |
210 | }, | |
8e0548e1 YCH |
211 | }, { |
212 | # VIP-only video. The first 2 parts (6 minutes) are available without login | |
1932476c | 213 | # MD5 sums omitted as values are different on Travis CI and my machine |
8e0548e1 YCH |
214 | 'url': 'http://www.iqiyi.com/v_19rrny4w8w.html', |
215 | 'info_dict': { | |
216 | 'id': 'f3cf468b39dddb30d676f89a91200dc1', | |
2644e911 | 217 | 'ext': 'mp4', |
8e0548e1 YCH |
218 | 'title': '泰坦尼克号', |
219 | }, | |
2644e911 | 220 | 'skip': 'Geo-restricted to China', |
73f9c286 YCH |
221 | }, { |
222 | 'url': 'http://www.iqiyi.com/a_19rrhb8ce1.html', | |
223 | 'info_dict': { | |
224 | 'id': '202918101', | |
225 | 'title': '灌篮高手 国语版', | |
226 | }, | |
227 | 'playlist_count': 101, | |
7e176eff YCH |
228 | }, { |
229 | 'url': 'http://www.pps.tv/w_19rrbav0ph.html', | |
230 | 'only_matching': True, | |
99481135 | 231 | }] |
605ec701 | 232 | |
2644e911 YCH |
233 | _FORMATS_MAP = { |
234 | '96': 1, # 216p, 240p | |
235 | '1': 2, # 336p, 360p | |
236 | '2': 3, # 480p, 504p | |
237 | '21': 4, # 504p | |
238 | '4': 5, # 720p | |
239 | '17': 5, # 720p | |
240 | '5': 6, # 1072p, 1080p | |
241 | '18': 7, # 1080p | |
242 | } | |
08bb8ef2 | 243 | |
99709cc3 YCH |
244 | def _real_initialize(self): |
245 | self._login() | |
246 | ||
57565375 | 247 | @staticmethod |
99709cc3 YCH |
248 | def _rsa_fun(data): |
249 | # public key extracted from http://static.iqiyi.com/js/qiyiV2/20160129180840/jobs/i18n/i18nIndex.js | |
250 | N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd | |
251 | e = 65537 | |
252 | ||
253 | return ohdave_rsa_encrypt(data, e, N) | |
254 | ||
255 | def _login(self): | |
68217024 | 256 | username, password = self._get_login_info() |
99709cc3 YCH |
257 | |
258 | # No authentication to be performed | |
259 | if not username: | |
260 | return True | |
261 | ||
262 | data = self._download_json( | |
263 | 'http://kylin.iqiyi.com/get_token', None, | |
264 | note='Get token for logging', errnote='Unable to get token for logging') | |
265 | sdk = data['sdk'] | |
266 | timestamp = int(time.time()) | |
267 | target = '/apis/reglogin/login.action?lang=zh_TW&area_code=null&email=%s&passwd=%s&agenttype=1&from=undefined&keeplogin=0&piccode=&fromurl=&_pos=1' % ( | |
268 | username, self._rsa_fun(password.encode('utf-8'))) | |
269 | ||
270 | interp = IqiyiSDKInterpreter(sdk) | |
271 | sign = interp.run(target, data['ip'], timestamp) | |
272 | ||
273 | validation_params = { | |
274 | 'target': target, | |
275 | 'server': 'BEA3AA1908656AABCCFF76582C4C6660', | |
276 | 'token': data['token'], | |
277 | 'bird_src': 'f8d91d57af224da7893dd397d52d811a', | |
278 | 'sign': sign, | |
279 | 'bird_t': timestamp, | |
280 | } | |
281 | validation_result = self._download_json( | |
15707c7e | 282 | 'http://kylin.iqiyi.com/validate?' + compat_urllib_parse_urlencode(validation_params), None, |
99709cc3 YCH |
283 | note='Validate credentials', errnote='Unable to validate credentials') |
284 | ||
285 | MSG_MAP = { | |
286 | 'P00107': 'please login via the web interface and enter the CAPTCHA code', | |
287 | 'P00117': 'bad username or password', | |
288 | } | |
289 | ||
290 | code = validation_result['code'] | |
291 | if code != 'A00000': | |
292 | msg = MSG_MAP.get(code) | |
293 | if not msg: | |
294 | msg = 'error %s' % code | |
295 | if validation_result.get('msg'): | |
296 | msg += ': ' + validation_result['msg'] | |
6a39ee13 | 297 | self.report_warning('unable to log in: ' + msg) |
99709cc3 YCH |
298 | return False |
299 | ||
300 | return True | |
57565375 | 301 | |
5b6ad863 YCH |
302 | def get_raw_data(self, tvid, video_id): |
303 | tm = int(time.time() * 1000) | |
304 | ||
2644e911 YCH |
305 | key = 'd5fb4bd9d50c4be6948c97edd7254b0e' |
306 | sc = md5_text(compat_str(tm) + key + tvid) | |
5b6ad863 | 307 | params = { |
8e0548e1 | 308 | 'tvid': tvid, |
605ec701 | 309 | 'vid': video_id, |
2644e911 | 310 | 'src': '76f90cbd92f94a2e925d83e8ccd22cb7', |
5b6ad863 | 311 | 'sc': sc, |
2644e911 | 312 | 't': tm, |
605ec701 P |
313 | } |
314 | ||
5b6ad863 YCH |
315 | return self._download_json( |
316 | 'http://cache.m.iqiyi.com/jp/tmts/%s/%s/' % (tvid, video_id), | |
317 | video_id, transform_source=lambda s: remove_start(s, 'var tvInfoJs='), | |
38cce791 | 318 | query=params, headers=self.geo_verification_headers()) |
605ec701 | 319 | |
73f9c286 YCH |
320 | def _extract_playlist(self, webpage): |
321 | PAGE_SIZE = 50 | |
322 | ||
323 | links = re.findall( | |
324 | r'<a[^>]+class="site-piclist_pic_link"[^>]+href="(http://www\.iqiyi\.com/.+\.html)"', | |
325 | webpage) | |
326 | if not links: | |
327 | return | |
328 | ||
329 | album_id = self._search_regex( | |
330 | r'albumId\s*:\s*(\d+),', webpage, 'album ID') | |
331 | album_title = self._search_regex( | |
332 | r'data-share-title="([^"]+)"', webpage, 'album title', fatal=False) | |
333 | ||
334 | entries = list(map(self.url_result, links)) | |
335 | ||
336 | # Start from 2 because links in the first page are already on webpage | |
337 | for page_num in itertools.count(2): | |
338 | pagelist_page = self._download_webpage( | |
339 | 'http://cache.video.qiyi.com/jp/avlist/%s/%d/%d/' % (album_id, page_num, PAGE_SIZE), | |
340 | album_id, | |
341 | note='Download playlist page %d' % page_num, | |
342 | errnote='Failed to download playlist page %d' % page_num) | |
343 | pagelist = self._parse_json( | |
344 | remove_start(pagelist_page, 'var tvInfoJs='), album_id) | |
345 | vlist = pagelist['data']['vlist'] | |
346 | for item in vlist: | |
347 | entries.append(self.url_result(item['vurl'])) | |
348 | if len(vlist) < PAGE_SIZE: | |
349 | break | |
350 | ||
351 | return self.playlist_result(entries, album_id, album_title) | |
352 | ||
605ec701 P |
353 | def _real_extract(self, url): |
354 | webpage = self._download_webpage( | |
355 | url, 'temp_id', note='download video page') | |
73f9c286 YCH |
356 | |
357 | # There's no simple way to determine whether an URL is a playlist or not | |
fbf56be2 YCH |
358 | # Sometimes there are playlist links in individual videos, so treat it |
359 | # as a single video first | |
605ec701 | 360 | tvid = self._search_regex( |
01cb5701 | 361 | r'data-(?:player|shareplattrigger)-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid', default=None) |
fbf56be2 YCH |
362 | if tvid is None: |
363 | playlist_result = self._extract_playlist(webpage) | |
364 | if playlist_result: | |
365 | return playlist_result | |
366 | raise ExtractorError('Can\'t find any video') | |
367 | ||
605ec701 | 368 | video_id = self._search_regex( |
01cb5701 | 369 | r'data-(?:player|shareplattrigger)-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id') |
5b6ad863 | 370 | |
2644e911 | 371 | formats = [] |
5b6ad863 YCH |
372 | for _ in range(5): |
373 | raw_data = self.get_raw_data(tvid, video_id) | |
374 | ||
375 | if raw_data['code'] != 'A00000': | |
376 | if raw_data['code'] == 'A00111': | |
377 | self.raise_geo_restricted() | |
378 | raise ExtractorError('Unable to load data. Error code: ' + raw_data['code']) | |
379 | ||
380 | data = raw_data['data'] | |
381 | ||
2644e911 YCH |
382 | for stream in data['vidl']: |
383 | if 'm3utx' not in stream: | |
384 | continue | |
385 | vd = compat_str(stream['vd']) | |
386 | formats.append({ | |
387 | 'url': stream['m3utx'], | |
388 | 'format_id': vd, | |
389 | 'ext': 'mp4', | |
f983b875 | 390 | 'quality': self._FORMATS_MAP.get(vd, -1), |
2644e911 YCH |
391 | 'protocol': 'm3u8_native', |
392 | }) | |
393 | ||
394 | if formats: | |
395 | break | |
396 | ||
397 | self._sleep(5, video_id) | |
5b6ad863 | 398 | |
2644e911 | 399 | self._sort_formats(formats) |
3089bc74 S |
400 | title = (get_element_by_id('widget-videotitle', webpage) |
401 | or clean_html(get_element_by_attribute('class', 'mod-play-tit', webpage)) | |
402 | or self._html_search_regex(r'<span[^>]+data-videochanged-title="word"[^>]*>([^<]+)</span>', webpage, 'title')) | |
5b6ad863 YCH |
403 | |
404 | return { | |
405 | 'id': video_id, | |
406 | 'title': title, | |
2644e911 | 407 | 'formats': formats, |
5b6ad863 | 408 | } |
42676437 M |
409 | |
410 | ||
411 | class IqIE(InfoExtractor): | |
412 | IE_NAME = 'iq.com' | |
413 | IE_DESC = 'International version of iQiyi' | |
414 | _VALID_URL = r'https?://(?:www\.)?iq\.com/play/(?:[\w%-]*-)?(?P<id>\w+)' | |
415 | _TESTS = [{ | |
416 | 'url': 'https://www.iq.com/play/one-piece-episode-1000-1ma1i6ferf4', | |
417 | 'md5': '2d7caf6eeca8a32b407094b33b757d39', | |
418 | 'info_dict': { | |
419 | 'ext': 'mp4', | |
420 | 'id': '1ma1i6ferf4', | |
421 | 'title': '航海王 第1000集', | |
422 | 'description': 'Subtitle available on Sunday 4PM(GMT+8).', | |
423 | 'duration': 1430, | |
424 | 'timestamp': 1637488203, | |
425 | 'upload_date': '20211121', | |
426 | 'episode_number': 1000, | |
427 | 'episode': 'Episode 1000', | |
428 | 'series': 'One Piece', | |
429 | 'age_limit': 13, | |
430 | 'average_rating': float, | |
431 | }, | |
432 | 'params': { | |
433 | 'format': '500', | |
434 | }, | |
435 | 'expected_warnings': ['format is restricted'] | |
05b23b41 M |
436 | }, { |
437 | # VIP-restricted video | |
438 | 'url': 'https://www.iq.com/play/mermaid-in-the-fog-2021-gbdpx13bs4', | |
439 | 'only_matching': True | |
42676437 M |
440 | }] |
441 | _BID_TAGS = { | |
442 | '100': '240P', | |
443 | '200': '360P', | |
444 | '300': '480P', | |
445 | '500': '720P', | |
446 | '600': '1080P', | |
447 | '610': '1080P50', | |
448 | '700': '2K', | |
449 | '800': '4K', | |
450 | } | |
451 | _LID_TAGS = { | |
452 | '1': 'zh_CN', | |
453 | '2': 'zh_TW', | |
454 | '3': 'en', | |
455 | '18': 'th', | |
456 | '21': 'my', | |
457 | '23': 'vi', | |
458 | '24': 'id', | |
459 | '26': 'es', | |
460 | '28': 'ar', | |
461 | } | |
462 | ||
463 | _DASH_JS = ''' | |
464 | console.log(page.evaluate(function() { | |
465 | var tvid = "%(tvid)s"; var vid = "%(vid)s"; var src = "%(src)s"; | |
05b23b41 M |
466 | var uid = "%(uid)s"; var dfp = "%(dfp)s"; var mode = "%(mode)s"; var lang = "%(lang)s"; |
467 | var bid_list = %(bid_list)s; var ut_list = %(ut_list)s; var tm = new Date().getTime(); | |
42676437 M |
468 | var cmd5x_func = %(cmd5x_func)s; var cmd5x_exporter = {}; cmd5x_func({}, cmd5x_exporter, {}); var cmd5x = cmd5x_exporter.cmd5x; |
469 | var authKey = cmd5x(cmd5x('') + tm + '' + tvid); | |
470 | var k_uid = Array.apply(null, Array(32)).map(function() {return Math.floor(Math.random() * 15).toString(16)}).join(''); | |
471 | var dash_paths = {}; | |
472 | bid_list.forEach(function(bid) { | |
473 | var query = { | |
474 | 'tvid': tvid, | |
475 | 'bid': bid, | |
476 | 'ds': 1, | |
477 | 'vid': vid, | |
478 | 'src': src, | |
479 | 'vt': 0, | |
480 | 'rs': 1, | |
05b23b41 | 481 | 'uid': uid, |
42676437 M |
482 | 'ori': 'pcw', |
483 | 'ps': 1, | |
484 | 'k_uid': k_uid, | |
485 | 'pt': 0, | |
486 | 'd': 0, | |
487 | 's': '', | |
488 | 'lid': '', | |
489 | 'slid': 0, | |
490 | 'cf': '', | |
491 | 'ct': '', | |
492 | 'authKey': authKey, | |
493 | 'k_tag': 1, | |
494 | 'ost': 0, | |
495 | 'ppt': 0, | |
496 | 'dfp': dfp, | |
497 | 'prio': JSON.stringify({ | |
498 | 'ff': 'f4v', | |
499 | 'code': 2 | |
500 | }), | |
501 | 'k_err_retries': 0, | |
502 | 'up': '', | |
503 | 'su': 2, | |
504 | 'applang': lang, | |
505 | 'sver': 2, | |
506 | 'X-USER-MODE': mode, | |
507 | 'qd_v': 2, | |
508 | 'tm': tm, | |
509 | 'qdy': 'a', | |
510 | 'qds': 0, | |
511 | 'k_ft1': 141287244169348, | |
512 | 'k_ft4': 34359746564, | |
513 | 'k_ft5': 1, | |
514 | 'bop': JSON.stringify({ | |
515 | 'version': '10.0', | |
516 | 'dfp': dfp | |
517 | }), | |
42676437 M |
518 | }; |
519 | var enc_params = []; | |
520 | for (var prop in query) { | |
521 | enc_params.push(encodeURIComponent(prop) + '=' + encodeURIComponent(query[prop])); | |
522 | } | |
05b23b41 M |
523 | ut_list.forEach(function(ut) { |
524 | enc_params.push('ut=' + ut); | |
525 | }) | |
42676437 M |
526 | var dash_path = '/dash?' + enc_params.join('&'); dash_path += '&vf=' + cmd5x(dash_path); |
527 | dash_paths[bid] = dash_path; | |
528 | }); | |
529 | return JSON.stringify(dash_paths); | |
530 | })); | |
531 | saveAndExit(); | |
532 | ''' | |
533 | ||
534 | def _extract_vms_player_js(self, webpage, video_id): | |
535 | player_js_cache = self._downloader.cache.load('iq', 'player_js') | |
536 | if player_js_cache: | |
537 | return player_js_cache | |
538 | webpack_js_url = self._proto_relative_url(self._search_regex( | |
539 | r'<script src="((?:https?)?//stc.iqiyipic.com/_next/static/chunks/webpack-\w+\.js)"', webpage, 'webpack URL')) | |
540 | webpack_js = self._download_webpage(webpack_js_url, video_id, note='Downloading webpack JS', errnote='Unable to download webpack JS') | |
541 | webpack_map1, webpack_map2 = [self._parse_json(js_map, video_id, transform_source=js_to_json) for js_map in self._search_regex( | |
542 | r'\(({[^}]*})\[\w+\][^\)]*\)\s*\+\s*["\']\.["\']\s*\+\s*({[^}]*})\[\w+\]\+["\']\.js', webpack_js, 'JS locations', group=(1, 2))] | |
ed408778 | 543 | for module_index in reversed(list(webpack_map2.keys())): |
42676437 M |
544 | module_js = self._download_webpage( |
545 | f'https://stc.iqiyipic.com/_next/static/chunks/{webpack_map1.get(module_index, module_index)}.{webpack_map2[module_index]}.js', | |
546 | video_id, note=f'Downloading #{module_index} module JS', errnote='Unable to download module JS', fatal=False) or '' | |
547 | if 'vms request' in module_js: | |
548 | self._downloader.cache.store('iq', 'player_js', module_js) | |
549 | return module_js | |
550 | raise ExtractorError('Unable to extract player JS') | |
551 | ||
552 | def _extract_cmd5x_function(self, webpage, video_id): | |
553 | return self._search_regex(r',\s*(function\s*\([^\)]*\)\s*{\s*var _qda.+_qdc\(\)\s*})\s*,', | |
554 | self._extract_vms_player_js(webpage, video_id), 'signature function') | |
555 | ||
556 | def _update_bid_tags(self, webpage, video_id): | |
557 | extracted_bid_tags = self._parse_json( | |
558 | self._search_regex( | |
559 | r'arguments\[1\][^,]*,\s*function\s*\([^\)]*\)\s*{\s*"use strict";?\s*var \w=({.+}})\s*,\s*\w\s*=\s*{\s*getNewVd', | |
560 | self._extract_vms_player_js(webpage, video_id), 'video tags', default=''), | |
561 | video_id, transform_source=js_to_json, fatal=False) | |
562 | if not extracted_bid_tags: | |
563 | return | |
564 | self._BID_TAGS = { | |
565 | bid: traverse_obj(extracted_bid_tags, (bid, 'value'), expected_type=str, default=self._BID_TAGS.get(bid)) | |
566 | for bid in extracted_bid_tags.keys() | |
567 | } | |
568 | ||
569 | def _get_cookie(self, name, default=None): | |
570 | cookie = self._get_cookies('https://iq.com/').get(name) | |
571 | return cookie.value if cookie else default | |
572 | ||
573 | def _real_extract(self, url): | |
574 | video_id = self._match_id(url) | |
575 | webpage = self._download_webpage(url, video_id) | |
576 | self._update_bid_tags(webpage, video_id) | |
577 | ||
578 | next_props = self._search_nextjs_data(webpage, video_id)['props'] | |
579 | page_data = next_props['initialState']['play'] | |
580 | video_info = page_data['curVideoInfo'] | |
581 | ||
05b23b41 M |
582 | uid = traverse_obj( |
583 | self._parse_json( | |
584 | self._get_cookie('I00002', '{}'), video_id, transform_source=compat_urllib_parse_unquote, fatal=False), | |
585 | ('data', 'uid'), default=0) | |
586 | ||
587 | if uid: | |
588 | vip_data = self._download_json( | |
589 | 'https://pcw-api.iq.com/api/vtype', video_id, note='Downloading VIP data', errnote='Unable to download VIP data', query={ | |
590 | 'batch': 1, | |
591 | 'platformId': 3, | |
592 | 'modeCode': self._get_cookie('mod', 'intl'), | |
593 | 'langCode': self._get_cookie('lang', 'en_us'), | |
594 | 'deviceId': self._get_cookie('QC005', '') | |
595 | }, fatal=False) | |
596 | ut_list = traverse_obj(vip_data, ('data', 'all_vip', ..., 'vipType'), expected_type=str_or_none, default=[]) | |
597 | else: | |
598 | ut_list = ['0'] | |
599 | ||
42676437 M |
600 | # bid 0 as an initial format checker |
601 | dash_paths = self._parse_json(PhantomJSwrapper(self).get( | |
602 | url, html='<!DOCTYPE html>', video_id=video_id, note2='Executing signature code', jscode=self._DASH_JS % { | |
603 | 'tvid': video_info['tvId'], | |
604 | 'vid': video_info['vid'], | |
605 | 'src': traverse_obj(next_props, ('initialProps', 'pageProps', 'ptid'), | |
05b23b41 M |
606 | expected_type=str, default='04022001010011000000'), |
607 | 'uid': uid, | |
42676437 M |
608 | 'dfp': self._get_cookie('dfp', ''), |
609 | 'mode': self._get_cookie('mod', 'intl'), | |
610 | 'lang': self._get_cookie('lang', 'en_us'), | |
611 | 'bid_list': '[' + ','.join(['0', *self._BID_TAGS.keys()]) + ']', | |
05b23b41 | 612 | 'ut_list': '[' + ','.join(ut_list) + ']', |
42676437 M |
613 | 'cmd5x_func': self._extract_cmd5x_function(webpage, video_id), |
614 | })[1].strip(), video_id) | |
615 | ||
616 | formats, subtitles = [], {} | |
617 | initial_format_data = self._download_json( | |
618 | urljoin('https://cache-video.iq.com', dash_paths['0']), video_id, | |
619 | note='Downloading initial video format info', errnote='Unable to download initial video format info')['data'] | |
620 | ||
05b23b41 M |
621 | preview_time = traverse_obj( |
622 | initial_format_data, ('boss_ts', (None, 'data'), ('previewTime', 'rtime')), expected_type=float_or_none, get_all=False) | |
623 | if traverse_obj(initial_format_data, ('boss_ts', 'data', 'prv'), expected_type=int_or_none): | |
624 | self.report_warning('This preview video is limited%s' % format_field(preview_time, template='to %s seconds')) | |
42676437 M |
625 | |
626 | # TODO: Extract audio-only formats | |
627 | for bid in set(traverse_obj(initial_format_data, ('program', 'video', ..., 'bid'), expected_type=str_or_none, default=[])): | |
628 | dash_path = dash_paths.get(bid) | |
629 | if not dash_path: | |
630 | self.report_warning(f'Unknown format id: {bid}. It is currently not being extracted') | |
631 | continue | |
632 | format_data = traverse_obj(self._download_json( | |
633 | urljoin('https://cache-video.iq.com', dash_path), video_id, | |
634 | note=f'Downloading format data for {self._BID_TAGS[bid]}', errnote='Unable to download format data', | |
635 | fatal=False), 'data', expected_type=dict) | |
636 | ||
637 | video_format = next((video_format for video_format in traverse_obj( | |
638 | format_data, ('program', 'video', ...), expected_type=dict, default=[]) if str(video_format['bid']) == bid), {}) | |
639 | extracted_formats = [] | |
640 | if video_format.get('m3u8Url'): | |
641 | extracted_formats.extend(self._extract_m3u8_formats( | |
642 | urljoin(format_data.get('dm3u8', 'https://cache-m.iq.com/dc/dt/'), video_format['m3u8Url']), | |
643 | 'mp4', m3u8_id=bid, fatal=False)) | |
644 | if video_format.get('mpdUrl'): | |
645 | # TODO: Properly extract mpd hostname | |
646 | extracted_formats.extend(self._extract_mpd_formats( | |
647 | urljoin(format_data.get('dm3u8', 'https://cache-m.iq.com/dc/dt/'), video_format['mpdUrl']), | |
648 | mpd_id=bid, fatal=False)) | |
649 | if video_format.get('m3u8'): | |
650 | ff = video_format.get('ff', 'ts') | |
651 | if ff == 'ts': | |
652 | m3u8_formats, _ = self._parse_m3u8_formats_and_subtitles( | |
653 | video_format['m3u8'], ext='mp4', m3u8_id=bid, fatal=False) | |
654 | extracted_formats.extend(m3u8_formats) | |
655 | elif ff == 'm4s': | |
656 | mpd_data = traverse_obj( | |
657 | self._parse_json(video_format['m3u8'], video_id, fatal=False), ('payload', ..., 'data'), expected_type=str) | |
658 | if not mpd_data: | |
659 | continue | |
660 | mpd_formats, _ = self._parse_mpd_formats_and_subtitles( | |
661 | mpd_data, bid, format_data.get('dm3u8', 'https://cache-m.iq.com/dc/dt/')) | |
662 | extracted_formats.extend(mpd_formats) | |
663 | else: | |
664 | self.report_warning(f'{ff} formats are currently not supported') | |
665 | ||
666 | if not extracted_formats: | |
667 | if video_format.get('s'): | |
668 | self.report_warning(f'{self._BID_TAGS[bid]} format is restricted') | |
669 | else: | |
670 | self.report_warning(f'Unable to extract {self._BID_TAGS[bid]} format') | |
671 | for f in extracted_formats: | |
672 | f.update({ | |
673 | 'quality': qualities(list(self._BID_TAGS.keys()))(bid), | |
674 | 'format_note': self._BID_TAGS[bid], | |
675 | **parse_resolution(video_format.get('scrsz')) | |
676 | }) | |
677 | formats.extend(extracted_formats) | |
678 | ||
679 | self._sort_formats(formats) | |
680 | ||
681 | for sub_format in traverse_obj(initial_format_data, ('program', 'stl', ...), expected_type=dict, default=[]): | |
682 | lang = self._LID_TAGS.get(str_or_none(sub_format.get('lid')), sub_format.get('_name')) | |
683 | subtitles.setdefault(lang, []).extend([{ | |
684 | 'ext': format_ext, | |
685 | 'url': urljoin(initial_format_data.get('dstl', 'http://meta.video.iqiyi.com'), sub_format[format_key]) | |
686 | } for format_key, format_ext in [('srt', 'srt'), ('webvtt', 'vtt')] if sub_format.get(format_key)]) | |
687 | ||
688 | extra_metadata = page_data.get('albumInfo') if video_info.get('albumId') and page_data.get('albumInfo') else video_info | |
689 | return { | |
690 | 'id': video_id, | |
691 | 'title': video_info['name'], | |
692 | 'formats': formats, | |
693 | 'subtitles': subtitles, | |
694 | 'description': video_info.get('mergeDesc'), | |
695 | 'duration': parse_duration(video_info.get('len')), | |
696 | 'age_limit': parse_age_limit(video_info.get('rating')), | |
697 | 'average_rating': traverse_obj(page_data, ('playScoreInfo', 'score'), expected_type=float_or_none), | |
698 | 'timestamp': parse_iso8601(video_info.get('isoUploadDate')), | |
699 | 'categories': traverse_obj(extra_metadata, ('videoTagMap', ..., ..., 'name'), expected_type=str), | |
700 | 'cast': traverse_obj(extra_metadata, ('actorArr', ..., 'name'), expected_type=str), | |
701 | 'episode_number': int_or_none(video_info.get('order')) or None, | |
702 | 'series': video_info.get('albumName'), | |
703 | } | |
704 | ||
705 | ||
706 | class IqAlbumIE(InfoExtractor): | |
707 | IE_NAME = 'iq.com:album' | |
708 | _VALID_URL = r'https?://(?:www\.)?iq\.com/album/(?:[\w%-]*-)?(?P<id>\w+)' | |
709 | _TESTS = [{ | |
710 | 'url': 'https://www.iq.com/album/one-piece-1999-1bk9icvr331', | |
711 | 'info_dict': { | |
712 | 'id': '1bk9icvr331', | |
713 | 'title': 'One Piece', | |
714 | 'description': 'Subtitle available on Sunday 4PM(GMT+8).' | |
715 | }, | |
716 | 'playlist_mincount': 238 | |
717 | }, { | |
718 | # Movie/single video | |
719 | 'url': 'https://www.iq.com/album/九龙城寨-2021-22yjnij099k', | |
720 | 'info_dict': { | |
721 | 'ext': 'mp4', | |
722 | 'id': '22yjnij099k', | |
723 | 'title': '九龙城寨', | |
724 | 'description': 'md5:8a09f50b8ba0db4dc69bc7c844228044', | |
725 | 'duration': 5000, | |
726 | 'timestamp': 1641911371, | |
727 | 'upload_date': '20220111', | |
728 | 'series': '九龙城寨', | |
729 | 'cast': ['Shi Yan Neng', 'Yu Lang', 'Peter lv', 'Sun Zi Jun', 'Yang Xiao Bo'], | |
730 | 'age_limit': 13, | |
731 | 'average_rating': float, | |
732 | }, | |
733 | 'expected_warnings': ['format is restricted'] | |
734 | }] | |
735 | ||
736 | def _entries(self, album_id_num, page_ranges, album_id=None, mode_code='intl', lang_code='en_us'): | |
737 | for page_range in page_ranges: | |
738 | page = self._download_json( | |
739 | f'https://pcw-api.iq.com/api/episodeListSource/{album_id_num}', album_id, | |
740 | note=f'Downloading video list episodes {page_range.get("msg", "")}', | |
741 | errnote='Unable to download video list', query={ | |
742 | 'platformId': 3, | |
743 | 'modeCode': mode_code, | |
744 | 'langCode': lang_code, | |
745 | 'endOrder': page_range['to'], | |
746 | 'startOrder': page_range['from'] | |
747 | }) | |
748 | for video in page['data']['epg']: | |
749 | yield self.url_result('https://www.iq.com/play/%s' % (video.get('playLocSuffix') or video['qipuIdStr']), | |
750 | IqIE.ie_key(), video.get('qipuIdStr'), video.get('name')) | |
751 | ||
752 | def _real_extract(self, url): | |
753 | album_id = self._match_id(url) | |
754 | webpage = self._download_webpage(url, album_id) | |
755 | next_data = self._search_nextjs_data(webpage, album_id) | |
756 | album_data = next_data['props']['initialState']['album']['videoAlbumInfo'] | |
757 | ||
758 | if album_data.get('videoType') == 'singleVideo': | |
759 | return self.url_result('https://www.iq.com/play/%s' % album_id, IqIE.ie_key()) | |
760 | return self.playlist_result( | |
761 | self._entries(album_data['albumId'], album_data['totalPageRange'], album_id, | |
762 | traverse_obj(next_data, ('props', 'initialProps', 'pageProps', 'modeCode')), | |
763 | traverse_obj(next_data, ('props', 'initialProps', 'pageProps', 'langCode'))), | |
764 | album_id, album_data.get('name'), album_data.get('desc')) |