[funimation] fix authentication(closes #13021)
[youtube-dl] / youtube_dl / extractor / funimation.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 from .common import InfoExtractor
5 from ..compat import (
6     compat_HTTPError,
7     compat_urllib_parse_unquote_plus,
8 )
9 from ..utils import (
10     determine_ext,
11     int_or_none,
12     js_to_json,
13     sanitized_Request,
14     ExtractorError,
15     urlencode_postdata
16 )
17
18
19 class FunimationIE(InfoExtractor):
20     _VALID_URL = r'https?://(?:www\.)?funimation(?:\.com|now\.uk)/shows/[^/]+/(?P<id>[^/?#&]+)'
21
22     _NETRC_MACHINE = 'funimation'
23     _TOKEN = None
24
25     _TESTS = [{
26         'url': 'https://www.funimation.com/shows/hacksign/role-play/',
27         'info_dict': {
28             'id': '91144',
29             'display_id': 'role-play',
30             'ext': 'mp4',
31             'title': '.hack//SIGN - Role Play',
32             'description': 'md5:b602bdc15eef4c9bbb201bb6e6a4a2dd',
33             'thumbnail': r're:https?://.*\.jpg',
34         },
35         'params': {
36             # m3u8 download
37             'skip_download': True,
38         },
39     }, {
40         'url': 'https://www.funimation.com/shows/attack-on-titan-junior-high/broadcast-dub-preview/',
41         'info_dict': {
42             'id': '9635',
43             'display_id': 'broadcast-dub-preview',
44             'ext': 'mp4',
45             'title': 'Attack on Titan: Junior High - Broadcast Dub Preview',
46             'description': 'md5:f8ec49c0aff702a7832cd81b8a44f803',
47             'thumbnail': r're:https?://.*\.(?:jpg|png)',
48         },
49         'skip': 'Access without user interaction is forbidden by CloudFlare',
50     }, {
51         'url': 'https://www.funimationnow.uk/shows/puzzle-dragons-x/drop-impact/simulcast/',
52         'only_matching': True,
53     }]
54
55     _LOGIN_URL = 'http://www.funimation.com/login'
56
57     def _extract_cloudflare_session_ua(self, url):
58         ci_session_cookie = self._get_cookies(url).get('ci_session')
59         if ci_session_cookie:
60             ci_session = compat_urllib_parse_unquote_plus(ci_session_cookie.value)
61             # ci_session is a string serialized by PHP function serialize()
62             # This case is simple enough to use regular expressions only
63             return self._search_regex(
64                 r'"user_agent";s:\d+:"([^"]+)"', ci_session, 'user agent',
65                 default=None)
66
67     def _login(self):
68         (username, password) = self._get_login_info()
69         if username is None:
70             return
71         try:
72             data = self._download_json(
73                 'https://prod-api-funimationnow.dadcdigital.com/api/auth/login/',
74                 None, 'Logging in as %s' % username, data=urlencode_postdata({
75                     'username': username,
76                     'password': password,
77                 }))
78             self._TOKEN = data['token']
79         except ExtractorError as e:
80             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
81                 error = self._parse_json(e.cause.read().decode(), None)['error']
82                 raise ExtractorError(error, expected=True)
83             raise
84
85     def _real_initialize(self):
86         self._login()
87
88     def _real_extract(self, url):
89         display_id = self._match_id(url)
90         webpage = self._download_webpage(url, display_id)
91
92         def _search_kane(name):
93             return self._search_regex(
94                 r"KANE_customdimensions\.%s\s*=\s*'([^']+)';" % name,
95                 webpage, name, default=None)
96
97         title_data = self._parse_json(self._search_regex(
98             r'TITLE_DATA\s*=\s*({[^}]+})',
99             webpage, 'title data', default=''),
100             display_id, js_to_json, fatal=False) or {}
101
102         video_id = title_data.get('id') or self._search_regex([
103             r"KANE_customdimensions.videoID\s*=\s*'(\d+)';",
104             r'<iframe[^>]+src="/player/(\d+)"',
105         ], webpage, 'video_id', default=None)
106         if not video_id:
107             player_url = self._html_search_meta([
108                 'al:web:url',
109                 'og:video:url',
110                 'og:video:secure_url',
111             ], webpage, fatal=True)
112             video_id = self._search_regex(r'/player/(\d+)', player_url, 'video id')
113
114         title = episode = title_data.get('title') or _search_kane('videoTitle') or self._og_search_title(webpage)
115         series = _search_kane('showName')
116         if series:
117             title = '%s - %s' % (series, title)
118         description = self._html_search_meta(['description', 'og:description'], webpage, fatal=True)
119
120         try:
121             headers = {}
122             if self._TOKEN:
123                 headers['Authorization'] = 'Token %s' % self._TOKEN
124             sources = self._download_json(
125                 'https://prod-api-funimationnow.dadcdigital.com/api/source/catalog/video/%s/signed/' % video_id,
126                 video_id, headers=headers)['items']
127         except ExtractorError as e:
128             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
129                 error = self._parse_json(e.cause.read(), video_id)['errors'][0]
130                 raise ExtractorError('%s said: %s' % (
131                     self.IE_NAME, error.get('detail') or error.get('title')), expected=True)
132             raise
133
134         formats = []
135         for source in sources:
136             source_url = source.get('src')
137             if not source_url:
138                 continue
139             source_type = source.get('videoType') or determine_ext(source_url)
140             if source_type == 'm3u8':
141                 formats.extend(self._extract_m3u8_formats(
142                     source_url, video_id, 'mp4',
143                     m3u8_id='hls', fatal=False))
144             else:
145                 formats.append({
146                     'format_id': source_type,
147                     'url': source_url,
148                 })
149         self._sort_formats(formats)
150
151         return {
152             'id': video_id,
153             'display_id': display_id,
154             'title': title,
155             'description': description,
156             'thumbnail': self._og_search_thumbnail(webpage),
157             'series': series,
158             'season_number': int_or_none(title_data.get('seasonNum') or _search_kane('season')),
159             'episode_number': int_or_none(title_data.get('episodeNum')),
160             'episode': episode,
161             'season_id': title_data.get('seriesId'),
162             'formats': formats,
163         }