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