]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/viu.py
[extractor] Deprecate `_sort_formats`
[yt-dlp.git] / yt_dlp / extractor / viu.py
CommitLineData
e7b6caef 1import re
1fb707ba 2import json
3import uuid
4import random
5import urllib.parse
e7b6caef 6
7from .common import InfoExtractor
1fb707ba 8from ..compat import compat_str
e7b6caef 9from ..utils import (
10 ExtractorError,
11 int_or_none,
1fb707ba 12 strip_or_none,
a7191c6f 13 try_get,
baa58739 14 smuggle_url,
15 unsmuggle_url,
1fb707ba 16 url_or_none,
e7b6caef 17)
18
19
20class ViuBaseIE(InfoExtractor):
1fb707ba 21 def _call_api(self, path, *args, headers={}, **kwargs):
72310315 22 response = self._download_json(
1fb707ba 23 f'https://www.viu.com/api/{path}', *args, **kwargs,
24 headers={**self.geo_verification_headers(), **headers})['response']
72310315 25 if response.get('status') != 'success':
1fb707ba 26 raise ExtractorError(f'{self.IE_NAME} said: {response["message"]}', expected=True)
72310315 27 return response
e7b6caef 28
29
30class ViuIE(ViuBaseIE):
c183e14f 31 _VALID_URL = r'(?:viu:|https?://[^/]+\.viu\.com/[a-z]{2}/media/)(?P<id>\d+)'
e7b6caef 32 _TESTS = [{
e7b6caef 33 'url': 'https://www.viu.com/en/media/1116705532?containerId=playlist-22168059',
34 'info_dict': {
35 'id': '1116705532',
36 'ext': 'mp4',
72310315 37 'title': 'Citizen Khan - Ep 1',
e7b6caef 38 'description': 'md5:d7ea1604f49e5ba79c212c551ce2110e',
39 },
40 'params': {
41 'skip_download': 'm3u8 download',
42 },
43 'skip': 'Geo-restricted to India',
44 }, {
45 'url': 'https://www.viu.com/en/media/1130599965',
46 'info_dict': {
47 'id': '1130599965',
48 'ext': 'mp4',
49 'title': 'Jealousy Incarnate - Episode 1',
50 'description': 'md5:d3d82375cab969415d2720b6894361e9',
51 },
52 'params': {
53 'skip_download': 'm3u8 download',
54 },
55 'skip': 'Geo-restricted to Indonesia',
c183e14f
S
56 }, {
57 'url': 'https://india.viu.com/en/media/1126286865',
58 'only_matching': True,
e7b6caef 59 }]
60
61 def _real_extract(self, url):
62 video_id = self._match_id(url)
63
72310315
RA
64 video_data = self._call_api(
65 'clip/load', video_id, 'Downloading video data', query={
66 'appid': 'viu_desktop',
67 'fmt': 'json',
68 'id': video_id
69 })['item'][0]
70
71 title = video_data['title']
72
73 m3u8_url = None
74 url_path = video_data.get('urlpathd') or video_data.get('urlpath')
75 tdirforwhole = video_data.get('tdirforwhole')
ed7b333f
RA
76 # #EXT-X-BYTERANGE is not supported by native hls downloader
77 # and ffmpeg (#10955)
1fb707ba 78 # FIXME: It is supported in yt-dlp
ed7b333f
RA
79 # hls_file = video_data.get('hlsfile')
80 hls_file = video_data.get('jwhlsfile')
72310315
RA
81 if url_path and tdirforwhole and hls_file:
82 m3u8_url = '%s/%s/%s' % (url_path, tdirforwhole, hls_file)
83 else:
ed7b333f
RA
84 # m3u8_url = re.sub(
85 # r'(/hlsc_)[a-z]+(\d+\.m3u8)',
86 # r'\1whe\2', video_data['href'])
87 m3u8_url = video_data['href']
47b8bf20 88 formats, subtitles = self._extract_m3u8_formats_and_subtitles(m3u8_url, video_id, 'mp4')
e7b6caef 89
72310315
RA
90 for key, value in video_data.items():
91 mobj = re.match(r'^subtitle_(?P<lang>[^_]+)_(?P<ext>(vtt|srt))', key)
92 if not mobj:
93 continue
94 subtitles.setdefault(mobj.group('lang'), []).append({
95 'url': value,
96 'ext': mobj.group('ext')
97 })
e7b6caef 98
99 return {
100 'id': video_id,
101 'title': title,
72310315
RA
102 'description': video_data.get('description'),
103 'series': video_data.get('moviealbumshowname'),
104 'episode': title,
105 'episode_number': int_or_none(video_data.get('episodeno')),
106 'duration': int_or_none(video_data.get('duration')),
e7b6caef 107 'formats': formats,
108 'subtitles': subtitles,
109 }
110
111
112class ViuPlaylistIE(ViuBaseIE):
113 IE_NAME = 'viu:playlist'
72310315 114 _VALID_URL = r'https?://www\.viu\.com/[^/]+/listing/playlist-(?P<id>\d+)'
e7b6caef 115 _TEST = {
116 'url': 'https://www.viu.com/en/listing/playlist-22461380',
117 'info_dict': {
72310315 118 'id': '22461380',
e7b6caef 119 'title': 'The Good Wife',
120 },
121 'playlist_count': 16,
122 'skip': 'Geo-restricted to Indonesia',
123 }
124
125 def _real_extract(self, url):
126 playlist_id = self._match_id(url)
72310315
RA
127 playlist_data = self._call_api(
128 'container/load', playlist_id,
129 'Downloading playlist info', query={
130 'appid': 'viu_desktop',
131 'fmt': 'json',
132 'id': 'playlist-' + playlist_id
133 })['container']
134
135 entries = []
136 for item in playlist_data.get('item', []):
137 item_id = item.get('id')
138 if not item_id:
139 continue
140 item_id = compat_str(item_id)
141 entries.append(self.url_result(
142 'viu:' + item_id, 'Viu', item_id))
143
144 return self.playlist_result(
145 entries, playlist_id, playlist_data.get('title'))
146
147
148class ViuOTTIE(InfoExtractor):
149 IE_NAME = 'viu:ott'
baa58739 150 _NETRC_MACHINE = 'viu'
151 _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
152 _TESTS = [{
153 'url': 'http://www.viu.com/ott/sg/en-us/vod/3421/The%20Prime%20Minister%20and%20I',
154 'info_dict': {
155 'id': '3421',
156 'ext': 'mp4',
157 'title': 'A New Beginning',
158 'description': 'md5:1e7486a619b6399b25ba6a41c0fe5b2c',
159 },
160 'params': {
161 'skip_download': 'm3u8 download',
baa58739 162 'noplaylist': True,
72310315
RA
163 },
164 'skip': 'Geo-restricted to Singapore',
165 }, {
f324fe8c 166 'url': 'https://www.viu.com/ott/hk/zh-hk/vod/430078/%E7%AC%AC%E5%85%AD%E6%84%9F-3',
72310315 167 'info_dict': {
f324fe8c 168 'id': '430078',
72310315 169 'ext': 'mp4',
f324fe8c 170 'title': '大韓民國的1%',
171 'description': 'md5:74d6db47ddd9ddb9c89a05739103ccdb',
172 'episode_number': 1,
173 'duration': 6614,
174 'episode': '大韓民國的1%',
175 'series': '第六感 3',
176 'thumbnail': 'https://d2anahhhmp1ffz.cloudfront.net/1313295781/d2b14f48d008ef2f3a9200c98d8e9b63967b9cc2',
72310315
RA
177 },
178 'params': {
179 'skip_download': 'm3u8 download',
baa58739 180 'noplaylist': True,
181 },
182 'skip': 'Geo-restricted to Hong Kong',
183 }, {
f324fe8c 184 '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',
185 'playlist_count': 16,
baa58739 186 'info_dict': {
f324fe8c 187 'id': '23807',
188 'title': '我的室友是九尾狐',
189 'description': 'md5:b42c95f2b4a316cdd6ae14ca695f33b9',
baa58739 190 },
191 'params': {
192 'skip_download': 'm3u8 download',
193 'noplaylist': False,
72310315
RA
194 },
195 'skip': 'Geo-restricted to Hong Kong',
196 }]
197
ecb6b6ae
S
198 _AREA_ID = {
199 'HK': 1,
200 'SG': 2,
201 'TH': 4,
202 'PH': 5,
203 }
baa58739 204 _LANGUAGE_FLAG = {
205 'zh-hk': 1,
206 'zh-cn': 2,
207 'en-us': 3,
208 }
1fb707ba 209
210 _user_token = None
211 _auth_codes = {}
baa58739 212
213 def _detect_error(self, response):
1fb707ba 214 code = try_get(response, lambda x: x['status']['code'])
215 if code and code > 0:
baa58739 216 message = try_get(response, lambda x: x['status']['message'])
1fb707ba 217 raise ExtractorError(f'{self.IE_NAME} said: {message} ({code})', expected=True)
218 return response.get('data') or {}
baa58739 219
220 def _login(self, country_code, video_id):
1fb707ba 221 if self._user_token is None:
baa58739 222 username, password = self._get_login_info()
1fb707ba 223 if username is None:
baa58739 224 return
1fb707ba 225 headers = {
226 'Authorization': f'Bearer {self._auth_codes[country_code]}',
227 'Content-Type': 'application/json'
228 }
229 data = self._download_json(
230 'https://api-gateway-global.viu.com/api/account/validate',
231 video_id, 'Validating email address', headers=headers,
232 data=json.dumps({
233 'principal': username,
234 'provider': 'email'
235 }).encode())
236 if not data.get('exists'):
237 raise ExtractorError('Invalid email address')
baa58739 238
239 data = self._download_json(
1fb707ba 240 'https://api-gateway-global.viu.com/api/auth/login',
241 video_id, 'Logging in', headers=headers,
baa58739 242 data=json.dumps({
1fb707ba 243 'email': username,
baa58739 244 'password': password,
1fb707ba 245 'provider': 'email',
baa58739 246 }).encode())
1fb707ba 247 self._detect_error(data)
248 self._user_token = data.get('identity')
249 # need to update with valid user's token else will throw an error again
250 self._auth_codes[country_code] = data.get('token')
251 return self._user_token
252
253 def _get_token(self, country_code, video_id):
254 rand = ''.join(random.choice('0123456789') for _ in range(10))
255 return self._download_json(
256 f'https://api-gateway-global.viu.com/api/auth/token?v={rand}000', video_id,
257 headers={'Content-Type': 'application/json'}, note='Getting bearer token',
258 data=json.dumps({
259 'countryCode': country_code.upper(),
260 'platform': 'browser',
261 'platformFlagLabel': 'web',
262 'language': 'en',
263 'uuid': str(uuid.uuid4()),
264 'carrierId': '0'
265 }).encode('utf-8'))['token']
ecb6b6ae 266
72310315 267 def _real_extract(self, url):
baa58739 268 url, idata = unsmuggle_url(url, {})
5ad28e7f 269 country_code, lang_code, video_id = self._match_valid_url(url).groups()
72310315 270
ecb6b6ae
S
271 query = {
272 'r': 'vod/ajax-detail',
273 'platform_flag_label': 'web',
274 'product_id': video_id,
275 }
276
277 area_id = self._AREA_ID.get(country_code.upper())
278 if area_id:
279 query['area_id'] = area_id
280
72310315 281 product_data = self._download_json(
1fb707ba 282 f'http://www.viu.com/ott/{country_code}/index.php', video_id,
ecb6b6ae 283 'Downloading video info', query=query)['data']
72310315
RA
284
285 video_data = product_data.get('current_product')
286 if not video_data:
1fb707ba 287 self.raise_geo_restricted()
72310315 288
baa58739 289 series_id = video_data.get('series_id')
f40ee5e9 290 if self._yes_playlist(series_id, video_id, idata):
1fb707ba 291 series = product_data.get('series') or {}
baa58739 292 product = series.get('product')
293 if product:
294 entries = []
295 for entry in sorted(product, key=lambda x: int_or_none(x.get('number', 0))):
296 item_id = entry.get('product_id')
297 if not item_id:
298 continue
baa58739 299 entries.append(self.url_result(
1fb707ba 300 smuggle_url(f'http://www.viu.com/ott/{country_code}/{lang_code}/vod/{item_id}/',
301 {'force_noplaylist': True}),
302 ViuOTTIE, str(item_id), entry.get('synopsis', '').strip()))
baa58739 303
304 return self.playlist_result(entries, series_id, series.get('name'), series.get('description'))
305
baa58739 306 duration_limit = False
307 query = {
308 'ccs_product_id': video_data['ccs_product_id'],
309 'language_flag_id': self._LANGUAGE_FLAG.get(lang_code.lower()) or '3',
310 }
1fb707ba 311
312 def download_playback():
baa58739 313 stream_data = self._download_json(
1fb707ba 314 'https://api-gateway-global.viu.com/api/playback/distribute',
315 video_id=video_id, query=query, fatal=False, note='Downloading stream info',
316 headers={
317 'Authorization': f'Bearer {self._auth_codes[country_code]}',
318 'Referer': url,
319 'Origin': url
320 })
321 return self._detect_error(stream_data).get('stream')
322
323 if not self._auth_codes.get(country_code):
324 self._auth_codes[country_code] = self._get_token(country_code, video_id)
baa58739 325
1fb707ba 326 stream_data = None
327 try:
328 stream_data = download_playback()
329 except (ExtractorError, KeyError):
330 token = self._login(country_code, video_id)
331 if token is not None:
332 query['identity'] = token
333 else:
c418e6b5 334 # The content is Preview or for VIP only.
335 # We can try to bypass the duration which is limited to 3mins only
1fb707ba 336 duration_limit, query['duration'] = True, '180'
337 try:
338 stream_data = download_playback()
339 except (ExtractorError, KeyError):
340 if token is not None:
341 raise
342 self.raise_login_required(method='password')
baa58739 343 if not stream_data:
344 raise ExtractorError('Cannot get stream info', expected=True)
72310315 345
72310315 346 formats = []
1fb707ba 347 for vid_format, stream_url in (stream_data.get('url') or {}).items():
348 height = int(self._search_regex(r's(\d+)p', vid_format, 'height', default=None))
baa58739 349
350 # bypass preview duration limit
351 if duration_limit:
c418e6b5 352 old_stream_url = urllib.parse.urlparse(stream_url)
353 query = dict(urllib.parse.parse_qsl(old_stream_url.query, keep_blank_values=True))
baa58739 354 query.update({
1fb707ba 355 'duration': video_data.get('time_duration') or '9999999',
baa58739 356 'duration_start': '0',
357 })
c418e6b5 358 stream_url = old_stream_url._replace(query=urllib.parse.urlencode(query)).geturl()
baa58739 359
72310315
RA
360 formats.append({
361 'format_id': vid_format,
362 'url': stream_url,
363 'height': height,
364 'ext': 'mp4',
1fb707ba 365 'filesize': try_get(stream_data, lambda x: x['size'][vid_format], int)
72310315 366 })
72310315
RA
367
368 subtitles = {}
1fb707ba 369 for sub in video_data.get('subtitle') or []:
f324fe8c 370 lang = sub.get('name') or 'und'
371 if sub.get('url'):
372 subtitles.setdefault(lang, []).append({
373 'url': sub['url'],
374 'ext': 'srt',
375 'name': f'Spoken text for {lang}',
376 })
377 if sub.get('second_subtitle_url'):
378 subtitles.setdefault(f'{lang}_ost', []).append({
379 'url': sub['second_subtitle_url'],
380 'ext': 'srt',
381 'name': f'On-screen text for {lang}',
382 })
72310315 383
1fb707ba 384 title = strip_or_none(video_data.get('synopsis'))
72310315
RA
385 return {
386 'id': video_id,
387 'title': title,
388 'description': video_data.get('description'),
1fb707ba 389 'series': try_get(product_data, lambda x: x['series']['name']),
72310315
RA
390 'episode': title,
391 'episode_number': int_or_none(video_data.get('number')),
392 'duration': int_or_none(stream_data.get('duration')),
1fb707ba 393 'thumbnail': url_or_none(video_data.get('cover_image_url')),
72310315
RA
394 'formats': formats,
395 'subtitles': subtitles,
396 }