viki.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. import hashlib
  2. import hmac
  3. import json
  4. import time
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. ExtractorError,
  8. int_or_none,
  9. parse_age_limit,
  10. parse_iso8601,
  11. try_get,
  12. )
  13. class VikiBaseIE(InfoExtractor):
  14. _VALID_URL_BASE = r'https?://(?:www\.)?viki\.(?:com|net|mx|jp|fr)/'
  15. _API_URL_TEMPLATE = 'https://api.viki.io%s'
  16. _DEVICE_ID = '112395910d'
  17. _APP = '100005a'
  18. _APP_VERSION = '6.11.3'
  19. _APP_SECRET = 'd96704b180208dbb2efa30fe44c48bd8690441af9f567ba8fd710a72badc85198f7472'
  20. _GEO_BYPASS = False
  21. _NETRC_MACHINE = 'viki'
  22. _token = None
  23. _ERRORS = {
  24. 'geo': 'Sorry, this content is not available in your region.',
  25. 'upcoming': 'Sorry, this content is not yet available.',
  26. 'paywall': 'Sorry, this content is only available to Viki Pass Plus subscribers',
  27. }
  28. def _stream_headers(self, timestamp, sig):
  29. return {
  30. 'X-Viki-manufacturer': 'vivo',
  31. 'X-Viki-device-model': 'vivo 1606',
  32. 'X-Viki-device-os-ver': '6.0.1',
  33. 'X-Viki-connection-type': 'WIFI',
  34. 'X-Viki-carrier': '',
  35. 'X-Viki-as-id': '100005a-1625321982-3932',
  36. 'timestamp': str(timestamp),
  37. 'signature': str(sig),
  38. 'x-viki-app-ver': self._APP_VERSION,
  39. }
  40. def _api_query(self, path, version=4, **kwargs):
  41. path += '?' if '?' not in path else '&'
  42. query = f'/v{version}/{path}app={self._APP}'
  43. if self._token:
  44. query += f'&token={self._token}'
  45. return query + ''.join(f'&{name}={val}' for name, val in kwargs.items())
  46. def _sign_query(self, path):
  47. timestamp = int(time.time())
  48. query = self._api_query(path, version=5)
  49. sig = hmac.new(
  50. self._APP_SECRET.encode('ascii'), f'{query}&t={timestamp}'.encode('ascii'), hashlib.sha1).hexdigest()
  51. return timestamp, sig, self._API_URL_TEMPLATE % query
  52. def _call_api(
  53. self, path, video_id, note='Downloading JSON metadata', data=None, query=None, fatal=True):
  54. if query is None:
  55. timestamp, sig, url = self._sign_query(path)
  56. else:
  57. url = self._API_URL_TEMPLATE % self._api_query(path, version=4)
  58. resp = self._download_json(
  59. url, video_id, note, fatal=fatal, query=query,
  60. data=json.dumps(data).encode() if data else None,
  61. headers=({'x-viki-app-ver': self._APP_VERSION} if data
  62. else self._stream_headers(timestamp, sig) if query is None
  63. else None), expected_status=400) or {}
  64. self._raise_error(resp.get('error'), fatal)
  65. return resp
  66. def _raise_error(self, error, fatal=True):
  67. if error is None:
  68. return
  69. msg = f'{self.IE_NAME} said: {error}'
  70. if fatal:
  71. raise ExtractorError(msg, expected=True)
  72. else:
  73. self.report_warning(msg)
  74. def _check_errors(self, data):
  75. for reason, status in (data.get('blocking') or {}).items():
  76. if status and reason in self._ERRORS:
  77. message = self._ERRORS[reason]
  78. if reason == 'geo':
  79. self.raise_geo_restricted(msg=message)
  80. elif reason == 'paywall':
  81. if try_get(data, lambda x: x['paywallable']['tvod']):
  82. self._raise_error('This video is for rent only or TVOD (Transactional Video On demand)')
  83. self.raise_login_required(message)
  84. self._raise_error(message)
  85. def _perform_login(self, username, password):
  86. self._token = self._call_api(
  87. 'sessions.json', None, 'Logging in', fatal=False,
  88. data={'username': username, 'password': password}).get('token')
  89. if not self._token:
  90. self.report_warning('Login Failed: Unable to get session token')
  91. @staticmethod
  92. def dict_selection(dict_obj, preferred_key):
  93. if preferred_key in dict_obj:
  94. return dict_obj[preferred_key]
  95. return (list(filter(None, dict_obj.values())) or [None])[0]
  96. class VikiIE(VikiBaseIE):
  97. IE_NAME = 'viki'
  98. _VALID_URL = rf'{VikiBaseIE._VALID_URL_BASE}(?:videos|player)/(?P<id>[0-9]+v)'
  99. _TESTS = [{
  100. 'note': 'Free non-DRM video with storyboards in MPD',
  101. 'url': 'https://www.viki.com/videos/1175236v-choosing-spouse-by-lottery-episode-1',
  102. 'info_dict': {
  103. 'id': '1175236v',
  104. 'ext': 'mp4',
  105. 'title': 'Choosing Spouse by Lottery - Episode 1',
  106. 'timestamp': 1606463239,
  107. 'age_limit': 13,
  108. 'uploader': 'FCC',
  109. 'upload_date': '20201127',
  110. },
  111. }, {
  112. 'url': 'http://www.viki.com/videos/1023585v-heirs-episode-14',
  113. 'info_dict': {
  114. 'id': '1023585v',
  115. 'ext': 'mp4',
  116. 'title': 'Heirs - Episode 14',
  117. 'uploader': 'SBS Contents Hub',
  118. 'timestamp': 1385047627,
  119. 'upload_date': '20131121',
  120. 'age_limit': 13,
  121. 'duration': 3570,
  122. 'episode_number': 14,
  123. },
  124. 'skip': 'Blocked in the US',
  125. }, {
  126. # clip
  127. 'url': 'http://www.viki.com/videos/1067139v-the-avengers-age-of-ultron-press-conference',
  128. 'md5': '86c0b5dbd4d83a6611a79987cc7a1989',
  129. 'info_dict': {
  130. 'id': '1067139v',
  131. 'ext': 'mp4',
  132. 'title': "'The Avengers: Age of Ultron' Press Conference",
  133. 'description': 'md5:d70b2f9428f5488321bfe1db10d612ea',
  134. 'duration': 352,
  135. 'timestamp': 1430380829,
  136. 'upload_date': '20150430',
  137. 'uploader': 'Arirang TV',
  138. 'like_count': int,
  139. 'age_limit': 0,
  140. },
  141. 'skip': 'Sorry. There was an error loading this video',
  142. }, {
  143. 'url': 'http://www.viki.com/videos/1048879v-ankhon-dekhi',
  144. 'info_dict': {
  145. 'id': '1048879v',
  146. 'ext': 'mp4',
  147. 'title': 'Ankhon Dekhi',
  148. 'duration': 6512,
  149. 'timestamp': 1408532356,
  150. 'upload_date': '20140820',
  151. 'uploader': 'Spuul',
  152. 'like_count': int,
  153. 'age_limit': 13,
  154. },
  155. 'skip': 'Blocked in the US',
  156. }, {
  157. # episode
  158. 'url': 'http://www.viki.com/videos/44699v-boys-over-flowers-episode-1',
  159. 'md5': '0a53dc252e6e690feccd756861495a8c',
  160. 'info_dict': {
  161. 'id': '44699v',
  162. 'ext': 'mp4',
  163. 'title': 'Boys Over Flowers - Episode 1',
  164. 'description': 'md5:b89cf50038b480b88b5b3c93589a9076',
  165. 'duration': 4172,
  166. 'timestamp': 1270496524,
  167. 'upload_date': '20100405',
  168. 'uploader': 'group8',
  169. 'like_count': int,
  170. 'age_limit': 13,
  171. 'episode_number': 1,
  172. },
  173. }, {
  174. # youtube external
  175. 'url': 'http://www.viki.com/videos/50562v-poor-nastya-complete-episode-1',
  176. 'md5': '63f8600c1da6f01b7640eee7eca4f1da',
  177. 'info_dict': {
  178. 'id': '50562v',
  179. 'ext': 'webm',
  180. 'title': 'Poor Nastya [COMPLETE] - Episode 1',
  181. 'description': '',
  182. 'duration': 606,
  183. 'timestamp': 1274949505,
  184. 'upload_date': '20101213',
  185. 'uploader': 'ad14065n',
  186. 'uploader_id': 'ad14065n',
  187. 'like_count': int,
  188. 'age_limit': 13,
  189. },
  190. 'skip': 'Page not found!',
  191. }, {
  192. 'url': 'http://www.viki.com/player/44699v',
  193. 'only_matching': True,
  194. }, {
  195. # non-English description
  196. 'url': 'http://www.viki.com/videos/158036v-love-in-magic',
  197. 'md5': '41faaba0de90483fb4848952af7c7d0d',
  198. 'info_dict': {
  199. 'id': '158036v',
  200. 'ext': 'mp4',
  201. 'uploader': 'I Planet Entertainment',
  202. 'upload_date': '20111122',
  203. 'timestamp': 1321985454,
  204. 'description': 'md5:44b1e46619df3a072294645c770cef36',
  205. 'title': 'Love In Magic',
  206. 'age_limit': 13,
  207. },
  208. }]
  209. def _real_extract(self, url):
  210. video_id = self._match_id(url)
  211. video = self._call_api(f'videos/{video_id}.json', video_id, 'Downloading video JSON', query={})
  212. self._check_errors(video)
  213. title = try_get(video, lambda x: x['titles']['en'], str)
  214. episode_number = int_or_none(video.get('number'))
  215. if not title:
  216. title = f'Episode {episode_number}' if video.get('type') == 'episode' else video.get('id') or video_id
  217. container_titles = try_get(video, lambda x: x['container']['titles'], dict) or {}
  218. container_title = self.dict_selection(container_titles, 'en')
  219. title = f'{container_title} - {title}'
  220. thumbnails = [{
  221. 'id': thumbnail_id,
  222. 'url': thumbnail['url'],
  223. } for thumbnail_id, thumbnail in (video.get('images') or {}).items() if thumbnail.get('url')]
  224. resp = self._call_api(
  225. f'playback_streams/{video_id}.json?drms=dt3&device_id={self._DEVICE_ID}',
  226. video_id, 'Downloading video streams JSON')['main'][0]
  227. stream_id = try_get(resp, lambda x: x['properties']['track']['stream_id'])
  228. subtitles = dict((lang, [{
  229. 'ext': ext,
  230. 'url': self._API_URL_TEMPLATE % self._api_query(
  231. f'videos/{video_id}/auth_subtitles/{lang}.{ext}', stream_id=stream_id),
  232. } for ext in ('srt', 'vtt')]) for lang in (video.get('subtitle_completions') or {}))
  233. mpd_url = resp['url']
  234. # 720p is hidden in another MPD which can be found in the current manifest content
  235. mpd_content = self._download_webpage(mpd_url, video_id, note='Downloading initial MPD manifest')
  236. mpd_url = self._search_regex(
  237. r'(?mi)<BaseURL>(http.+.mpd)', mpd_content, 'new manifest', default=mpd_url)
  238. if 'mpdhd_high' not in mpd_url and 'sig=' not in mpd_url:
  239. # Modify the URL to get 1080p
  240. mpd_url = mpd_url.replace('mpdhd', 'mpdhd_high')
  241. formats = self._extract_mpd_formats(mpd_url, video_id)
  242. return {
  243. 'id': video_id,
  244. 'formats': formats,
  245. 'title': title,
  246. 'description': self.dict_selection(video.get('descriptions', {}), 'en'),
  247. 'duration': int_or_none(video.get('duration')),
  248. 'timestamp': parse_iso8601(video.get('created_at')),
  249. 'uploader': video.get('author'),
  250. 'uploader_url': video.get('author_url'),
  251. 'like_count': int_or_none(try_get(video, lambda x: x['likes']['count'])),
  252. 'age_limit': parse_age_limit(video.get('rating')),
  253. 'thumbnails': thumbnails,
  254. 'subtitles': subtitles,
  255. 'episode_number': episode_number,
  256. }
  257. class VikiChannelIE(VikiBaseIE):
  258. IE_NAME = 'viki:channel'
  259. _VALID_URL = rf'{VikiBaseIE._VALID_URL_BASE}(?:tv|news|movies|artists)/(?P<id>[0-9]+c)'
  260. _TESTS = [{
  261. 'url': 'http://www.viki.com/tv/50c-boys-over-flowers',
  262. 'info_dict': {
  263. 'id': '50c',
  264. 'title': 'Boys Over Flowers',
  265. 'description': 'md5:804ce6e7837e1fd527ad2f25420f4d59',
  266. },
  267. 'playlist_mincount': 51,
  268. }, {
  269. 'url': 'http://www.viki.com/tv/1354c-poor-nastya-complete',
  270. 'info_dict': {
  271. 'id': '1354c',
  272. 'title': 'Poor Nastya [COMPLETE]',
  273. 'description': 'md5:05bf5471385aa8b21c18ad450e350525',
  274. },
  275. 'playlist_count': 127,
  276. 'skip': 'Page not found',
  277. }, {
  278. 'url': 'http://www.viki.com/news/24569c-showbiz-korea',
  279. 'only_matching': True,
  280. }, {
  281. 'url': 'http://www.viki.com/movies/22047c-pride-and-prejudice-2005',
  282. 'only_matching': True,
  283. }, {
  284. 'url': 'http://www.viki.com/artists/2141c-shinee',
  285. 'only_matching': True,
  286. }]
  287. _video_types = ('episodes', 'movies', 'clips', 'trailers')
  288. def _entries(self, channel_id):
  289. params = {
  290. 'app': self._APP, 'token': self._token, 'only_ids': 'true',
  291. 'direction': 'asc', 'sort': 'number', 'per_page': 30,
  292. }
  293. video_types = self._configuration_arg('video_types') or self._video_types
  294. for video_type in video_types:
  295. if video_type not in self._video_types:
  296. self.report_warning(f'Unknown video_type: {video_type}')
  297. page_num = 0
  298. while True:
  299. page_num += 1
  300. params['page'] = page_num
  301. res = self._call_api(
  302. f'containers/{channel_id}/{video_type}.json', channel_id, query=params, fatal=False,
  303. note=f'Downloading {video_type.title()} JSON page {page_num}')
  304. for video_id in res.get('response') or []:
  305. yield self.url_result(f'https://www.viki.com/videos/{video_id}', VikiIE.ie_key(), video_id)
  306. if not res.get('more'):
  307. break
  308. def _real_extract(self, url):
  309. channel_id = self._match_id(url)
  310. channel = self._call_api(f'containers/{channel_id}.json', channel_id, 'Downloading channel JSON')
  311. self._check_errors(channel)
  312. return self.playlist_result(
  313. self._entries(channel_id), channel_id,
  314. self.dict_selection(channel['titles'], 'en'),
  315. self.dict_selection(channel['descriptions'], 'en'))