logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

viki.py (14590B)


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