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