animeondemand.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import compat_str
  5. from ..utils import (
  6. determine_ext,
  7. extract_attributes,
  8. ExtractorError,
  9. join_nonempty,
  10. url_or_none,
  11. urlencode_postdata,
  12. urljoin,
  13. )
  14. class AnimeOnDemandIE(InfoExtractor):
  15. _VALID_URL = r'https?://(?:www\.)?anime-on-demand\.de/anime/(?P<id>\d+)'
  16. _LOGIN_URL = 'https://www.anime-on-demand.de/users/sign_in'
  17. _APPLY_HTML5_URL = 'https://www.anime-on-demand.de/html5apply'
  18. _NETRC_MACHINE = 'animeondemand'
  19. # German-speaking countries of Europe
  20. _GEO_COUNTRIES = ['AT', 'CH', 'DE', 'LI', 'LU']
  21. _TESTS = [{
  22. # jap, OmU
  23. 'url': 'https://www.anime-on-demand.de/anime/161',
  24. 'info_dict': {
  25. 'id': '161',
  26. 'title': 'Grimgar, Ashes and Illusions (OmU)',
  27. 'description': 'md5:6681ce3c07c7189d255ac6ab23812d31',
  28. },
  29. 'playlist_mincount': 4,
  30. }, {
  31. # Film wording is used instead of Episode, ger/jap, Dub/OmU
  32. 'url': 'https://www.anime-on-demand.de/anime/39',
  33. 'only_matching': True,
  34. }, {
  35. # Episodes without titles, jap, OmU
  36. 'url': 'https://www.anime-on-demand.de/anime/162',
  37. 'only_matching': True,
  38. }, {
  39. # ger/jap, Dub/OmU, account required
  40. 'url': 'https://www.anime-on-demand.de/anime/169',
  41. 'only_matching': True,
  42. }, {
  43. # Full length film, non-series, ger/jap, Dub/OmU, account required
  44. 'url': 'https://www.anime-on-demand.de/anime/185',
  45. 'only_matching': True,
  46. }, {
  47. # Flash videos
  48. 'url': 'https://www.anime-on-demand.de/anime/12',
  49. 'only_matching': True,
  50. }]
  51. def _perform_login(self, username, password):
  52. login_page = self._download_webpage(
  53. self._LOGIN_URL, None, 'Downloading login page')
  54. if '>Our licensing terms allow the distribution of animes only to German-speaking countries of Europe' in login_page:
  55. self.raise_geo_restricted(
  56. '%s is only available in German-speaking countries of Europe' % self.IE_NAME)
  57. login_form = self._form_hidden_inputs('new_user', login_page)
  58. login_form.update({
  59. 'user[login]': username,
  60. 'user[password]': password,
  61. })
  62. post_url = self._search_regex(
  63. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  64. 'post url', default=self._LOGIN_URL, group='url')
  65. if not post_url.startswith('http'):
  66. post_url = urljoin(self._LOGIN_URL, post_url)
  67. response = self._download_webpage(
  68. post_url, None, 'Logging in',
  69. data=urlencode_postdata(login_form), headers={
  70. 'Referer': self._LOGIN_URL,
  71. })
  72. if all(p not in response for p in ('>Logout<', 'href="/users/sign_out"')):
  73. error = self._search_regex(
  74. r'<p[^>]+\bclass=(["\'])(?:(?!\1).)*\balert\b(?:(?!\1).)*\1[^>]*>(?P<error>.+?)</p>',
  75. response, 'error', default=None, group='error')
  76. if error:
  77. raise ExtractorError('Unable to login: %s' % error, expected=True)
  78. raise ExtractorError('Unable to log in')
  79. def _real_extract(self, url):
  80. anime_id = self._match_id(url)
  81. webpage = self._download_webpage(url, anime_id)
  82. if 'data-playlist=' not in webpage:
  83. self._download_webpage(
  84. self._APPLY_HTML5_URL, anime_id,
  85. 'Activating HTML5 beta', 'Unable to apply HTML5 beta')
  86. webpage = self._download_webpage(url, anime_id)
  87. csrf_token = self._html_search_meta(
  88. 'csrf-token', webpage, 'csrf token', fatal=True)
  89. anime_title = self._html_search_regex(
  90. r'(?s)<h1[^>]+itemprop="name"[^>]*>(.+?)</h1>',
  91. webpage, 'anime name')
  92. anime_description = self._html_search_regex(
  93. r'(?s)<div[^>]+itemprop="description"[^>]*>(.+?)</div>',
  94. webpage, 'anime description', default=None)
  95. def extract_info(html, video_id, num=None):
  96. title, description = [None] * 2
  97. formats = []
  98. for input_ in re.findall(
  99. r'<input[^>]+class=["\'].*?streamstarter[^>]+>', html):
  100. attributes = extract_attributes(input_)
  101. title = attributes.get('data-dialog-header')
  102. playlist_urls = []
  103. for playlist_key in ('data-playlist', 'data-otherplaylist', 'data-stream'):
  104. playlist_url = attributes.get(playlist_key)
  105. if isinstance(playlist_url, compat_str) and re.match(
  106. r'/?[\da-zA-Z]+', playlist_url):
  107. playlist_urls.append(attributes[playlist_key])
  108. if not playlist_urls:
  109. continue
  110. lang = attributes.get('data-lang')
  111. lang_note = attributes.get('value')
  112. for playlist_url in playlist_urls:
  113. kind = self._search_regex(
  114. r'videomaterialurl/\d+/([^/]+)/',
  115. playlist_url, 'media kind', default=None)
  116. format_id = join_nonempty(lang, kind) if lang or kind else str(num)
  117. format_note = join_nonempty(kind, lang_note, delim=', ')
  118. item_id_list = []
  119. if format_id:
  120. item_id_list.append(format_id)
  121. item_id_list.append('videomaterial')
  122. playlist = self._download_json(
  123. urljoin(url, playlist_url), video_id,
  124. 'Downloading %s JSON' % ' '.join(item_id_list),
  125. headers={
  126. 'X-Requested-With': 'XMLHttpRequest',
  127. 'X-CSRF-Token': csrf_token,
  128. 'Referer': url,
  129. 'Accept': 'application/json, text/javascript, */*; q=0.01',
  130. }, fatal=False)
  131. if not playlist:
  132. continue
  133. stream_url = url_or_none(playlist.get('streamurl'))
  134. if stream_url:
  135. rtmp = re.search(
  136. r'^(?P<url>rtmpe?://(?P<host>[^/]+)/(?P<app>.+/))(?P<playpath>mp[34]:.+)',
  137. stream_url)
  138. if rtmp:
  139. formats.append({
  140. 'url': rtmp.group('url'),
  141. 'app': rtmp.group('app'),
  142. 'play_path': rtmp.group('playpath'),
  143. 'page_url': url,
  144. 'player_url': 'https://www.anime-on-demand.de/assets/jwplayer.flash-55abfb34080700304d49125ce9ffb4a6.swf',
  145. 'rtmp_real_time': True,
  146. 'format_id': 'rtmp',
  147. 'ext': 'flv',
  148. })
  149. continue
  150. start_video = playlist.get('startvideo', 0)
  151. playlist = playlist.get('playlist')
  152. if not playlist or not isinstance(playlist, list):
  153. continue
  154. playlist = playlist[start_video]
  155. title = playlist.get('title')
  156. if not title:
  157. continue
  158. description = playlist.get('description')
  159. for source in playlist.get('sources', []):
  160. file_ = source.get('file')
  161. if not file_:
  162. continue
  163. ext = determine_ext(file_)
  164. format_id = join_nonempty(
  165. lang, kind,
  166. 'hls' if ext == 'm3u8' else None,
  167. 'dash' if source.get('type') == 'video/dash' or ext == 'mpd' else None)
  168. if ext == 'm3u8':
  169. file_formats = self._extract_m3u8_formats(
  170. file_, video_id, 'mp4',
  171. entry_protocol='m3u8_native', m3u8_id=format_id, fatal=False)
  172. elif source.get('type') == 'video/dash' or ext == 'mpd':
  173. continue
  174. file_formats = self._extract_mpd_formats(
  175. file_, video_id, mpd_id=format_id, fatal=False)
  176. else:
  177. continue
  178. for f in file_formats:
  179. f.update({
  180. 'language': lang,
  181. 'format_note': format_note,
  182. })
  183. formats.extend(file_formats)
  184. return {
  185. 'title': title,
  186. 'description': description,
  187. 'formats': formats,
  188. }
  189. def extract_entries(html, video_id, common_info, num=None):
  190. info = extract_info(html, video_id, num)
  191. if info['formats']:
  192. self._sort_formats(info['formats'])
  193. f = common_info.copy()
  194. f.update(info)
  195. yield f
  196. # Extract teaser/trailer only when full episode is not available
  197. if not info['formats']:
  198. m = re.search(
  199. r'data-dialog-header=(["\'])(?P<title>.+?)\1[^>]+href=(["\'])(?P<href>.+?)\3[^>]*>(?P<kind>Teaser|Trailer)<',
  200. html)
  201. if m:
  202. f = common_info.copy()
  203. f.update({
  204. 'id': '%s-%s' % (f['id'], m.group('kind').lower()),
  205. 'title': m.group('title'),
  206. 'url': urljoin(url, m.group('href')),
  207. })
  208. yield f
  209. def extract_episodes(html):
  210. for num, episode_html in enumerate(re.findall(
  211. r'(?s)<h3[^>]+class="episodebox-title".+?>Episodeninhalt<', html), 1):
  212. episodebox_title = self._search_regex(
  213. (r'class="episodebox-title"[^>]+title=(["\'])(?P<title>.+?)\1',
  214. r'class="episodebox-title"[^>]+>(?P<title>.+?)<'),
  215. episode_html, 'episodebox title', default=None, group='title')
  216. if not episodebox_title:
  217. continue
  218. episode_number = int(self._search_regex(
  219. r'(?:Episode|Film)\s*(\d+)',
  220. episodebox_title, 'episode number', default=num))
  221. episode_title = self._search_regex(
  222. r'(?:Episode|Film)\s*\d+\s*-\s*(.+)',
  223. episodebox_title, 'episode title', default=None)
  224. video_id = 'episode-%d' % episode_number
  225. common_info = {
  226. 'id': video_id,
  227. 'series': anime_title,
  228. 'episode': episode_title,
  229. 'episode_number': episode_number,
  230. }
  231. for e in extract_entries(episode_html, video_id, common_info):
  232. yield e
  233. def extract_film(html, video_id):
  234. common_info = {
  235. 'id': anime_id,
  236. 'title': anime_title,
  237. 'description': anime_description,
  238. }
  239. for e in extract_entries(html, video_id, common_info):
  240. yield e
  241. def entries():
  242. has_episodes = False
  243. for e in extract_episodes(webpage):
  244. has_episodes = True
  245. yield e
  246. if not has_episodes:
  247. for e in extract_film(webpage, anime_id):
  248. yield e
  249. return self.playlist_result(
  250. entries(), anime_id, anime_title, anime_description)