animeondemand.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_urlparse,
  6. compat_str,
  7. )
  8. from ..utils import (
  9. determine_ext,
  10. encode_dict,
  11. extract_attributes,
  12. ExtractorError,
  13. sanitized_Request,
  14. urlencode_postdata,
  15. )
  16. class AnimeOnDemandIE(InfoExtractor):
  17. _VALID_URL = r'https?://(?:www\.)?anime-on-demand\.de/anime/(?P<id>\d+)'
  18. _LOGIN_URL = 'https://www.anime-on-demand.de/users/sign_in'
  19. _APPLY_HTML5_URL = 'https://www.anime-on-demand.de/html5apply'
  20. _NETRC_MACHINE = 'animeondemand'
  21. _TESTS = [{
  22. 'url': 'https://www.anime-on-demand.de/anime/161',
  23. 'info_dict': {
  24. 'id': '161',
  25. 'title': 'Grimgar, Ashes and Illusions (OmU)',
  26. 'description': 'md5:6681ce3c07c7189d255ac6ab23812d31',
  27. },
  28. 'playlist_mincount': 4,
  29. }, {
  30. # Film wording is used instead of Episode
  31. 'url': 'https://www.anime-on-demand.de/anime/39',
  32. 'only_matching': True,
  33. }, {
  34. # Episodes without titles
  35. 'url': 'https://www.anime-on-demand.de/anime/162',
  36. 'only_matching': True,
  37. }, {
  38. # ger/jap, Dub/OmU, account required
  39. 'url': 'https://www.anime-on-demand.de/anime/169',
  40. 'only_matching': True,
  41. }]
  42. def _login(self):
  43. (username, password) = self._get_login_info()
  44. if username is None:
  45. return
  46. login_page = self._download_webpage(
  47. self._LOGIN_URL, None, 'Downloading login page')
  48. if '>Our licensing terms allow the distribution of animes only to German-speaking countries of Europe' in login_page:
  49. self.raise_geo_restricted(
  50. '%s is only available in German-speaking countries of Europe' % self.IE_NAME)
  51. login_form = self._form_hidden_inputs('new_user', login_page)
  52. login_form.update({
  53. 'user[login]': username,
  54. 'user[password]': password,
  55. })
  56. post_url = self._search_regex(
  57. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  58. 'post url', default=self._LOGIN_URL, group='url')
  59. if not post_url.startswith('http'):
  60. post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
  61. request = sanitized_Request(
  62. post_url, urlencode_postdata(encode_dict(login_form)))
  63. request.add_header('Referer', self._LOGIN_URL)
  64. response = self._download_webpage(
  65. request, None, 'Logging in as %s' % username)
  66. if all(p not in response for p in ('>Logout<', 'href="/users/sign_out"')):
  67. error = self._search_regex(
  68. r'<p class="alert alert-danger">(.+?)</p>',
  69. response, 'error', default=None)
  70. if error:
  71. raise ExtractorError('Unable to login: %s' % error, expected=True)
  72. raise ExtractorError('Unable to log in')
  73. def _real_initialize(self):
  74. self._login()
  75. def _real_extract(self, url):
  76. anime_id = self._match_id(url)
  77. webpage = self._download_webpage(url, anime_id)
  78. if 'data-playlist=' not in webpage:
  79. self._download_webpage(
  80. self._APPLY_HTML5_URL, anime_id,
  81. 'Activating HTML5 beta', 'Unable to apply HTML5 beta')
  82. webpage = self._download_webpage(url, anime_id)
  83. csrf_token = self._html_search_meta(
  84. 'csrf-token', webpage, 'csrf token', fatal=True)
  85. anime_title = self._html_search_regex(
  86. r'(?s)<h1[^>]+itemprop="name"[^>]*>(.+?)</h1>',
  87. webpage, 'anime name')
  88. anime_description = self._html_search_regex(
  89. r'(?s)<div[^>]+itemprop="description"[^>]*>(.+?)</div>',
  90. webpage, 'anime description', default=None)
  91. entries = []
  92. for num, episode_html in enumerate(re.findall(
  93. r'(?s)<h3[^>]+class="episodebox-title".+?>Episodeninhalt<', webpage), 1):
  94. episodebox_title = self._search_regex(
  95. (r'class="episodebox-title"[^>]+title=(["\'])(?P<title>.+?)\1',
  96. r'class="episodebox-title"[^>]+>(?P<title>.+?)<'),
  97. episode_html, 'episodebox title', default=None, group='title')
  98. if not episodebox_title:
  99. continue
  100. episode_number = int(self._search_regex(
  101. r'(?:Episode|Film)\s*(\d+)',
  102. episodebox_title, 'episode number', default=num))
  103. episode_title = self._search_regex(
  104. r'(?:Episode|Film)\s*\d+\s*-\s*(.+)',
  105. episodebox_title, 'episode title', default=None)
  106. video_id = 'episode-%d' % episode_number
  107. common_info = {
  108. 'id': video_id,
  109. 'series': anime_title,
  110. 'episode': episode_title,
  111. 'episode_number': episode_number,
  112. }
  113. formats = []
  114. for input_ in re.findall(
  115. r'<input[^>]+class=["\'].*?streamstarter_html5[^>]+>', episode_html):
  116. attributes = extract_attributes(input_)
  117. playlist_urls = []
  118. for playlist_key in ('data-playlist', 'data-otherplaylist'):
  119. playlist_url = attributes.get(playlist_key)
  120. if isinstance(playlist_url, compat_str) and re.match(
  121. r'/?[\da-zA-Z]+', playlist_url):
  122. playlist_urls.append(attributes[playlist_key])
  123. if not playlist_urls:
  124. continue
  125. lang = attributes.get('data-lang')
  126. lang_note = attributes.get('value')
  127. for playlist_url in playlist_urls:
  128. kind = self._search_regex(
  129. r'videomaterialurl/\d+/([^/]+)/',
  130. playlist_url, 'media kind', default=None)
  131. format_id_list = []
  132. if lang:
  133. format_id_list.append(lang)
  134. if kind:
  135. format_id_list.append(kind)
  136. if not format_id_list:
  137. format_id_list.append('hls')
  138. format_id = '-'.join(format_id_list)
  139. format_note = ', '.join(filter(None, (kind, lang_note)))
  140. request = sanitized_Request(
  141. compat_urlparse.urljoin(url, playlist_url),
  142. headers={
  143. 'X-Requested-With': 'XMLHttpRequest',
  144. 'X-CSRF-Token': csrf_token,
  145. 'Referer': url,
  146. 'Accept': 'application/json, text/javascript, */*; q=0.01',
  147. })
  148. playlist = self._download_json(
  149. request, video_id, 'Downloading %s playlist JSON' % format_id,
  150. fatal=False)
  151. if not playlist:
  152. continue
  153. playlist = playlist.get('playlist')
  154. if not playlist or not isinstance(playlist, list):
  155. continue
  156. playlist = playlist[0]
  157. title = playlist.get('title')
  158. if not title:
  159. continue
  160. description = playlist.get('description')
  161. for source in playlist.get('sources', []):
  162. file_ = source.get('file')
  163. if file_ and determine_ext(file_) == 'm3u8':
  164. m3u8_formats = self._extract_m3u8_formats(
  165. file_, video_id, 'mp4',
  166. entry_protocol='m3u8_native', m3u8_id=format_id)
  167. for f in m3u8_formats:
  168. f.update({
  169. 'language': lang,
  170. 'format_note': format_note,
  171. })
  172. formats.extend(m3u8_formats)
  173. if formats:
  174. self._sort_formats(formats)
  175. f = common_info.copy()
  176. f.update({
  177. 'title': title,
  178. 'description': description,
  179. 'formats': formats,
  180. })
  181. entries.append(f)
  182. m = re.search(
  183. r'data-dialog-header=(["\'])(?P<title>.+?)\1[^>]+href=(["\'])(?P<href>.+?)\3[^>]*>Teaser<',
  184. episode_html)
  185. if m:
  186. f = common_info.copy()
  187. f.update({
  188. 'id': '%s-teaser' % f['id'],
  189. 'title': m.group('title'),
  190. 'url': compat_urlparse.urljoin(url, m.group('href')),
  191. })
  192. entries.append(f)
  193. return self.playlist_result(entries, anime_id, anime_title, anime_description)