2 from __future__
import unicode_literals
4 from .common
import InfoExtractor
7 compat_urllib_parse_unquote_plus
,
19 class FunimationIE(InfoExtractor
):
20 _VALID_URL
= r
'https?://(?:www\.)?funimation\.com/shows/[^/]+/videos/(?:official|promotional)/(?P<id>[^/?#&]+)'
22 _NETRC_MACHINE
= 'funimation'
25 'url': 'http://www.funimation.com/shows/air/videos/official/breeze',
28 'display_id': 'breeze',
30 'title': 'Air - 1 - Breeze',
31 'description': 'md5:1769f43cd5fc130ace8fd87232207892',
32 'thumbnail': 're:https?://.*\.jpg',
34 'skip': 'Access without user interaction is forbidden by CloudFlare, and video removed',
36 'url': 'http://www.funimation.com/shows/hacksign/videos/official/role-play',
39 'display_id': 'role-play',
41 'title': '.hack//SIGN - 1 - Role Play',
42 'description': 'md5:b602bdc15eef4c9bbb201bb6e6a4a2dd',
43 'thumbnail': 're:https?://.*\.jpg',
45 'skip': 'Access without user interaction is forbidden by CloudFlare',
47 'url': 'http://www.funimation.com/shows/attack-on-titan-junior-high/videos/promotional/broadcast-dub-preview',
50 'display_id': 'broadcast-dub-preview',
52 'title': 'Attack on Titan: Junior High - Broadcast Dub Preview',
53 'description': 'md5:f8ec49c0aff702a7832cd81b8a44f803',
54 'thumbnail': 're:https?://.*\.(?:jpg|png)',
56 'skip': 'Access without user interaction is forbidden by CloudFlare',
59 _LOGIN_URL
= 'http://www.funimation.com/login'
61 def _download_webpage(self
, *args
, **kwargs
):
63 return super(FunimationIE
, self
)._download
_webpage
(*args
, **kwargs
)
64 except ExtractorError
as ee
:
65 if isinstance(ee
.cause
, compat_HTTPError
) and ee
.cause
.code
== 403:
66 response
= ee
.cause
.read()
67 if b
'>Please complete the security check to access<' in response
:
69 'Access to funimation.com is blocked by CloudFlare. '
70 'Please browse to http://www.funimation.com/, solve '
71 'the reCAPTCHA, export browser cookies to a text file,'
72 ' and then try again with --cookies YOUR_COOKIE_FILE.',
76 def _extract_cloudflare_session_ua(self
, url
):
77 ci_session_cookie
= self
._get
_cookies
(url
).get('ci_session')
79 ci_session
= compat_urllib_parse_unquote_plus(ci_session_cookie
.value
)
80 # ci_session is a string serialized by PHP function serialize()
81 # This case is simple enough to use regular expressions only
82 return self
._search
_regex
(
83 r
'"user_agent";s:\d+:"([^"]+)"', ci_session
, 'user agent',
87 (username
, password
) = self
._get
_login
_info
()
90 data
= urlencode_postdata({
91 'email_field': username
,
92 'password_field': password
,
94 user_agent
= self
._extract
_cloudflare
_session
_ua
(self
._LOGIN
_URL
)
96 user_agent
= 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0'
97 login_request
= sanitized_Request(self
._LOGIN
_URL
, data
, headers
={
98 'User-Agent': user_agent
,
99 'Content-Type': 'application/x-www-form-urlencoded'
101 login_page
= self
._download
_webpage
(
102 login_request
, None, 'Logging in as %s' % username
)
103 if any(p
in login_page
for p
in ('funimation.com/logout', '>Log Out<')):
105 error
= self
._html
_search
_regex
(
106 r
'(?s)<div[^>]+id=["\']errorMessages
["\'][^>]*>(.+?)</div>',
107 login_page, 'error messages', default=None)
109 raise ExtractorError('Unable to login: %s' % error, expected=True)
110 raise ExtractorError('Unable to log in')
112 def _real_initialize(self):
115 def _real_extract(self, url):
116 display_id = self._match_id(url)
122 'ERROR_MATURE_CONTENT_LOGGED_IN': 'matureContentLoggedIn',
123 'ERROR_MATURE_CONTENT_LOGGED_OUT': 'matureContentLoggedOut',
124 'ERROR_SUBSCRIPTION_LOGGED_OUT': 'subscriptionLoggedOut',
125 'ERROR_VIDEO_EXPIRED': 'videoExpired',
126 'ERROR_TERRITORY_UNAVAILABLE': 'territoryUnavailable',
127 'SVODBASIC_SUBSCRIPTION_IN_PLAYER': 'basicSubscription',
128 'SVODNON_SUBSCRIPTION_IN_PLAYER': 'nonSubscription',
129 'ERROR_PLAYER_NOT_RESPONDING': 'playerNotResponding',
130 'ERROR_UNABLE_TO_CONNECT_TO_CDN': 'unableToConnectToCDN',
131 'ERROR_STREAM_NOT_FOUND': 'streamNotFound',
135 # PC UA is served with m3u8 that provides some bonus lower quality formats
136 ('pc', 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0'),
137 # Mobile UA allows to extract direct links and also does not fail when
138 # PC UA fails with hulu error (e.g.
139 # http://www.funimation.com/shows/hacksign/videos/official/role-play)
140 ('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'),
143 user_agent = self._extract_cloudflare_session_ua(url)
145 USER_AGENTS = ((None, user_agent),)
147 for kind, user_agent in USER_AGENTS:
148 request = sanitized_Request(url)
149 request.add_header('User-Agent', user_agent)
150 webpage = self._download_webpage(
152 'Downloading %s webpage' % kind if kind else 'Downloading webpage')
154 playlist = self._parse_json(
156 r'var\s+playersData\s*=\s*(\[.+?\]);\n',
157 webpage, 'players data'),
158 display_id)[0]['playlist']
160 items = next(item['items'] for item in playlist if item.get('items'))
161 item = next(item for item in items if item.get('itemAK') == display_id)
164 video_error_messages = self._search_regex(
165 r'var\s+videoErrorMessages\s*=\s*({.+?});\n',
166 webpage, 'error messages', default=None)
167 if video_error_messages:
168 error_messages_json = self._parse_json(video_error_messages, display_id, fatal=False)
169 if error_messages_json:
170 for _, error in error_messages_json.items():
171 type_ = error.get('type')
172 description = error.get('description')
173 content = error.get('content')
174 if type_ == 'text' and description and content:
175 error_message = ERRORS_MAP.get(description)
177 error_messages[error_message] = content
179 for video in item.get('videoSet', []):
180 auth_token = video.get('authToken')
183 funimation_id = video.get('FUNImationID') or video.get('videoId')
184 preference = 1 if video.get('languageMode') == 'dub' else 0
185 if not auth_token.startswith('?'):
186 auth_token = '?%s' % auth_token
187 for quality, height in (('sd', 480), ('hd', 720), ('hd1080', 1080)):
188 format_url = video.get('%sUrl' % quality)
191 if not format_url.startswith(('http', '//')):
192 errors.append(format_url)
194 if determine_ext(format_url) == 'm3u8':
195 formats.extend(self._extract_m3u8_formats(
196 format_url + auth_token, display_id, 'mp4', entry_protocol='m3u8_native',
197 preference=preference, m3u8_id='%s-hls' % funimation_id, fatal=False))
199 tbr = int_or_none(self._search_regex(
200 r'-(\d+)[Kk]', format_url, 'tbr', default=None))
202 'url': format_url + auth_token,
203 'format_id': '%s-http-%dp' % (funimation_id, height),
206 'preference': preference,
209 if not formats and errors:
210 raise ExtractorError(
211 '%s returned error: %s'
212 % (self.IE_NAME, clean_html(error_messages.get(errors[0], errors[0]))),
215 self._sort_formats(formats)
217 title = item['title']
218 artist = item.get('artist')
220 title = '%s - %s' % (artist, title)
221 description = self._og_search_description(webpage) or item.get('description')
222 thumbnail = self._og_search_thumbnail(webpage) or item.get('posterUrl')
223 video_id = item.get('itemId') or display_id
227 'display_id': display_id,
229 'description': description,
230 'thumbnail': thumbnail,