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