[animeondemand] Improve extraction
[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 compat_urlparse
7 from ..utils import (
8     determine_ext,
9     encode_dict,
10     ExtractorError,
11     sanitized_Request,
12     urlencode_postdata,
13 )
14
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
39     def _login(self):
40         (username, password) = self._get_login_info()
41         if username is None:
42             return
43
44         login_page = self._download_webpage(
45             self._LOGIN_URL, None, 'Downloading login page')
46
47         login_form = self._form_hidden_inputs('new_user', login_page)
48
49         login_form.update({
50             'user[login]': username,
51             'user[password]': password,
52         })
53
54         post_url = self._search_regex(
55             r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
56             'post url', default=self._LOGIN_URL, group='url')
57
58         if not post_url.startswith('http'):
59             post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
60
61         request = sanitized_Request(
62             post_url, urlencode_postdata(encode_dict(login_form)))
63         request.add_header('Referer', self._LOGIN_URL)
64
65         response = self._download_webpage(
66             request, None, 'Logging in as %s' % username)
67
68         if all(p not in response for p in ('>Logout<', 'href="/users/sign_out"')):
69             error = self._search_regex(
70                 r'<p class="alert alert-danger">(.+?)</p>',
71                 response, 'error', default=None)
72             if error:
73                 raise ExtractorError('Unable to login: %s' % error, expected=True)
74             raise ExtractorError('Unable to log in')
75
76     def _real_initialize(self):
77         self._login()
78
79     def _real_extract(self, url):
80         anime_id = self._match_id(url)
81
82         webpage = self._download_webpage(url, anime_id)
83
84         if 'data-playlist=' not in webpage:
85             self._download_webpage(
86                 self._APPLY_HTML5_URL, anime_id,
87                 'Activating HTML5 beta', 'Unable to apply HTML5 beta')
88             webpage = self._download_webpage(url, anime_id)
89
90         csrf_token = self._html_search_meta(
91             'csrf-token', webpage, 'csrf token', fatal=True)
92
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
100         entries = []
101
102         for num, episode_html in enumerate(re.findall(
103                 r'(?s)<h3[^>]+class="episodebox-title".+?>Episodeninhalt<', webpage)):
104             episodebox_title = self._search_regex(
105                 (r'class="episodebox-title"[^>]+title="(.+?)"',
106                  r'class="episodebox-title"[^>]+>(.+?)<'),
107                 webpage, 'episodebox title', default=None)
108             if not episodebox_title:
109                 continue
110
111             episode_number = int(self._search_regex(
112                 r'^(?:Episode|Film)\s*(\d+)',
113                 episodebox_title, 'episode number', default=num))
114             episode_title = self._search_regex(
115                 r'(?:Episode|Film)\s*\d+\s*-\s*(?P<title>.+?)',
116                 episodebox_title, 'episode title', default=None)
117
118             video_id = 'episode-%d' % episode_number
119
120             common_info = {
121                 'id': video_id,
122                 'series': anime_title,
123                 'episode': episode_title,
124                 'episode_number': episode_number,
125             }
126
127             formats = []
128
129             playlist_url = self._search_regex(
130                 r'data-playlist=(["\'])(?P<url>.+?)\1',
131                 episode_html, 'data playlist', default=None, group='url')
132             if playlist_url:
133                 request = sanitized_Request(
134                     compat_urlparse.urljoin(url, playlist_url),
135                     headers={
136                         'X-Requested-With': 'XMLHttpRequest',
137                         'X-CSRF-Token': csrf_token,
138                         'Referer': url,
139                         'Accept': 'application/json, text/javascript, */*; q=0.01',
140                     })
141
142                 playlist = self._download_json(
143                     request, video_id, 'Downloading playlist JSON', fatal=False)
144                 if playlist:
145                     playlist = playlist['playlist'][0]
146                     title = playlist['title']
147                     description = playlist.get('description')
148                     for source in playlist.get('sources', []):
149                         file_ = source.get('file')
150                         if file_ and determine_ext(file_) == 'm3u8':
151                             formats = self._extract_m3u8_formats(
152                                 file_, video_id, 'mp4',
153                                 entry_protocol='m3u8_native', m3u8_id='hls')
154
155             if formats:
156                 f = common_info.copy()
157                 f.update({
158                     'title': title,
159                     'description': description,
160                     'formats': formats,
161                 })
162                 entries.append(f)
163
164             m = re.search(
165                 r'data-dialog-header=(["\'])(?P<title>.+?)\1[^>]+href=(["\'])(?P<href>.+?)\3[^>]*>Teaser<',
166                 episode_html)
167             if m:
168                 f = common_info.copy()
169                 f.update({
170                     'id': '%s-teaser' % f['id'],
171                     'title': m.group('title'),
172                     'url': compat_urlparse.urljoin(url, m.group('href')),
173                 })
174                 entries.append(f)
175
176         return self.playlist_result(entries, anime_id, anime_title, anime_description)