[safari] Fix authentication
[youtube-dl] / youtube_dl / extractor / safari.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from .brightcove import BrightcoveLegacyIE
8
9 from ..utils import (
10     ExtractorError,
11     sanitized_Request,
12     smuggle_url,
13     std_headers,
14     urlencode_postdata,
15     update_url_query,
16 )
17
18
19 class SafariBaseIE(InfoExtractor):
20     _LOGIN_URL = 'https://www.safaribooksonline.com/accounts/login/'
21     _SUCCESSFUL_LOGIN_REGEX = r'<a href="/accounts/logout/"[^>]*>Sign Out</a>'
22     _NETRC_MACHINE = 'safari'
23
24     _API_BASE = 'https://www.safaribooksonline.com/api/v1'
25     _API_FORMAT = 'json'
26
27     LOGGED_IN = False
28
29     def _real_initialize(self):
30         self._login()
31
32     def _login(self):
33         # We only need to log in once for courses or individual videos
34         if self.LOGGED_IN:
35             return
36
37         (username, password) = self._get_login_info()
38         if username is None:
39             return
40
41         headers = std_headers.copy()
42         if 'Referer' not in headers:
43             headers['Referer'] = self._LOGIN_URL
44         login_page_request = sanitized_Request(self._LOGIN_URL, headers=headers)
45
46         login_page = self._download_webpage(
47             login_page_request, None,
48             'Downloading login form')
49
50         csrf = self._html_search_regex(
51             r"name='csrfmiddlewaretoken'\s+value='([^']+)'",
52             login_page, 'csrf token')
53
54         login_form = {
55             'csrfmiddlewaretoken': csrf,
56             'email': username,
57             'password1': password,
58             'login': 'Sign In',
59             'next': '',
60         }
61
62         request = sanitized_Request(
63             self._LOGIN_URL, urlencode_postdata(login_form), headers=headers)
64         login_page = self._download_webpage(
65             request, None, 'Logging in as %s' % username)
66
67         if re.search(self._SUCCESSFUL_LOGIN_REGEX, login_page) is None:
68             raise ExtractorError(
69                 'Login failed; make sure your credentials are correct and try again.',
70                 expected=True)
71
72         SafariBaseIE.LOGGED_IN = True
73
74         self.to_screen('Login successful')
75
76
77 class SafariIE(SafariBaseIE):
78     IE_NAME = 'safari'
79     IE_DESC = 'safaribooksonline.com online video'
80     _VALID_URL = r'''(?x)https?://
81                             (?:www\.)?safaribooksonline\.com/
82                                 (?:
83                                     library/view/[^/]+|
84                                     api/v1/book
85                                 )/
86                                 (?P<course_id>[^/]+)/
87                                     (?:chapter(?:-content)?/)?
88                                 (?P<part>part\d+)\.html
89     '''
90
91     _TESTS = [{
92         'url': 'https://www.safaribooksonline.com/library/view/hadoop-fundamentals-livelessons/9780133392838/part00.html',
93         'md5': 'dcc5a425e79f2564148652616af1f2a3',
94         'info_dict': {
95             'id': '0_qbqx90ic',
96             'ext': 'mp4',
97             'title': 'Introduction to Hadoop Fundamentals LiveLessons',
98             'timestamp': 1437758058,
99             'upload_date': '20150724',
100             'uploader_id': 'stork',
101         },
102     }, {
103         'url': 'https://www.safaribooksonline.com/api/v1/book/9780133392838/chapter/part00.html',
104         'only_matching': True,
105     }, {
106         # non-digits in course id
107         'url': 'https://www.safaribooksonline.com/library/view/create-a-nodejs/100000006A0210/part00.html',
108         'only_matching': True,
109     }]
110
111     def _real_extract(self, url):
112         mobj = re.match(self._VALID_URL, url)
113         course_id = mobj.group('course_id')
114         part = mobj.group('part')
115
116         webpage = self._download_webpage(url, '%s/%s' % (course_id, part))
117         reference_id = self._search_regex(r'data-reference-id="([^"]+)"', webpage, 'kaltura reference id')
118         partner_id = self._search_regex(r'data-partner-id="([^"]+)"', webpage, 'kaltura widget id')
119         ui_id = self._search_regex(r'data-ui-id="([^"]+)"', webpage, 'kaltura uiconf id')
120
121         query = {
122             'wid': '_%s' % partner_id,
123             'uiconf_id': ui_id,
124             'flashvars[referenceId]': reference_id,
125         }
126
127         if self.LOGGED_IN:
128             kaltura_session = self._download_json(
129                 '%s/player/kaltura_session/?reference_id=%s' % (self._API_BASE, reference_id),
130                 course_id, 'Downloading kaltura session JSON',
131                 'Unable to download kaltura session JSON', fatal=False)
132             if kaltura_session:
133                 session = kaltura_session.get('session')
134                 if session:
135                     query['flashvars[ks]'] = session
136
137         return self.url_result(update_url_query(
138             'https://cdnapisec.kaltura.com/html5/html5lib/v2.37.1/mwEmbedFrame.php', query),
139             'Kaltura')
140
141
142 class SafariCourseIE(SafariBaseIE):
143     IE_NAME = 'safari:course'
144     IE_DESC = 'safaribooksonline.com online courses'
145
146     _VALID_URL = r'https?://(?:www\.)?safaribooksonline\.com/(?:library/view/[^/]+|api/v1/book)/(?P<id>[^/]+)/?(?:[#?]|$)'
147
148     _TESTS = [{
149         'url': 'https://www.safaribooksonline.com/library/view/hadoop-fundamentals-livelessons/9780133392838/',
150         'info_dict': {
151             'id': '9780133392838',
152             'title': 'Hadoop Fundamentals LiveLessons',
153         },
154         'playlist_count': 22,
155         'skip': 'Requires safaribooksonline account credentials',
156     }, {
157         'url': 'https://www.safaribooksonline.com/api/v1/book/9781449396459/?override_format=json',
158         'only_matching': True,
159     }]
160
161     def _real_extract(self, url):
162         course_id = self._match_id(url)
163
164         course_json = self._download_json(
165             '%s/book/%s/?override_format=%s' % (self._API_BASE, course_id, self._API_FORMAT),
166             course_id, 'Downloading course JSON')
167
168         if 'chapters' not in course_json:
169             raise ExtractorError(
170                 'No chapters found for course %s' % course_id, expected=True)
171
172         entries = [
173             self.url_result(chapter, 'Safari')
174             for chapter in course_json['chapters']]
175
176         course_title = course_json['title']
177
178         return self.playlist_result(entries, course_id, course_title)