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