You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

336 lines
11 KiB

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