[udemy] Fix course enroll (Closes #9393)
[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_HTTPError,
8     compat_urllib_parse_urlencode,
9     compat_urllib_request,
10     compat_urlparse,
11 )
12 from ..utils import (
13     determine_ext,
14     extract_attributes,
15     ExtractorError,
16     float_or_none,
17     int_or_none,
18     sanitized_Request,
19     unescapeHTML,
20     urlencode_postdata,
21 )
22
23
24 class UdemyIE(InfoExtractor):
25     IE_NAME = 'udemy'
26     _VALID_URL = r'''(?x)
27                     https?://
28                         www\.udemy\.com/
29                         (?:
30                             [^#]+\#/lecture/|
31                             lecture/view/?\?lectureId=|
32                             [^/]+/learn/v4/t/lecture/
33                         )
34                         (?P<id>\d+)
35                     '''
36     _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
37     _ORIGIN_URL = 'https://www.udemy.com'
38     _NETRC_MACHINE = 'udemy'
39
40     _TESTS = [{
41         'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
42         'md5': '98eda5b657e752cf945d8445e261b5c5',
43         'info_dict': {
44             'id': '160614',
45             'ext': 'mp4',
46             'title': 'Introduction and Installation',
47             'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
48             'duration': 579.29,
49         },
50         'skip': 'Requires udemy account credentials',
51     }, {
52         # new URL schema
53         'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
54         'only_matching': True,
55     }]
56
57     def _extract_course_info(self, webpage, video_id):
58         course = self._parse_json(
59             unescapeHTML(self._search_regex(
60                 r'ng-init=["\'].*\bcourse=({.+?});', webpage, 'course', default='{}')),
61             video_id, fatal=False) or {}
62         course_id = course.get('id') or self._search_regex(
63             (r'&quot;id&quot;\s*:\s*(\d+)', r'data-course-id=["\'](\d+)'),
64             webpage, 'course id')
65         return course_id, course.get('title')
66
67     def _enroll_course(self, base_url, webpage, course_id):
68         def combine_url(base_url, url):
69             return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
70
71         checkout_url = unescapeHTML(self._search_regex(
72             r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/payment/checkout/.+?)\1',
73             webpage, 'checkout url', group='url', default=None))
74         if checkout_url:
75             raise ExtractorError(
76                 'Course %s is not free. You have to pay for it before you can download. '
77                 'Use this URL to confirm purchase: %s'
78                 % (course_id, combine_url(base_url, checkout_url)),
79                 expected=True)
80
81         enroll_url = unescapeHTML(self._search_regex(
82             r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
83             webpage, 'enroll url', group='url', default=None))
84         if enroll_url:
85             webpage = self._download_webpage(
86                 combine_url(base_url, enroll_url),
87                 course_id, 'Enrolling in the course',
88                 headers={'Referer': base_url})
89             if '>You have enrolled in' in webpage:
90                 self.to_screen('%s: Successfully enrolled in the course' % course_id)
91
92     def _download_lecture(self, course_id, lecture_id):
93         return self._download_json(
94             'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % (
95                 course_id, lecture_id, compat_urllib_parse_urlencode({
96                     'fields[lecture]': 'title,description,view_html,asset',
97                     'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
98                 })),
99             lecture_id, 'Downloading lecture JSON')
100
101     def _handle_error(self, response):
102         if not isinstance(response, dict):
103             return
104         error = response.get('error')
105         if error:
106             error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
107             error_data = error.get('data')
108             if error_data:
109                 error_str += ' - %s' % error_data.get('formErrors')
110             raise ExtractorError(error_str, expected=True)
111
112     def _download_json(self, url_or_request, *args, **kwargs):
113         headers = {
114             'X-Udemy-Snail-Case': 'true',
115             'X-Requested-With': 'XMLHttpRequest',
116         }
117         for cookie in self._downloader.cookiejar:
118             if cookie.name == 'client_id':
119                 headers['X-Udemy-Client-Id'] = cookie.value
120             elif cookie.name == 'access_token':
121                 headers['X-Udemy-Bearer-Token'] = cookie.value
122                 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
123
124         if isinstance(url_or_request, compat_urllib_request.Request):
125             for header, value in headers.items():
126                 url_or_request.add_header(header, value)
127         else:
128             url_or_request = sanitized_Request(url_or_request, headers=headers)
129
130         response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
131         self._handle_error(response)
132         return response
133
134     def _real_initialize(self):
135         self._login()
136
137     def _login(self):
138         (username, password) = self._get_login_info()
139         if username is None:
140             return
141
142         login_popup = self._download_webpage(
143             self._LOGIN_URL, None, 'Downloading login popup')
144
145         def is_logged(webpage):
146             return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
147
148         # already logged in
149         if is_logged(login_popup):
150             return
151
152         login_form = self._form_hidden_inputs('login-form', login_popup)
153
154         login_form.update({
155             'email': username,
156             'password': password,
157         })
158
159         request = sanitized_Request(
160             self._LOGIN_URL, urlencode_postdata(login_form))
161         request.add_header('Referer', self._ORIGIN_URL)
162         request.add_header('Origin', self._ORIGIN_URL)
163
164         response = self._download_webpage(
165             request, None, 'Logging in as %s' % username)
166
167         if not is_logged(response):
168             error = self._html_search_regex(
169                 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
170                 response, 'error message', default=None)
171             if error:
172                 raise ExtractorError('Unable to login: %s' % error, expected=True)
173             raise ExtractorError('Unable to log in')
174
175     def _real_extract(self, url):
176         lecture_id = self._match_id(url)
177
178         webpage = self._download_webpage(url, lecture_id)
179
180         course_id, _ = self._extract_course_info(webpage, lecture_id)
181
182         try:
183             lecture = self._download_lecture(course_id, lecture_id)
184         except ExtractorError as e:
185             # Error could possibly mean we are not enrolled in the course
186             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
187                 self._enroll_course(url, webpage, course_id)
188                 lecture = self._download_lecture(course_id, lecture_id)
189             else:
190                 raise
191
192         title = lecture['title']
193         description = lecture.get('description')
194
195         asset = lecture['asset']
196
197         asset_type = asset.get('asset_type') or asset.get('assetType')
198         if asset_type != 'Video':
199             raise ExtractorError(
200                 'Lecture %s is not a video' % lecture_id, expected=True)
201
202         stream_url = asset.get('stream_url') or asset.get('streamUrl')
203         if stream_url:
204             youtube_url = self._search_regex(
205                 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
206             if youtube_url:
207                 return self.url_result(youtube_url, 'Youtube')
208
209         video_id = asset['id']
210         thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
211         duration = float_or_none(asset.get('data', {}).get('duration'))
212
213         formats = []
214
215         def extract_output_format(src):
216             return {
217                 'url': src['url'],
218                 'format_id': '%sp' % (src.get('height') or format_id),
219                 'width': int_or_none(src.get('width')),
220                 'height': int_or_none(src.get('height')),
221                 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
222                 'vcodec': src.get('video_codec'),
223                 'fps': int_or_none(src.get('frame_rate')),
224                 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
225                 'acodec': src.get('audio_codec'),
226                 'asr': int_or_none(src.get('audio_sample_rate')),
227                 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
228                 'filesize': int_or_none(src.get('file_size_in_bytes')),
229             }
230
231         outputs = asset.get('data', {}).get('outputs')
232         if not isinstance(outputs, dict):
233             outputs = {}
234
235         def add_output_format_meta(f, key):
236             output = outputs.get(key)
237             if isinstance(output, dict):
238                 output_format = extract_output_format(output)
239                 output_format.update(f)
240                 return output_format
241             return f
242
243         download_urls = asset.get('download_urls')
244         if isinstance(download_urls, dict):
245             video = download_urls.get('Video')
246             if isinstance(video, list):
247                 for format_ in video:
248                     video_url = format_.get('file')
249                     if not video_url:
250                         continue
251                     format_id = format_.get('label')
252                     f = {
253                         'url': format_['file'],
254                         'format_id': '%sp' % format_id,
255                         'height': int_or_none(format_id),
256                     }
257                     if format_id:
258                         # Some videos contain additional metadata (e.g.
259                         # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
260                         f = add_output_format_meta(f, format_id)
261                     formats.append(f)
262
263         view_html = lecture.get('view_html')
264         if view_html:
265             view_html_urls = set()
266             for source in re.findall(r'<source[^>]+>', view_html):
267                 attributes = extract_attributes(source)
268                 src = attributes.get('src')
269                 if not src:
270                     continue
271                 res = attributes.get('data-res')
272                 height = int_or_none(res)
273                 if src in view_html_urls:
274                     continue
275                 view_html_urls.add(src)
276                 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
277                     m3u8_formats = self._extract_m3u8_formats(
278                         src, video_id, 'mp4', entry_protocol='m3u8_native',
279                         m3u8_id='hls', fatal=False)
280                     for f in m3u8_formats:
281                         m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
282                         if m:
283                             if not f.get('height'):
284                                 f['height'] = int(m.group('height'))
285                             if not f.get('tbr'):
286                                 f['tbr'] = int(m.group('tbr'))
287                     formats.extend(m3u8_formats)
288                 else:
289                     formats.append(add_output_format_meta({
290                         'url': src,
291                         'format_id': '%dp' % height if height else None,
292                         'height': height,
293                     }, res))
294
295         self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
296
297         return {
298             'id': video_id,
299             'title': title,
300             'description': description,
301             'thumbnail': thumbnail,
302             'duration': duration,
303             'formats': formats
304         }
305
306
307 class UdemyCourseIE(UdemyIE):
308     IE_NAME = 'udemy:course'
309     _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[^/?#&]+)'
310     _TESTS = []
311
312     @classmethod
313     def suitable(cls, url):
314         return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
315
316     def _real_extract(self, url):
317         course_path = self._match_id(url)
318
319         webpage = self._download_webpage(url, course_path)
320
321         course_id, title = self._extract_course_info(webpage, course_path)
322
323         self._enroll_course(url, webpage, course_id)
324
325         response = self._download_json(
326             'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
327             course_id, 'Downloading course curriculum', query={
328                 'fields[chapter]': 'title,object_index',
329                 'fields[lecture]': 'title,asset',
330                 'page_size': '1000',
331             })
332
333         entries = []
334         chapter, chapter_number = [None] * 2
335         for entry in response['results']:
336             clazz = entry.get('_class')
337             if clazz == 'lecture':
338                 asset = entry.get('asset')
339                 if isinstance(asset, dict):
340                     asset_type = asset.get('asset_type') or asset.get('assetType')
341                     if asset_type != 'Video':
342                         continue
343                 lecture_id = entry.get('id')
344                 if lecture_id:
345                     entry = {
346                         '_type': 'url_transparent',
347                         'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
348                         'title': entry.get('title'),
349                         'ie_key': UdemyIE.ie_key(),
350                     }
351                     if chapter_number:
352                         entry['chapter_number'] = chapter_number
353                     if chapter:
354                         entry['chapter'] = chapter
355                     entries.append(entry)
356             elif clazz == 'chapter':
357                 chapter_number = entry.get('object_index')
358                 chapter = entry.get('title')
359
360         return self.playlist_result(entries, course_id, title)