viu.py 15 KB

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