[funimation] Improve extraction (Closes #7775)
[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     _TEST = {
22         'url': 'http://www.funimation.com/shows/air/videos/official/breeze',
23         'info_dict': {
24             'id': 'AIRENG0001',
25             'title': 'Air - 1 - Breeze ',
26             'ext': 'mp4',
27             'thumbnail': 'http://www.funimation.com/admin/uploads/default/recap_thumbnails/7555590/home_spotlight/AIR0001.jpg',
28             'description': 'Travelling puppeteer Yukito arrives in a small town where he hopes to earn money through the magic of his puppets. When a young girl named Misuzu lures him to her home with the promise of food, his life changes forever. ',
29         }
30     }
31
32     def _download_webpage(self, url_or_request, video_id, note='Downloading webpage'):
33         HEADERS = {
34             'User-Agent': 'Mozilla/5.0 (Windows NT 5.2; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0',
35         }
36         if isinstance(url_or_request, compat_urllib_request.Request):
37             for header, value in HEADERS.items():
38                 url_or_request.add_header(header, value)
39         else:
40             url_or_request = sanitized_Request(url_or_request, headers=HEADERS)
41         response = super(FunimationIE, self)._download_webpage(url_or_request, video_id, note)
42         return response
43
44     def _login(self):
45         (username, password) = self._get_login_info()
46         if username is None:
47             return
48         data = urlencode_postdata(encode_dict({
49             'email_field': username,
50             'password_field': password,
51         }))
52         login_request = sanitized_Request('http://www.funimation.com/login', data, headers={
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         webpage = self._download_webpage(url, display_id)
67
68         items = self._parse_json(
69             self._search_regex(
70                 r'var\s+playersData\s*=\s*(\[.+?\]);\n',
71                 webpage, 'players data'),
72             display_id)[0]['playlist'][0]['items']
73
74         item = next(item for item in items if item.get('itemAK') == display_id)
75
76         ERRORS_MAP = {
77             'ERROR_MATURE_CONTENT_LOGGED_IN': 'matureContentLoggedIn',
78             'ERROR_MATURE_CONTENT_LOGGED_OUT': 'matureContentLoggedOut',
79             'ERROR_SUBSCRIPTION_LOGGED_OUT': 'subscriptionLoggedOut',
80             'ERROR_VIDEO_EXPIRED': 'videoExpired',
81             'ERROR_TERRITORY_UNAVAILABLE': 'territoryUnavailable',
82             'SVODBASIC_SUBSCRIPTION_IN_PLAYER': 'basicSubscription',
83             'SVODNON_SUBSCRIPTION_IN_PLAYER': 'nonSubscription',
84             'ERROR_PLAYER_NOT_RESPONDING': 'playerNotResponding',
85             'ERROR_UNABLE_TO_CONNECT_TO_CDN': 'unableToConnectToCDN',
86             'ERROR_STREAM_NOT_FOUND': 'streamNotFound',
87         }
88
89         error_messages = {}
90         video_error_messages = self._search_regex(
91             r'var\s+videoErrorMessages\s*=\s*({.+?});\n',
92             webpage, 'error messages', default=None)
93         if video_error_messages:
94             error_messages_json = self._parse_json(video_error_messages, display_id, fatal=False)
95             if error_messages_json:
96                 for _, error in error_messages_json.items():
97                     type_ = error.get('type')
98                     description = error.get('description')
99                     content = error.get('content')
100                     if type_ == 'text' and description and content:
101                         error_message = ERRORS_MAP.get(description)
102                         if error_message:
103                             error_messages[error_message] = content
104
105         errors = []
106         formats = []
107         for video in item['videoSet']:
108             auth_token = video.get('authToken')
109             if not auth_token:
110                 continue
111             funimation_id = video.get('FUNImationID') or video.get('videoId')
112             if not auth_token.startswith('?'):
113                 auth_token = '?%s' % auth_token
114             for quality in ('sd', 'hd', 'hd1080'):
115                 format_url = video.get('%sUrl' % quality)
116                 if not format_url:
117                     continue
118                 if not format_url.startswith(('http', '//')):
119                     errors.append(format_url)
120                     continue
121                 if determine_ext(format_url) == 'm3u8':
122                     m3u8_formats = self._extract_m3u8_formats(
123                         format_url + auth_token, display_id, 'mp4', entry_protocol='m3u8_native',
124                         m3u8_id=funimation_id or 'hls', fatal=False)
125                     if m3u8_formats:
126                         formats.extend(m3u8_formats)
127                 else:
128                     formats.append({
129                         'url': format_url + auth_token,
130                     })
131
132         if not formats and errors:
133             raise ExtractorError(
134                 '%s returned error: %s'
135                 % (self.IE_NAME, clean_html(error_messages.get(errors[0], errors[0]))),
136                 expected=True)
137
138         title = item['title']
139         artist = item.get('artist')
140         if artist:
141             title = '%s - %s' % (artist, title)
142         description = self._og_search_description(webpage) or item.get('description')
143         thumbnail = self._og_search_thumbnail(webpage) or item.get('posterUrl')
144         video_id = item.get('itemId') or display_id
145
146         return {
147             'id': video_id,
148             'display_id': display_id,
149             'title': title,
150             'description': description,
151             'thumbnail': thumbnail,
152             'formats': formats,
153         }