viki.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. from __future__ import unicode_literals
  2. import time
  3. import hmac
  4. import hashlib
  5. import itertools
  6. from ..utils import (
  7. ExtractorError,
  8. int_or_none,
  9. parse_age_limit,
  10. parse_iso8601,
  11. )
  12. from .common import InfoExtractor
  13. class VikiBaseIE(InfoExtractor):
  14. _API_QUERY_TEMPLATE = '/v4/%sapp=%s&t=%s&site=www.viki.com'
  15. _API_URL_TEMPLATE = 'http://api.viki.io%s&sig=%s'
  16. _APP = '65535a'
  17. _APP_VERSION = '2.2.5.1428709186'
  18. _APP_SECRET = '-$iJ}@p7!G@SyU/je1bEyWg}upLu-6V6-Lg9VD(]siH,r.,m-r|ulZ,U4LC/SeR)'
  19. def _prepare_call(self, path, timestamp=None):
  20. path += '?' if '?' not in path else '&'
  21. if not timestamp:
  22. timestamp = int(time.time())
  23. query = self._API_QUERY_TEMPLATE % (path, self._APP, timestamp)
  24. sig = hmac.new(
  25. self._APP_SECRET.encode('ascii'),
  26. query.encode('ascii'),
  27. hashlib.sha1
  28. ).hexdigest()
  29. return self._API_URL_TEMPLATE % (query, sig)
  30. def _call_api(self, path, video_id, note, timestamp=None):
  31. resp = self._download_json(
  32. self._prepare_call(path, timestamp), video_id, note)
  33. error = resp.get('error')
  34. if error:
  35. if error == 'invalid timestamp':
  36. resp = self._download_json(
  37. self._prepare_call(path, int(resp['current_timestamp'])),
  38. video_id, '%s (retry)' % note)
  39. error = resp.get('error')
  40. if error:
  41. self._raise_error(resp['error'])
  42. return resp
  43. def _raise_error(self, error):
  44. raise ExtractorError(
  45. '%s returned error: %s' % (self.IE_NAME, error),
  46. expected=True)
  47. class VikiIE(VikiBaseIE):
  48. IE_NAME = 'viki'
  49. _VALID_URL = r'https?://(?:www\.)?viki\.com/(?:videos|player)/(?P<id>[0-9]+v)'
  50. _TESTS = [{
  51. 'url': 'http://www.viki.com/videos/1023585v-heirs-episode-14',
  52. 'info_dict': {
  53. 'id': '1023585v',
  54. 'ext': 'mp4',
  55. 'title': 'Heirs Episode 14',
  56. 'uploader': 'SBS',
  57. 'description': 'md5:c4b17b9626dd4b143dcc4d855ba3474e',
  58. 'upload_date': '20131121',
  59. 'age_limit': 13,
  60. },
  61. 'skip': 'Blocked in the US',
  62. }, {
  63. # clip
  64. 'url': 'http://www.viki.com/videos/1067139v-the-avengers-age-of-ultron-press-conference',
  65. 'md5': '86c0b5dbd4d83a6611a79987cc7a1989',
  66. 'info_dict': {
  67. 'id': '1067139v',
  68. 'ext': 'mp4',
  69. 'title': "'The Avengers: Age of Ultron' Press Conference",
  70. 'description': 'md5:d70b2f9428f5488321bfe1db10d612ea',
  71. 'duration': 352,
  72. 'timestamp': 1430380829,
  73. 'upload_date': '20150430',
  74. 'uploader': 'Arirang TV',
  75. 'like_count': int,
  76. 'age_limit': 0,
  77. }
  78. }, {
  79. 'url': 'http://www.viki.com/videos/1048879v-ankhon-dekhi',
  80. 'info_dict': {
  81. 'id': '1048879v',
  82. 'ext': 'mp4',
  83. 'title': 'Ankhon Dekhi',
  84. 'duration': 6512,
  85. 'timestamp': 1408532356,
  86. 'upload_date': '20140820',
  87. 'uploader': 'Spuul',
  88. 'like_count': int,
  89. 'age_limit': 13,
  90. },
  91. 'params': {
  92. # m3u8 download
  93. 'skip_download': True,
  94. }
  95. }, {
  96. # episode
  97. 'url': 'http://www.viki.com/videos/44699v-boys-over-flowers-episode-1',
  98. 'md5': '190f3ef426005ba3a080a63325955bc3',
  99. 'info_dict': {
  100. 'id': '44699v',
  101. 'ext': 'mp4',
  102. 'title': 'Boys Over Flowers - Episode 1',
  103. 'description': 'md5:52617e4f729c7d03bfd4bcbbb6e946f2',
  104. 'duration': 4155,
  105. 'timestamp': 1270496524,
  106. 'upload_date': '20100405',
  107. 'uploader': 'group8',
  108. 'like_count': int,
  109. 'age_limit': 13,
  110. }
  111. }, {
  112. # youtube external
  113. 'url': 'http://www.viki.com/videos/50562v-poor-nastya-complete-episode-1',
  114. 'md5': '216d1afdc0c64d1febc1e9f2bd4b864b',
  115. 'info_dict': {
  116. 'id': '50562v',
  117. 'ext': 'mp4',
  118. 'title': 'Poor Nastya [COMPLETE] - Episode 1',
  119. 'description': '',
  120. 'duration': 607,
  121. 'timestamp': 1274949505,
  122. 'upload_date': '20101213',
  123. 'uploader': 'ad14065n',
  124. 'uploader_id': 'ad14065n',
  125. 'like_count': int,
  126. 'age_limit': 13,
  127. }
  128. }, {
  129. 'url': 'http://www.viki.com/player/44699v',
  130. 'only_matching': True,
  131. }]
  132. def _real_extract(self, url):
  133. video_id = self._match_id(url)
  134. video = self._call_api(
  135. 'videos/%s.json' % video_id, video_id, 'Downloading video JSON')
  136. title = None
  137. titles = video.get('titles')
  138. if titles:
  139. title = titles.get('en') or titles[titles.keys()[0]]
  140. if not title:
  141. title = 'Episode %d' % video.get('number') if video.get('type') == 'episode' else video.get('id') or video_id
  142. container_titles = video.get('container', {}).get('titles')
  143. if container_titles:
  144. container_title = container_titles.get('en') or container_titles[container_titles.keys()[0]]
  145. title = '%s - %s' % (container_title, title)
  146. descriptions = video.get('descriptions')
  147. description = descriptions.get('en') or descriptions[titles.keys()[0]] if descriptions else None
  148. duration = int_or_none(video.get('duration'))
  149. timestamp = parse_iso8601(video.get('created_at'))
  150. uploader = video.get('author')
  151. like_count = int_or_none(video.get('likes', {}).get('count'))
  152. age_limit = parse_age_limit(video.get('rating'))
  153. thumbnails = []
  154. for thumbnail_id, thumbnail in video.get('images', {}).items():
  155. thumbnails.append({
  156. 'id': thumbnail_id,
  157. 'url': thumbnail.get('url'),
  158. })
  159. subtitles = {}
  160. for subtitle_lang, _ in video.get('subtitle_completions', {}).items():
  161. subtitles[subtitle_lang] = [{
  162. 'ext': subtitles_format,
  163. 'url': self._prepare_call(
  164. 'videos/%s/subtitles/%s.%s' % (video_id, subtitle_lang, subtitles_format)),
  165. } for subtitles_format in ('srt', 'vtt')]
  166. result = {
  167. 'id': video_id,
  168. 'title': title,
  169. 'description': description,
  170. 'duration': duration,
  171. 'timestamp': timestamp,
  172. 'uploader': uploader,
  173. 'like_count': like_count,
  174. 'age_limit': age_limit,
  175. 'thumbnails': thumbnails,
  176. 'subtitles': subtitles,
  177. }
  178. streams = self._call_api(
  179. 'videos/%s/streams.json' % video_id, video_id,
  180. 'Downloading video streams JSON')
  181. if 'external' in streams:
  182. result.update({
  183. '_type': 'url_transparent',
  184. 'url': streams['external']['url'],
  185. })
  186. return result
  187. formats = []
  188. for format_id, stream_dict in streams.items():
  189. height = self._search_regex(
  190. r'^(\d+)[pP]$', format_id, 'height', default=None)
  191. for protocol, format_dict in stream_dict.items():
  192. if format_id == 'm3u8':
  193. formats = self._extract_m3u8_formats(
  194. format_dict['url'], video_id, 'mp4', m3u8_id='m3u8-%s' % protocol)
  195. else:
  196. formats.append({
  197. 'url': format_dict['url'],
  198. 'format_id': '%s-%s' % (format_id, protocol),
  199. 'height': height,
  200. })
  201. self._sort_formats(formats)
  202. result['formats'] = formats
  203. return result
  204. class VikiChannelIE(VikiBaseIE):
  205. IE_NAME = 'viki:channel'
  206. _VALID_URL = r'https?://(?:www\.)?viki\.com/(?:tv|news|movies|artists)/(?P<id>[0-9]+c)'
  207. _TESTS = [{
  208. 'url': 'http://www.viki.com/tv/50c-boys-over-flowers',
  209. 'info_dict': {
  210. 'id': '50c',
  211. 'title': 'Boys Over Flowers',
  212. 'description': 'md5:ecd3cff47967fe193cff37c0bec52790',
  213. },
  214. 'playlist_count': 70,
  215. }, {
  216. 'url': 'http://www.viki.com/tv/1354c-poor-nastya-complete',
  217. 'info_dict': {
  218. 'id': '1354c',
  219. 'title': 'Poor Nastya [COMPLETE]',
  220. 'description': 'md5:05bf5471385aa8b21c18ad450e350525',
  221. },
  222. 'playlist_count': 127,
  223. }, {
  224. 'url': 'http://www.viki.com/news/24569c-showbiz-korea',
  225. 'only_matching': True,
  226. }, {
  227. 'url': 'http://www.viki.com/movies/22047c-pride-and-prejudice-2005',
  228. 'only_matching': True,
  229. }, {
  230. 'url': 'http://www.viki.com/artists/2141c-shinee',
  231. 'only_matching': True,
  232. }]
  233. _PER_PAGE = 25
  234. def _real_extract(self, url):
  235. channel_id = self._match_id(url)
  236. channel = self._call_api(
  237. 'containers/%s.json' % channel_id, channel_id,
  238. 'Downloading channel JSON')
  239. titles = channel['titles']
  240. title = titles.get('en') or titles[titles.keys()[0]]
  241. descriptions = channel['descriptions']
  242. description = descriptions.get('en') or descriptions[descriptions.keys()[0]]
  243. entries = []
  244. for video_type in ('episodes', 'clips', 'movies'):
  245. for page_num in itertools.count(1):
  246. page = self._call_api(
  247. 'containers/%s/%s.json?per_page=%d&sort=number&direction=asc&with_paging=true&page=%d'
  248. % (channel_id, video_type, self._PER_PAGE, page_num), channel_id,
  249. 'Downloading %s JSON page #%d' % (video_type, page_num))
  250. for video in page['response']:
  251. video_id = video['id']
  252. entries.append(self.url_result(
  253. 'http://www.viki.com/videos/%s' % video_id, 'Viki'))
  254. if not page['pagination']['next']:
  255. break
  256. return self.playlist_result(entries, channel_id, title, description)