Merge branch 'youku_bugfix' of https://github.com/Celthi/youtube-dl into Celthi-youku...
[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 ..utils import (
8     clean_html,
9     determine_ext,
10     encode_dict,
11     int_or_none,
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|promotional)/(?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         'url': 'http://www.funimation.com/shows/attack-on-titan-junior-high/videos/promotional/broadcast-dub-preview',
43         'info_dict': {
44             'id': '9635',
45             'display_id': 'broadcast-dub-preview',
46             'ext': 'mp4',
47             'title': 'Attack on Titan: Junior High - Broadcast Dub Preview',
48             'description': 'md5:f8ec49c0aff702a7832cd81b8a44f803',
49             'thumbnail': 're:https?://.*\.(?:jpg|png)',
50         },
51     }]
52
53     def _login(self):
54         (username, password) = self._get_login_info()
55         if username is None:
56             return
57         data = urlencode_postdata(encode_dict({
58             'email_field': username,
59             'password_field': password,
60         }))
61         login_request = sanitized_Request('http://www.funimation.com/login', data, headers={
62             'User-Agent': 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0',
63             'Content-Type': 'application/x-www-form-urlencoded'
64         })
65         login = self._download_webpage(
66             login_request, None, 'Logging in as %s' % username)
67         if re.search(r'<meta property="og:url" content="http://www.funimation.com/login"/>', login) is not None:
68             raise ExtractorError('Unable to login, wrong username or password.', expected=True)
69
70     def _real_initialize(self):
71         self._login()
72
73     def _real_extract(self, url):
74         display_id = self._match_id(url)
75
76         errors = []
77         formats = []
78
79         ERRORS_MAP = {
80             'ERROR_MATURE_CONTENT_LOGGED_IN': 'matureContentLoggedIn',
81             'ERROR_MATURE_CONTENT_LOGGED_OUT': 'matureContentLoggedOut',
82             'ERROR_SUBSCRIPTION_LOGGED_OUT': 'subscriptionLoggedOut',
83             'ERROR_VIDEO_EXPIRED': 'videoExpired',
84             'ERROR_TERRITORY_UNAVAILABLE': 'territoryUnavailable',
85             'SVODBASIC_SUBSCRIPTION_IN_PLAYER': 'basicSubscription',
86             'SVODNON_SUBSCRIPTION_IN_PLAYER': 'nonSubscription',
87             'ERROR_PLAYER_NOT_RESPONDING': 'playerNotResponding',
88             'ERROR_UNABLE_TO_CONNECT_TO_CDN': 'unableToConnectToCDN',
89             'ERROR_STREAM_NOT_FOUND': 'streamNotFound',
90         }
91
92         USER_AGENTS = (
93             # PC UA is served with m3u8 that provides some bonus lower quality formats
94             ('pc', 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0'),
95             # Mobile UA allows to extract direct links and also does not fail when
96             # PC UA fails with hulu error (e.g.
97             # http://www.funimation.com/shows/hacksign/videos/official/role-play)
98             ('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'),
99         )
100
101         for kind, user_agent in USER_AGENTS:
102             request = sanitized_Request(url)
103             request.add_header('User-Agent', user_agent)
104             webpage = self._download_webpage(
105                 request, display_id, 'Downloading %s webpage' % kind)
106
107             playlist = self._parse_json(
108                 self._search_regex(
109                     r'var\s+playersData\s*=\s*(\[.+?\]);\n',
110                     webpage, 'players data'),
111                 display_id)[0]['playlist']
112
113             items = next(item['items'] for item in playlist if item.get('items'))
114             item = next(item for item in items if item.get('itemAK') == display_id)
115
116             error_messages = {}
117             video_error_messages = self._search_regex(
118                 r'var\s+videoErrorMessages\s*=\s*({.+?});\n',
119                 webpage, 'error messages', default=None)
120             if video_error_messages:
121                 error_messages_json = self._parse_json(video_error_messages, display_id, fatal=False)
122                 if error_messages_json:
123                     for _, error in error_messages_json.items():
124                         type_ = error.get('type')
125                         description = error.get('description')
126                         content = error.get('content')
127                         if type_ == 'text' and description and content:
128                             error_message = ERRORS_MAP.get(description)
129                             if error_message:
130                                 error_messages[error_message] = content
131
132             for video in item.get('videoSet', []):
133                 auth_token = video.get('authToken')
134                 if not auth_token:
135                     continue
136                 funimation_id = video.get('FUNImationID') or video.get('videoId')
137                 preference = 1 if video.get('languageMode') == 'dub' else 0
138                 if not auth_token.startswith('?'):
139                     auth_token = '?%s' % auth_token
140                 for quality, height in (('sd', 480), ('hd', 720), ('hd1080', 1080)):
141                     format_url = video.get('%sUrl' % quality)
142                     if not format_url:
143                         continue
144                     if not format_url.startswith(('http', '//')):
145                         errors.append(format_url)
146                         continue
147                     if determine_ext(format_url) == 'm3u8':
148                         m3u8_formats = self._extract_m3u8_formats(
149                             format_url + auth_token, display_id, 'mp4', entry_protocol='m3u8_native',
150                             preference=preference, m3u8_id='%s-hls' % funimation_id, fatal=False)
151                         if m3u8_formats:
152                             formats.extend(m3u8_formats)
153                     else:
154                         tbr = int_or_none(self._search_regex(
155                             r'-(\d+)[Kk]', format_url, 'tbr', default=None))
156                         formats.append({
157                             'url': format_url + auth_token,
158                             'format_id': '%s-http-%dp' % (funimation_id, height),
159                             'height': height,
160                             'tbr': tbr,
161                             'preference': preference,
162                         })
163
164         if not formats and errors:
165             raise ExtractorError(
166                 '%s returned error: %s'
167                 % (self.IE_NAME, clean_html(error_messages.get(errors[0], errors[0]))),
168                 expected=True)
169
170         self._sort_formats(formats)
171
172         title = item['title']
173         artist = item.get('artist')
174         if artist:
175             title = '%s - %s' % (artist, title)
176         description = self._og_search_description(webpage) or item.get('description')
177         thumbnail = self._og_search_thumbnail(webpage) or item.get('posterUrl')
178         video_id = item.get('itemId') or display_id
179
180         return {
181             'id': video_id,
182             'display_id': display_id,
183             'title': title,
184             'description': description,
185             'thumbnail': thumbnail,
186             'formats': formats,
187         }