animelab.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. from .common import InfoExtractor
  4. from ..utils import (
  5. ExtractorError,
  6. urlencode_postdata,
  7. int_or_none,
  8. str_or_none,
  9. determine_ext,
  10. )
  11. from ..compat import compat_HTTPError
  12. class AnimeLabBaseIE(InfoExtractor):
  13. _LOGIN_URL = 'https://www.animelab.com/login'
  14. _NETRC_MACHINE = 'animelab'
  15. _LOGGED_IN = False
  16. def _is_logged_in(self, login_page=None):
  17. if not self._LOGGED_IN:
  18. if not login_page:
  19. login_page = self._download_webpage(self._LOGIN_URL, None, 'Downloading login page')
  20. AnimeLabBaseIE._LOGGED_IN = 'Sign In' not in login_page
  21. return self._LOGGED_IN
  22. def _perform_login(self, username, password):
  23. if self._is_logged_in():
  24. return
  25. login_form = {
  26. 'email': username,
  27. 'password': password,
  28. }
  29. try:
  30. response = self._download_webpage(
  31. self._LOGIN_URL, None, 'Logging in', 'Wrong login info',
  32. data=urlencode_postdata(login_form),
  33. headers={'Content-Type': 'application/x-www-form-urlencoded'})
  34. except ExtractorError as e:
  35. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 400:
  36. raise ExtractorError('Unable to log in (wrong credentials?)', expected=True)
  37. raise
  38. if not self._is_logged_in(response):
  39. raise ExtractorError('Unable to login (cannot verify if logged in)')
  40. def _real_initialize(self):
  41. if not self._is_logged_in():
  42. self.raise_login_required('Login is required to access any AnimeLab content')
  43. class AnimeLabIE(AnimeLabBaseIE):
  44. _VALID_URL = r'https?://(?:www\.)?animelab\.com/player/(?P<id>[^/]+)'
  45. # the following tests require authentication, but a free account will suffice
  46. # just set 'usenetrc' to true in test/local_parameters.json if you use a .netrc file
  47. # or you can set 'username' and 'password' there
  48. # the tests also select a specific format so that the same video is downloaded
  49. # regardless of whether the user is premium or not (needs testing on a premium account)
  50. _TEST = {
  51. 'url': 'https://www.animelab.com/player/fullmetal-alchemist-brotherhood-episode-42',
  52. 'md5': '05bde4b91a5d1ff46ef5b94df05b0f7f',
  53. 'info_dict': {
  54. 'id': '383',
  55. 'ext': 'mp4',
  56. 'display_id': 'fullmetal-alchemist-brotherhood-episode-42',
  57. 'title': 'Fullmetal Alchemist: Brotherhood - Episode 42 - Signs of a Counteroffensive',
  58. 'description': 'md5:103eb61dd0a56d3dfc5dbf748e5e83f4',
  59. 'series': 'Fullmetal Alchemist: Brotherhood',
  60. 'episode': 'Signs of a Counteroffensive',
  61. 'episode_number': 42,
  62. 'duration': 1469,
  63. 'season': 'Season 1',
  64. 'season_number': 1,
  65. 'season_id': '38',
  66. },
  67. 'params': {
  68. 'format': '[format_id=21711_yeshardsubbed_ja-JP][height=480]',
  69. },
  70. 'skip': 'All AnimeLab content requires authentication',
  71. }
  72. def _real_extract(self, url):
  73. display_id = self._match_id(url)
  74. # unfortunately we can get different URLs for the same formats
  75. # e.g. if we are using a "free" account so no dubs available
  76. # (so _remove_duplicate_formats is not effective)
  77. # so we use a dictionary as a workaround
  78. formats = {}
  79. for language_option_url in ('https://www.animelab.com/player/%s/subtitles',
  80. 'https://www.animelab.com/player/%s/dubbed'):
  81. actual_url = language_option_url % display_id
  82. webpage = self._download_webpage(actual_url, display_id, 'Downloading URL ' + actual_url)
  83. video_collection = self._parse_json(self._search_regex(r'new\s+?AnimeLabApp\.VideoCollection\s*?\((.*?)\);', webpage, 'AnimeLab VideoCollection'), display_id)
  84. position = int_or_none(self._search_regex(r'playlistPosition\s*?=\s*?(\d+)', webpage, 'Playlist Position'))
  85. raw_data = video_collection[position]['videoEntry']
  86. video_id = str_or_none(raw_data['id'])
  87. # create a title from many sources (while grabbing other info)
  88. # TODO use more fallback sources to get some of these
  89. series = raw_data.get('showTitle')
  90. video_type = raw_data.get('videoEntryType', {}).get('name')
  91. episode_number = raw_data.get('episodeNumber')
  92. episode_name = raw_data.get('name')
  93. title_parts = (series, video_type, episode_number, episode_name)
  94. if None not in title_parts:
  95. title = '%s - %s %s - %s' % title_parts
  96. else:
  97. title = episode_name
  98. description = raw_data.get('synopsis') or self._og_search_description(webpage, default=None)
  99. duration = int_or_none(raw_data.get('duration'))
  100. thumbnail_data = raw_data.get('images', [])
  101. thumbnails = []
  102. for thumbnail in thumbnail_data:
  103. for instance in thumbnail['imageInstances']:
  104. image_data = instance.get('imageInfo', {})
  105. thumbnails.append({
  106. 'id': str_or_none(image_data.get('id')),
  107. 'url': image_data.get('fullPath'),
  108. 'width': image_data.get('width'),
  109. 'height': image_data.get('height'),
  110. })
  111. season_data = raw_data.get('season', {}) or {}
  112. season = str_or_none(season_data.get('name'))
  113. season_number = int_or_none(season_data.get('seasonNumber'))
  114. season_id = str_or_none(season_data.get('id'))
  115. for video_data in raw_data['videoList']:
  116. current_video_list = {}
  117. current_video_list['language'] = video_data.get('language', {}).get('languageCode')
  118. is_hardsubbed = video_data.get('hardSubbed')
  119. for video_instance in video_data['videoInstances']:
  120. httpurl = video_instance.get('httpUrl')
  121. url = httpurl if httpurl else video_instance.get('rtmpUrl')
  122. if url is None:
  123. # this video format is unavailable to the user (not premium etc.)
  124. continue
  125. current_format = current_video_list.copy()
  126. format_id_parts = []
  127. format_id_parts.append(str_or_none(video_instance.get('id')))
  128. if is_hardsubbed is not None:
  129. if is_hardsubbed:
  130. format_id_parts.append('yeshardsubbed')
  131. else:
  132. format_id_parts.append('nothardsubbed')
  133. format_id_parts.append(current_format['language'])
  134. format_id = '_'.join([x for x in format_id_parts if x is not None])
  135. ext = determine_ext(url)
  136. if ext == 'm3u8':
  137. for format_ in self._extract_m3u8_formats(
  138. url, video_id, m3u8_id=format_id, fatal=False):
  139. formats[format_['format_id']] = format_
  140. continue
  141. elif ext == 'mpd':
  142. for format_ in self._extract_mpd_formats(
  143. url, video_id, mpd_id=format_id, fatal=False):
  144. formats[format_['format_id']] = format_
  145. continue
  146. current_format['url'] = url
  147. quality_data = video_instance.get('videoQuality')
  148. if quality_data:
  149. quality = quality_data.get('name') or quality_data.get('description')
  150. else:
  151. quality = None
  152. height = None
  153. if quality:
  154. height = int_or_none(self._search_regex(r'(\d+)p?$', quality, 'Video format height', default=None))
  155. if height is None:
  156. self.report_warning('Could not get height of video')
  157. else:
  158. current_format['height'] = height
  159. current_format['format_id'] = format_id
  160. formats[current_format['format_id']] = current_format
  161. formats = list(formats.values())
  162. self._sort_formats(formats)
  163. return {
  164. 'id': video_id,
  165. 'display_id': display_id,
  166. 'title': title,
  167. 'description': description,
  168. 'series': series,
  169. 'episode': episode_name,
  170. 'episode_number': int_or_none(episode_number),
  171. 'thumbnails': thumbnails,
  172. 'duration': duration,
  173. 'formats': formats,
  174. 'season': season,
  175. 'season_number': season_number,
  176. 'season_id': season_id,
  177. }
  178. class AnimeLabShowsIE(AnimeLabBaseIE):
  179. _VALID_URL = r'https?://(?:www\.)?animelab\.com/shows/(?P<id>[^/]+)'
  180. _TEST = {
  181. 'url': 'https://www.animelab.com/shows/attack-on-titan',
  182. 'info_dict': {
  183. 'id': '45',
  184. 'title': 'Attack on Titan',
  185. 'description': 'md5:989d95a2677e9309368d5cf39ba91469',
  186. },
  187. 'playlist_count': 59,
  188. 'skip': 'All AnimeLab content requires authentication',
  189. }
  190. def _real_extract(self, url):
  191. _BASE_URL = 'http://www.animelab.com'
  192. _SHOWS_API_URL = '/api/videoentries/show/videos/'
  193. display_id = self._match_id(url)
  194. webpage = self._download_webpage(url, display_id, 'Downloading requested URL')
  195. show_data_str = self._search_regex(r'({"id":.*}),\svideoEntry', webpage, 'AnimeLab show data')
  196. show_data = self._parse_json(show_data_str, display_id)
  197. show_id = str_or_none(show_data.get('id'))
  198. title = show_data.get('name')
  199. description = show_data.get('shortSynopsis') or show_data.get('longSynopsis')
  200. entries = []
  201. for season in show_data['seasons']:
  202. season_id = season['id']
  203. get_data = urlencode_postdata({
  204. 'seasonId': season_id,
  205. 'limit': 1000,
  206. })
  207. # despite using urlencode_postdata, we are sending a GET request
  208. target_url = _BASE_URL + _SHOWS_API_URL + show_id + "?" + get_data.decode('utf-8')
  209. response = self._download_webpage(
  210. target_url,
  211. None, 'Season id %s' % season_id)
  212. season_data = self._parse_json(response, display_id)
  213. for video_data in season_data['list']:
  214. entries.append(self.url_result(
  215. _BASE_URL + '/player/' + video_data['slug'], 'AnimeLab',
  216. str_or_none(video_data.get('id')), video_data.get('name')
  217. ))
  218. return {
  219. '_type': 'playlist',
  220. 'id': show_id,
  221. 'title': title,
  222. 'description': description,
  223. 'entries': entries,
  224. }
  225. # TODO implement myqueue