[compat] Add compat_urllib_parse_urlencode and eliminate encode_dict
[youtube-dl] / youtube_dl / extractor / funimation.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 from .common import InfoExtractor
5 from ..utils import (
6     clean_html,
7     determine_ext,
8     int_or_none,
9     sanitized_Request,
10     ExtractorError,
11     urlencode_postdata
12 )
13
14
15 class FunimationIE(InfoExtractor):
16     _VALID_URL = r'https?://(?:www\.)?funimation\.com/shows/[^/]+/videos/(?:official|promotional)/(?P<id>[^/?#&]+)'
17
18     _NETRC_MACHINE = 'funimation'
19
20     _TESTS = [{
21         'url': 'http://www.funimation.com/shows/air/videos/official/breeze',
22         'info_dict': {
23             'id': '658',
24             'display_id': 'breeze',
25             'ext': 'mp4',
26             'title': 'Air - 1 - Breeze',
27             'description': 'md5:1769f43cd5fc130ace8fd87232207892',
28             'thumbnail': 're:https?://.*\.jpg',
29         },
30     }, {
31         'url': 'http://www.funimation.com/shows/hacksign/videos/official/role-play',
32         'info_dict': {
33             'id': '31128',
34             'display_id': 'role-play',
35             'ext': 'mp4',
36             'title': '.hack//SIGN - 1 - Role Play',
37             'description': 'md5:b602bdc15eef4c9bbb201bb6e6a4a2dd',
38             'thumbnail': 're:https?://.*\.jpg',
39         },
40     }, {
41         'url': 'http://www.funimation.com/shows/attack-on-titan-junior-high/videos/promotional/broadcast-dub-preview',
42         'info_dict': {
43             'id': '9635',
44             'display_id': 'broadcast-dub-preview',
45             'ext': 'mp4',
46             'title': 'Attack on Titan: Junior High - Broadcast Dub Preview',
47             'description': 'md5:f8ec49c0aff702a7832cd81b8a44f803',
48             'thumbnail': 're:https?://.*\.(?:jpg|png)',
49         },
50     }]
51
52     def _login(self):
53         (username, password) = self._get_login_info()
54         if username is None:
55             return
56         data = urlencode_postdata({
57             'email_field': username,
58             'password_field': password,
59         })
60         login_request = sanitized_Request('http://www.funimation.com/login', data, headers={
61             'User-Agent': 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0',
62             'Content-Type': 'application/x-www-form-urlencoded'
63         })
64         login_page = self._download_webpage(
65             login_request, None, 'Logging in as %s' % username)
66         if any(p in login_page for p in ('funimation.com/logout', '>Log Out<')):
67             return
68         error = self._html_search_regex(
69             r'(?s)<div[^>]+id=["\']errorMessages["\'][^>]*>(.+?)</div>',
70             login_page, 'error messages', default=None)
71         if error:
72             raise ExtractorError('Unable to login: %s' % error, expected=True)
73         raise ExtractorError('Unable to log in')
74
75     def _real_initialize(self):
76         self._login()
77
78     def _real_extract(self, url):
79         display_id = self._match_id(url)
80
81         errors = []
82         formats = []
83
84         ERRORS_MAP = {
85             'ERROR_MATURE_CONTENT_LOGGED_IN': 'matureContentLoggedIn',
86             'ERROR_MATURE_CONTENT_LOGGED_OUT': 'matureContentLoggedOut',
87             'ERROR_SUBSCRIPTION_LOGGED_OUT': 'subscriptionLoggedOut',
88             'ERROR_VIDEO_EXPIRED': 'videoExpired',
89             'ERROR_TERRITORY_UNAVAILABLE': 'territoryUnavailable',
90             'SVODBASIC_SUBSCRIPTION_IN_PLAYER': 'basicSubscription',
91             'SVODNON_SUBSCRIPTION_IN_PLAYER': 'nonSubscription',
92             'ERROR_PLAYER_NOT_RESPONDING': 'playerNotResponding',
93             'ERROR_UNABLE_TO_CONNECT_TO_CDN': 'unableToConnectToCDN',
94             'ERROR_STREAM_NOT_FOUND': 'streamNotFound',
95         }
96
97         USER_AGENTS = (
98             # PC UA is served with m3u8 that provides some bonus lower quality formats
99             ('pc', 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0'),
100             # Mobile UA allows to extract direct links and also does not fail when
101             # PC UA fails with hulu error (e.g.
102             # http://www.funimation.com/shows/hacksign/videos/official/role-play)
103             ('mobile', 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36'),
104         )
105
106         for kind, user_agent in USER_AGENTS:
107             request = sanitized_Request(url)
108             request.add_header('User-Agent', user_agent)
109             webpage = self._download_webpage(
110                 request, display_id, 'Downloading %s webpage' % kind)
111
112             playlist = self._parse_json(
113                 self._search_regex(
114                     r'var\s+playersData\s*=\s*(\[.+?\]);\n',
115                     webpage, 'players data'),
116                 display_id)[0]['playlist']
117
118             items = next(item['items'] for item in playlist if item.get('items'))
119             item = next(item for item in items if item.get('itemAK') == display_id)
120
121             error_messages = {}
122             video_error_messages = self._search_regex(
123                 r'var\s+videoErrorMessages\s*=\s*({.+?});\n',
124                 webpage, 'error messages', default=None)
125             if video_error_messages:
126                 error_messages_json = self._parse_json(video_error_messages, display_id, fatal=False)
127                 if error_messages_json:
128                     for _, error in error_messages_json.items():
129                         type_ = error.get('type')
130                         description = error.get('description')
131                         content = error.get('content')
132                         if type_ == 'text' and description and content:
133                             error_message = ERRORS_MAP.get(description)
134                             if error_message:
135                                 error_messages[error_message] = content
136
137             for video in item.get('videoSet', []):
138                 auth_token = video.get('authToken')
139                 if not auth_token:
140                     continue
141                 funimation_id = video.get('FUNImationID') or video.get('videoId')
142                 preference = 1 if video.get('languageMode') == 'dub' else 0
143                 if not auth_token.startswith('?'):
144                     auth_token = '?%s' % auth_token
145                 for quality, height in (('sd', 480), ('hd', 720), ('hd1080', 1080)):
146                     format_url = video.get('%sUrl' % quality)
147                     if not format_url:
148                         continue
149                     if not format_url.startswith(('http', '//')):
150                         errors.append(format_url)
151                         continue
152                     if determine_ext(format_url) == 'm3u8':
153                         formats.extend(self._extract_m3u8_formats(
154                             format_url + auth_token, display_id, 'mp4', entry_protocol='m3u8_native',
155                             preference=preference, m3u8_id='%s-hls' % funimation_id, fatal=False))
156                     else:
157                         tbr = int_or_none(self._search_regex(
158                             r'-(\d+)[Kk]', format_url, 'tbr', default=None))
159                         formats.append({
160                             'url': format_url + auth_token,
161                             'format_id': '%s-http-%dp' % (funimation_id, height),
162                             'height': height,
163                             'tbr': tbr,
164                             'preference': preference,
165                         })
166
167         if not formats and errors:
168             raise ExtractorError(
169                 '%s returned error: %s'
170                 % (self.IE_NAME, clean_html(error_messages.get(errors[0], errors[0]))),
171                 expected=True)
172
173         self._sort_formats(formats)
174
175         title = item['title']
176         artist = item.get('artist')
177         if artist:
178             title = '%s - %s' % (artist, title)
179         description = self._og_search_description(webpage) or item.get('description')
180         thumbnail = self._og_search_thumbnail(webpage) or item.get('posterUrl')
181         video_id = item.get('itemId') or display_id
182
183         return {
184             'id': video_id,
185             'display_id': display_id,
186             'title': title,
187             'description': description,
188             'thumbnail': thumbnail,
189             'formats': formats,
190         }