]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/viu.py
[misc] Add `hatch`, `ruff`, `pre-commit` and improve dev docs (#7409)
[yt-dlp.git] / yt_dlp / extractor / viu.py
CommitLineData
1fb707ba 1import json
1fb707ba 2import random
e897bd82 3import re
1fb707ba 4import urllib.parse
e897bd82 5import uuid
e7b6caef 6
7from .common import InfoExtractor
1fb707ba 8from ..compat import compat_str
e7b6caef 9from ..utils import (
10 ExtractorError,
11 int_or_none,
72671a21 12 remove_end,
e897bd82 13 smuggle_url,
1fb707ba 14 strip_or_none,
72671a21 15 traverse_obj,
a7191c6f 16 try_get,
72671a21 17 unified_timestamp,
baa58739 18 unsmuggle_url,
1fb707ba 19 url_or_none,
e7b6caef 20)
21
22
23class ViuBaseIE(InfoExtractor):
1fb707ba 24 def _call_api(self, path, *args, headers={}, **kwargs):
72310315 25 response = self._download_json(
1fb707ba 26 f'https://www.viu.com/api/{path}', *args, **kwargs,
27 headers={**self.geo_verification_headers(), **headers})['response']
72310315 28 if response.get('status') != 'success':
1fb707ba 29 raise ExtractorError(f'{self.IE_NAME} said: {response["message"]}', expected=True)
72310315 30 return response
e7b6caef 31
32
33class ViuIE(ViuBaseIE):
c183e14f 34 _VALID_URL = r'(?:viu:|https?://[^/]+\.viu\.com/[a-z]{2}/media/)(?P<id>\d+)'
e7b6caef 35 _TESTS = [{
e7b6caef 36 'url': 'https://www.viu.com/en/media/1116705532?containerId=playlist-22168059',
37 'info_dict': {
38 'id': '1116705532',
39 'ext': 'mp4',
72310315 40 'title': 'Citizen Khan - Ep 1',
e7b6caef 41 'description': 'md5:d7ea1604f49e5ba79c212c551ce2110e',
42 },
43 'params': {
44 'skip_download': 'm3u8 download',
45 },
46 'skip': 'Geo-restricted to India',
47 }, {
48 'url': 'https://www.viu.com/en/media/1130599965',
49 'info_dict': {
50 'id': '1130599965',
51 'ext': 'mp4',
52 'title': 'Jealousy Incarnate - Episode 1',
53 'description': 'md5:d3d82375cab969415d2720b6894361e9',
54 },
55 'params': {
56 'skip_download': 'm3u8 download',
57 },
58 'skip': 'Geo-restricted to Indonesia',
c183e14f
S
59 }, {
60 'url': 'https://india.viu.com/en/media/1126286865',
61 'only_matching': True,
e7b6caef 62 }]
63
64 def _real_extract(self, url):
65 video_id = self._match_id(url)
66
72310315
RA
67 video_data = self._call_api(
68 'clip/load', video_id, 'Downloading video data', query={
69 'appid': 'viu_desktop',
70 'fmt': 'json',
71 'id': video_id
72 })['item'][0]
73
74 title = video_data['title']
75
76 m3u8_url = None
77 url_path = video_data.get('urlpathd') or video_data.get('urlpath')
78 tdirforwhole = video_data.get('tdirforwhole')
ed7b333f
RA
79 # #EXT-X-BYTERANGE is not supported by native hls downloader
80 # and ffmpeg (#10955)
1fb707ba 81 # FIXME: It is supported in yt-dlp
ed7b333f
RA
82 # hls_file = video_data.get('hlsfile')
83 hls_file = video_data.get('jwhlsfile')
72310315
RA
84 if url_path and tdirforwhole and hls_file:
85 m3u8_url = '%s/%s/%s' % (url_path, tdirforwhole, hls_file)
86 else:
ed7b333f
RA
87 # m3u8_url = re.sub(
88 # r'(/hlsc_)[a-z]+(\d+\.m3u8)',
89 # r'\1whe\2', video_data['href'])
90 m3u8_url = video_data['href']
47b8bf20 91 formats, subtitles = self._extract_m3u8_formats_and_subtitles(m3u8_url, video_id, 'mp4')
e7b6caef 92
72310315
RA
93 for key, value in video_data.items():
94 mobj = re.match(r'^subtitle_(?P<lang>[^_]+)_(?P<ext>(vtt|srt))', key)
95 if not mobj:
96 continue
97 subtitles.setdefault(mobj.group('lang'), []).append({
98 'url': value,
99 'ext': mobj.group('ext')
100 })
e7b6caef 101
102 return {
103 'id': video_id,
104 'title': title,
72310315
RA
105 'description': video_data.get('description'),
106 'series': video_data.get('moviealbumshowname'),
107 'episode': title,
108 'episode_number': int_or_none(video_data.get('episodeno')),
109 'duration': int_or_none(video_data.get('duration')),
e7b6caef 110 'formats': formats,
111 'subtitles': subtitles,
112 }
113
114
115class ViuPlaylistIE(ViuBaseIE):
116 IE_NAME = 'viu:playlist'
72310315 117 _VALID_URL = r'https?://www\.viu\.com/[^/]+/listing/playlist-(?P<id>\d+)'
e7b6caef 118 _TEST = {
119 'url': 'https://www.viu.com/en/listing/playlist-22461380',
120 'info_dict': {
72310315 121 'id': '22461380',
e7b6caef 122 'title': 'The Good Wife',
123 },
124 'playlist_count': 16,
125 'skip': 'Geo-restricted to Indonesia',
126 }
127
128 def _real_extract(self, url):
129 playlist_id = self._match_id(url)
72310315
RA
130 playlist_data = self._call_api(
131 'container/load', playlist_id,
132 'Downloading playlist info', query={
133 'appid': 'viu_desktop',
134 'fmt': 'json',
135 'id': 'playlist-' + playlist_id
136 })['container']
137
138 entries = []
139 for item in playlist_data.get('item', []):
140 item_id = item.get('id')
141 if not item_id:
142 continue
143 item_id = compat_str(item_id)
144 entries.append(self.url_result(
145 'viu:' + item_id, 'Viu', item_id))
146
147 return self.playlist_result(
148 entries, playlist_id, playlist_data.get('title'))
149
150
151class ViuOTTIE(InfoExtractor):
152 IE_NAME = 'viu:ott'
baa58739 153 _NETRC_MACHINE = 'viu'
154 _VALID_URL = r'https?://(?:www\.)?viu\.com/ott/(?P<country_code>[a-z]{2})/(?P<lang_code>[a-z]{2}-[a-z]{2})/vod/(?P<id>\d+)'
72310315
RA
155 _TESTS = [{
156 'url': 'http://www.viu.com/ott/sg/en-us/vod/3421/The%20Prime%20Minister%20and%20I',
157 'info_dict': {
158 'id': '3421',
159 'ext': 'mp4',
160 'title': 'A New Beginning',
161 'description': 'md5:1e7486a619b6399b25ba6a41c0fe5b2c',
162 },
163 'params': {
164 'skip_download': 'm3u8 download',
baa58739 165 'noplaylist': True,
72310315
RA
166 },
167 'skip': 'Geo-restricted to Singapore',
168 }, {
f324fe8c 169 'url': 'https://www.viu.com/ott/hk/zh-hk/vod/430078/%E7%AC%AC%E5%85%AD%E6%84%9F-3',
72310315 170 'info_dict': {
f324fe8c 171 'id': '430078',
72310315 172 'ext': 'mp4',
f324fe8c 173 'title': '大韓民國的1%',
174 'description': 'md5:74d6db47ddd9ddb9c89a05739103ccdb',
175 'episode_number': 1,
176 'duration': 6614,
177 'episode': '大韓民國的1%',
178 'series': '第六感 3',
179 'thumbnail': 'https://d2anahhhmp1ffz.cloudfront.net/1313295781/d2b14f48d008ef2f3a9200c98d8e9b63967b9cc2',
72310315
RA
180 },
181 'params': {
182 'skip_download': 'm3u8 download',
baa58739 183 'noplaylist': True,
184 },
185 'skip': 'Geo-restricted to Hong Kong',
186 }, {
f324fe8c 187 'url': 'https://www.viu.com/ott/hk/zh-hk/vod/444666/%E6%88%91%E7%9A%84%E5%AE%A4%E5%8F%8B%E6%98%AF%E4%B9%9D%E5%B0%BE%E7%8B%90',
188 'playlist_count': 16,
baa58739 189 'info_dict': {
f324fe8c 190 'id': '23807',
191 'title': '我的室友是九尾狐',
192 'description': 'md5:b42c95f2b4a316cdd6ae14ca695f33b9',
baa58739 193 },
194 'params': {
195 'skip_download': 'm3u8 download',
196 'noplaylist': False,
72310315
RA
197 },
198 'skip': 'Geo-restricted to Hong Kong',
199 }]
200
ecb6b6ae
S
201 _AREA_ID = {
202 'HK': 1,
203 'SG': 2,
204 'TH': 4,
205 'PH': 5,
206 }
baa58739 207 _LANGUAGE_FLAG = {
208 'zh-hk': 1,
209 'zh-cn': 2,
210 'en-us': 3,
211 }
1fb707ba 212
213 _user_token = None
214 _auth_codes = {}
baa58739 215
216 def _detect_error(self, response):
1fb707ba 217 code = try_get(response, lambda x: x['status']['code'])
218 if code and code > 0:
baa58739 219 message = try_get(response, lambda x: x['status']['message'])
1fb707ba 220 raise ExtractorError(f'{self.IE_NAME} said: {message} ({code})', expected=True)
221 return response.get('data') or {}
baa58739 222
223 def _login(self, country_code, video_id):
1fb707ba 224 if self._user_token is None:
baa58739 225 username, password = self._get_login_info()
1fb707ba 226 if username is None:
baa58739 227 return
1fb707ba 228 headers = {
229 'Authorization': f'Bearer {self._auth_codes[country_code]}',
230 'Content-Type': 'application/json'
231 }
232 data = self._download_json(
233 'https://api-gateway-global.viu.com/api/account/validate',
234 video_id, 'Validating email address', headers=headers,
235 data=json.dumps({
236 'principal': username,
237 'provider': 'email'
238 }).encode())
239 if not data.get('exists'):
240 raise ExtractorError('Invalid email address')
baa58739 241
242 data = self._download_json(
1fb707ba 243 'https://api-gateway-global.viu.com/api/auth/login',
244 video_id, 'Logging in', headers=headers,
baa58739 245 data=json.dumps({
1fb707ba 246 'email': username,
baa58739 247 'password': password,
1fb707ba 248 'provider': 'email',
baa58739 249 }).encode())
1fb707ba 250 self._detect_error(data)
251 self._user_token = data.get('identity')
252 # need to update with valid user's token else will throw an error again
253 self._auth_codes[country_code] = data.get('token')
254 return self._user_token
255
256 def _get_token(self, country_code, video_id):
efa944f4 257 rand = ''.join(random.choices('0123456789', k=10))
1fb707ba 258 return self._download_json(
259 f'https://api-gateway-global.viu.com/api/auth/token?v={rand}000', video_id,
260 headers={'Content-Type': 'application/json'}, note='Getting bearer token',
261 data=json.dumps({
262 'countryCode': country_code.upper(),
263 'platform': 'browser',
264 'platformFlagLabel': 'web',
265 'language': 'en',
266 'uuid': str(uuid.uuid4()),
267 'carrierId': '0'
268 }).encode('utf-8'))['token']
ecb6b6ae 269
72310315 270 def _real_extract(self, url):
baa58739 271 url, idata = unsmuggle_url(url, {})
5ad28e7f 272 country_code, lang_code, video_id = self._match_valid_url(url).groups()
72310315 273
ecb6b6ae
S
274 query = {
275 'r': 'vod/ajax-detail',
276 'platform_flag_label': 'web',
277 'product_id': video_id,
278 }
279
280 area_id = self._AREA_ID.get(country_code.upper())
281 if area_id:
282 query['area_id'] = area_id
283
72310315 284 product_data = self._download_json(
1fb707ba 285 f'http://www.viu.com/ott/{country_code}/index.php', video_id,
ecb6b6ae 286 'Downloading video info', query=query)['data']
72310315
RA
287
288 video_data = product_data.get('current_product')
289 if not video_data:
1fb707ba 290 self.raise_geo_restricted()
72310315 291
baa58739 292 series_id = video_data.get('series_id')
f40ee5e9 293 if self._yes_playlist(series_id, video_id, idata):
1fb707ba 294 series = product_data.get('series') or {}
baa58739 295 product = series.get('product')
296 if product:
297 entries = []
298 for entry in sorted(product, key=lambda x: int_or_none(x.get('number', 0))):
299 item_id = entry.get('product_id')
300 if not item_id:
301 continue
baa58739 302 entries.append(self.url_result(
1fb707ba 303 smuggle_url(f'http://www.viu.com/ott/{country_code}/{lang_code}/vod/{item_id}/',
304 {'force_noplaylist': True}),
305 ViuOTTIE, str(item_id), entry.get('synopsis', '').strip()))
baa58739 306
307 return self.playlist_result(entries, series_id, series.get('name'), series.get('description'))
308
baa58739 309 duration_limit = False
310 query = {
311 'ccs_product_id': video_data['ccs_product_id'],
312 'language_flag_id': self._LANGUAGE_FLAG.get(lang_code.lower()) or '3',
313 }
1fb707ba 314
315 def download_playback():
baa58739 316 stream_data = self._download_json(
1fb707ba 317 'https://api-gateway-global.viu.com/api/playback/distribute',
318 video_id=video_id, query=query, fatal=False, note='Downloading stream info',
319 headers={
320 'Authorization': f'Bearer {self._auth_codes[country_code]}',
321 'Referer': url,
322 'Origin': url
323 })
324 return self._detect_error(stream_data).get('stream')
325
326 if not self._auth_codes.get(country_code):
327 self._auth_codes[country_code] = self._get_token(country_code, video_id)
baa58739 328
1fb707ba 329 stream_data = None
330 try:
331 stream_data = download_playback()
332 except (ExtractorError, KeyError):
333 token = self._login(country_code, video_id)
334 if token is not None:
335 query['identity'] = token
336 else:
c418e6b5 337 # The content is Preview or for VIP only.
338 # We can try to bypass the duration which is limited to 3mins only
1fb707ba 339 duration_limit, query['duration'] = True, '180'
340 try:
341 stream_data = download_playback()
342 except (ExtractorError, KeyError):
343 if token is not None:
344 raise
345 self.raise_login_required(method='password')
baa58739 346 if not stream_data:
347 raise ExtractorError('Cannot get stream info', expected=True)
72310315 348
72310315 349 formats = []
1fb707ba 350 for vid_format, stream_url in (stream_data.get('url') or {}).items():
351 height = int(self._search_regex(r's(\d+)p', vid_format, 'height', default=None))
baa58739 352
353 # bypass preview duration limit
354 if duration_limit:
c418e6b5 355 old_stream_url = urllib.parse.urlparse(stream_url)
356 query = dict(urllib.parse.parse_qsl(old_stream_url.query, keep_blank_values=True))
baa58739 357 query.update({
1fb707ba 358 'duration': video_data.get('time_duration') or '9999999',
baa58739 359 'duration_start': '0',
360 })
c418e6b5 361 stream_url = old_stream_url._replace(query=urllib.parse.urlencode(query)).geturl()
baa58739 362
72310315
RA
363 formats.append({
364 'format_id': vid_format,
365 'url': stream_url,
366 'height': height,
367 'ext': 'mp4',
1fb707ba 368 'filesize': try_get(stream_data, lambda x: x['size'][vid_format], int)
72310315 369 })
72310315
RA
370
371 subtitles = {}
1fb707ba 372 for sub in video_data.get('subtitle') or []:
f324fe8c 373 lang = sub.get('name') or 'und'
374 if sub.get('url'):
375 subtitles.setdefault(lang, []).append({
376 'url': sub['url'],
377 'ext': 'srt',
378 'name': f'Spoken text for {lang}',
379 })
380 if sub.get('second_subtitle_url'):
381 subtitles.setdefault(f'{lang}_ost', []).append({
382 'url': sub['second_subtitle_url'],
383 'ext': 'srt',
384 'name': f'On-screen text for {lang}',
385 })
72310315 386
1fb707ba 387 title = strip_or_none(video_data.get('synopsis'))
72310315
RA
388 return {
389 'id': video_id,
390 'title': title,
391 'description': video_data.get('description'),
1fb707ba 392 'series': try_get(product_data, lambda x: x['series']['name']),
72310315
RA
393 'episode': title,
394 'episode_number': int_or_none(video_data.get('number')),
395 'duration': int_or_none(stream_data.get('duration')),
1fb707ba 396 'thumbnail': url_or_none(video_data.get('cover_image_url')),
72310315
RA
397 'formats': formats,
398 'subtitles': subtitles,
399 }
72671a21
H
400
401
402class ViuOTTIndonesiaBaseIE(InfoExtractor):
403 _BASE_QUERY = {
404 'ver': 1.0,
405 'fmt': 'json',
406 'aver': 5.0,
407 'appver': 2.0,
408 'appid': 'viu_desktop',
409 'platform': 'desktop',
410 }
411
412 _DEVICE_ID = str(uuid.uuid4())
413 _SESSION_ID = str(uuid.uuid4())
414 _TOKEN = None
415
416 _HEADERS = {
417 'x-session-id': _SESSION_ID,
418 'x-client': 'browser'
419 }
420
421 _AGE_RATINGS_MAPPER = {
422 'ADULTS': 18,
423 'teens': 13
424 }
425
426 def _real_initialize(self):
427 ViuOTTIndonesiaBaseIE._TOKEN = self._download_json(
428 'https://um.viuapi.io/user/identity', None,
429 headers={'Content-type': 'application/json', **self._HEADERS},
430 query={**self._BASE_QUERY, 'iid': self._DEVICE_ID},
431 data=json.dumps({'deviceId': self._DEVICE_ID}).encode(),
432 note='Downloading token information')['token']
433
434
435class ViuOTTIndonesiaIE(ViuOTTIndonesiaBaseIE):
436 _VALID_URL = r'https?://www\.viu\.com/ott/\w+/\w+/all/video-[\w-]+-(?P<id>\d+)'
437 _TESTS = [{
438 'url': 'https://www.viu.com/ott/id/id/all/video-japanese-drama-tv_shows-detective_conan_episode_793-1165863142?containerId=playlist-26271226',
439 'info_dict': {
440 'id': '1165863142',
441 'ext': 'mp4',
442 'episode_number': 793,
443 'episode': 'Episode 793',
444 'title': 'Detective Conan - Episode 793',
445 'duration': 1476,
446 'description': 'md5:b79d55345bc1e0217ece22616267c9a5',
447 'thumbnail': 'https://vuclipi-a.akamaihd.net/p/cloudinary/h_171,w_304,dpr_1.5,f_auto,c_thumb,q_auto:low/1165863189/d-1',
448 'upload_date': '20210101',
449 'timestamp': 1609459200,
450 }
451 }, {
452 'url': 'https://www.viu.com/ott/id/id/all/video-korean-reality-tv_shows-entertainment_weekly_episode_1622-1118617054',
453 'info_dict': {
454 'id': '1118617054',
455 'ext': 'mp4',
456 'episode_number': 1622,
457 'episode': 'Episode 1622',
458 'description': 'md5:6d68ca450004020113e9bf27ad99f0f8',
459 'title': 'Entertainment Weekly - Episode 1622',
460 'duration': 4729,
461 'thumbnail': 'https://vuclipi-a.akamaihd.net/p/cloudinary/h_171,w_304,dpr_1.5,f_auto,c_thumb,q_auto:low/1120187848/d-1',
462 'timestamp': 1420070400,
463 'upload_date': '20150101',
464 'cast': ['Shin Hyun-joon', 'Lee Da-Hee']
465 }
466 }, {
467 # age-limit test
468 'url': 'https://www.viu.com/ott/id/id/all/video-japanese-trailer-tv_shows-trailer_jujutsu_kaisen_ver_01-1166044219?containerId=playlist-26273140',
469 'info_dict': {
470 'id': '1166044219',
471 'ext': 'mp4',
472 'upload_date': '20200101',
473 'timestamp': 1577836800,
474 'title': 'Trailer \'Jujutsu Kaisen\' Ver.01',
475 'duration': 92,
476 'thumbnail': 'https://vuclipi-a.akamaihd.net/p/cloudinary/h_171,w_304,dpr_1.5,f_auto,c_thumb,q_auto:low/1166044240/d-1',
477 'description': 'Trailer \'Jujutsu Kaisen\' Ver.01',
478 'cast': ['Junya Enoki', ' Yûichi Nakamura', ' Yuma Uchida', 'Asami Seto'],
479 'age_limit': 13,
480 }
481 }, {
482 # json ld metadata type equal to Movie instead of TVEpisodes
483 'url': 'https://www.viu.com/ott/id/id/all/video-japanese-animation-movies-demon_slayer_kimetsu_no_yaiba_the_movie_mugen_train-1165892707?containerId=1675060691786',
484 'info_dict': {
485 'id': '1165892707',
486 'ext': 'mp4',
487 'timestamp': 1577836800,
488 'upload_date': '20200101',
489 'title': 'Demon Slayer - Kimetsu no Yaiba - The Movie: Mugen Train',
490 'age_limit': 13,
491 'cast': 'count:9',
492 'thumbnail': 'https://vuclipi-a.akamaihd.net/p/cloudinary/h_171,w_304,dpr_1.5,f_auto,c_thumb,q_auto:low/1165895279/d-1',
493 'description': 'md5:1ce9c35a3aeab384085533f746c87469',
494 'duration': 7021,
495 }
496 }]
497
498 def _real_extract(self, url):
499 display_id = self._match_id(url)
500 webpage = self._download_webpage(url, display_id)
501
502 video_data = self._download_json(
503 f'https://um.viuapi.io/drm/v1/content/{display_id}', display_id, data=b'',
504 headers={'Authorization': ViuOTTIndonesiaBaseIE._TOKEN, **self._HEADERS, 'ccode': 'ID'})
505 formats, subtitles = self._extract_m3u8_formats_and_subtitles(video_data['playUrl'], display_id)
506
507 initial_state = self._search_json(
508 r'window\.__INITIAL_STATE__\s*=', webpage, 'initial state',
509 display_id)['content']['clipDetails']
510 for key, url in initial_state.items():
511 lang, ext = self._search_regex(
512 r'^subtitle_(?P<lang>[\w-]+)_(?P<ext>\w+)$', key, 'subtitle metadata',
513 default=(None, None), group=('lang', 'ext'))
514 if lang and ext:
515 subtitles.setdefault(lang, []).append({
516 'ext': ext,
517 'url': url,
518 })
519
520 if ext == 'vtt':
521 subtitles[lang].append({
522 'ext': 'srt',
523 'url': f'{remove_end(initial_state[key], "vtt")}srt',
524 })
525
526 episode = traverse_obj(list(filter(
527 lambda x: x.get('@type') in ('TVEpisode', 'Movie'), self._yield_json_ld(webpage, display_id))), 0) or {}
528 return {
529 'id': display_id,
530 'title': (traverse_obj(initial_state, 'title', 'display_title')
531 or episode.get('name')),
532 'description': initial_state.get('description') or episode.get('description'),
533 'duration': initial_state.get('duration'),
534 'thumbnail': traverse_obj(episode, ('image', 'url')),
535 'timestamp': unified_timestamp(episode.get('dateCreated')),
536 'formats': formats,
537 'subtitles': subtitles,
538 'episode_number': (traverse_obj(initial_state, 'episode_no', 'episodeno', expected_type=int_or_none)
539 or int_or_none(episode.get('episodeNumber'))),
540 'cast': traverse_obj(episode, ('actor', ..., 'name'), default=None),
541 'age_limit': self._AGE_RATINGS_MAPPER.get(initial_state.get('internal_age_rating'))
542 }