[funimation] Add test for promotional video
[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     sanitized_Request,
12     ExtractorError,
13     urlencode_postdata
14 )
15
16
17 class FunimationIE(InfoExtractor):
18     _VALID_URL = r'https?://(?:www\.)?funimation\.com/shows/[^/]+/videos/(?:official|promotional)/(?P<id>[^/?#&]+)'
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(encode_dict({
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 = self._download_webpage(
65             login_request, None, 'Logging in as %s' % username)
66         if re.search(r'<meta property="og:url" content="http://www.funimation.com/login"/>', login) is not None:
67             raise ExtractorError('Unable to login, wrong username or password.', expected=True)
68
69     def _real_initialize(self):
70         self._login()
71
72     def _real_extract(self, url):
73         display_id = self._match_id(url)
74
75         errors = []
76         formats = []
77
78         ERRORS_MAP = {
79             'ERROR_MATURE_CONTENT_LOGGED_IN': 'matureContentLoggedIn',
80             'ERROR_MATURE_CONTENT_LOGGED_OUT': 'matureContentLoggedOut',
81             'ERROR_SUBSCRIPTION_LOGGED_OUT': 'subscriptionLoggedOut',
82             'ERROR_VIDEO_EXPIRED': 'videoExpired',
83             'ERROR_TERRITORY_UNAVAILABLE': 'territoryUnavailable',
84             'SVODBASIC_SUBSCRIPTION_IN_PLAYER': 'basicSubscription',
85             'SVODNON_SUBSCRIPTION_IN_PLAYER': 'nonSubscription',
86             'ERROR_PLAYER_NOT_RESPONDING': 'playerNotResponding',
87             'ERROR_UNABLE_TO_CONNECT_TO_CDN': 'unableToConnectToCDN',
88             'ERROR_STREAM_NOT_FOUND': 'streamNotFound',
89         }
90
91         USER_AGENTS = (
92             # PC UA is served with m3u8 that provides some bonus lower quality formats
93             ('pc', 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0'),
94             # Mobile UA allows to extract direct links and also does not fail when
95             # PC UA fails with hulu error (e.g.
96             # http://www.funimation.com/shows/hacksign/videos/official/role-play)
97             ('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'),
98         )
99
100         for kind, user_agent in USER_AGENTS:
101             request = sanitized_Request(url)
102             request.add_header('User-Agent', user_agent)
103             webpage = self._download_webpage(
104                 request, display_id, 'Downloading %s webpage' % kind)
105
106             playlist = self._parse_json(
107                 self._search_regex(
108                     r'var\s+playersData\s*=\s*(\[.+?\]);\n',
109                     webpage, 'players data'),
110                 display_id)[0]['playlist']
111
112             items = next(item['items'] for item in playlist if item.get('items'))
113             item = next(item for item in items if item.get('itemAK') == display_id)
114
115             error_messages = {}
116             video_error_messages = self._search_regex(
117                 r'var\s+videoErrorMessages\s*=\s*({.+?});\n',
118                 webpage, 'error messages', default=None)
119             if video_error_messages:
120                 error_messages_json = self._parse_json(video_error_messages, display_id, fatal=False)
121                 if error_messages_json:
122                     for _, error in error_messages_json.items():
123                         type_ = error.get('type')
124                         description = error.get('description')
125                         content = error.get('content')
126                         if type_ == 'text' and description and content:
127                             error_message = ERRORS_MAP.get(description)
128                             if error_message:
129                                 error_messages[error_message] = content
130
131             for video in item.get('videoSet', []):
132                 auth_token = video.get('authToken')
133                 if not auth_token:
134                     continue
135                 funimation_id = video.get('FUNImationID') or video.get('videoId')
136                 preference = 1 if video.get('languageMode') == 'dub' else 0
137                 if not auth_token.startswith('?'):
138                     auth_token = '?%s' % auth_token
139                 for quality in ('sd', 'hd', 'hd1080'):
140                     format_url = video.get('%sUrl' % quality)
141                     if not format_url:
142                         continue
143                     if not format_url.startswith(('http', '//')):
144                         errors.append(format_url)
145                         continue
146                     if determine_ext(format_url) == 'm3u8':
147                         m3u8_formats = self._extract_m3u8_formats(
148                             format_url + auth_token, display_id, 'mp4', entry_protocol='m3u8_native',
149                             preference=preference, m3u8_id=funimation_id or 'hls', fatal=False)
150                         if m3u8_formats:
151                             formats.extend(m3u8_formats)
152                     else:
153                         f = {
154                             'url': format_url + auth_token,
155                             'format_id': funimation_id,
156                             'preference': preference,
157                         }
158                         mobj = re.search(r'(?P<height>\d+)-(?P<tbr>\d+)[Kk]', format_url)
159                         if mobj:
160                             f.update({
161                                 'height': int(mobj.group('height')),
162                                 'tbr': int(mobj.group('tbr')),
163                             })
164                         formats.append(f)
165
166         if not formats and errors:
167             raise ExtractorError(
168                 '%s returned error: %s'
169                 % (self.IE_NAME, clean_html(error_messages.get(errors[0], errors[0]))),
170                 expected=True)
171
172         self._sort_formats(formats)
173
174         title = item['title']
175         artist = item.get('artist')
176         if artist:
177             title = '%s - %s' % (artist, title)
178         description = self._og_search_description(webpage) or item.get('description')
179         thumbnail = self._og_search_thumbnail(webpage) or item.get('posterUrl')
180         video_id = item.get('itemId') or display_id
181
182         return {
183             'id': video_id,
184             'display_id': display_id,
185             'title': title,
186             'description': description,
187             'thumbnail': thumbnail,
188             'formats': formats,
189         }