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