[udemy] Allow authentication via cookies
[youtube-dl] / youtube_dl / extractor / udemy.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import (
7     compat_urllib_parse,
8     compat_urllib_request,
9 )
10 from ..utils import (
11     ExtractorError,
12     int_or_none,
13     sanitized_Request,
14 )
15
16
17 class UdemyIE(InfoExtractor):
18     IE_NAME = 'udemy'
19     _VALID_URL = r'https?://www\.udemy\.com/(?:[^#]+#/lecture/|lecture/view/?\?lectureId=)(?P<id>\d+)'
20     _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
21     _ORIGIN_URL = 'https://www.udemy.com'
22     _NETRC_MACHINE = 'udemy'
23
24     _TESTS = [{
25         'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
26         'md5': '98eda5b657e752cf945d8445e261b5c5',
27         'info_dict': {
28             'id': '160614',
29             'ext': 'mp4',
30             'title': 'Introduction and Installation',
31             'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
32             'duration': 579.29,
33         },
34         'skip': 'Requires udemy account credentials',
35     }]
36
37     def _handle_error(self, response):
38         if not isinstance(response, dict):
39             return
40         error = response.get('error')
41         if error:
42             error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
43             error_data = error.get('data')
44             if error_data:
45                 error_str += ' - %s' % error_data.get('formErrors')
46             raise ExtractorError(error_str, expected=True)
47
48     def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'):
49         headers = {
50             'X-Udemy-Snail-Case': 'true',
51             'X-Requested-With': 'XMLHttpRequest',
52         }
53         for cookie in self._downloader.cookiejar:
54             if cookie.name == 'client_id':
55                 headers['X-Udemy-Client-Id'] = cookie.value
56             elif cookie.name == 'access_token':
57                 headers['X-Udemy-Bearer-Token'] = cookie.value
58
59         if isinstance(url_or_request, compat_urllib_request.Request):
60             for header, value in headers.items():
61                 url_or_request.add_header(header, value)
62         else:
63             url_or_request = sanitized_Request(url_or_request, headers=headers)
64
65         response = super(UdemyIE, self)._download_json(url_or_request, video_id, note)
66         self._handle_error(response)
67         return response
68
69     def _real_initialize(self):
70         self._login()
71
72     def _login(self):
73         (username, password) = self._get_login_info()
74         if username is None:
75             return
76
77         login_popup = self._download_webpage(
78             self._LOGIN_URL, None, 'Downloading login popup')
79
80         def is_logged(webpage):
81             return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
82
83         # already logged in
84         if is_logged(login_popup):
85             return
86
87         login_form = self._form_hidden_inputs('login-form', login_popup)
88
89         login_form.update({
90             'email': username.encode('utf-8'),
91             'password': password.encode('utf-8'),
92         })
93
94         request = sanitized_Request(
95             self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
96         request.add_header('Referer', self._ORIGIN_URL)
97         request.add_header('Origin', self._ORIGIN_URL)
98
99         response = self._download_webpage(
100             request, None, 'Logging in as %s' % username)
101
102         if not is_logged(response):
103             error = self._html_search_regex(
104                 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
105                 response, 'error message', default=None)
106             if error:
107                 raise ExtractorError('Unable to login: %s' % error, expected=True)
108             raise ExtractorError('Unable to log in')
109
110     def _real_extract(self, url):
111         lecture_id = self._match_id(url)
112
113         lecture = self._download_json(
114             'https://www.udemy.com/api-1.1/lectures/%s' % lecture_id,
115             lecture_id, 'Downloading lecture JSON')
116
117         asset_type = lecture.get('assetType') or lecture.get('asset_type')
118         if asset_type != 'Video':
119             raise ExtractorError(
120                 'Lecture %s is not a video' % lecture_id, expected=True)
121
122         asset = lecture['asset']
123
124         stream_url = asset.get('streamUrl') or asset.get('stream_url')
125         mobj = re.search(r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url)
126         if mobj:
127             return self.url_result(mobj.group(1), 'Youtube')
128
129         video_id = asset['id']
130         thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
131         duration = int_or_none(asset.get('data', {}).get('duration'))
132
133         download_url = asset.get('downloadUrl') or asset.get('download_url')
134
135         video = download_url.get('Video') or download_url.get('video')
136         video_480p = download_url.get('Video480p') or download_url.get('video_480p')
137
138         formats = [{
139             'url': video_480p[0],
140             'format_id': 'download-360p',
141         }, {
142             'url': video[0],
143             'format_id': 'download-720p',
144         }]
145
146         # Some videos also contain formats in asset['data']['outputs'] (e.g.
147         # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
148         outputs = asset.get('data', {}).get('outputs')
149         if isinstance(outputs, dict):
150             for format_id, f in outputs.items():
151                 video_url = f.get('url')
152                 if video_url:
153                     formats.append({
154                         'url': video_url,
155                         'format_id': '%sp' % (f.get('labe1l') or format_id),
156                         'width': int_or_none(f.get('width')),
157                         'height': int_or_none(f.get('height')),
158                         'vbr': int_or_none(f.get('video_bitrate_in_kbps')),
159                         'vcodec': f.get('video_codec'),
160                         'fps': int_or_none(f.get('frame_rate')),
161                         'abr': int_or_none(f.get('audio_bitrate_in_kbps')),
162                         'acodec': f.get('audio_codec'),
163                         'asr': int_or_none(f.get('audio_sample_rate')),
164                         'tbr': int_or_none(f.get('total_bitrate_in_kbps')),
165                         'filesize': int_or_none(f.get('file_size_in_bytes')),
166                     })
167
168         self._sort_formats(formats)
169
170         title = lecture['title']
171         description = lecture.get('description')
172
173         return {
174             'id': video_id,
175             'title': title,
176             'description': description,
177             'thumbnail': thumbnail,
178             'duration': duration,
179             'formats': formats
180         }
181
182
183 class UdemyCourseIE(UdemyIE):
184     IE_NAME = 'udemy:course'
185     _VALID_URL = r'https?://www\.udemy\.com/(?P<coursepath>[\da-z-]+)'
186     _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<'
187     _ALREADY_ENROLLED = '>You are already taking this course.<'
188     _TESTS = []
189
190     @classmethod
191     def suitable(cls, url):
192         return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
193
194     def _real_extract(self, url):
195         mobj = re.match(self._VALID_URL, url)
196         course_path = mobj.group('coursepath')
197
198         response = self._download_json(
199             'https://www.udemy.com/api-1.1/courses/%s' % course_path,
200             course_path, 'Downloading course JSON')
201
202         course_id = int(response['id'])
203         course_title = response['title']
204
205         webpage = self._download_webpage(
206             'https://www.udemy.com/course/subscribe/?courseId=%s' % course_id,
207             course_id, 'Enrolling in the course')
208
209         if self._SUCCESSFULLY_ENROLLED in webpage:
210             self.to_screen('%s: Successfully enrolled in' % course_id)
211         elif self._ALREADY_ENROLLED in webpage:
212             self.to_screen('%s: Already enrolled in' % course_id)
213
214         response = self._download_json(
215             'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
216             course_id, 'Downloading course curriculum')
217
218         entries = [
219             self.url_result(
220                 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), 'Udemy')
221             for asset in response if asset.get('assetType') or asset.get('asset_type') == 'Video'
222         ]
223
224         return self.playlist_result(entries, course_id, course_title)