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