logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

animeondemand.py (12536B)


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