viu.py 21 KB

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