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