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