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.

266 lines
9.2 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import json
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_HTTPError,
  8. compat_urlparse,
  9. )
  10. from ..utils import (
  11. clean_html,
  12. ExtractorError,
  13. int_or_none,
  14. parse_age_limit,
  15. parse_duration,
  16. unified_timestamp,
  17. url_or_none,
  18. )
  19. class DramaFeverBaseIE(InfoExtractor):
  20. _NETRC_MACHINE = 'dramafever'
  21. _CONSUMER_SECRET = 'DA59dtVXYLxajktV'
  22. _consumer_secret = None
  23. def _get_consumer_secret(self):
  24. mainjs = self._download_webpage(
  25. 'http://www.dramafever.com/static/51afe95/df2014/scripts/main.js',
  26. None, 'Downloading main.js', fatal=False)
  27. if not mainjs:
  28. return self._CONSUMER_SECRET
  29. return self._search_regex(
  30. r"var\s+cs\s*=\s*'([^']+)'", mainjs,
  31. 'consumer secret', default=self._CONSUMER_SECRET)
  32. def _real_initialize(self):
  33. self._consumer_secret = self._get_consumer_secret()
  34. self._login()
  35. def _login(self):
  36. username, password = self._get_login_info()
  37. if username is None:
  38. return
  39. login_form = {
  40. 'username': username,
  41. 'password': password,
  42. }
  43. try:
  44. response = self._download_json(
  45. 'https://www.dramafever.com/api/users/login', None, 'Logging in',
  46. data=json.dumps(login_form).encode('utf-8'), headers={
  47. 'x-consumer-key': self._consumer_secret,
  48. })
  49. except ExtractorError as e:
  50. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (403, 404):
  51. response = self._parse_json(
  52. e.cause.read().decode('utf-8'), None)
  53. else:
  54. raise
  55. # Successful login
  56. if response.get('result') or response.get('guid') or response.get('user_guid'):
  57. return
  58. errors = response.get('errors')
  59. if errors and isinstance(errors, list):
  60. error = errors[0]
  61. message = error.get('message') or error['reason']
  62. raise ExtractorError('Unable to login: %s' % message, expected=True)
  63. raise ExtractorError('Unable to log in')
  64. class DramaFeverIE(DramaFeverBaseIE):
  65. IE_NAME = 'dramafever'
  66. _VALID_URL = r'https?://(?:www\.)?dramafever\.com/(?:[^/]+/)?drama/(?P<id>[0-9]+/[0-9]+)(?:/|$)'
  67. _TESTS = [{
  68. 'url': 'https://www.dramafever.com/drama/4274/1/Heirs/',
  69. 'info_dict': {
  70. 'id': '4274.1',
  71. 'ext': 'wvm',
  72. 'title': 'Heirs - Episode 1',
  73. 'description': 'md5:362a24ba18209f6276e032a651c50bc2',
  74. 'thumbnail': r're:^https?://.*\.jpg',
  75. 'duration': 3783,
  76. 'timestamp': 1381354993,
  77. 'upload_date': '20131009',
  78. 'series': 'Heirs',
  79. 'season_number': 1,
  80. 'episode': 'Episode 1',
  81. 'episode_number': 1,
  82. },
  83. 'params': {
  84. # m3u8 download
  85. 'skip_download': True,
  86. },
  87. }, {
  88. 'url': 'http://www.dramafever.com/drama/4826/4/Mnet_Asian_Music_Awards_2015/?ap=1',
  89. 'info_dict': {
  90. 'id': '4826.4',
  91. 'ext': 'flv',
  92. 'title': 'Mnet Asian Music Awards 2015',
  93. 'description': 'md5:3ff2ee8fedaef86e076791c909cf2e91',
  94. 'episode': 'Mnet Asian Music Awards 2015 - Part 3',
  95. 'episode_number': 4,
  96. 'thumbnail': r're:^https?://.*\.jpg',
  97. 'timestamp': 1450213200,
  98. 'upload_date': '20151215',
  99. 'duration': 5359,
  100. },
  101. 'params': {
  102. # m3u8 download
  103. 'skip_download': True,
  104. },
  105. }, {
  106. 'url': 'https://www.dramafever.com/zh-cn/drama/4972/15/Doctor_Romantic/',
  107. 'only_matching': True,
  108. }]
  109. def _call_api(self, path, video_id, note, fatal=False):
  110. return self._download_json(
  111. 'https://www.dramafever.com/api/5/' + path,
  112. video_id, note=note, headers={
  113. 'x-consumer-key': self._consumer_secret,
  114. }, fatal=fatal)
  115. def _get_subtitles(self, video_id):
  116. subtitles = {}
  117. subs = self._call_api(
  118. 'video/%s/subtitles/webvtt/' % video_id, video_id,
  119. 'Downloading subtitles JSON', fatal=False)
  120. if not subs or not isinstance(subs, list):
  121. return subtitles
  122. for sub in subs:
  123. if not isinstance(sub, dict):
  124. continue
  125. sub_url = url_or_none(sub.get('url'))
  126. if not sub_url:
  127. continue
  128. subtitles.setdefault(
  129. sub.get('code') or sub.get('language') or 'en', []).append({
  130. 'url': sub_url
  131. })
  132. return subtitles
  133. def _real_extract(self, url):
  134. video_id = self._match_id(url).replace('/', '.')
  135. series_id, episode_number = video_id.split('.')
  136. video = self._call_api(
  137. 'series/%s/episodes/%s/' % (series_id, episode_number), video_id,
  138. 'Downloading video JSON')
  139. formats = []
  140. download_assets = video.get('download_assets')
  141. if download_assets and isinstance(download_assets, dict):
  142. for format_id, format_dict in download_assets.items():
  143. if not isinstance(format_dict, dict):
  144. continue
  145. format_url = url_or_none(format_dict.get('url'))
  146. if not format_url:
  147. continue
  148. formats.append({
  149. 'url': format_url,
  150. 'format_id': format_id,
  151. 'filesize': int_or_none(video.get('filesize')),
  152. })
  153. stream = self._call_api(
  154. 'video/%s/stream/' % video_id, video_id, 'Downloading stream JSON',
  155. fatal=False)
  156. if stream:
  157. stream_url = stream.get('stream_url')
  158. if stream_url:
  159. formats.extend(self._extract_m3u8_formats(
  160. stream_url, video_id, 'mp4', entry_protocol='m3u8_native',
  161. m3u8_id='hls', fatal=False))
  162. self._sort_formats(formats)
  163. title = video.get('title') or 'Episode %s' % episode_number
  164. description = video.get('description')
  165. thumbnail = video.get('thumbnail')
  166. timestamp = unified_timestamp(video.get('release_date'))
  167. duration = parse_duration(video.get('duration'))
  168. age_limit = parse_age_limit(video.get('tv_rating'))
  169. series = video.get('series_title')
  170. season_number = int_or_none(video.get('season'))
  171. if series:
  172. title = '%s - %s' % (series, title)
  173. subtitles = self.extract_subtitles(video_id)
  174. return {
  175. 'id': video_id,
  176. 'title': title,
  177. 'description': description,
  178. 'thumbnail': thumbnail,
  179. 'duration': duration,
  180. 'timestamp': timestamp,
  181. 'age_limit': age_limit,
  182. 'series': series,
  183. 'season_number': season_number,
  184. 'episode_number': int_or_none(episode_number),
  185. 'formats': formats,
  186. 'subtitles': subtitles,
  187. }
  188. class DramaFeverSeriesIE(DramaFeverBaseIE):
  189. IE_NAME = 'dramafever:series'
  190. _VALID_URL = r'https?://(?:www\.)?dramafever\.com/(?:[^/]+/)?drama/(?P<id>[0-9]+)(?:/(?:(?!\d+(?:/|$)).+)?)?$'
  191. _TESTS = [{
  192. 'url': 'http://www.dramafever.com/drama/4512/Cooking_with_Shin/',
  193. 'info_dict': {
  194. 'id': '4512',
  195. 'title': 'Cooking with Shin',
  196. 'description': 'md5:84a3f26e3cdc3fb7f500211b3593b5c1',
  197. },
  198. 'playlist_count': 4,
  199. }, {
  200. 'url': 'http://www.dramafever.com/drama/124/IRIS/',
  201. 'info_dict': {
  202. 'id': '124',
  203. 'title': 'IRIS',
  204. 'description': 'md5:b3a30e587cf20c59bd1c01ec0ee1b862',
  205. },
  206. 'playlist_count': 20,
  207. }]
  208. _PAGE_SIZE = 60 # max is 60 (see http://api.drama9.com/#get--api-4-episode-series-)
  209. def _real_extract(self, url):
  210. series_id = self._match_id(url)
  211. series = self._download_json(
  212. 'http://www.dramafever.com/api/4/series/query/?cs=%s&series_id=%s'
  213. % (self._consumer_secret, series_id),
  214. series_id, 'Downloading series JSON')['series'][series_id]
  215. title = clean_html(series['name'])
  216. description = clean_html(series.get('description') or series.get('description_short'))
  217. entries = []
  218. for page_num in itertools.count(1):
  219. episodes = self._download_json(
  220. 'http://www.dramafever.com/api/4/episode/series/?cs=%s&series_id=%s&page_size=%d&page_number=%d'
  221. % (self._consumer_secret, series_id, self._PAGE_SIZE, page_num),
  222. series_id, 'Downloading episodes JSON page #%d' % page_num)
  223. for episode in episodes.get('value', []):
  224. episode_url = episode.get('episode_url')
  225. if not episode_url:
  226. continue
  227. entries.append(self.url_result(
  228. compat_urlparse.urljoin(url, episode_url),
  229. 'DramaFever', episode.get('guid')))
  230. if page_num == episodes['num_pages']:
  231. break
  232. return self.playlist_result(entries, series_id, title, description)