[udemy] Improve course enrolling
[youtube-dl] / youtube_dl / extractor / udemy.py
1 from __future__ import unicode_literals
2
3 from .common import InfoExtractor
4 from ..compat import (
5     compat_HTTPError,
6     compat_urllib_parse,
7     compat_urllib_request,
8     compat_urlparse,
9 )
10 from ..utils import (
11     ExtractorError,
12     float_or_none,
13     int_or_none,
14     sanitized_Request,
15     unescapeHTML,
16 )
17
18
19 class UdemyIE(InfoExtractor):
20     IE_NAME = 'udemy'
21     _VALID_URL = r'https?://www\.udemy\.com/(?:[^#]+#/lecture/|lecture/view/?\?lectureId=)(?P<id>\d+)'
22     _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
23     _ORIGIN_URL = 'https://www.udemy.com'
24     _NETRC_MACHINE = 'udemy'
25
26     _TESTS = [{
27         'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
28         'md5': '98eda5b657e752cf945d8445e261b5c5',
29         'info_dict': {
30             'id': '160614',
31             'ext': 'mp4',
32             'title': 'Introduction and Installation',
33             'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
34             'duration': 579.29,
35         },
36         'skip': 'Requires udemy account credentials',
37     }]
38
39     def _enroll_course(self, base_url, webpage, course_id):
40         checkout_url = unescapeHTML(self._search_regex(
41             r'href=(["\'])(?P<url>https?://(?:www\.)?udemy\.com/payment/checkout/.+?)\1',
42             webpage, 'checkout url', group='url', default=None))
43         if checkout_url:
44             raise ExtractorError(
45                 'Course %s is not free. You have to pay for it before you can download. '
46                 'Use this URL to confirm purchase: %s' % (course_id, checkout_url), expected=True)
47
48         enroll_url = unescapeHTML(self._search_regex(
49             r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
50             webpage, 'enroll url', group='url', default=None))
51         if enroll_url:
52             if not enroll_url.startswith('http'):
53                 enroll_url = compat_urlparse.urljoin(base_url, enroll_url)
54             webpage = self._download_webpage(enroll_url, course_id, 'Enrolling in the course')
55             if '>You have enrolled in' in webpage:
56                 self.to_screen('%s: Successfully enrolled in the course' % course_id)
57
58     def _download_lecture(self, course_id, lecture_id):
59         return self._download_json(
60             'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % (
61                 course_id, lecture_id, compat_urllib_parse.urlencode({
62                     'video_only': '',
63                     'auto_play': '',
64                     'fields[lecture]': 'title,description,asset',
65                     'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
66                     'instructorPreviewMode': 'False',
67                 })),
68             lecture_id, 'Downloading lecture JSON')
69
70     def _handle_error(self, response):
71         if not isinstance(response, dict):
72             return
73         error = response.get('error')
74         if error:
75             error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
76             error_data = error.get('data')
77             if error_data:
78                 error_str += ' - %s' % error_data.get('formErrors')
79             raise ExtractorError(error_str, expected=True)
80
81     def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'):
82         headers = {
83             'X-Udemy-Snail-Case': 'true',
84             'X-Requested-With': 'XMLHttpRequest',
85         }
86         for cookie in self._downloader.cookiejar:
87             if cookie.name == 'client_id':
88                 headers['X-Udemy-Client-Id'] = cookie.value
89             elif cookie.name == 'access_token':
90                 headers['X-Udemy-Bearer-Token'] = cookie.value
91                 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
92
93         if isinstance(url_or_request, compat_urllib_request.Request):
94             for header, value in headers.items():
95                 url_or_request.add_header(header, value)
96         else:
97             url_or_request = sanitized_Request(url_or_request, headers=headers)
98
99         response = super(UdemyIE, self)._download_json(url_or_request, video_id, note)
100         self._handle_error(response)
101         return response
102
103     def _real_initialize(self):
104         self._login()
105
106     def _login(self):
107         (username, password) = self._get_login_info()
108         if username is None:
109             return
110
111         login_popup = self._download_webpage(
112             self._LOGIN_URL, None, 'Downloading login popup')
113
114         def is_logged(webpage):
115             return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
116
117         # already logged in
118         if is_logged(login_popup):
119             return
120
121         login_form = self._form_hidden_inputs('login-form', login_popup)
122
123         login_form.update({
124             'email': username.encode('utf-8'),
125             'password': password.encode('utf-8'),
126         })
127
128         request = sanitized_Request(
129             self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
130         request.add_header('Referer', self._ORIGIN_URL)
131         request.add_header('Origin', self._ORIGIN_URL)
132
133         response = self._download_webpage(
134             request, None, 'Logging in as %s' % username)
135
136         if not is_logged(response):
137             error = self._html_search_regex(
138                 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
139                 response, 'error message', default=None)
140             if error:
141                 raise ExtractorError('Unable to login: %s' % error, expected=True)
142             raise ExtractorError('Unable to log in')
143
144     def _real_extract(self, url):
145         lecture_id = self._match_id(url)
146
147         webpage = self._download_webpage(url, lecture_id)
148
149         course_id = self._search_regex(
150             (r'data-course-id=["\'](\d+)', r'&quot;id&quot;\s*:\s*(\d+)'),
151             webpage, 'course id')
152
153         try:
154             lecture = self._download_lecture(course_id, lecture_id)
155         except ExtractorError as e:
156             # Error could possibly mean we are not enrolled in the course
157             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
158                 self._enroll_course(url, webpage, course_id)
159                 lecture = self._download_lecture(course_id, lecture_id)
160             else:
161                 raise
162
163         title = lecture['title']
164         description = lecture.get('description')
165
166         asset = lecture['asset']
167
168         asset_type = asset.get('assetType') or asset.get('asset_type')
169         if asset_type != 'Video':
170             raise ExtractorError(
171                 'Lecture %s is not a video' % lecture_id, expected=True)
172
173         stream_url = asset.get('streamUrl') or asset.get('stream_url')
174         if stream_url:
175             youtube_url = self._search_regex(
176                 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
177             if youtube_url:
178                 return self.url_result(youtube_url, 'Youtube')
179
180         video_id = asset['id']
181         thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
182         duration = float_or_none(asset.get('data', {}).get('duration'))
183         outputs = asset.get('data', {}).get('outputs', {})
184
185         formats = []
186         for format_ in asset.get('download_urls', {}).get('Video', []):
187             video_url = format_.get('file')
188             if not video_url:
189                 continue
190             format_id = format_.get('label')
191             f = {
192                 'url': format_['file'],
193                 'height': int_or_none(format_id),
194             }
195             if format_id:
196                 # Some videos contain additional metadata (e.g.
197                 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
198                 output = outputs.get(format_id)
199                 if isinstance(output, dict):
200                     f.update({
201                         'format_id': '%sp' % (output.get('label') or format_id),
202                         'width': int_or_none(output.get('width')),
203                         'height': int_or_none(output.get('height')),
204                         'vbr': int_or_none(output.get('video_bitrate_in_kbps')),
205                         'vcodec': output.get('video_codec'),
206                         'fps': int_or_none(output.get('frame_rate')),
207                         'abr': int_or_none(output.get('audio_bitrate_in_kbps')),
208                         'acodec': output.get('audio_codec'),
209                         'asr': int_or_none(output.get('audio_sample_rate')),
210                         'tbr': int_or_none(output.get('total_bitrate_in_kbps')),
211                         'filesize': int_or_none(output.get('file_size_in_bytes')),
212                     })
213                 else:
214                     f['format_id'] = '%sp' % format_id
215             formats.append(f)
216
217         self._sort_formats(formats)
218
219         return {
220             'id': video_id,
221             'title': title,
222             'description': description,
223             'thumbnail': thumbnail,
224             'duration': duration,
225             'formats': formats
226         }
227
228
229 class UdemyCourseIE(UdemyIE):
230     IE_NAME = 'udemy:course'
231     _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
232     _TESTS = []
233
234     @classmethod
235     def suitable(cls, url):
236         return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
237
238     def _real_extract(self, url):
239         course_path = self._match_id(url)
240
241         webpage = self._download_webpage(url, course_path)
242
243         response = self._download_json(
244             'https://www.udemy.com/api-1.1/courses/%s' % course_path,
245             course_path, 'Downloading course JSON')
246
247         course_id = response['id']
248         course_title = response.get('title')
249
250         self._enroll_course(url, webpage, course_id)
251
252         response = self._download_json(
253             'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
254             course_id, 'Downloading course curriculum')
255
256         entries = []
257         chapter, chapter_number = None, None
258         for asset in response:
259             asset_type = asset.get('assetType') or asset.get('asset_type')
260             if asset_type == 'Video':
261                 asset_id = asset.get('id')
262                 if asset_id:
263                     entry = {
264                         '_type': 'url_transparent',
265                         'url': 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']),
266                         'ie_key': UdemyIE.ie_key(),
267                     }
268                     if chapter_number:
269                         entry['chapter_number'] = chapter_number
270                     if chapter:
271                         entry['chapter'] = chapter
272                     entries.append(entry)
273             elif asset.get('type') == 'chapter':
274                 chapter_number = asset.get('index') or asset.get('object_index')
275                 chapter = asset.get('title')
276
277         return self.playlist_result(entries, course_id, course_title)